chore(#604): rename get-shit-done/ runtime directory to gsd-core/ (#615)

* chore(#604): rename get-shit-done/ runtime directory to gsd-core/

Renames the installed runtime directory `get-shit-done/` to `gsd-core/` so the
on-disk name matches the package (`@opengsd/gsd-core`), repo, and binary
(`gsd-tools`). The npm package name and binary are unchanged; npx/npm consumers
are unaffected.

Mechanical (bulk, ~90% of the diff):
- `git mv get-shit-done gsd-core`
- Swept path/identifier references across the repo via
  `perl -pe 's/get-shit-done(?!-\w)/gsd-core/g'`. The negative lookahead
  preserves the five legitimate slug variants that are NOT the directory:
  get-shit-done-{OLD,cc,classic,cli,redux} (old package/repo names).
- Build/manifest wiring: package.json (bin, files, coverage globs),
  tsconfig.build.json (outDir), ~86 .gitignore build-output entries,
  stryker.config.mjs, scan-ignore files, install.js path strings.
- Frozen (not rewritten): CHANGELOG.md history; translated docs
  (README.<locale>.md and docs/{ja-JP,ko-KR,pt-BR,zh-CN}/).

New logic (review here):
- src/installer-migrations/003-rename-get-shit-done-to-gsd-core.cts: a proper
  ADR-0008 installer migration. On upgrade it walks the legacy
  `~/.claude/get-shit-done/` tree, classifies each file via the prior install
  manifest, and emits remove-managed / backup-and-remove for managed files
  while PRESERVING unknown user-added files. Symlink-safe (skips a symlinked
  root and symlinked entries; bounds-checks every path under configDir). The
  framework rolls back on install failure. Emptied dirs may remain (framework
  has no recursive dir-removal primitive) — documented.
- scripts/lint-legacy-dir-name.cjs: CI regression guard forbidding the bare
  `get-shit-done` directory token (split token to avoid self-match; case-
  insensitive; `(?!-\w)` lookahead allows the slug variants; allowlists
  CHANGELOG, translated docs, and `gsd-allow-legacy-name` marker lines).
  Wired into the lint-tests CI job.
- Restored scripts/lint-package-identity-drift.cjs detection regexes (the
  mechanical sweep had wrongly rewritten the old-name patterns it exists to
  detect) and marked them as intentional legacy references.
- TDD tests for the migration and the guard; do.md slash-command guard regex
  tightened so a `/gsd-core/bin` path segment is not mistaken for a command;
  changeset + docs/installer-migrations.md row added.

Breaking: the installed runtime path moves `~/.claude/get-shit-done/` ->
`~/.claude/gsd-core/`. Migration 003 removes the stale legacy dir's managed
files (preserving user files) on upgrade. Users with custom hooks/configs
hardcoding the old path must update them.

Closes #604

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): unsweep pending changesets + allowlist injection-example docs

CI fixes for the rename PR:
- Do not sweep pending .changeset/*.md (ephemeral release-note fragments,
  like CHANGELOG); reverted those body edits so 5 pre-existing malformed
  fragments (missing type/pr) no longer enter the PR diff and trip docs-lint.
  Allowlisted .changeset/ in the legacy-name guard accordingly.
- Allowlisted TEST-EXAMPLES.md and docs/explanation/security-model.md in
  prompt-injection-scan.sh: they contain intentional injection examples /
  security-model prose; the path-reference rewrites are kept.

CodeQL alerts on this PR are pre-existing (alert lines unchanged by this PR;
none in the new migration/guard) and are out of scope for the rename.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): resolve CodeQL alerts surfaced on this PR

The rename diff touched files carrying pre-existing CodeQL findings; per the
no-pre-existing-dismissal rule, fixing every surfaced alert rather than waving
them off. All behavior-preserving:

- scripts/ci-test-scope.cjs: build the config-path match from string
  .includes() instead of a RegExp over an arg-derived value (js/regex-injection).
- src/profile-output.cts: escape backslashes before pipe-escaping desc/safeName
  so the table-cell escape is complete (js/incomplete-sanitization).
- tests/{bug-2643,bug-2808,docs-parity-live-registry}: two-pass HTML-comment
  strip so a bare/unclosed `<!--` cannot survive (js/incomplete-multi-character-sanitization).
- tests/inline-plan-threshold: drop the no-op `\s`->`\s` identity replace,
  keep the meaningful POSIX-class conversion (js/identity-replacement).

Verified: build:lib green; the touched test files + ci-test-scope + profile-output
suites pass; lint:legacy-name clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): correctly resolve remaining CodeQL alerts (regex-injection + sanitization)

The prior commit's fixes for two alerts were ineffective:
- ci-test-scope.cjs js/regex-injection: the alert is the CLI-arg-derived `file`
  reaching static regex `.test(file)` calls (not the config rule). Removed ALL
  regex over file/t — startsWith/includes/=== string checks + an isWindowsHint
  helper — so there is no regex sink for the tainted value.
- js/incomplete-multi-character-sanitization (3 test files): a single
  `.replace(/<!--...-->/g,'')` can let `<!--` re-form. Replaced with a fixpoint
  loop (replace until stable) plus a final bare-opener strip.

Verified: no regex over file/t remains; ci-test-scope + the 3 test suites pass;
lint:legacy-name clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): make ci-test-scope + comment-strippers regex-free to clear CodeQL

CodeQL flags the regex PATTERNS syntactically (regex-injection on the
--files arg split; incomplete-multi-character-sanitization on the <!--...-->
replace), so loop fixes do not satisfy it. Made these paths regex-free:
- ci-test-scope.cjs splitFiles: char-by-char separator tokenizer (no /[,\\s]+/).
- 3 test files: indexOf/slice HTML-comment stripper (no .replace(/<!--/)).
Behavior preserved; ci-test-scope + the 3 suites pass; guard clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): unblock security base64 scan on the large rename diff

The security job hit its 10m timeout: base64-scan.sh choked on the binary
test fixture tests/feat-3594-parser-property-style.test.cjs (embedded NUL/
non-UTF8 bytes -> thousands of bogus blobs + "ignored null byte" warnings),
and the ~800-file rename diff is slow to scan regardless.

- scripts/base64-scan.sh: skip binary-by-content files (grep -Iq .) — they
  can't carry base64-obfuscated *text* and feeding NUL bytes through the
  per-line scanner is pathologically slow. collect_files already filtered
  binary *extensions*; this catches binary *content* in text extensions.
- .github/workflows/security-scan.yml: raise the security job timeout 10m->30m
  to accommodate very large diffs (the scan itself is unchanged).

Verified locally: scan skips the fixture, 0 "ignored null byte" warnings,
0 findings, exit 0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): sweep get-shit-done refs introduced by merging next

The branch was updated with next (#614/#384/#618 etc.), which reference the
get-shit-done/ dir (still named that on next). Swept the stale references in
the merged files to gsd-core so the rename stays consistent and lint:legacy-name
passes:
- commands/gsd/discuss-phase.md (runtime-launcher shim paths)
- src/core.cts (getAgentsDir layout comments)
- tests/bug-384-agents-runtime-aware.test.cjs (require path to runtime lib)

Verified: guard 0 violations; build green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): exclude gsd-core/ path segments from bug-3683 command cross-ref invariant

The #614 runtime-launcher shim added to discuss-phase.md references
`${_GSD_RUNTIME_ROOT}/gsd-core/bin/...`. bug-3683's REF_PATTERN excluded path-y
refs only via lookbehind, but `}` precedes `/gsd-core/` in the shim, so it
mis-read the directory path as a dangling `/gsd-core` command ref (same class as
the #604 bug-2954 fix). Added a trailing `(?![\w-]*\/)` so `/gsd-<x>/...` path
segments are not treated as slash-command references.

Verified locally on BOTH platforms before pushing:
- mac (node 26) full suite: 0 failures
- gsd-test-runner (linux, node22 image) full suite: 0 failures
- bug-3683 + bug-2954 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): lazily resolve findProjectRoot in gsd-tools (harden flaky CI)

CI intermittently failed state.test's gsd-tools subprocess with
"findProjectRoot is not a function" (flip-flopping across legs; not reproducible
on mac full suite, gsd-test linux full suite, test:unit, or state.test x8).
findProjectRoot is a re-export from core.cjs (sourced from project-root.cjs);
binding it via destructure at module-load can be undefined under a load-ordering
edge. Resolve it lazily at call time via a small wrapper so the lookup happens
after core.cjs is fully initialized.

Verified green on BOTH platforms before pushing:
- mac (node 26) full suite: 0 failures
- gsd-test-runner (linux, node22) full suite: 0 failures
- state.test.cjs: 106/106; gsd-tools loads cleanly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix(#604): allowlist verification-patterns.md placeholder examples in secret scan

The rename git-mv'd references/verification-patterns.md into gsd-core/, pulling
it into the secret-scan diff. It documents stub/placeholder RED-FLAG env-var
examples (illustrative Stripe test-key / database-URL / API-key placeholders) —
not real credentials. Added it to .secretscanignore with the strict annotation,
mirroring the existing gsd-core/workflows/plan-phase.md exception.

Verified locally: secret-scan-lint --strict OK; secret-scan --diff origin/next
exits 0 with 0 findings.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-06-02 18:35:29 -04:00
committed by GitHub
parent b177c1704f
commit 463cffd894
845 changed files with 3316 additions and 2373 deletions

View File

@@ -0,0 +1,176 @@
# Advisor mode — research-backed comparison tables
> **Lazy-loaded and gated.** The parent `workflows/discuss-phase.md` Reads
> this file ONLY when `ADVISOR_MODE` is true (i.e., when
> `$HOME/.claude/gsd-core/USER-PROFILE.md` exists). Skip the Read
> entirely when no profile is present — that's the inverse of the
> `--advisor` flag from #2174 (don't pay the cost when unused).
## Activation
```bash
PROFILE_PATH="$HOME/.claude/gsd-core/USER-PROFILE.md"
if [ -f "$PROFILE_PATH" ]; then
ADVISOR_MODE=true
else
ADVISOR_MODE=false
fi
```
If `ADVISOR_MODE` is false, do **not** Read this file — proceed with the
standard `default.md` discussion flow.
## Calibration tier
Resolve `vendor_philosophy` calibration tier:
1. **Priority 1:** Read `config.json` > `preferences.vendor_philosophy`
(project-level override)
2. **Priority 2:** Read USER-PROFILE.md `Vendor Choices/Philosophy` rating
(global)
3. **Priority 3:** Default to `"standard"` if neither has a value or value
is `UNSCORED`
Map to calibration tier:
- `conservative` OR `thorough-evaluator` → `full_maturity`
- `opinionated` → `minimal_decisive`
- `pragmatic-fast` OR any other value OR empty → `standard`
Resolve advisor model:
```bash
_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 command -v gsd-tools >/dev/null 2>&1; then GSD_TOOLS="$(command -v gsd-tools)"; gsd_run() { "$GSD_TOOLS" "$@"; }; elif [ -f "$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="$HOME/.claude/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
ADVISOR_MODEL=$(gsd_run query resolve-model gsd-advisor-researcher --raw)
```
## Non-technical owner detection
Read USER-PROFILE.md and check for product-owner signals:
```bash
PROFILE_CONTENT=$(cat "$HOME/.claude/gsd-core/USER-PROFILE.md" 2>/dev/null || true)
```
Set `NON_TECHNICAL_OWNER = true` if ANY of the following are present:
- `learning_style: guided`
- The word `jargon` appears in a `frustration_triggers` section
- `explanation_depth: practical-detailed` (without a technical modifier)
- `explanation_depth: high-level`
**Tie-breaker / precedence (when signals conflict):**
1. An explicit `technical_background: true` (or any `explanation_depth` value
tagged with a technical modifier such as `practical-detailed:technical`)
**overrides** all inferred non-technical signals — set
`NON_TECHNICAL_OWNER = false`.
2. Otherwise, ANY single matching signal is sufficient to set
`NON_TECHNICAL_OWNER = true` (signals are OR-aggregated, not weighted).
3. Contradictory `explanation_depth` values: the most recent entry wins.
Log the resolved value and the matched/overriding signal so the user can
audit why a given framing was used.
When `NON_TECHNICAL_OWNER` is true, reframe gray area labels and
descriptions in product-outcome language before presenting them. Preserve
the same underlying decision — only change the framing:
- Technical implementation term → outcome the user will experience
- "Token architecture" → "Color system: which approach prevents the dark theme from flashing white on open"
- "CSS variable strategy" → "Theme colors: how your brand colors stay consistent in both light and dark mode"
- "Component API surface area" → "How the building blocks connect: how tightly coupled should these parts be"
- "Caching strategy: SWR vs React Query" → "Loading speed: should screens show saved data right away or wait for fresh data"
This reframing applies to:
1. Gray area labels and descriptions in `present_gray_areas`
2. Advisor research rationale rewrites in the synthesis step below
## advisor_research step
After the user selects gray areas in `present_gray_areas`, spawn parallel
research agents.
1. Display brief status: `Researching {N} areas...` (each runs in a subagent — no output until they return, ~1–5 min; expected, not a freeze)
2. For EACH user-selected gray area, spawn a `Agent()` in parallel:
```
Agent(
prompt="First, read @~/.claude/agents/gsd-advisor-researcher.md for your role and instructions.
<gray_area>{area_name}: {area_description from gray area identification}</gray_area>
<phase_context>{phase_goal and description from ROADMAP.md}</phase_context>
<project_context>{project name and brief description from PROJECT.md}</project_context>
<calibration_tier>{resolved calibration tier: full_maturity | standard | minimal_decisive}</calibration_tier>
Research this gray area and return a structured comparison table with rationale.
${AGENT_SKILLS_ADVISOR}",
subagent_type="general-purpose",
model="{ADVISOR_MODEL}",
description="Research: {area_name}"
)
```
All `Agent()` calls spawn simultaneously — do NOT wait for one before
starting the next.
> **ORCHESTRATOR RULE — CODEX RUNTIME**: After calling all Agent() calls above to spawn research agents, do NOT independently research or analyze any of the gray areas while the subagents are active. Wait for all subagents to return before synthesizing results. This prevents duplicate work and wasted context.
3. After ALL agents return, **synthesize results** before presenting:
For each agent's return:
a. Parse the markdown comparison table and rationale paragraph
b. Verify all 5 columns present (Option | Pros | Cons | Complexity | Recommendation) — fill any missing columns rather than showing broken table
c. Verify option count matches calibration tier:
- `full_maturity`: 3-5 options acceptable
- `standard`: 2-4 options acceptable
- `minimal_decisive`: 1-2 options acceptable
If agent returned too many, trim least viable. If too few, accept as-is.
d. Rewrite rationale paragraph to weave in project context and ongoing discussion context that the agent did not have access to
e. If agent returned only 1 option, convert from table format to direct recommendation: "Standard approach for {area}: {option}. {rationale}"
f. **If `NON_TECHNICAL_OWNER` is true:** apply a plain language rewrite to the rationale paragraph. Replace implementation-level terms with outcome descriptions the user can reason about without technical context. The Recommendation column value and the table structure remain intact. Do not remove detail; translate it. Example: "SWR uses stale-while-revalidate to serve cached responses immediately" → "This approach shows you something right away, then quietly updates in the background — users see data instantly."
4. Store synthesized tables for use in `discuss_areas` (table-first flow).
## discuss_areas (advisor table-first flow)
For each selected area:
1. **Present the synthesized comparison table + rationale paragraph** (from
`advisor_research`)
2. **Use AskUserQuestion** (or text-mode equivalent if `--text` overlay):
- header: `{area_name}`
- question: `Which approach for {area_name}?`
- options: extract from the table's Option column (AskUserQuestion adds
"Other" automatically)
3. **Record the user's selection:**
- If user picks from table options → record as locked decision for that
area
- If user picks "Other" → receive their input, reflect it back for
confirmation, record
4. **Thinking partner (conditional):** same rule as default mode — if
`features.thinking_partner` is enabled and tradeoff signals are
detected, offer a 3-5 bullet analysis before locking in.
5. **After recording pick, decide whether follow-up questions are needed:**
- If the pick has ambiguity that would affect downstream planning →
ask 1-2 targeted follow-up questions using AskUserQuestion
- If the pick is clear and self-contained → move to next area
- Do NOT ask the standard 4 questions — the table already provided the
context
6. **After all areas processed:**
- header: "Done"
- question: "That covers [list areas]. Ready to create context?"
- options: "Create context" / "Revisit an area"
## Scope creep handling (advisor mode)
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.

View File

@@ -0,0 +1,28 @@
# --all mode — auto-select ALL gray areas, discuss interactively
> **Lazy-loaded.** Read this file from `workflows/discuss-phase.md` when
> `--all` is present in `$ARGUMENTS`. Behavior overlays the default mode.
## Effect
- In `present_gray_areas`: auto-select ALL gray areas without asking the user
(skips the AskUserQuestion area-selection step).
- Discussion for each area proceeds **fully interactively** — the user drives
every question for every area (use the default-mode `discuss_areas` flow).
- Does NOT auto-advance to plan-phase afterward — use `--chain` or `--auto`
if you want auto-advance.
- Log: `[--all] Auto-selected all gray areas: [list area names].`
## Why this mode exists
This is the "discuss everything" shortcut: skip the selection friction, keep
full interactive control over each individual question.
## Combination rules
- `--all --auto`: `--auto` wins for the discussion phase too (Claude picks
recommended answers); `--all`'s contribution is just area auto-selection.
- `--all --chain`: areas auto-selected, discussion interactive, then
auto-advance to plan/execute (chain semantics).
- `--all --batch` / `--all --text` / `--all --analyze`: layered overlays
apply during discussion as documented in their respective files.

View File

@@ -0,0 +1,44 @@
# --analyze mode — trade-off tables before each question
> **Lazy-loaded overlay.** Read this file from `workflows/discuss-phase.md`
> when `--analyze` is present in `$ARGUMENTS`. Combinable with default,
> `--all`, `--chain`, `--text`, `--batch`.
## Effect
Before presenting each question (or question group, in batch mode), provide
a brief **trade-off analysis** for the decision:
- 2-3 options with pros/cons based on codebase context and common patterns
- A recommended approach with reasoning
- Known pitfalls or constraints from prior phases
## Example
```markdown
**Trade-off analysis: Authentication strategy**
| Approach | Pros | Cons |
|----------|------|------|
| Session cookies | Simple, httpOnly prevents XSS | Requires CSRF protection, sticky sessions |
| JWT (stateless) | Scalable, no server state | Token size, revocation complexity |
| OAuth 2.0 + PKCE | Industry standard for SPAs | More setup, redirect flow UX |
💡 Recommended: OAuth 2.0 + PKCE — your app has social login in requirements (REQ-04) and this aligns with the existing NextAuth setup in `src/lib/auth.ts`.
How should users authenticate?
```
This gives the user context to make informed decisions without extra
prompting.
When `--analyze` is absent, present questions directly as before (no
trade-off table).
## Sourcing the analysis
- Pros/cons should reflect the codebase context loaded in `scout_codebase`
and any prior decisions surfaced in `load_prior_context`.
- The recommendation must explicitly tie to project context (e.g.,
existing libraries, prior phase decisions, documented requirements).
- If a related ADR or spec is referenced in CONTEXT.md `<canonical_refs>`,
cite it in the recommendation.

View File

@@ -0,0 +1,57 @@
# --auto mode — fully autonomous discuss-phase
> **Lazy-loaded.** Read this file from `workflows/discuss-phase.md` when
> `--auto` is present in `$ARGUMENTS`. After the discussion completes, the
> parent's `auto_advance` step also reads `modes/chain.md` to drive the
> auto-advance to plan-phase.
## Effect across steps
- **`check_existing`**: if CONTEXT.md exists, auto-select "Update it" — load
existing context and continue to `analyze_phase` (matches the parent step's
documented `--auto` branch). If no context exists, continue without
prompting. For interrupted checkpoints, auto-select "Resume". For existing
plans, auto-select "Continue and replan after". Log every decision so the
user can audit.
- **`cross_reference_todos`**: fold all todos with relevance score >= 0.4
automatically. Log the selection.
- **`present_gray_areas`**: auto-select ALL gray areas. Log:
`[--auto] Selected all gray areas: [list area names].`
- **`discuss_areas`**: for each discussion question, choose the recommended
option (first option, or the one explicitly marked "recommended") **without
using AskUserQuestion**. Skip interactive prompts entirely. Log each
auto-selected choice inline so the user can review decisions in the
context file:
```
[auto] [Area] — Q: "[question text]" → Selected: "[chosen option]" (recommended default)
```
- After all areas are auto-resolved, skip the "Explore more gray areas"
prompt and proceed directly to `write_context`.
- After `write_context`, **auto-advance** to plan-phase via `modes/chain.md`.
## CRITICAL — Auto-mode pass cap
In `--auto` mode, the discuss step MUST complete in a **single pass**. After
writing CONTEXT.md once, you are DONE — proceed immediately to
`write_context` and then auto_advance. Do NOT re-read your own CONTEXT.md to
find "gaps", "undefined types", or "missing decisions" and run additional
passes. This creates a self-feeding loop where each pass generates references
that the next pass treats as gaps, consuming unbounded time and resources.
Check the pass cap from config:
```bash
_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 command -v gsd-tools >/dev/null 2>&1; then GSD_TOOLS="$(command -v gsd-tools)"; gsd_run() { "$GSD_TOOLS" "$@"; }; elif [ -f "$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="$HOME/.claude/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
MAX_PASSES=$(gsd_run query config-get workflow.max_discuss_passes 2>/dev/null || echo "3")
```
If you have already written and committed CONTEXT.md, the discuss step is
complete. Move on.
## Combination rules
- `--auto --text` / `--auto --batch`: text/batch overlays are no-ops in
auto mode (no user prompts to render).
- `--auto --analyze`: trade-off tables can still be logged for the audit
trail; selection still uses the recommended option.
- `--auto --power`: `--power` wins (power mode generates files for offline
answering — incompatible with autonomous selection).

View File

@@ -0,0 +1,52 @@
# --batch mode — grouped question batches
> **Lazy-loaded overlay.** Read this file from `workflows/discuss-phase.md`
> when `--batch` is present in `$ARGUMENTS`. Combinable with default,
> `--all`, `--chain`, `--text`, `--analyze`.
## Argument parsing
Parse optional `--batch` from `$ARGUMENTS`:
- Accept `--batch`, `--batch=N`, or `--batch N`
- Default to **4 questions per batch** when no number is provided
- Clamp explicit sizes to **2–5** so a batch stays answerable
- If `--batch` is absent, keep the existing one-question-at-a-time flow
(default mode).
## Effect on discuss_areas
`--batch` mode: ask **2–5 numbered questions in one plain-text turn** per
area, instead of the default 4 single-question AskUserQuestion turns.
- Group closely related questions for the current area into a single
message
- Keep each question concrete and answerable in one reply
- When options are helpful, include short inline choices per question
rather than a separate AskUserQuestion for every item
- After the user replies, reflect back the captured decisions, note any
unanswered items, and ask only the minimum follow-up needed before
moving on
- Preserve adaptiveness between batches: use the full set of answers to
decide the next batch or whether the area is sufficiently clear
## Philosophy
Stay adaptive, but let the user choose the pacing.
- Default mode: 4 single-question turns, then check whether to continue
- `--batch` mode: 1 grouped turn with 2–5 numbered questions, then check
whether to continue
Each answer set should reveal the next question or next batch.
## Example batch
```
Authentication — please answer 1–4:
1. Which auth strategy? (a) Session cookies (b) JWT (c) OAuth 2.0 + PKCE
2. Where do tokens live? (a) httpOnly cookie (b) localStorage (c) memory only
3. Session lifetime? (a) 1h (b) 24h (c) 30d (d) configurable
4. Account recovery? (a) email reset (b) magic link (c) both
Reply with your choices (e.g. "1c, 2a, 3b, 4c") or describe in your own words.
```

View File

@@ -0,0 +1,98 @@
# --chain mode — interactive discuss, then auto-advance
> **Lazy-loaded.** Read this file from `workflows/discuss-phase.md` when
> `--chain` is present in `$ARGUMENTS`, or when the parent's `auto_advance`
> step needs to dispatch to plan-phase under `--auto`.
## Effect
- Discussion is **fully interactive** — questions, gray-area selection, and
follow-ups behave exactly the same as default mode.
- After discussion completes, **auto-advance to plan-phase → execute-phase**
(same downstream behavior as `--auto`).
- This is the middle ground: the user controls the discuss decisions, then
plan and execute run autonomously.
## auto_advance step (executed by the parent file)
1. Parse `--auto` and `--chain` flags from `$ARGUMENTS`. **Note:** `--all`
is NOT an auto-advance trigger — it only affects area selection. A
session with `--all` but without `--auto` or `--chain` returns to manual
next-steps after discussion completes.
2. **Sync chain flag with intent** — if user invoked manually (no `--auto`
and no `--chain`), 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
_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 command -v gsd-tools >/dev/null 2>&1; then GSD_TOOLS="$(command -v gsd-tools)"; gsd_run() { "$GSD_TOOLS" "$@"; }; elif [ -f "$HOME/.claude/gsd-core/bin/${_GSD_SHIM_NAME}" ]; then GSD_TOOLS="$HOME/.claude/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 [[ ! "$ARGUMENTS" =~ --auto ]] && [[ ! "$ARGUMENTS" =~ --chain ]]; then
gsd_run query config-set workflow._auto_chain_active false || true
fi
```
3. Read consolidated auto-mode (`active` = chain flag OR user preference):
```bash
AUTO_MODE=$(gsd_run query check auto-mode --pick active 2>/dev/null || echo "false")
```
4. **If `--auto` or `--chain` flag present AND `AUTO_MODE` is not true:**
Persist chain flag to config (handles direct usage without new-project):
```bash
gsd_run query config-set workflow._auto_chain_active true
```
5. **If `--auto` flag present OR `--chain` flag present OR `AUTO_MODE` is
true:** display banner and launch plan-phase.
Banner:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
GSD ► 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="gsd-plan-phase", args="${PHASE} --auto ${GSD_WS}")
```
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.
6. **Handle plan-phase return:**
- **PHASE COMPLETE** → Full chain succeeded. Display:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
GSD ► PHASE ${PHASE} COMPLETE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Auto-advance pipeline finished: discuss → plan → execute
/clear then:
Next: /gsd:discuss-phase ${NEXT_PHASE} ${WAS_CHAIN ? "--chain" : "--auto"} ${GSD_WS}
```
- **PLANNING COMPLETE** → Planning done, execution didn't complete:
```
Auto-advance partial: Planning complete, execution did not finish.
Continue: /gsd:execute-phase ${PHASE} ${GSD_WS}
```
- **PLANNING INCONCLUSIVE / CHECKPOINT** → Stop chain:
```
Auto-advance stopped: Planning needs input.
Continue: /gsd:plan-phase ${PHASE} ${GSD_WS}
```
- **GAPS FOUND** → Stop chain:
```
Auto-advance stopped: Gaps found during execution.
Continue: /gsd:plan-phase ${PHASE} --gaps ${GSD_WS}
```
7. **If none of `--auto`, `--chain`, nor config enabled:** route to
`confirm_creation` step (existing behavior — show manual next steps).

View File

@@ -0,0 +1,141 @@
# Default mode — interactive discuss-phase
> **Lazy-loaded.** Read this file from `workflows/discuss-phase.md` when no
> mode flag is present (the baseline interactive flow). When `--text`,
> `--batch`, or `--analyze` is also present, layer the corresponding overlay
> file from this directory on top of the rules below.
This document defines `discuss_areas` for the default flow. The shared steps
that come before (`initialize`, `check_blocking_antipatterns`, `check_spec`,
`check_existing`, `load_prior_context`, `cross_reference_todos`,
`scout_codebase`, `analyze_phase`, `present_gray_areas`) live in the parent
file and run for every mode.
## discuss_areas (default, interactive)
For each selected area, conduct a focused discussion loop.
**Research-before-questions mode:** Check if `workflow.research_before_questions` is enabled in config (from init context or `.planning/config.json`). When enabled, before presenting questions for each area:
1. Do a brief web search for best practices related to the area topic
2. Summarize the top findings in 2-3 bullet points
3. Present the research alongside the question so the user can make a more informed decision
Example with research enabled:
```text
Let's talk about [Authentication Strategy].
📊 Best practices research:
• OAuth 2.0 + PKCE is the current standard for SPAs (replaces implicit flow)
• Session tokens with httpOnly cookies preferred over localStorage for XSS protection
• Consider passkey/WebAuthn support — adoption is accelerating in 2025-2026
With that context: How should users authenticate?
```
When disabled (default), skip the research and present questions directly as before.
**Philosophy:** stay adaptive. Default flow is 4 single-question turns, then
check whether to continue. Each answer should reveal the next question.
**For each area:**
1. **Announce the area:**
```text
Let's talk about [Area].
```
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:
```text
"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 the current set of questions, check:**
- header: "[Area]" (max 12 chars)
- question: "More questions about [area], or move to next? (Remaining: [list other unvisited areas])"
- options: "More questions" / "Next area"
When building the question text, list the remaining unvisited areas so the user knows what's ahead. For example: "More questions about Layout, or move to next? (Remaining: Loading behavior, Content ordering)"
If "More questions" → ask another 4 single questions, 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
**Canonical ref accumulation during discussion:**
When the user references a doc, spec, or ADR during any answer — e.g., "read adr-014", "check the MCP spec", "per browse-spec.md" — immediately:
1. Read the referenced doc (or confirm it exists)
2. Add it to the canonical refs accumulator with full relative path
3. Use what you learned from the doc to inform subsequent questions
These user-referenced docs are often MORE important than ROADMAP.md refs because they represent docs the user specifically wants downstream agents to follow. Never drop them.
**Question design:**
- Options should be concrete, not abstract ("Cards" not "Option A")
- Each answer should inform the next question or next batch
- 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 or the next numbered batch.
**Thinking partner (conditional):**
If `features.thinking_partner` is enabled in config, check the user's answer for tradeoff signals
(see `references/thinking-partner.md` for signal list). If tradeoff detected:
```text
I notice competing priorities here — {option_A} optimizes for {goal_A} while {option_B} optimizes for {goal_B}.
Want me to think through the tradeoffs before we lock this in?
[Yes, analyze] / [No, decision made]
```
If yes: provide 3-5 bullet analysis (what each optimizes/sacrifices, alignment with PROJECT.md goals, recommendation). Then return to normal flow.
**Scope creep handling:**
If user mentions something outside the phase domain:
```text
"[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.
**Incremental checkpoint — save after each area completes:**
After each area is resolved (user says "Next area"), immediately write a checkpoint file with all decisions captured so far. This prevents data loss if the session is interrupted mid-discussion.
**Checkpoint file:** `${phase_dir}/${padded_phase}-DISCUSS-CHECKPOINT.json`
Schema: read `workflows/discuss-phase/templates/checkpoint.json` for the
canonical structure — copy it and substitute the live values.
**On session resume:** Handled in the parent's `check_existing` step. After
`write_context` completes successfully, the parent's `git_commit` step
deletes the checkpoint.
**Track discussion log data internally:**
For each question asked, accumulate:
- Area name
- All options presented (label + description)
- Which option the user selected (or their free-text response)
- Any follow-up notes or clarifications the user provided
This data is used to generate DISCUSSION-LOG.md in the parent's `git_commit` step.

View File

@@ -0,0 +1,44 @@
# --power mode — bulk question generation, async answering
> **Lazy-loaded.** Read this file from `workflows/discuss-phase.md` when
> `--power` is present in `$ARGUMENTS`. The full step-by-step instructions
> live in the existing `discuss-phase-power.md` workflow file (kept stable
> at its original path so installed `@`-references continue to resolve).
## Dispatch
```
Read @~/.claude/gsd-core/workflows/discuss-phase-power.md
```
Execute it end-to-end. Do not continue with the standard interactive steps.
## Summary of flow
The power user mode generates ALL questions upfront into machine-readable
and human-friendly files, then waits for the user to answer at their own
pace before processing all answers in a single pass.
1. Run the same phase analysis (gray area identification) as standard mode
2. Write all questions to
`{phase_dir}/{padded_phase}-QUESTIONS.json` and
`{phase_dir}/{padded_phase}-QUESTIONS.html`
3. Notify user with file paths and wait for a "refresh" or "finalize"
command
4. On "refresh": read the JSON, process answered questions, update stats
and HTML
5. On "finalize": read all answers from JSON, generate CONTEXT.md in the
standard format
## When to use
Large phases with many gray areas, or when users prefer to answer
questions offline / asynchronously rather than interactively in the chat
session.
## Combination rules
- `--power --auto`: power wins. Power mode is incompatible with
autonomous selection — its purpose is offline answering.
- `--power --chain`: after the power-mode finalize step writes
CONTEXT.md, the chain auto-advance still applies (Read `chain.md`).

View File

@@ -0,0 +1,55 @@
# --text mode — plain-text overlay (no AskUserQuestion)
> **Lazy-loaded overlay.** Read this file from `workflows/discuss-phase.md`
> when `--text` is present in `$ARGUMENTS`, OR when
> `workflow.text_mode: true` is set in config (e.g., per-project default).
## Effect
When text mode is active, **do not use AskUserQuestion at all**. Instead,
present every question as a plain-text numbered list and ask the user to
type their choice number. Free-text input maps to the "Other" branch of
the equivalent AskUserQuestion call.
This is required for Claude Code remote sessions (`/rc` mode) where the
Claude App cannot forward TUI menu selections back to the host.
## Activation
- Per-session: pass `--text` flag to any command (e.g.,
`/gsd:discuss-phase --text`)
- Per-project: `gsd-tools.cjs query config-set workflow.text_mode true`
Text mode applies to ALL workflows in the session, not just discuss-phase.
## Question rendering
Replace this:
```text
AskUserQuestion(
header="Layout",
question="How should posts be displayed?",
options=["Cards", "List", "Timeline"]
)
```
With this:
```text
Layout — How should posts be displayed?
1. Cards
2. List
3. Timeline
4. Other (type freeform)
Reply with a number, or describe your preference.
```
Wait for the user's reply at the normal prompt. Parse:
- Numeric reply → mapped to that option
- Free text → treated as "Other" — reflect it back, confirm, then proceed
## Empty-answer handling
The same answer-validation rules from the parent file apply: empty
responses trigger one retry, then a clarifying question. Do not proceed
with empty input.

View File

@@ -0,0 +1,18 @@
{
"phase": "{PHASE_NUM}",
"phase_name": "{phase_name}",
"timestamp": "{ISO timestamp}",
"areas_completed": ["Area 1", "Area 2"],
"areas_remaining": ["Area 3", "Area 4"],
"decisions": {
"Area 1": [
{"question": "...", "answer": "...", "options_presented": ["..."]},
{"question": "...", "answer": "...", "options_presented": ["..."]}
],
"Area 2": [
{"question": "...", "answer": "...", "options_presented": ["..."]}
]
},
"deferred_ideas": ["..."],
"canonical_refs": ["..."]
}

View File

@@ -0,0 +1,136 @@
# CONTEXT.md template — for discuss-phase write_context step
> **Lazy-loaded.** Read this file only inside the `write_context` step of
> `workflows/discuss-phase.md`, immediately before writing
> `${phase_dir}/${padded_phase}-CONTEXT.md`. Do not put a reference to this
> file in `<required_reading>` — that defeats the progressive-disclosure
> savings introduced by issue #2551.
## Variable substitutions
The caller substitutes:
- `[X]` → phase number
- `[Name]` → phase name
- `[date]` → ISO date when context was gathered
- `${padded_phase}` → zero-padded phase number (e.g., `07`, `15`)
- `{N}` → counts (requirements, etc.)
## Conditional sections
- **`<spec_lock>`** — include only when `spec_loaded = true` (a `*-SPEC.md`
was found by `check_spec`). Otherwise omit the entire `<spec_lock>` block.
- **Folded Todos / Reviewed Todos** — include subsections only when the
`cross_reference_todos` step folded or reviewed at least one todo.
## Template body
```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>
[If spec_loaded = true, insert this section:]
<spec_lock>
## Requirements (locked via SPEC.md)
**{N} requirements are locked.** See `{padded_phase}-SPEC.md` for full requirements, boundaries, and acceptance criteria.
Downstream agents MUST read `{padded_phase}-SPEC.md` before planning or implementing. Requirements are not duplicated here.
**In scope (from SPEC.md):** [copy the "In scope" bullet list from SPEC.md Boundaries]
**Out of scope (from SPEC.md):** [copy the "Out of scope" bullet list from SPEC.md Boundaries]
</spec_lock>
<decisions>
## Implementation Decisions
### [Category 1 that was discussed]
- **D-01:** [Decision or preference captured]
- **D-02:** [Another decision if applicable]
### [Category 2 that was discussed]
- **D-03:** [Decision or preference captured]
### Claude's Discretion
[Areas where user said "you decide" — note that Claude has flexibility here]
### Folded Todos
[If any todos were folded into scope from the cross_reference_todos step, list them here.
Each entry should include the todo title, original problem, and how it fits this phase's scope.
If no todos were folded: omit this subsection entirely.]
</decisions>
<canonical_refs>
## Canonical References
**Downstream agents MUST read these before planning or implementing.**
[MANDATORY section. Write the FULL accumulated canonical refs list here.
Sources: ROADMAP.md refs + REQUIREMENTS.md refs + user-referenced docs during
discussion + any docs discovered during codebase scout. Group by topic area.
Every entry needs a full relative path — not just a name.]
### [Topic area 1]
- `path/to/adr-or-spec.md` — [What it decides/defines that's relevant]
- `path/to/doc.md` §N — [Specific section reference]
### [Topic area 2]
- `path/to/feature-doc.md` — [What this doc defines]
[If no external specs: "No external specs — requirements fully captured in decisions above"]
</canonical_refs>
<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.]
### Reviewed Todos (not folded)
[If any todos were reviewed in cross_reference_todos but not folded into scope,
list them here so future phases know they were considered.
Each entry: todo title + reason it was deferred (out of scope, belongs in Phase Y, etc.)
If no reviewed-but-deferred todos: omit this subsection entirely.]
[If none: "None — discussion stayed within phase scope"]
</deferred>
---
*Phase: [X]-[Name]*
*Context gathered: [date]*
```

View File

@@ -0,0 +1,50 @@
# DISCUSSION-LOG.md template — for discuss-phase git_commit step
> **Lazy-loaded.** Read this file only inside the `git_commit` step of
> `workflows/discuss-phase.md`, immediately before writing
> `${phase_dir}/${padded_phase}-DISCUSSION-LOG.md`.
## Purpose
Audit trail for human review (compliance, learning, retrospectives). NOT
consumed by downstream agents — those read CONTEXT.md only.
## Template body
```markdown
# Phase [X]: [Name] - Discussion Log
> **Audit trail only.** Do not use as input to planning, research, or execution agents.
> Decisions are captured in CONTEXT.md — this log preserves the alternatives considered.
**Date:** [ISO date]
**Phase:** [phase number]-[phase name]
**Areas discussed:** [comma-separated list]
---
[For each gray area discussed:]
## [Area Name]
| Option | Description | Selected |
|--------|-------------|----------|
| [Option 1] | [Description from AskUserQuestion] | |
| [Option 2] | [Description] | ✓ |
| [Option 3] | [Description] | |
**User's choice:** [Selected option or free-text response]
**Notes:** [Any clarifications, follow-up context, or rationale the user provided]
---
[Repeat for each area]
## Claude's Discretion
[List areas where user said "you decide" or deferred to Claude]
## Deferred Ideas
[Ideas mentioned during discussion that were noted for future phases]
```