Files
msd-core/src/roadmap-command-router.cts
Behruz Nassre Esfahani 12b35eeeaf fix(#1729): resolve phase headers with a pre-colon parenthetical tag (#1765)
* fix(#1729): resolve phase headers with a pre-colon parenthetical tag

A phase header may carry a parenthetical tag between the number and the
colon, e.g. `### Phase 26 (Cluster B): Title`. Every phase-header regex
built `Phase\s+<num>` immediately against the colon delimiter, so the
tagged phase was invisible: the resolver returned found:false and, just
as bad, the capture-all enumeration/parse paths (roadmap analyze,
milestone listing + milestone-scope filter, verify, init/import, state
total_phases, validate, the command router, preamble stripping, and the
phase-remove renumbering rewrite) silently dropped, miscounted, or
failed to renumber it — wrong phase_count, progress_percent, next_phase,
or corrupt numbering after a removal.

The fix tolerates the tag at the header seam. Parameterized resolver
sites compose the exported OPTIONAL_PHASE_TAG_SOURCE fragment; literal
enumeration sites inline its character-for-character mirror
`(?:\s*\([^)\n]*\))?`, placed immediately before the colon so it cannot
alter an existing match (optional, single-line, one paren pair, no
capture-group shift). In the renumber-on-removal rewrite the tag is
folded into the re-emitted suffix capture so it survives verbatim. Both
forms are documented to change together and a drift-guard test asserts
their behavioral equivalence over a header corpus.

Deliberately excluded: roadmap-upgrade.cts (legacy one-time migration),
where tolerating the tag would silently drop it on header rewrite — that
needs its own data-preserving treatment. Known boundaries left for
follow-up: checklist/bullet-style phase entries (`- [ ] Phase N (tag):`)
and a malformed space-before-colon variant, both pre-existing.

Validated empirically against the issue's reproduction: `roadmap
get-phase 26` resolves and `roadmap analyze` lists Phase 26 with the tag
excluded from the name (phase_count 2, next 26); an all-tagged versioned
roadmap now scopes correctly instead of falling back to a pass-all
filter. Regression coverage in tests/phase.test.cjs asserts resolver
parity (pre- vs post-colon), padding tolerance (#3537), decimal
sub-phases, no cross-phase false match, the shared seam, enumeration
coherence, renumber-preserves-tag, and seam/mirror drift. Full unit
suite green (7291 pass, 0 fail); eslint + regression-name +
resolution-provenance + changeset lints pass. Reviewed by Codex
(no critical/high; the two enumeration misses it surfaced are folded in).

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

* chore(#1729): add changeset for pre-colon phase-tag fix

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 11:55:44 -04:00

215 lines
9.2 KiB
TypeScript

/**
* Manifest-backed roadmap subcommand router.
* Keeps gsd-tools.cjs thin while preserving existing command semantics.
*
* ADR-457 build-at-publish: the hand-written bin/lib/roadmap-command-router.cjs
* collapsed to a TypeScript source of truth. Behaviour is preserved byte-for-behaviour
* from the prior hand-written .cjs; only types are added.
*/
import fs from 'node:fs';
import path from 'node:path';
import { ROADMAP_SUBCOMMANDS } from './command-aliases.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import cjsCommandRouterAdapter = require('./cjs-command-router-adapter.cjs');
const { routeCjsCommandFamily } = cjsCommandRouterAdapter;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import roadmapUpgrade = require('./roadmap-upgrade.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
import planningWorkspace = require('./planning-workspace.cjs');
const { planningDir } = planningWorkspace;
// eslint-disable-next-line @typescript-eslint/no-require-imports
import configLoaderMod = require('./config-loader.cjs');
const { loadConfig } = configLoaderMod;
// ─── Types ────────────────────────────────────────────────────────────────────
interface RoadmapModule {
cmdRoadmapGetPhase(cwd: string, phase: string | undefined, raw: boolean): void;
cmdRoadmapAnalyze(cwd: string, raw: boolean): void;
cmdRoadmapUpdatePlanProgress(cwd: string, phase: string | undefined, raw: boolean): void;
cmdRoadmapAnnotateDependencies(cwd: string, phase: string | undefined, raw: boolean): void;
}
interface RouteRoadmapCommandOptions {
roadmap: RoadmapModule;
args: string[];
cwd: string;
raw: boolean;
error: (message: string) => void;
}
interface W021Warning {
code: 'W021';
message: string;
}
// ─── W021 Implementation ──────────────────────────────────────────────────────
/**
* Check each phase entry in a milestone-prefixed ROADMAP.md for W021 violations.
*
* W021: a phase whose ID integer prefix does not match its enclosing milestone's
* major version number.
*
* Sentinel milestones (0 = pre-milestone, 999 = backlog) are exempt.
*
* @param content - ROADMAP.md content
* @returns Array of W021 warnings
*/
function checkW021(content: string): W021Warning[] {
const warnings: W021Warning[] = [];
// Sentinel milestone integers exempt from W021
const SENTINELS = new Set([0, 999]);
const MIGRATION_CMD = 'gsd-tools roadmap upgrade --convention milestone-prefixed';
// Milestone section heading: ## [GSD] v2.0 — Label OR ## v2.0: Label OR ## Roadmap v2.0
// OR ## ✅ v2.0 OR ## 🚧 v2.0 (emoji-prefixed variants used by roadmap templates)
// Capture the major integer.
const MILESTONE_RE = /^#{1,3}\s+(?:\[[^\]]+\]\s+|Roadmap\s+|[✅🚧]\s*)?v(\d+)\.\d+(?:\s|:|\s*—)/iu;
// Migrated phase heading: ### Phase M-NN: Name (M-NN or unpadded M-N form)
// #1729: `(?:\s*\([^)\n]*\))?` tolerates a pre-colon ( ) tag (literal mirror of OPTIONAL_PHASE_TAG_SOURCE).
const PHASE_RE = /^#{2,4}\s*(?:\[[^\]]+\]\s*)?Phase\s+(\d+)-(\d+)(?:-\d+)*(?:\s*\([^)\n]*\))?\s*:/i;
// Unprefixed legacy phase heading: ### Phase N: Name (no hyphen sub-index)
const UNPREFIXED_PHASE_RE = /^#{2,4}\s*(?:\[[^\]]+\]\s*)?Phase\s+(\d+[A-Za-z]?(?:\.\d+)*)(?:\s*\([^)\n]*\))?\s*:/i;
let currentMilestoneMajor: number | null = null;
const lines = content.split('\n');
for (const line of lines) {
const milestoneMatch = line.match(MILESTONE_RE);
if (milestoneMatch) {
currentMilestoneMajor = parseInt(milestoneMatch[1], 10);
continue;
}
const phaseMatch = line.match(PHASE_RE);
if (phaseMatch) {
const phaseMajor = parseInt(phaseMatch[1], 10);
if (SENTINELS.has(phaseMajor)) continue; // exempt
if (currentMilestoneMajor !== null && phaseMajor !== currentMilestoneMajor) {
const phaseId = `${phaseMatch[1]}-${phaseMatch[2]}`;
warnings.push({
code: 'W021',
message:
`Phase ID prefix mismatch: phase "${phaseId}" is listed under v${currentMilestoneMajor}.x ` +
`but its prefix (${phaseMajor}) does not match. ` +
`Run \`${MIGRATION_CMD}\` to fix.`,
});
}
continue;
}
// When the convention is active, an unprefixed heading (### Phase 1:) is itself a W021
// violation — it is missing the required M-NN prefix entirely.
const unprefixedMatch = line.match(UNPREFIXED_PHASE_RE);
if (unprefixedMatch && currentMilestoneMajor !== null) {
const rawId = unprefixedMatch[1];
// Skip if it matched PHASE_RE already (it didn't reach here in that case)
// Also skip if it looks like a bare integer whose prefix matches the section
// — those pass; only non-matching or non-prefixed forms fire W021.
const numericMajor = parseInt(rawId, 10);
if (!SENTINELS.has(numericMajor)) {
warnings.push({
code: 'W021',
message:
`Phase ID "${rawId}" is not in M-NN form (milestone-prefixed convention is active). ` +
`Run \`${MIGRATION_CMD}\` to migrate.`,
});
}
}
}
return warnings;
}
// ─── Router ───────────────────────────────────────────────────────────────────
function routeRoadmapCommand({ roadmap, args, cwd, raw, error }: RouteRoadmapCommandOptions): void {
routeCjsCommandFamily({
args,
subcommands: ROADMAP_SUBCOMMANDS,
unsupported: {},
error,
unknownMessage: (_subcommand: string, available: string[]) => `Unknown roadmap subcommand. Available: ${available.join(', ')}`,
handlers: {
'get-phase': () => roadmap.cmdRoadmapGetPhase(cwd, args[2], raw),
analyze: () => roadmap.cmdRoadmapAnalyze(cwd, raw),
'update-plan-progress': () => roadmap.cmdRoadmapUpdatePlanProgress(cwd, args[2], raw),
'annotate-dependencies': () => roadmap.cmdRoadmapAnnotateDependencies(cwd, args[2], raw),
'validate': () => {
const roadmapPath = path.join(planningDir(cwd), 'ROADMAP.md');
let roadmapContent = '';
try {
roadmapContent = fs.readFileSync(roadmapPath, 'utf8');
} catch {
// ROADMAP.md missing — return empty warnings
}
// W021 only fires when phase_id_convention is explicitly 'milestone-prefixed'.
// Authoritative source: .planning/config.json (set by the upgrade command).
// Fallback: ROADMAP.md frontmatter (for projects that set the field there directly).
let convention: string | undefined | null;
try {
const cfg = loadConfig(cwd);
convention = cfg['phase_id_convention'] as string | undefined | null;
} catch {
convention = undefined;
}
if (convention === undefined || convention === null) {
// Fallback: read from ROADMAP.md frontmatter
const fmMatch = roadmapContent.match(/^---\r?\n([\s\S]+?)\r?\n---/);
if (fmMatch) {
const kvMatch = fmMatch[1].match(/^phase_id_convention:\s*(.*)$/m);
if (kvMatch) {
const val = kvMatch[1].trim();
if (val !== 'null' && val !== '') {
convention = val.replace(/^["']|["']$/g, '');
}
}
}
}
const warnings = (convention === 'milestone-prefixed')
? checkW021(roadmapContent)
: [];
const result = { warnings };
if (raw) process.stdout.write(JSON.stringify(result));
else process.stdout.write(JSON.stringify(result, null, 2));
},
'upgrade': () => {
const dryRun = !args.includes('--apply');
// Parse `--convention <value>` and `--convention=<value>`. When the flag is
// absent entirely, default to the only supported convention; when present
// with a missing/unsupported value, fall through to the rejection below
// (fail-closed — never silently run a migration the user did not request).
let convention = 'milestone-prefixed';
const conventionFlagIdx = args.findIndex(
(a) => a === '--convention' || a.startsWith('--convention='),
);
if (conventionFlagIdx !== -1) {
const token = args[conventionFlagIdx];
convention = token.includes('=')
? token.slice(token.indexOf('=') + 1)
: (args[conventionFlagIdx + 1] ?? '');
}
if (convention !== 'milestone-prefixed') {
// No-throw hub contract (ADR-0012): a hub-dispatched handler must not call
// process.exit. Throw instead — the hub converts this to HandlerFailure and
// the adapter routes it through the injected error() boundary.
throw new Error('Only --convention milestone-prefixed is supported');
}
const plan = roadmapUpgrade.computeMigrationPlan(cwd);
roadmapUpgrade.applyMigration(cwd, plan, { dryRun });
},
},
});
}
export = {
routeRoadmapCommand,
};