Files
msd-core/tests/phase-id-drift-guard.test.cjs
Tom Boucher 5e0a7b1b56 fix(#4433,#4569,#4126): consolidate the phase-identity seam at name-validity, allocation, and branch-slug (#4640)
* fix(#4433): apply the name-validity guard symmetrically to every milestone-name capture

extractMilestoneHeadingName already refused a punctuation-only captured name
(#4134), but its two sibling capture sites in getMilestoneInfo — the
STATE.md-anchored 🚧-bullet match and the no-STATE.md in-progress 🚧-bullet
fallback — skipped straight to a bare truthiness check, so a malformed bullet
whose only content past the version was punctuation passed through as a real
milestone name.

Extracts the existing inline /[\p{L}\p{N}]/u check into a single shared
hasNameableContent predicate and applies it at all three capture sites, so
the guard is one owner rather than a copy that happened to land at only one
of them.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4433): pin the name-validity guard at all three milestone-name capture sites

Failing-first coverage for the hasNameableContent extraction: a
punctuation-only 🚧-bullet name must not surface as a real milestone name,
either on the STATE.md-anchored path or the no-STATE.md in-progress
fallback, while a real name (including a digits-only one) still resolves
COMPLETE exactly as before.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4569): consolidate decimal-phase-number allocation into one function

cmdPhaseInsert allocated its next decimal sub-phase number by scanning only
on-disk phases/ directories and ### Phase N.M: headings, never the roadmap
summary checklist — so a decimal that existed only as a checklist bullet
(no heading yet, no on-disk directory yet) was invisible, and phase insert
could silently reallocate an already-used number. It also always nested one
level deeper under afterPhase, with no way to request a sibling.

cmdPhaseNextDecimal had its own separate, near-identical two-source scan
(missing the checklist source too) — the exact "duplicate implementations
kept in sync instead of deleted" pattern this issue exists to close.

Extracts scanExistingDecimalPhaseNumbers (directories + headings + checklist
bullets, in one place) and migrates both cmdPhaseInsert and
cmdPhaseNextDecimal onto it — deleting cmdPhaseNextDecimal's own copy rather
than patching it in parallel. Adds an allocation: 'nested' | 'sibling'
argument to cmdPhaseInsert (default 'nested', matching every existing
caller's behavior); a top-level phase with no existing decimal segment falls
back to nested since there is no sibling level to join. No CLI flag wires
'sibling' yet — that is a separate, disclosed follow-up.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4569): pin decimal-allocation coverage across phase insert and next-decimal

Failing-first coverage for scanExistingDecimalPhaseNumbers: a checklist-only
decimal must not be reallocated by phase insert; a decimal present in
heading, checklist, and on-disk directory simultaneously must count once;
an unrelated phase family's checklist bullet must not cross-pollute; and
phase next-decimal (migrated onto the same shared helper) must see a
checklist-only decimal too, closing the same gap in a second command.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4634): extend the phase-id drift guard for name-validity and shell arithmetic

The epic's ratchet requirement: lint-phase-id-drift.cjs must cover the two
new predicates this PR introduces, and must also scan shell inside
gsd-core/workflows/**/*.md and gsd-core/references/**/*.md for
integer-coercing phase-number arithmetic ($((10#...)) and friends), which
neither the canonical TypeScript module nor a source-only lint can reach.

Adds findNameValidityDrift (bans re-deriving /[\p{L}\p{N}]/u outside
hasNameableContent's owner file) and findShellPhaseArithDrift +
scanMarkdownShellArith (bans $((10#...)) in workflow/reference markdown,
sanctioned via <!-- phase-id-owner: --> on the preceding line). scanRepo
keeps its existing, narrower contract (src/**/*.cts only) so the
already-passing "the live repo is clean" test is untouched; a new scanAll
merges both for the CLI's full report.

Running the guard directly against this tree correctly reports the 7
pre-existing #4619 shell sites (workflows/execute-phase.md x4,
workflows/execute-phase/steps/completion-reconciliation.md x2,
references/tdd.md x1) as violations — demonstrating the ratchet works, not
fixing them. #4619 is a live regression tracked and fixed separately; this
PR does not touch those markdown files. A characterization test pins the
current count of 7 so a future change to that number is investigated rather
than silently absorbed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4569): wire --sibling through phase insert's CLI so the argument is reachable

cmdPhaseInsert's allocation parameter had no CLI path to 'sibling' — shipped,
untested, unreachable code (code-review finding: a guaranteed surviving
mutant). Adds --sibling to phase insert's argument parsing, threads it
through, and documents the flag in docs/CLI-TOOLS.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4569): exercise --sibling end-to-end through the real CLI

Confirms --sibling joins afterPhase's parent decimal level rather than
nesting, and falls back to nested when afterPhase has no existing decimal
segment (no sibling level to join).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4634): demonstrate the two new drift detectors end-to-end via a planted violation

The epic asks for the guard to be "demonstrated by watching it go red" on a
reintroduced copy. The two new detectors (name-validity, shell-arith) had
only unit-level fixture tests; mirrors the existing bracket-rule's
planted-violation-in-a-temp-tree test for both, proving they're actually
wired into scanRepo/scanMarkdownShellArith end-to-end, not just correct in
isolation.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4634): consolidate the drift guard's own owner-sanction-check logic

Standards review flagged the "walk to nearest preceding non-blank line,
check for a phase-id-owner comment" logic as duplicated across all four
detector functions in a PR whose whole point is eliminating exactly that
pattern. Extracts isSanctionedByPrecedingComment, shared by all four;
behavior-preserving (verified: identical output before/after, same 7 known
#4619 violations, zero token/bracket/name-validity).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4634): add Fixed changeset for the name-validity guard and allocation consolidation

pr:0 placeholder — backfilled once the real PR number exists.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(#4126): consolidate branch-name slug substitution into one shared renderer

cmdCommit (commands.cts) and cmdInitExecutePhase (init.cts) each
independently implemented branch-name template substitution, and both
substituted the literal string 'phase' when phase_slug was empty or
undeliverable — producing a non-identifying branch name (gsd/phase-08-phase)
that contradicted the honestly-reported phase_slug: null in the same
payload. Same structural defect as the other three gaps in this epic: two
consumers reimplementing one concept independently instead of sharing an
owner.

Adds renderPhaseBranchName (src/phase-id.cts) as the sole owner: a real slug
substitutes normally; an empty/undeliverable one drops the {slug} token plus
one adjacent separator (collapsing/trimming the result) rather than
substituting a placeholder word, for the shipped default template and any
user-configured shape alike. Both call sites now delegate to it; the old
inline duplicates are deleted, not kept in sync. {project} substitution
stays a separate step in init.cts, unchanged, since it is a config-level
field with its own fallback contract.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4126): pin renderPhaseBranchName and both migrated call sites

Property-based coverage for the shared renderer's degrade-path invariant
(output, when non-null, never contains {slug} and never starts/ends with a
separator), plus example coverage for real-slug substitution, empty/null/
non-string slug, token position at either edge, a doubled-separator
template, and the only-{slug} -> null case. One regression test each in
commands.test.cjs and init.test.cjs confirms a phase with no derivable slug
no longer produces a branch name ending in the literal '-phase'.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix: route scanExistingDecimalPhaseNumbers through the canonical enumeration owner

Caught by an actual gsd-test run, not a hypothesis: the new decimal-scan
helper (fix(#4569)) enumerated phases/ directories via a raw
fs.readdirSync, which the pre-existing phase-enumeration drift guard
(#3185/#3882) correctly flags as an unsanctioned re-derivation outside its
canonical owner (listAllPhaseDirs / isSentinelPhaseId). Ironic given this
epic's own thesis, and exactly why the guard exists: consolidating one seam
can reintroduce drift in an adjacent one if the new code doesn't route
through what's already there. Migrates the enumeration to listAllPhaseDirs;
identical decimal-detection output for every existing case.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(#4634): extend the drift guard for branch-slug fallback; fix a real regex bug

Adds the fourth detector the epic's ratchet section names ("both
branch-name sites"): bans a `.replace('{slug}', ... || 'phase')` call
outright, sanctioned via renderPhaseBranchName or a dedicated comment.
Wired into scanRepo (no per-file exemption — this is a banned anti-pattern
everywhere, not a grammar with one legitimate owner). Now that #4126's fix
(prior commit) has landed, scanRepo reports zero violations across all four
.cts-scanning rules, restoring the simple "the live repo is clean" assertion
instead of a pinned-known-count characterization.

Also fixes a real bug an actual gsd-test run caught: findNameValidityDrift's
regex didn't tolerate the doubled-backslash template-string form its own
test claimed to cover (0 !== 1) — widened to \{1,2} matching
TOKEN_DRIFT_RE's existing tolerance for the same two forms.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(#4126): document the {slug} degrade behavior; update changeset for the full seam

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix: detectPhaseNumberFromFiles wrongly rejected bare, slug-less phase directories

Caught by an actual gsd-test run on the #4126 regression test, not a
hypothesis: a bare phase directory with no slug remainder (e.g.
.planning/phases/01/) has extractPhaseToken correctly return "01" — which is
simply identical to the directory name in that case, not its no-match
fallback. A stale `token !== phaseDir` check treated that equality as "no
numeric token found" and rejected it regardless, leaving phaseNum null and
silently skipping cmdCommit's phase-branching block entirely (the commit
proceeded on whatever branch was already checked out instead of the
phase branch).

phaseTokenShape.test(normalized) already excludes every genuine non-phase
case on its own: extractPhaseToken's real no-match fallback only fires for a
dirName that doesn't start with a digit or short letter+digit prefix, and
normalizePhaseName's leading-\d+ requirement rejects those regardless. The
equality check was redundant for real rejections and actively wrong for
bare-numeric directories.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore: backfill changeset PR number to 4640

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: sim <sim@local>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-11 12:42:04 -04:00

429 lines
20 KiB
JavaScript

'use strict';
process.env.GSD_TEST_MODE = '1';
/**
* Anti-divergence guard for the phase-identifier parsing seam
* (epic #2121 Phase 4 / issue #2128, ADR-2121 Decision 7).
*
* `src/phase-id.cts` is the single canonical owner of phase-ID parsing. Two guards
* keep it that way:
* 1. DRIFT SCANNER (scripts/lint-phase-id-drift.cjs) — fails CI if any module
* outside phase-id.cts re-derives the canonical phase-number token as a
* literal without a `// phase-id-owner:` sanction.
* 2. IDENTITY guard — phase-id.cjs exports the complete locked surface, and no
* consumer re-exports a DIVERGENT copy of a canonical function (re-export,
* never re-implement).
*
* Behavioral throughout: assertions drive `findPhaseIdRegexDrift` / `scanRepo`
* and compare object identity — no `readFileSync().includes()` in a test body.
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
const { findPhaseIdRegexDrift, findBracketGrammarDrift, scanRepo, scanMarkdownShellArith } = require(
path.join(ROOT, 'scripts', 'lint-phase-id-drift.cjs'),
);
const phaseId = require(path.join(ROOT, 'gsd-core', 'bin', 'lib', 'phase-id.cjs'));
// The locked canonical surface (ADR-2121 Decision 1/2; PHASE_NUMBER_TOKEN_SOURCE
// added in Phase 4). Every name is exported by phase-id.cjs; the identity guard
// forbids any other module from re-exporting a divergent copy of one.
// #3212 Phase 1: `escapeRegex` moved off this locked surface entirely — it is
// no longer owned (or re-exported) by phase-id.cjs, it is owned by the
// pattern-construction seam (src/pattern.cts / gsd-core/bin/lib/pattern.cjs).
// Dropped from CANONICAL rather than kept: phase-id.cjs no longer exports the
// name at all, so `name in phaseId` below would fail if it stayed listed, and
// the identity-guard test's job (no consumer re-exports a DIVERGENT copy) is
// now the pattern seam's own single-owner property, not phase-id's.
const CANONICAL = [
'OPTIONAL_PROJECT_CODE_PREFIX_SOURCE', 'OPTIONAL_PHASE_TAG_SOURCE',
'PHASE_NUMBER_TOKEN_SOURCE', 'stripProjectCodePrefix', 'normalizePhaseName',
'getMilestoneFromPhaseId', 'getPhaseDirFromPhaseId', 'phaseMarkdownRegexSource',
'phaseMarkdownRegexSourceExact', 'comparePhaseNum', 'extractPhaseToken',
'phaseTokenMatches', 'parsePhaseFromProse', 'stripConfiguredProjectCodePrefix',
'isForeignPrefixedPhaseQuery', 'roadmapPhaseLookupSources',
// #612 PR-2: the one bracket identity grammar + the gated heading-intro selector.
'BRACKET_ID_SRC', 'BRACKET_MILESTONE_NUMERIC_SRC', 'BRACKET_DIR_PREFIX_SRC',
'BASE_ANY_BRACKET_HEADING_PREFIX_SRC', 'BASE_PHASE_LABEL_PREFIX_SRC',
'PHASE_HEADING_BASELINE', 'phaseHeadingPrefixSrcFor', 'foldBracketId',
'bracketQualifiedKey',
// #2761 M3: the bracket project-code class and the two milestone-intro shapes
// three readers used to re-type. Locked here so a consumer cannot re-export a
// divergent copy of what it now imports.
'BRACKET_PROJECT_CODE_SRC', 'bracketMilestoneIntroSrcFor',
'BRACKET_MILESTONE_INTRO_CAPTURING_SRC',
];
describe('#2128 phase-id drift scanner: findPhaseIdRegexDrift (pure)', () => {
test('a regex built from PHASE_NUMBER_TOKEN_SOURCE is NOT drift', () => {
assert.deepEqual(
findPhaseIdRegexDrift('const re = new RegExp(`Phase\\s+(${PHASE_NUMBER_TOKEN_SOURCE})`);'),
[],
);
});
test('a literal re-derivation of the canonical token IS flagged (fail-first)', () => {
const v = findPhaseIdRegexDrift('const re = /Phase\\s+(\\d+[A-Z]?(?:\\.\\d+)*)/;');
assert.equal(v.length, 1);
assert.equal(v[0].found, '\\d+[A-Z]?(?:\\.\\d+)*');
});
test('a re-derivation inside a new RegExp template (\\\\d escaping) IS flagged', () => {
const v = findPhaseIdRegexDrift('new RegExp(`Phase\\\\s+(\\\\d+[A-Z]?(?:\\\\.\\\\d+)*)`)');
assert.equal(v.length, 1);
});
test('the [A-Za-z], [.-] and [0-9] near-variants ARE flagged (no trivial evasion)', () => {
assert.equal(findPhaseIdRegexDrift('/(\\d+[A-Za-z]?(?:\\.\\d+)*)/').length, 1, '[A-Za-z] letter class');
assert.equal(findPhaseIdRegexDrift('/(\\d+[A-Z]?(?:[.-]\\d+)*)/').length, 1, '[.-] separator');
assert.equal(findPhaseIdRegexDrift('/([0-9]+[A-Z]?(?:\\.[0-9]+)*)/').length, 1, '[0-9] in place of \\d');
});
test('a dedicated preceding // phase-id-owner: comment line suppresses the flag', () => {
assert.deepEqual(
findPhaseIdRegexDrift(' // phase-id-owner: sanctioned exception\n const re = /(\\d+[A-Z]?(?:\\.\\d+)*)/;'),
[],
);
});
test('a blank line between the // phase-id-owner: comment and the regex still suppresses', () => {
assert.deepEqual(
findPhaseIdRegexDrift(' // phase-id-owner: sanctioned exception\n\n const re = /(\\d+[A-Z]?(?:\\.\\d+)*)/;'),
[],
);
});
test('a trailing same-line // phase-id-owner: is NOT a sanction (must be a dedicated line above)', () => {
// The marker must lead its own comment line; a trailing comment on a code
// line is not honored, so the regex is still flagged.
const v = findPhaseIdRegexDrift('const re = /(\\d+[A-Z]?(?:\\.\\d+)*)/; // phase-id-owner: not honored here');
assert.equal(v.length, 1);
});
test('a // phase-id-owner: embedded in a STRING literal does NOT suppress (decoy)', () => {
// A `//` inside a string is not a comment — help/doc text that quotes the
// sanction syntax must not silently suppress a real re-derivation.
const decoyLine = findPhaseIdRegexDrift('const help = "use // phase-id-owner: <reason>"; const re = /(\\d+[A-Z]?(?:\\.\\d+)*)/;');
assert.equal(decoyLine.length, 1);
const decoyPrev = findPhaseIdRegexDrift('const help = "use // phase-id-owner: <reason>";\nconst re = /(\\d+[A-Z]?(?:\\.\\d+)*)/;');
assert.equal(decoyPrev.length, 1);
});
test('a bare "phase-id-owner:" substring with no // does NOT suppress', () => {
const v = findPhaseIdRegexDrift('const msg = "ping the phase-id-owner for review"; const re = /(\\d+[A-Z]?(?:\\.\\d+)*)/;');
assert.equal(v.length, 1);
});
test('non-token phase regexes are NOT flagged (no false positives)', () => {
assert.deepEqual(findPhaseIdRegexDrift('/^Executing Phase\\s+\\d+/'), [], 'status-message bare \\d+');
assert.deepEqual(findPhaseIdRegexDrift('/#{2,4}\\s*Phase\\s+(\\d+)[A-Z]?(?:\\.\\d+)*/'), [], 'digits-only capture is non-contiguous');
assert.deepEqual(findPhaseIdRegexDrift('/Phase\\s+([\\w][\\w.-]*)/'), [], '\\w id grammar is not the canonical token');
assert.deepEqual(findPhaseIdRegexDrift('/\\|\\s*Phase\\s*\\|\\s*Plans\\s*\\|/'), [], 'pipe-table structure');
});
test('reports 1-based line numbers', () => {
const v = findPhaseIdRegexDrift('line1\nconst re = /(\\d+[A-Z]?(?:\\.\\d+)*)/;\nline3');
assert.equal(v[0].line, 2);
});
});
// ─── #2761 M3: the BRACKET grammar rule ────────────────────────────────────
//
// trek-e's finding: the bracket grammar was re-typed in roadmap-parser, state
// and verify — a violation of #2761's own "no token literal outside
// src/phase-id.cts" gate — and `check:phase-id-drift` passed anyway, because
// its detector only knew the phase-NUMBER token. These are the guard's negative
// fixtures: the three literals AS THEY SHIPPED, transcribed here so the rule is
// proven against the real drift and not against a convenient stand-in.
describe('#2761 M3 bracket drift scanner: findBracketGrammarDrift (pure)', () => {
const SHIPPED_DRIFT = [
['roadmap-parser.cts bracket-fallback selector',
'const bracketMilestoneHeadingRe = new RegExp(`^\\\\[[A-Z][A-Z0-9_]*\\\\.${canonical}\\\\]`, \'i\');'],
['state.cts isMilestoneBounded',
'const bracketMilestoneHeadingRe = new RegExp(`^\\\\[[A-Z][A-Z0-9_]*\\\\.${canonical}\\\\]`, \'i\');'],
['verify.cts checkBracketCoherence',
'const bracketSectionRe = new RegExp(`^\\\\[[A-Z][A-Z0-9_]*\\\\.(${BRACKET_MILESTONE_NUMERIC_SRC})\\\\]`, \'i\');'],
];
for (const [label, line] of SHIPPED_DRIFT) {
test(`flags the literal that shipped in ${label}`, () => {
const v = findBracketGrammarDrift(line);
assert.equal(v.length, 1, `the guard must flag ${label}`);
assert.equal(v[0].found, '[A-Z][A-Z0-9_]*');
});
}
test('an owner reference on the SAME LINE does not excuse a re-typed class', () => {
// The precise blind spot. verify.cts's copy referenced the owner for the
// MILESTONE field while re-typing the PROJECT-CODE class, so a line-level
// "mentions the owner, therefore clean" escape — which the phase-token rule
// does carry — would wave the reported site straight through. Partial
// ownership is the drift.
assert.equal(
findBracketGrammarDrift(
'new RegExp(`[A-Z][A-Z0-9_]*\\\\.(${BRACKET_MILESTONE_NUMERIC_SRC})`)',
).length,
1,
);
});
test('the case-widened rewrite does not evade the rule', () => {
assert.equal(findBracketGrammarDrift('/^\\\\[[A-Za-z][A-Za-z0-9_]*\\\\./').length, 1);
});
test('a dedicated phase-id-owner comment sanctions the site', () => {
assert.deepEqual(
findBracketGrammarDrift(' // phase-id-owner: deliberate\n const re = /[A-Z][A-Z0-9_]*/;'),
[],
);
// …but only as its own line, never trailing the code — same rule the
// phase-token scanner enforces.
assert.equal(
findBracketGrammarDrift('const re = /[A-Z][A-Z0-9_]*/; // phase-id-owner: not honored here').length,
1,
);
});
test('the spellings that replaced the drift are clean', () => {
for (const line of [
'const re = new RegExp(`^${bracketMilestoneIntroSrcFor(milestoneInt)}`, \'i\');',
'const re = new RegExp(`^${BRACKET_MILESTONE_INTRO_CAPTURING_SRC}`, \'i\');',
'const re = new RegExp(`^\\\\[(${BRACKET_ID_SRC})\\\\]`, \'i\');',
]) {
assert.deepEqual(findBracketGrammarDrift(line), [], line);
}
});
test('reports the 1-indexed line', () => {
assert.equal(findBracketGrammarDrift('a\nconst re = /[A-Z][A-Z0-9_]*/;\nc')[0].line, 2);
});
});
// ─── #2761 M3: parity between the owner and what the call sites spelled ─────
describe('#2761 M3 bracket grammar: one owner, byte-identical to the sites it replaced', () => {
// Transcribed by hand from the pre-fix sources, NOT assembled from the
// constants under test — comparing the owner against something built from the
// owner would restate the implementation and pass whatever either side said.
// Byte-equality with an independent transcription is the whole proof.
const PRE_FIX = {
// roadmap-parser.cts and state.cts, character-identical to each other, with
// `canonical` = String(milestoneInt).padStart(2, '0').
pinned: (canonical) => `\\[[A-Z][A-Z0-9_]*\\.${canonical}\\]`,
// verify.cts, with the milestone field captured.
capturing: (numericSrc) => `\\[[A-Z][A-Z0-9_]*\\.(${numericSrc})\\]`,
};
test('bracketMilestoneIntroSrcFor reproduces both re-typed pinned copies', () => {
for (const milestone of [0, 1, 2, 9, 10, 99, 100, 999]) {
assert.equal(
phaseId.bracketMilestoneIntroSrcFor(milestone),
PRE_FIX.pinned(String(milestone).padStart(2, '0')),
`milestone ${milestone}`,
);
}
});
test('BRACKET_MILESTONE_INTRO_CAPTURING_SRC reproduces the verify copy', () => {
assert.equal(
phaseId.BRACKET_MILESTONE_INTRO_CAPTURING_SRC,
PRE_FIX.capturing(phaseId.BRACKET_MILESTONE_NUMERIC_SRC),
);
});
test('the owner also composes BRACKET_ID_SRC, so the two cannot drift apart', () => {
assert.ok(
phaseId.BRACKET_ID_SRC.startsWith(phaseId.BRACKET_PROJECT_CODE_SRC),
'BRACKET_ID_SRC must be built from BRACKET_PROJECT_CODE_SRC',
);
assert.equal(phaseId.BRACKET_PROJECT_CODE_SRC, '[A-Z][A-Z0-9_]*');
});
test('the pinned builder owns the pad2 rule, not just the grammar', () => {
// "Canonical spelling only, not `0*N`" was restated beside each re-typed
// regex. An unpadded `[GSD.2]` scopes a milestone no phase heading resolves
// into, which is how total_phases fell back to the on-disk count.
const re = new RegExp(`^${phaseId.bracketMilestoneIntroSrcFor(2)}`, 'i');
assert.ok(re.test('[GSD.02] Foundation'), 'canonical pad2 spelling matches');
assert.ok(!re.test('[GSD.2] Foundation'), 'unpadded is malformed');
assert.ok(!re.test('[GSD.002] Foundation'), 'over-padded is malformed');
assert.ok(re.test('[gsd.02] Foundation'), 'recognition is case-insensitive at the reader');
});
test('the capturing shape puts the milestone digits in group 1', () => {
const re = new RegExp(`^${phaseId.BRACKET_MILESTONE_INTRO_CAPTURING_SRC}`, 'i');
assert.equal('[GSD.02] Foundation'.match(re)[1], '02');
assert.equal('[A_B9.100] Later'.match(re)[1], '100');
assert.equal('[GSD.2] Foundation'.match(re), null, 'unpadded is not a milestone intro');
});
});
describe('#2128 phase-id drift scanner: the live repo is clean', () => {
test('scanRepo finds zero unsanctioned re-derivations (token, bracket, name-validity, and branch-slug-fallback)', () => {
const violations = scanRepo(ROOT);
assert.deepEqual(
violations,
[],
'unsanctioned re-derivation(s) — build from the phase-id.cjs owner or add // phase-id-owner:\n' +
violations.map((d) => ` [${d.kind}] ${d.file}:${d.line} ${d.found}`).join('\n'),
);
});
test('scanRepo actually runs the bracket rule (coverage, not just a clean result)', () => {
// A clean scan is also what a scanner that forgot to call the bracket rule
// returns. Plant the shipped verify.cts literal into a temp tree and require
// the scan to fail on it — the same end-to-end path `check:phase-id-drift`
// takes, proving the rule is wired into scanRepo and not merely exported.
const os = require('node:os');
const { cleanup } = require('./helpers.cjs');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'phase-id-drift-'));
try {
fs.mkdirSync(path.join(tmp, 'src'));
fs.writeFileSync(
path.join(tmp, 'src', 'planted.cts'),
'const bracketSectionRe = new RegExp(`^\\\\[[A-Z][A-Z0-9_]*\\\\.(${BRACKET_MILESTONE_NUMERIC_SRC})\\\\]`, \'i\');\n',
);
const found = scanRepo(tmp);
assert.equal(found.length, 1, 'scanRepo must report the planted bracket literal');
assert.equal(found[0].kind, 'bracket');
assert.equal(found[0].file, path.join('src', 'planted.cts'));
} finally {
cleanup(tmp);
}
});
test('scanRepo actually runs the name-validity rule (coverage, not just a clean result)', () => {
// Same proof shape as the bracket-rule test above, for #4634's new
// name-validity detector: plant a literal re-derivation of
// hasNameableContent's character class in a temp tree and require the
// real scanRepo() to catch it end-to-end.
const os = require('node:os');
const { cleanup } = require('./helpers.cjs');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'phase-id-drift-'));
try {
fs.mkdirSync(path.join(tmp, 'src'));
fs.writeFileSync(
path.join(tmp, 'src', 'planted.cts'),
'function fakeCheck(s) {\n return /[\\p{L}\\p{N}]/u.test(s);\n}\n',
);
const found = scanRepo(tmp);
assert.equal(found.length, 1, 'scanRepo must report the planted name-validity literal');
assert.equal(found[0].kind, 'name-validity');
assert.equal(found[0].file, path.join('src', 'planted.cts'));
} finally {
cleanup(tmp);
}
});
test('scanRepo actually runs the branch-slug-fallback rule (coverage, not just a clean result)', () => {
// Same proof shape again, for #4634's branch-slug-fallback detector: plant
// the shipped commands.cts/init.cts shape into a temp tree and require the
// real scanRepo() to catch it end-to-end.
const os = require('node:os');
const { cleanup } = require('./helpers.cjs');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'phase-id-drift-'));
try {
fs.mkdirSync(path.join(tmp, 'src'));
fs.writeFileSync(
path.join(tmp, 'src', 'planted.cts'),
"const x = template.replace('{slug}', (phaseInfo['phase_slug'] as string) || 'phase');\n",
);
const found = scanRepo(tmp);
assert.equal(found.length, 1, 'scanRepo must report the planted branch-slug-fallback literal');
assert.equal(found[0].kind, 'branch-slug-fallback');
assert.equal(found[0].file, path.join('src', 'planted.cts'));
} finally {
cleanup(tmp);
}
});
test('scanMarkdownShellArith actually runs the shell-arith rule (coverage, not just a clean result)', () => {
// Same proof shape again, for #4634's markdown shell-arithmetic detector:
// plant a `$((10#$VAR))` site under the real scan roots
// (gsd-core/workflows/**/*.md) and require scanMarkdownShellArith() to
// catch it end-to-end, over the real MD_SCAN_DIRS walk.
const os = require('node:os');
const { cleanup } = require('./helpers.cjs');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'phase-id-drift-'));
try {
const workflowsDir = path.join(tmp, 'gsd-core', 'workflows');
fs.mkdirSync(workflowsDir, { recursive: true });
fs.writeFileSync(
path.join(workflowsDir, 'planted.md'),
'```bash\nPHASE_N=$((10#$PHASE_NUM))\n```\n',
);
const found = scanMarkdownShellArith(tmp);
assert.equal(found.length, 1, 'scanMarkdownShellArith must report the planted shell-arith literal');
assert.equal(found[0].kind, 'shell-arith');
assert.equal(found[0].file, path.join('gsd-core', 'workflows', 'planted.md'));
} finally {
cleanup(tmp);
}
});
test(
"#4619 shell-arith violations are known and tracked separately (characterization, not this PR's scope)",
() => {
const violations = scanMarkdownShellArith(ROOT);
assert.equal(
violations.length,
7,
'expected exactly the 7 known #4619 sites (workflows/execute-phase.md x4, ' +
'workflows/execute-phase/steps/completion-reconciliation.md x2, references/tdd.md x1) — ' +
'if this count changed, either #4619 was fixed (great — update/remove this pin) or a NEW ' +
'unrelated shell-arith site was introduced (investigate before adjusting the number)',
);
},
);
});
describe('#2128 phase-id single-owner identity guard', () => {
test('phase-id.cjs exports the complete locked canonical surface', () => {
for (const name of CANONICAL) {
assert.ok(name in phaseId, `phase-id.cjs must export the canonical member '${name}'`);
}
});
test('no consumer module re-exports a DIVERGENT copy of a canonical phase-id function', () => {
// Forward guard: if any built lib module re-exports a name that phase-id.cjs
// owns, it MUST be the identical reference — a re-export, never a local
// re-implementation. All consumers pass today (none re-export); the guard
// fails the moment a divergent copy ships.
const libDir = path.join(ROOT, 'gsd-core', 'bin', 'lib');
const consumers = fs.readdirSync(libDir).filter((f) => f.endsWith('.cjs') && f !== 'phase-id.cjs');
let checked = 0;
const requireFailures = [];
for (const f of consumers) {
let mod;
try {
mod = require(path.join(libDir, f));
} catch (e) {
// Surfaced, not silently skipped — a module that cannot be required
// would otherwise erode the guard's coverage without any signal.
requireFailures.push(`${f}: ${e.message}`);
continue;
}
if (!mod || typeof mod !== 'object') continue; // bare-function exports carry no named canonical member
checked++;
for (const name of CANONICAL) {
if (Object.prototype.hasOwnProperty.call(mod, name)) {
assert.strictEqual(
mod[name],
phaseId[name],
`${f} re-exports '${name}' but it is NOT the phase-id.cjs reference — re-export the canonical, do not re-implement`,
);
}
}
}
assert.deepEqual(requireFailures, [], `consumer module(s) failed to require (guard coverage would silently degrade):\n ${requireFailures.join('\n ')}`);
// Coverage floor: the vast majority of the ~150 built lib modules export an
// object and must actually be inspected — not a token "at least one".
assert.ok(checked > consumers.length * 0.75, `expected to inspect most of the ${consumers.length} consumer modules, only inspected ${checked}`);
});
});