fix(3584): runtime-aware slash formatter for user-facing emissions

Introduce `runtime-slash.cjs` as the single source of truth for emitting
GSD slash-command references in user-facing runtime output and persisted
artifacts. `formatGsdSlash(commandName, runtime)` produces `/gsd-<cmd>`
for skills-based runtimes (Claude/Cursor/OpenCode/Kilo/etc.) and
`$gsd-<cmd>` for Codex. The deprecated `/gsd:<cmd>` colon form is never
emitted — pasting a recommended-action command into Claude Code now
routes correctly instead of failing with `Unknown command`.

Wired into the high-impact emitters identified in #3584:

- `init.cjs` `cmdInitManager` recommended_actions[].command (the
  original failure path in the bug report) plus the no-ROADMAP /
  no-STATE error hints.
- `phase.cjs` `cmdPhaseAdd`, `cmdPhaseAddBatch`, `cmdPhaseInsert` —
  ROADMAP.md `Plans:` references now persist the routable form
  instead of the legacy colon form.
- `verify.cjs` `cmdValidateHealth` — every fix-hint addIssue() call
  (E001/E002/E003/E004/E005, W002/W003/W008/W009/W011/W016/W018) and
  the persisted STATE.md regenerate / MILESTONES.md backfill notes.
- `milestone.cjs` `cmdMilestoneComplete` — Operator Next Steps tail
  rewrite.
- `validate-command-router.cjs` — `validate context` recommendation
  strings for WARNING/CRITICAL utilization bands.
- `workstream.cjs` — missing .planning hint.
- `profile-output.cjs` — `generate-claude-md` workflow enforcement
  block, project/skills fallbacks, profile placeholder, and the
  dev-preferences refresh hints.
- `drift.cjs`, `gsd2-import.cjs`, `commands.cjs scaffold context` —
  remaining one-off persisted references.

Runtime detection: `resolveRuntime(projectDir)` reads
`process.env.GSD_RUNTIME` first, then a side-effect-free direct read of
`.planning/config.json` (NOT `loadConfig`, which would normalize legacy
keys and re-write the file just to read the runtime name).

Tests:
- `tests/bug-3584-runtime-slash-formatter.test.cjs` — 22 unit tests
  covering the pure formatter and resolver (hyphen vs codex, prefix
  normalization, defensive returns, env/config/default chain).
- `tests/bug-3584-runtime-slash-emitters.test.cjs` — 6 integration
  tests exercising `init manager`, `phase add` (via the structured
  `roadmap get-phase` payload to avoid raw-text matching on the
  on-disk artifact), `validate health`, `validate context`, and the
  codex variant.
- Existing tests updated to assert the new contract: validate-context
  recommendations, claude-md workflow block, milestone complete
  Operator Next Steps. Copilot-install engine-conversion test now
  asserts against a synthetic input since bin/lib/*.cjs no longer
  contains literal `/gsd:` references for the install-time converter
  to rewrite.

INVENTORY.md and INVENTORY-MANIFEST.json updated for the new module
(64 CLI modules shipped, +1).

Fixes #3584

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tom Boucher
2026-05-15 19:32:02 -04:00
parent 823b4ece0a
commit 034b47c8d0
20 changed files with 751 additions and 86 deletions

View File

@@ -8,6 +8,7 @@ const { loadConfig, isGitIgnored, normalizePhaseName, comparePhaseNum, getArchiv
const { planningDir, planningPaths } = require('./planning-workspace.cjs');
const { extractFrontmatter } = require('./frontmatter.cjs');
const { MODEL_PROFILES } = require('./model-profiles.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
/**
* Determine phase status by checking plan/summary counts AND verification state.
@@ -779,7 +780,7 @@ function cmdScaffold(cwd, type, options, raw) {
switch (type) {
case 'context': {
filePath = path.join(phaseDir, `${padded}-CONTEXT.md`);
content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Context\n\n## Decisions\n\n_Decisions will be captured during /gsd:discuss-phase ${phase}_\n\n## Discretion Areas\n\n_Areas where the executor can use judgment_\n\n## Deferred Ideas\n\n_Ideas to consider later_\n`;
content = `---\nphase: "${padded}"\nname: "${name || phaseInfo?.phase_name || 'Unnamed'}"\ncreated: ${today}\n---\n\n# Phase ${phase}: ${name || phaseInfo?.phase_name || 'Unnamed'} — Context\n\n## Decisions\n\n_Decisions will be captured during ${formatGsdSlash('discuss-phase', resolveRuntime(cwd))} ${phase}_\n\n## Discretion Areas\n\n_Areas where the executor can use judgment_\n\n## Deferred Ideas\n\n_Ideas to consider later_\n`;
break;
}
case 'uat': {

View File

@@ -253,8 +253,10 @@ function buildMessage(elements, affectedPaths, action) {
if (action === 'auto-remap') {
lines.push(`Auto-remap scheduled for paths: ${affectedPaths.join(', ')}`);
} else {
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
const mapCmd = formatGsdSlash('map-codebase', resolveRuntime(null));
lines.push(
`Run /gsd:map-codebase --paths ${affectedPaths.join(',')} to refresh planning context.`,
`Run ${mapCmd} --paths ${affectedPaths.join(',')} to refresh planning context.`,
);
}
return lines.join('\n');

View File

@@ -421,7 +421,8 @@ function buildPreview(gsd2Data, artifacts) {
lines.push('');
lines.push('Cannot migrate automatically:');
lines.push(' - GSD-2 cost/token ledger (no v1 equivalent)');
lines.push(' - GSD-2 database state (rebuilt from files on first /gsd:health)');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
lines.push(` - GSD-2 database state (rebuilt from files on first ${formatGsdSlash('health', resolveRuntime(null))})`);
lines.push(' - VS Code extension state');
return lines.join('\n');

View File

@@ -10,6 +10,7 @@ const { planningPaths, planningDir, planningRoot } = require('./planning-workspa
const { maskIfSecret } = require('./secrets.cjs');
const scanPhasePlans = require('./plan-scan.cjs');
const { stateExtractField } = require('./state-document.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
// Accept all bold/colon variants of the Requirements header (#2769):
// **Requirements:** / **Requirements**: / **Requirements** : render the
@@ -1055,16 +1056,20 @@ function cmdInitMapCodebase(cwd, raw) {
function cmdInitManager(cwd, raw) {
const config = loadConfig(cwd);
const milestone = getMilestoneInfo(cwd);
// Resolve the runtime once so every emitted slash-command reference uses
// the routable shape for this install (#3584). Hyphen form for skills-based
// runtimes, $gsd-<cmd> shell-var for codex.
const _slashRuntime = resolveRuntime(cwd);
// Use planningPaths for forward-compatibility with workstream scoping (#1268)
const paths = planningPaths(cwd);
// Validate prerequisites
if (!fs.existsSync(paths.roadmap)) {
error('No ROADMAP.md found. Run /gsd:new-milestone first.');
error(`No ROADMAP.md found. Run ${formatGsdSlash('new-milestone', _slashRuntime)} first.`);
}
if (!fs.existsSync(paths.state)) {
error('No STATE.md found. Run /gsd:new-milestone first.');
error(`No STATE.md found. Run ${formatGsdSlash('new-milestone', _slashRuntime)} first.`);
}
const rawContent = fs.readFileSync(paths.roadmap, 'utf-8');
const content = extractCurrentMilestone(rawContent, cwd);
@@ -1244,7 +1249,7 @@ function cmdInitManager(cwd, raw) {
phase_name: phase.name,
action: 'execute',
reason: `${phase.plan_count} plans ready, dependencies met`,
command: `/gsd:execute-phase ${phase.number}`,
command: `${formatGsdSlash('execute-phase', _slashRuntime)} ${phase.number}`,
});
} else if (phase.disk_status === 'discussed' || phase.disk_status === 'researched') {
recommendedActions.push({
@@ -1252,7 +1257,7 @@ function cmdInitManager(cwd, raw) {
phase_name: phase.name,
action: 'plan',
reason: 'Context gathered, ready for planning',
command: `/gsd:plan-phase ${phase.number}`,
command: `${formatGsdSlash('plan-phase', _slashRuntime)} ${phase.number}`,
});
} else if ((phase.disk_status === 'empty' || phase.disk_status === 'no_directory') && phase.is_next_to_discuss) {
recommendedActions.push({
@@ -1260,7 +1265,7 @@ function cmdInitManager(cwd, raw) {
phase_name: phase.name,
action: 'discuss',
reason: 'Unblocked, ready to gather context',
command: `/gsd:discuss-phase ${phase.number}`,
command: `${formatGsdSlash('discuss-phase', _slashRuntime)} ${phase.number}`,
});
}
}

View File

@@ -9,6 +9,7 @@ const { platformWriteSync, platformEnsureDir } = require('./shell-command-projec
const { planningPaths } = require('./planning-workspace.cjs');
const { extractFrontmatter } = require('./frontmatter.cjs');
const { writeStateMd, stateReplaceFieldWithFallback } = require('./state.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
function cmdRequirementsMarkComplete(cwd, reqIdsRaw, raw) {
if (!reqIdsRaw || reqIdsRaw.length === 0) {
@@ -228,10 +229,10 @@ function cmdMilestoneComplete(cwd, version, options, raw) {
if (operatorPattern.test(stateContent)) {
stateContent = stateContent.replace(
operatorPattern,
`$1\n- Start the next milestone with /gsd:new-milestone\n\n`,
`$1\n- Start the next milestone with ${formatGsdSlash('new-milestone', resolveRuntime(cwd))}\n\n`,
);
} else {
stateContent = `${stateContent.trimEnd()}\n\n## Operator Next Steps\n\n- Start the next milestone with /gsd:new-milestone\n`;
stateContent = `${stateContent.trimEnd()}\n\n## Operator Next Steps\n\n- Start the next milestone with ${formatGsdSlash('new-milestone', resolveRuntime(cwd))}\n`;
}
writeStateMd(statePath, stateContent, cwd);

View File

@@ -9,6 +9,7 @@ const { platformWriteSync, platformReadSync, platformEnsureDir } = require('./sh
const { planningDir, withPlanningLock } = require('./planning-workspace.cjs');
const { extractFrontmatter } = require('./frontmatter.cjs');
const { writeStateMd, readModifyWriteStateMd, stateExtractField, stateReplaceField, stateReplaceFieldWithFallback, updatePerformanceMetricsSection } = require('./state.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
// #2893 — strict canonical filter: `{padded_phase}-{NN}-PLAN.md` or `PLAN.md`.
// Documented in agents/gsd-planner.md (write_phase_prompt step). The wider
@@ -579,7 +580,7 @@ function cmdPhaseAdd(cwd, description, raw, customId) {
// Build phase entry
const dependsOn = config.phase_naming === 'custom' ? '' : `\n**Depends on:** Phase ${typeof _newPhaseId === 'number' ? _newPhaseId - 1 : 'TBD'}`;
const phaseEntry = `\n### Phase ${_newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd:plan-phase ${_newPhaseId} to break down)\n`;
const phaseEntry = `\n### Phase ${_newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run ${formatGsdSlash('plan-phase', resolveRuntime(cwd))} ${_newPhaseId} to break down)\n`;
// Find insertion point: before last "---" or at end
let updatedContent;
@@ -656,7 +657,7 @@ function cmdPhaseAddBatch(cwd, descriptions, raw) {
platformEnsureDir(dirPath);
platformWriteSync(path.join(dirPath, '.gitkeep'), '');
const dependsOn = config.phase_naming === 'custom' ? '' : `\n**Depends on:** Phase ${typeof newPhaseId === 'number' ? newPhaseId - 1 : 'TBD'}`;
const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd:plan-phase ${newPhaseId} to break down)\n`;
const phaseEntry = `\n### Phase ${newPhaseId}: ${description}\n\n**Goal:** [To be planned]\n**Requirements**: TBD${dependsOn}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run ${formatGsdSlash('plan-phase', resolveRuntime(cwd))} ${newPhaseId} to break down)\n`;
const lastSeparator = rawContent.lastIndexOf('\n---');
rawContent = lastSeparator > 0
? rawContent.slice(0, lastSeparator) + phaseEntry + rawContent.slice(lastSeparator)
@@ -747,7 +748,7 @@ function cmdPhaseInsert(cwd, afterPhase, description, raw) {
platformWriteSync(path.join(dirPath, '.gitkeep'), '');
// Build phase entry
const phaseEntry = `\n### Phase ${_decimalPhase}: ${description} (INSERTED)\n\n**Goal:** [Urgent work - to be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${afterPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run /gsd:plan-phase ${_decimalPhase} to break down)\n`;
const phaseEntry = `\n### Phase ${_decimalPhase}: ${description} (INSERTED)\n\n**Goal:** [Urgent work - to be planned]\n**Requirements**: TBD\n**Depends on:** Phase ${afterPhase}\n**Plans:** 0 plans\n\nPlans:\n- [ ] TBD (run ${formatGsdSlash('plan-phase', resolveRuntime(cwd))} ${_decimalPhase} to break down)\n`;
// Insert after the target phase section
const headerPattern = new RegExp(`(#{2,4}\\s*Phase\\s+${afterPhaseEscaped}:[^\\n]*\\n)`, 'i');

View File

@@ -15,6 +15,7 @@ const os = require('os');
const { output, error, loadConfig } = require('./core.cjs');
const { platformReadSync: safeReadFile, platformWriteSync, platformEnsureDir } = require('./shell-command-projection.cjs');
const { getGlobalSkillDir } = require('./runtime-homes.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
// ─── Constants ────────────────────────────────────────────────────────────────
@@ -174,36 +175,46 @@ const CLAUDE_INSTRUCTIONS = {
},
};
const CLAUDE_MD_FALLBACKS = {
project: 'Project not yet initialized. Run /gsd:new-project to set up.',
stack: 'Technology stack not yet documented. Will populate after codebase mapping or first phase.',
conventions: 'Conventions not yet established. Will populate as patterns emerge during development.',
architecture: 'Architecture not yet mapped. Follow existing patterns found in the codebase.',
skills: 'No project skills found. Add skills to any of: `.claude/skills/`, `.agents/skills/`, `.cursor/skills/`, `.github/skills/`, or `.codex/skills/` with a `SKILL.md` index file.',
};
// CLAUDE.md fallback / placeholder text — runtime-aware so emitted slash
// commands route correctly under the active install (#3584). The values must
// be computed per-call rather than at module load because the slash form
// depends on the runtime resolved from the project's config/env.
function buildClaudeMdFallbacks(runtime) {
return {
project: `Project not yet initialized. Run ${formatGsdSlash('new-project', runtime)} to set up.`,
stack: 'Technology stack not yet documented. Will populate after codebase mapping or first phase.',
conventions: 'Conventions not yet established. Will populate as patterns emerge during development.',
architecture: 'Architecture not yet mapped. Follow existing patterns found in the codebase.',
skills: 'No project skills found. Add skills to any of: `.claude/skills/`, `.agents/skills/`, `.cursor/skills/`, `.github/skills/`, or `.codex/skills/` with a `SKILL.md` index file.',
};
}
// Directories where project skills may live (checked in order)
const SKILL_SEARCH_DIRS = ['.claude/skills', '.agents/skills', '.cursor/skills', '.github/skills', '.codex/skills'];
const CLAUDE_MD_WORKFLOW_ENFORCEMENT = [
'Before using Edit, Write, or other file-changing tools, start work through a GSD command so planning artifacts and execution context stay in sync.',
'',
'Use these entry points:',
'- `/gsd:quick` for small fixes, doc updates, and ad-hoc tasks',
'- `/gsd:debug` for investigation and bug fixing',
'- `/gsd:execute-phase` for planned phase work',
'',
'Do not make direct repo edits outside a GSD workflow unless the user explicitly asks to bypass it.',
].join('\n');
function buildClaudeMdWorkflowEnforcement(runtime) {
return [
'Before using Edit, Write, or other file-changing tools, start work through a GSD command so planning artifacts and execution context stay in sync.',
'',
'Use these entry points:',
`- \`${formatGsdSlash('quick', runtime)}\` for small fixes, doc updates, and ad-hoc tasks`,
`- \`${formatGsdSlash('debug', runtime)}\` for investigation and bug fixing`,
`- \`${formatGsdSlash('execute-phase', runtime)}\` for planned phase work`,
'',
'Do not make direct repo edits outside a GSD workflow unless the user explicitly asks to bypass it.',
].join('\n');
}
const CLAUDE_MD_PROFILE_PLACEHOLDER = [
'<!-- GSD:profile-start -->',
'## Developer Profile',
'',
'> Profile not yet configured. Run `/gsd:profile-user` to generate your developer profile.',
'> This section is managed by `generate-claude-profile` -- do not edit manually.',
'<!-- GSD:profile-end -->',
].join('\n');
function buildClaudeMdProfilePlaceholder(runtime) {
return [
'<!-- GSD:profile-start -->',
'## Developer Profile',
'',
`> Profile not yet configured. Run \`${formatGsdSlash('profile-user', runtime)}\` to generate your developer profile.`,
'> This section is managed by `generate-claude-profile` -- do not edit manually.',
'<!-- GSD:profile-end -->',
].join('\n');
}
// ─── Helper Functions ─────────────────────────────────────────────────────────
@@ -284,10 +295,11 @@ function extractMarkdownSection(content, sectionName) {
// ─── CLAUDE.md Section Generators ─────────────────────────────────────────────
function generateProjectSection(cwd) {
const fallbacks = buildClaudeMdFallbacks(resolveRuntime(cwd));
const projectPath = path.join(cwd, '.planning', 'PROJECT.md');
const content = safeReadFile(projectPath);
if (!content) {
return { content: CLAUDE_MD_FALLBACKS.project, source: 'PROJECT.md', linkPath: null, hasFallback: true };
return { content: fallbacks.project, source: 'PROJECT.md', linkPath: null, hasFallback: true };
}
const parts = [];
const h1Match = content.match(/^# (.+)$/m);
@@ -308,12 +320,13 @@ function generateProjectSection(cwd) {
if (body) parts.push(`### Constraints\n\n${body}`);
}
if (parts.length === 0) {
return { content: CLAUDE_MD_FALLBACKS.project, source: 'PROJECT.md', linkPath: null, hasFallback: true };
return { content: fallbacks.project, source: 'PROJECT.md', linkPath: null, hasFallback: true };
}
return { content: parts.join('\n\n'), source: 'PROJECT.md', linkPath: '.planning/PROJECT.md', hasFallback: false };
}
function generateStackSection(cwd) {
const fallbacks = buildClaudeMdFallbacks(resolveRuntime(cwd));
const codebasePath = path.join(cwd, '.planning', 'codebase', 'STACK.md');
const researchPath = path.join(cwd, '.planning', 'research', 'STACK.md');
let content = safeReadFile(codebasePath);
@@ -325,7 +338,7 @@ function generateStackSection(cwd) {
linkPath = '.planning/research/STACK.md';
}
if (!content) {
return { content: CLAUDE_MD_FALLBACKS.stack, source: 'STACK.md', linkPath: null, hasFallback: true };
return { content: fallbacks.stack, source: 'STACK.md', linkPath: null, hasFallback: true };
}
const lines = content.split('\n');
const summaryLines = [];
@@ -344,10 +357,11 @@ function generateStackSection(cwd) {
}
function generateConventionsSection(cwd) {
const fallbacks = buildClaudeMdFallbacks(resolveRuntime(cwd));
const conventionsPath = path.join(cwd, '.planning', 'codebase', 'CONVENTIONS.md');
const content = safeReadFile(conventionsPath);
if (!content) {
return { content: CLAUDE_MD_FALLBACKS.conventions, source: 'CONVENTIONS.md', linkPath: null, hasFallback: true };
return { content: fallbacks.conventions, source: 'CONVENTIONS.md', linkPath: null, hasFallback: true };
}
const lines = content.split('\n');
const summaryLines = [];
@@ -360,10 +374,11 @@ function generateConventionsSection(cwd) {
}
function generateArchitectureSection(cwd) {
const fallbacks = buildClaudeMdFallbacks(resolveRuntime(cwd));
const architecturePath = path.join(cwd, '.planning', 'codebase', 'ARCHITECTURE.md');
const content = safeReadFile(architecturePath);
if (!content) {
return { content: CLAUDE_MD_FALLBACKS.architecture, source: 'ARCHITECTURE.md', linkPath: null, hasFallback: true };
return { content: fallbacks.architecture, source: 'ARCHITECTURE.md', linkPath: null, hasFallback: true };
}
const lines = content.split('\n');
const summaryLines = [];
@@ -375,9 +390,9 @@ function generateArchitectureSection(cwd) {
return { content: summary, source: 'ARCHITECTURE.md', linkPath: '.planning/codebase/ARCHITECTURE.md', hasFallback: false };
}
function generateWorkflowSection() {
function generateWorkflowSection(cwd) {
return {
content: CLAUDE_MD_WORKFLOW_ENFORCEMENT,
content: buildClaudeMdWorkflowEnforcement(resolveRuntime(cwd)),
source: 'GSD defaults',
linkPath: null,
hasFallback: false,
@@ -390,6 +405,7 @@ function generateWorkflowSection() {
* agents know which skills are available at session startup (Layer 1 discovery).
*/
function generateSkillsSection(cwd) {
const fallbacks = buildClaudeMdFallbacks(resolveRuntime(cwd));
const discovered = [];
for (const dir of SKILL_SEARCH_DIRS) {
@@ -426,7 +442,7 @@ function generateSkillsSection(cwd) {
}
if (discovered.length === 0) {
return { content: CLAUDE_MD_FALLBACKS.skills, source: 'skills/', hasFallback: true };
return { content: fallbacks.skills, source: 'skills/', hasFallback: true };
}
const lines = ['| Skill | Description | Path |', '|-------|-------------|------|'];
@@ -774,7 +790,7 @@ function cmdGenerateDevPreferences(cwd, options, raw) {
let stackBlock;
if (analysis.data_source === 'questionnaire') {
stackBlock = 'Stack preferences not available (questionnaire-only profile). Run `/gsd:profile-user --refresh` with session data to populate.';
stackBlock = `Stack preferences not available (questionnaire-only profile). Run \`${formatGsdSlash('profile-user', resolveRuntime(cwd))} --refresh\` with session data to populate.`;
} else if (options.stack) {
stackBlock = options.stack;
} else {
@@ -881,7 +897,7 @@ function cmdGenerateClaudeProfile(cwd, options, raw) {
'<!-- GSD:profile-start -->',
'## Developer Profile',
'',
`> Generated by GSD from ${dataSource}. Run \`/gsd:profile-user --refresh\` to update.`,
`> Generated by GSD from ${dataSource}. Run \`${formatGsdSlash('profile-user', resolveRuntime(cwd))} --refresh\` to update.`,
'',
'| Dimension | Rating | Confidence |',
'|-----------|--------|------------|',
@@ -1025,7 +1041,7 @@ function cmdGenerateClaudeMd(cwd, options, raw) {
sections.push(buildSectionContent(name, gen, heading));
}
sections.push('');
sections.push(CLAUDE_MD_PROFILE_PLACEHOLDER);
sections.push(buildClaudeMdProfilePlaceholder(resolveRuntime(cwd)));
existingContent = sections.join('\n\n') + '\n';
action = 'created';
platformEnsureDir(path.dirname(outputPath));
@@ -1064,7 +1080,7 @@ function cmdGenerateClaudeMd(cwd, options, raw) {
}
if (!options.auto && fileContent.indexOf('<!-- GSD:profile-start') === -1) {
fileContent = fileContent.trimEnd() + '\n\n' + CLAUDE_MD_PROFILE_PLACEHOLDER + '\n';
fileContent = fileContent.trimEnd() + '\n\n' + buildClaudeMdProfilePlaceholder(resolveRuntime(cwd)) + '\n';
}
platformWriteSync(outputPath, fileContent);
@@ -1087,7 +1103,7 @@ function cmdGenerateClaudeMd(cwd, options, raw) {
let message = `Generated ${genCount}/${totalManaged} sections.`;
if (sectionsFallback.length > 0) message += ` Fallback: ${sectionsFallback.join(', ')}.`;
if (sectionsSkipped.length > 0) message += ` Skipped (manually edited): ${sectionsSkipped.join(', ')}.`;
if (profileStatus === 'placeholder_added') message += ' Run /gsd:profile-user to unlock Developer Profile.';
if (profileStatus === 'placeholder_added') message += ` Run ${formatGsdSlash('profile-user', resolveRuntime(cwd))} to unlock Developer Profile.`;
const result = {
claude_md_path: outputPath,

View File

@@ -0,0 +1,96 @@
'use strict';
/**
* runtime-slash.cjs — single source of truth for emitting GSD slash-command
* references in user-facing runtime output (recommended-actions JSON, persisted
* ROADMAP.md entries, verify/validate fix hints, error messages, etc.).
*
* Background: #2808 unified all GSD skill installs to register under the hyphen
* form (`name: gsd-<cmd>`). The legacy colon form `/gsd:<cmd>` is no longer
* routable by Claude Code skill installs, but ~50 runtime emissions in
* bin/lib/*.cjs still hardcoded it (#3584). Codex installs need the shell-var
* `$gsd-<cmd>` form. This module is the only place the runtime should decide
* which shape to emit.
*
* - codex: $gsd-<cmd> (shell-var syntax)
* - claude, cursor, opencode, kilo, etc.: /gsd-<cmd>
*
* The colon form is never emitted.
*/
function formatGsdSlash(commandName, runtime) {
if (typeof commandName !== 'string') return commandName;
if (commandName === '') return commandName;
// Strip any existing leading prefix so the helper is idempotent and accepts
// both legacy `/gsd:<name>` and canonical hyphen-form input (plus the bare
// `gsd:<name>` shorthand and codex `$gsd-<name>` shell-var input).
const stripped = commandName.replace(/^[/$]?gsd[-:]/i, '');
// If the regex matched nothing (no prefix), the input is already a bare name.
const bare = stripped === commandName ? commandName : stripped;
if (bare === '') return commandName;
const rt = String(runtime || 'claude').toLowerCase();
if (rt === 'codex') {
// Codex skills are invoked as $gsd-<cmd> (shell-var syntax). Lowercased
// because shell-var identifiers in the surrounding prose are conventionally
// lowercase; matches the convertCodexSlash() projection in bin/install.js.
return `$gsd-${bare.toLowerCase()}`;
}
return `/gsd-${bare}`;
}
/**
* Resolve the effective runtime for a project directory.
*
* process.env.GSD_RUNTIME > config.runtime > 'claude'
*
* Mirrors the precedence already used by profile-output.cjs and the rest of
* the runtime resolution chain. Returns a lowercased string so downstream
* comparisons can be case-blind.
*
* @param {string|null|undefined} projectDir
* @returns {string}
*/
function resolveRuntime(projectDir) {
if (process.env.GSD_RUNTIME) {
return String(process.env.GSD_RUNTIME).toLowerCase();
}
if (projectDir) {
try {
// Read config.json directly (not via loadConfig). loadConfig has a side
// effect of normalizing and re-writing legacy keys back to disk, which
// would mutate the project file just to read the runtime name. We only
// need the literal `runtime:` value, so a plain JSON read is sufficient
// and side-effect-free.
const fs = require('fs');
const path = require('path');
const configPath = path.join(projectDir, '.planning', 'config.json');
if (fs.existsSync(configPath)) {
const raw = fs.readFileSync(configPath, 'utf-8');
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === 'object' && parsed.runtime) {
return String(parsed.runtime).toLowerCase();
}
}
} catch {
// Fall through to default — a missing/broken config must not crash
// runtime output formatting.
}
}
return 'claude';
}
/**
* Convenience: format using the runtime resolved from a project directory.
* Equivalent to `formatGsdSlash(name, resolveRuntime(projectDir))`.
*/
function formatGsdSlashFor(projectDir, commandName) {
return formatGsdSlash(commandName, resolveRuntime(projectDir));
}
module.exports = {
formatGsdSlash,
resolveRuntime,
formatGsdSlashFor,
};

View File

@@ -1,6 +1,7 @@
'use strict';
const { VALIDATE_SUBCOMMANDS } = require('./command-aliases.generated.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
function routeValidateCommand({ verify, args, cwd, raw, parseNamedArgs, output, error }) {
const subcommand = args[1];
@@ -24,10 +25,11 @@ function routeValidateCommand({ verify, args, cwd, raw, parseNamedArgs, output,
return;
}
const { classifyContextUtilization, STATES } = require('./context-utilization.cjs');
const threadCmd = formatGsdSlash('thread', resolveRuntime(cwd));
const RECOMMENDATIONS = {
[STATES.HEALTHY]: null,
[STATES.WARNING]: 'Context is approaching the fracture zone — consider /gsd:thread to continue in a fresh window.',
[STATES.CRITICAL]: 'Reasoning quality may degrade past 70% utilization (fracture point). Run /gsd:thread now to preserve output quality.',
[STATES.WARNING]: `Context is approaching the fracture zone — consider ${threadCmd} to continue in a fresh window.`,
[STATES.CRITICAL]: `Reasoning quality may degrade past 70% utilization (fracture point). Run ${threadCmd} now to preserve output quality.`,
};
let classified;
try {

View File

@@ -10,6 +10,7 @@ const { execGit, platformReadSync: safeReadFile, platformWriteSync } = require('
const { planningDir } = require('./planning-workspace.cjs');
const { extractFrontmatter, parseMustHavesBlock } = require('./frontmatter.cjs');
const { writeStateMd } = require('./state.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
function cmdVerifySummary(cwd, summaryPath, checkFileCount, raw) {
if (!summaryPath) {
@@ -593,6 +594,10 @@ function cmdValidateHealth(cwd, options, raw) {
const statePath = path.join(planBase, 'STATE.md');
const configPath = path.join(planBase, 'config.json');
const phasesDir = path.join(planBase, 'phases');
// Resolve runtime once so every emitted fix hint uses the routable slash
// form for this install (#3584).
const _slashRuntime = resolveRuntime(cwd);
const slash = (name) => formatGsdSlash(name, _slashRuntime);
const errors = [];
const warnings = [];
@@ -609,7 +614,7 @@ function cmdValidateHealth(cwd, options, raw) {
// ─── Check 1: .planning/ exists ───────────────────────────────────────────
if (!fs.existsSync(planBase)) {
addIssue('error', 'E001', '.planning/ directory not found', 'Run /gsd:new-project to initialize');
addIssue('error', 'E001', '.planning/ directory not found', `Run ${slash('new-project')} to initialize`);
output({
status: 'broken',
errors,
@@ -622,7 +627,7 @@ function cmdValidateHealth(cwd, options, raw) {
// ─── Check 2: PROJECT.md exists and has required sections ─────────────────
if (!fs.existsSync(projectPath)) {
addIssue('error', 'E002', 'PROJECT.md not found', 'Run /gsd:new-project to create');
addIssue('error', 'E002', 'PROJECT.md not found', `Run ${slash('new-project')} to create`);
} else {
const content = fs.readFileSync(projectPath, 'utf-8');
const requiredSections = ['## What This Is', '## Core Value', '## Requirements'];
@@ -635,12 +640,12 @@ function cmdValidateHealth(cwd, options, raw) {
// ─── Check 3: ROADMAP.md exists ───────────────────────────────────────────
if (!fs.existsSync(roadmapPath)) {
addIssue('error', 'E003', 'ROADMAP.md not found', 'Run /gsd:new-milestone to create roadmap');
addIssue('error', 'E003', 'ROADMAP.md not found', `Run ${slash('new-milestone')} to create roadmap`);
}
// ─── Check 4: STATE.md exists and references valid phases ─────────────────
if (!fs.existsSync(statePath)) {
addIssue('error', 'E004', 'STATE.md not found', 'Run /gsd:health --repair to regenerate', true);
addIssue('error', 'E004', 'STATE.md not found', `Run ${slash('health')} --repair to regenerate`, true);
repairs.push('regenerateState');
} else {
const stateContent = fs.readFileSync(statePath, 'utf-8');
@@ -687,7 +692,7 @@ function cmdValidateHealth(cwd, options, raw) {
'warning',
'W002',
`STATE.md references phase ${ref}, but only phases ${[...validPhases].sort().join(', ')} are declared`,
'Review STATE.md manually before changing it; /gsd:health --repair will not overwrite an existing STATE.md for phase mismatches'
`Review STATE.md manually before changing it; ${slash('health')} --repair will not overwrite an existing STATE.md for phase mismatches`
);
}
}
@@ -696,7 +701,7 @@ function cmdValidateHealth(cwd, options, raw) {
// ─── Check 5: config.json valid JSON + valid schema ───────────────────────
if (!fs.existsSync(configPath)) {
addIssue('warning', 'W003', 'config.json not found', 'Run /gsd:health --repair to create with defaults', true);
addIssue('warning', 'W003', 'config.json not found', `Run ${slash('health')} --repair to create with defaults`, true);
repairs.push('createConfig');
} else {
try {
@@ -708,7 +713,7 @@ function cmdValidateHealth(cwd, options, raw) {
addIssue('warning', 'W004', `config.json: invalid model_profile "${parsed.model_profile}"`, `Valid values: ${validProfiles.join(', ')}`);
}
} catch (err) {
addIssue('error', 'E005', `config.json: JSON parse error - ${err.message}`, 'Run /gsd:health --repair to reset to defaults', true);
addIssue('error', 'E005', `config.json: JSON parse error - ${err.message}`, `Run ${slash('health')} --repair to reset to defaults`, true);
repairs.push('resetConfig');
}
}
@@ -719,11 +724,11 @@ function cmdValidateHealth(cwd, options, raw) {
const configRaw = fs.readFileSync(configPath, 'utf-8');
const configParsed = JSON.parse(configRaw);
if (configParsed.workflow && configParsed.workflow.nyquist_validation === undefined) {
addIssue('warning', 'W008', 'config.json: workflow.nyquist_validation absent (defaults to enabled but agents may skip)', 'Run /gsd:health --repair to add key', true);
addIssue('warning', 'W008', 'config.json: workflow.nyquist_validation absent (defaults to enabled but agents may skip)', `Run ${slash('health')} --repair to add key`, true);
if (!repairs.includes('addNyquistKey')) repairs.push('addNyquistKey');
}
if (configParsed.workflow && configParsed.workflow.ai_integration_phase === undefined) {
addIssue('warning', 'W016', 'config.json: workflow.ai_integration_phase absent (defaults to enabled — run /gsd:ai-integration-phase before planning AI system phases)', 'Run /gsd:health --repair to add key', true);
addIssue('warning', 'W016', `config.json: workflow.ai_integration_phase absent (defaults to enabled — run ${slash('ai-integration-phase')} before planning AI system phases)`, `Run ${slash('health')} --repair to add key`, true);
if (!repairs.includes('addAiIntegrationPhaseKey')) repairs.push('addAiIntegrationPhaseKey');
}
} catch { /* intentionally empty */ }
@@ -773,7 +778,7 @@ function cmdValidateHealth(cwd, options, raw) {
try {
const researchContent = fs.readFileSync(path.join(phasesDir, e.name, researchFile), 'utf-8');
if (researchContent.includes('## Validation Architecture')) {
addIssue('warning', 'W009', `Phase ${e.name}: has Validation Architecture in RESEARCH.md but no VALIDATION.md`, 'Re-run /gsd:plan-phase with --research to regenerate');
addIssue('warning', 'W009', `Phase ${e.name}: has Validation Architecture in RESEARCH.md but no VALIDATION.md`, `Re-run ${slash('plan-phase')} with --research to regenerate`);
}
} catch { /* intentionally empty */ }
}
@@ -862,7 +867,7 @@ function cmdValidateHealth(cwd, options, raw) {
if (statusVal !== 'complete' && statusVal !== 'done') {
addIssue('warning', 'W011',
`STATE.md says current phase is ${statePhase} (status: ${statusVal || 'unknown'}) but ROADMAP.md shows it as [x] complete — state files may be out of sync`,
'Run /gsd:progress to re-derive current position, or manually update STATE.md');
`Run ${slash('progress')} to re-derive current position, or manually update STATE.md`);
}
}
}
@@ -971,7 +976,7 @@ function cmdValidateHealth(cwd, options, raw) {
if (missingFromRegistry.length > 0) {
addIssue('warning', 'W018',
`MILESTONES.md missing ${missingFromRegistry.length} archived milestone(s): ${missingFromRegistry.join(', ')}`,
'Run /gsd:health --backfill to synthesize missing entries from archive snapshots',
`Run ${slash('health')} --backfill to synthesize missing entries from archive snapshots`,
true);
repairs.push('backfillMilestones');
}
@@ -1045,7 +1050,7 @@ function cmdValidateHealth(cwd, options, raw) {
stateContent += `**Current phase:** (determining...)\n`;
stateContent += `**Status:** Resuming\n\n`;
stateContent += `## Session Log\n\n`;
stateContent += `- ${new Date().toISOString().split('T')[0]}: STATE.md regenerated by /gsd:health --repair\n`;
stateContent += `- ${new Date().toISOString().split('T')[0]}: STATE.md regenerated by ${slash('health')} --repair\n`;
writeStateMd(statePath, stateContent, cwd);
repairActions.push({ action: repair, success: true, path: 'STATE.md' });
break;
@@ -1095,7 +1100,7 @@ function cmdValidateHealth(cwd, options, raw) {
// Build minimal entry from snapshot title or version
const titleMatch = snapshot && snapshot.match(/^#\s+(.+)$/m);
const milestoneName = titleMatch ? titleMatch[1].replace(/^Milestone\s+/i, '').replace(/^v[\d.]+\s*/, '').trim() : ver;
const entry = `## ${ver}${milestoneName && milestoneName !== ver ? ` ${milestoneName}` : ''} (Backfilled: ${today})\n\n**Note:** Synthesized from archive snapshot by \`/gsd:health --backfill\`. Original completion date unknown.\n\n---\n\n`;
const entry = `## ${ver}${milestoneName && milestoneName !== ver ? ` ${milestoneName}` : ''} (Backfilled: ${today})\n\n**Note:** Synthesized from archive snapshot by \`${slash('health')} --backfill\`. Original completion date unknown.\n\n---\n\n`;
const milestonesContent = fs.existsSync(milestonesPath)
? fs.readFileSync(milestonesPath, 'utf-8')
: '';

View File

@@ -14,6 +14,7 @@ const { output, error, toPosixPath, getMilestoneInfo, generateSlugInternal } = r
const { platformWriteSync, platformEnsureDir } = require('./shell-command-projection.cjs');
const { planningRoot, setActiveWorkstream, getActiveWorkstream } = require('./planning-workspace.cjs');
const { toWorkstreamSlug, hasInvalidPathSegment, isValidActiveWorkstreamName } = require('./workstream-name-policy.cjs');
const { formatGsdSlash, resolveRuntime } = require('./runtime-slash.cjs');
const {
getOtherActiveWorkstreamInventories,
inspectWorkstream,
@@ -85,7 +86,7 @@ function cmdWorkstreamCreate(cwd, name, options, raw) {
const baseDir = planningRoot(cwd);
if (!fs.existsSync(baseDir)) {
error('.planning/ directory not found — run /gsd:new-project first');
error(`.planning/ directory not found — run ${formatGsdSlash('new-project', resolveRuntime(cwd))} first`);
}
const wsRoot = path.join(baseDir, 'workstreams');