Files
msd-core/tests/phase-id-drift-guard.test.cjs
Tom Boucher db4d8a9bae fix(#4619): execute-phase computes decimal/N-segment phase numbers without breaking shell arithmetic (#4644)
* fix(#4619): execute-phase computes decimal/N-segment phase numbers without breaking shell arithmetic

$((10#${PHASE_NUMBER})) is a hard bash/zsh syntax error when PHASE_NUMBER is
decimal (01.1, from an inserted phase) or N-segment (23.1.2) — neither is
valid shell-arithmetic syntax at all, and the failed expansion aborts the
rest of the snippet in a non-interactive shell. safe_resume_gate runs
unconditionally before trusting STATE.md or dispatching any executor, so
execute-phase failed at its own gate before the first executor on any
decimal phase, regardless of workflow.tdd_mode. Regression from #4194.

Fixes all 4 sites: safe_resume_gate and the TDD gate in
workflows/execute-phase.md, the completion-signal spot-check fallback in
workflows/execute-phase/steps/completion-reconciliation.md, and the
executor gate validation example in references/tdd.md. Each now zero-strips
only the leading integer segment into a *_INT variable (via %%.* / #
parameter expansion — always valid shell syntax regardless of what follows)
and keeps the remainder as an escaped-dot string for the anchored commit-
scope regex, exactly as issue #4619 verified in both bash and zsh. A plain
integer phase (12, 01) computes byte-identically to before.

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

* test(#4619): pin the decimal/N-segment fix and characterize the pre-fix bug

Behavioral coverage via real bash execution: the old $((10#01.1)) form
throws (characterizes the bug, matching the issue's own reproduction); the
new form resolves 01.1 -> 1\.1 and 23.1.2 -> 23\.1\.2, unchanged for plain
integers (12 -> 12, 01 -> 1); the resulting anchored ERE matches
feat(01.1-03):/test(1.1-3): and correctly rejects feat(01-03):,
feat(01.2-03):, feat(011-03):, feat(12-03): for a decimal phase — mirroring
issue #4619's own verified table exactly. Updates
safe-resume-gate-anchoring.test.cjs's 4 existing source-text assertions
(one per site) to the new fixed text.

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

* chore(#4634): refine the shell-arith drift detector to distinguish safe from unsafe arithmetic

With #4619's fix in place, the guard's original "ban $((10#... outright,
match any occurrence" was too blunt: it flagged a comment merely mentioning
the pattern in prose, the now-safe $((10#$PHASE_INT)) arithmetic on an
already-%%.*-stripped integer, and the always-safe plan-id arithmetic
(plan ids are plain integers, never decimal). Refines the detector to skip
full-line comments and to only flag a captured variable/placeholder name
that contains "phase" and does NOT end in _INT/_int — the naming convention
the #4619 fix establishes at all four sites for "already reduced to a safe
integer." A plan-id variable was never phase-number arithmetic in the first
place and is excluded on the same basis.

This closes epic #4634's D6 ("lint-phase-id-drift... passes with no new
exemptions") and D7 ("a decimal and N-segment phase id survive an
end-to-end execute-phase selection without error") for real — the guard now
reports zero violations across all five .cts/.md rules.

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

* chore: regenerate conformance-tier manifests for the new test file

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

* test(#4619): cover the plain-padded-integer near-miss matrix too

Review found the anchored-ERE near-miss coverage only exercised the
decimal case (PHASE_NUMBER=01.1); issue #4619's own worked table also
verifies the plain padded-integer case (01 -> PHASE_N=1) against its own
near-miss set (matches 01-03, rejects 01.1-03/011-03/12-03). Adds the
missing assertion.

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

* docs(#4619): add Fixed changeset

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

* fix(#4619): correct JS backslash-escaping in safe-resume-gate anchoring test

The test's string-literal assertions for the PHASE_FRAC//./\\.} pattern wrote
only 2 backslash characters in JS source, which single-quoted-string parsing
collapses to 1 real backslash at runtime -- but the workflow/reference files
actually contain 2 raw backslash bytes at that position (needed so bash's
${var//pattern/replacement} produces the correct single-backslash output).
Write 4 backslash characters in the JS source at all 4 occurrences so the
runtime string matches the files' real bytes.

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

* chore(#4619): refresh the committed compact-content benchmark baseline

The new PHASE_INT/PHASE_FRAC arithmetic lines added to
gsd-core/workflows/execute-phase.md shifted its committed compaction-ratio
baseline. Regenerate via `node scripts/benchmark-compact-content.cjs --write`.

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

* docs(#4619): note the safe_resume_gate arithmetic growth in the test header

The emitted-attribution gate flags execute-phase.md growing 91253 -> 91846
bytes (593 bytes). The growth is the fix: the safe_resume_gate and TDD RED
block now derive PHASE_INT/PHASE_FRAC before computing PHASE_N, so a
decimal/N-segment phase number (e.g. 01.1, 2.3.1) zero-strips its leading
integer segment via base-10 arithmetic instead of forcing the whole value
through $((10#...)) and hitting a hard shell syntax error on the first dot.

A blank line previously separated the Emitted-Drift-Ack-Growth trailer from
the Co-Authored-By trailer below it, which splits git's trailer-block
detection: only the last contiguous non-blank run of Key: Value lines at the
end of a commit message is recognized as trailers, so the growth ack was
silently read as ordinary body text and the differential-attribution gate
failed with the growth unacknowledged. Joining the two trailers into one
contiguous block fixes it.

Emitted-Drift-Ack-Growth: execute-phase.md — adds PHASE_INT/PHASE_FRAC derivation to the safe_resume_gate and TDD RED commit-scope grep so a decimal/N-segment phase number zero-strips its leading integer segment via base-10 arithmetic instead of failing on a non-numeric value (#4619)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(#4208): replace chmod-based restore-failure injection with a root-proof git shim

`tests/commit-files-deletion.test.cjs`'s two restore-failure tests simulated
an unwritable index via a `post-index-change` hook running `chmod a-w` on
the git dir. That relies on the OS enforcing the *owner's own* permission
bits against itself, which uid 0 (a routine identity inside this repo's
Docker-based gsd-test benches) does not: every DAC check short-circuits true
for root, so the write the chmod meant to block silently succeeds, the
restore comes back clean, and the disclosure/rollback behavior under test
never actually gets exercised.

This is CLAUDE.md's own named anti-pattern for I/O-failure injection
("Cross-platform test IO-failure injection" — chmod tricks fail under root
Docker/CI). It is confirmed as the actual root cause here, not a production
defect: `src/commands.cts`'s `restoreRemovedEntries`/rollback-disclosure
logic (added by #4253, merged just before this run) was hand-traced and
manually reproduced end to end on an unprivileged workstation against a
freshly built `gsd-core/bin/lib/commands.cjs`, and it already produces
exactly the `staging_failed` + "could not be restored" / "could NOT be
restored during rollback" results both tests assert. The other
`post-index-change`-based tests in this file (a `sleep` to force a timeout;
a real `update-index` to flip a restored entry's mode) are unaffected
because neither depends on a permission check — consistent with only the
two chmod-based tests failing on the real remote run.

Replaces the chmod fixture with a fake `git` placed ahead of the real one on
PATH that fails only `update-index --add --cacheinfo` — the one call the
restore makes — unconditionally, regardless of privilege level. Every other
git invocation execs straight through to the real binary, so the rest of
each scenario (`rm --cached`, the restore's own `ls-files` verification,
etc.) is exercised exactly as before.

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

* chore(#4619): backfill changeset pr number to 4644

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

* fix(#4619): feed the bash fixture script via stdin, not argv, to fix Windows CI

Passing the script as a `-c "<script>"` argv element made it subject to
Windows' CreateProcess command-line argument encoding, which silently
dropped the escaped-dot backslashes before bash ever saw them (observed on
PR #4644's windows-latest CI shard: `1\.1` came back as `1.1`). Feeding the
same script via stdin instead removes argv entirely from the transport, so
there is nothing for Windows to re-encode. POSIX behavior is unchanged.

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 15:47:14 -04:00

427 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('scanMarkdownShellArith finds zero unsanctioned shell phase-arithmetic (#4619 fixed)', () => {
// Was a characterization test pinning 7 known #4619 sites
// (workflows/execute-phase.md x4, workflows/execute-phase/steps/
// completion-reconciliation.md x2, references/tdd.md x1) while #4619 was
// still unfixed. #4619 is now fixed — every site zero-strips the leading
// integer segment into a `*_INT`-suffixed variable before doing
// `$((10#...))` arithmetic on it, which the refined detector recognizes
// as safe — so this retires back to the same "must be zero" assertion
// the branch-slug-fallback pin used once ITS underlying bug was fixed.
const violations = scanMarkdownShellArith(ROOT);
assert.equal(violations.length, 0);
});
});
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}`);
});
});