Files
msd-core/tests/precommit-alias-drift-hook.test.cjs
Tom Boucher 107eb8c1d9 feat(#3753): run docs guards on the PR that changes the docs they read (#3787)
A PR whose diff is entirely under docs/ runs zero tests, so a guard whose INPUT
is shipped prose cannot protect the PR lane of the diffs it exists to check. Its
only firing opportunity is after merge, on the shared branch -- which is how next
went red on dacae9273 while the PR that caused it (#3746) was green on every
check.

The docs-lint job in .github/workflows/docs-required.yml -- an ALREADY-REQUIRED
context -- now selects and runs the docs guards that read the specific docs files
the PR changed.

  scripts/docs-guard-registry.cjs    test file -> the docs paths it reads (63)
  scripts/select-docs-guards.cjs     pure (changedPaths, registry) -> test files
  scripts/lint-docs-guard-registration.cjs   drift guard, wired into lint:ci

scripts/ci-test-scope.cjs is NOT touched -- `git diff origin/next --` on it is
empty -- so #764's saving stands and its 21 pinning tests are untouched.

Selection: exact path; trailing-slash directory prefix (boundary-checked --
docs/adrenaline.md does NOT match docs/adr/, which a naive startsWith gets
wrong); and '*' for the 6 entries that walk docs/ generally or read a computed
path. Unknown maps to '*' -- guessing narrow is how a guard silently stops
running. Measured: a typo fix selects 6 of 63; docs/AGENTS.md selects 12;
docs/COMMANDS.md selects 18.

Four things this got wrong first, each found by an independent reviewer or by
probe, and each having been asserted safe in a comment:

1. The registry started as a RULE in ci-test-scope.cjs's RULES, on the theory
   that classify()'s !codeChanged normalization made it inert. True for
   docs-ONLY diffs; false for MIXED docs+code diffs, where codeChanged is true
   and the normalization never runs:

     node scripts/ci-test-scope.cjs --files "docs/a.md src/semver.cts"
       with the RULE:  25 targeted_tests
       origin/next:     3 targeted_tests

   Category error: RULES is the scoped lane's input; a docs-guard registry is a
   lane manifest for a consumer that never calls classify(). Extracted; pinned
   by value.

2. The second attempt was a dedicated workflow with paths: [docs/**]. Such a
   workflow never reports on a non-docs PR, so it can never be a required
   context without hanging every non-docs PR -- and a non-required check does not
   block a merge, so the guard would have been advisory and #3753 unfixed.
   docs-required.yml already has no paths: filter, already supplies the required
   docs-lint context, already computes docs_changed, and already ran one docs
   guard gated on it. Generalizing that step needs no ruleset edit at all.

3. The registry and the drift lint were built from ONE path-segment heuristic, so
   both were blind identically -- and blind at the guard that motivated the issue.
   The reader-call regex required a character BEFORE its keyword, so a callee
   named exactly read( / load( / parse( / doc( / file( / content( could never
   match; and only an INLINE path.join(ROOT,'docs','X.md') argument was caught,
   missing the two-step-via-variable form -- the MAJORITY spelling -- plus
   template literals and concatenation. Detector 1 fired on 14 of ~450 files, so
   35 genuine guards sat unregistered while the lint reported 0 violations,
   including cursor-reviewer (reads docs/COMMANDS.md, asserts
   .includes('--cursor')) and inventory-headings-countfree. The "accepted blind
   spot" this shipped with was the common case, not a fringe.

4. With detection fixed the true population is 115 files: 63 genuine guards, 52
   incidental. Running all 63 in a REQUIRED check on a one-line typo fix is the
   cost #764 exists to avoid -- install.test.cjs is 7840 lines and reads exactly
   one docs file, docs/AGENTS.md, for its frontmatter. Dropping it reproduces the
   bug; running it for a typo elsewhere is waste. Hence the map.

Then a second review round found six more, all fixed here:

- fragment-single-edit-propagation.install.test.cjs was EXEMPTED as
  "overlay fixture only". False: it reads the real docs/registries/eos.json and
  asserts on a registry entry name, and reads the real ADR-0001 and asserts its
  H1. A docs-only PR touching either would have gone green and red next -- #3753
  shipping again, from inside the fix for it. Now registered against both paths,
  and all 52 remaining exemptions were re-audited one by one.
- The SUITES-collision guard compared RAW registry keys, but run-tests.cjs strips
  a leading `tests/` BEFORE its suite check. So it caught 'all' and missed
  'tests/all' -- the only spelling that can actually occur, since every key
  carries the prefix. One typo would have run all 824 test files inside the
  required job. Now normalized the same way run-tests.cjs normalizes.
- The lint failed OPEN on an unreadable tests dir or candidate file: 0 violations,
  ok:true. A guard that cannot read its input must never report success.
- The exemption ratchet gated identity only, so a baselined file that later
  STARTED asserting on shipped docs stayed exempt silently -- 52 permanently blind
  files. The baseline now fingerprints the docs paths each exempted file
  references and fails when that set changes, naming what changed.
- The exemption marker was still honored inside a multi-line template literal in
  the header window. The scanner now tracks template-literal and block-comment
  state.
- `git diff --name-only | grep '^docs/'` silently dropped C-quoted non-ASCII docs
  paths, making docs_changed=false a green zero-guard check. Both call sites now
  pass -c core.quotepath=false.
- The run step was gated on hashFiles(), which a force-committed
  .docs-guard-tests.txt would satisfy. The step now rm -f's both scratch files
  first and gates on an output it sets itself.

Three empty states, deliberately distinct, because conflating them rebuilds
#3753: an empty or malformed registry HARD-FAILS; docs changed with no guard
covering them logs and skips; no docs change is already gated. The middle state
must never be expressed as an empty --files-from, which prints `no tests in suite
"all"` and exits 0 -- a green check that guarded nothing. With the current
registry that state is unreachable, because the six '*' entries always match;
the branch is kept as defensive handling for a future registry and says so.

timeout-minutes: 15 bounds the required job against a hanging fork-supplied test;
it had none. npm ci was added because the job never installed dependencies -- the
previous single-file step got away without it, the registry does not.

docs/contributing/docs-guard-registration.md documents the rule, following its
sibling cross-platform-portability-rules.md, and CONTRIBUTING.md's CI Test
Quality Checks table links to it. It is also load-bearing: without a docs/ file
in the diff this PR would not have triggered its own lane, shipping an
unexercised change to a required check.

One unrelated fix, included because this PR surfaced it and CLAUDE.md forbids
deferring a defect found while working. On this branch's first CI run,
`full test (windows-latest, 24, shard 3/3)` was CANCELLED at exactly 30 minutes;
tests were still passing 0.8s before the cancel, so it is a wall-clock timeout,
not a hang, and a cancelled job reddens `Required tests`.

The cause is not this PR's test file, which costs ~60ms. Shard composition is
unstable: adding ONE file to the unit suite reshuffled 115 of 268 files between
shards, and shard 3 drew a heavier mix. Underneath that is a real pre-existing
defect. tests/ci-test-job-timeout-budget.test.cjs requires every lane's budget to
be >= 1.5x its MEASURED cost -- "a lane that got slower must be re-budgeted, not
excused" -- and its test-full entry recorded 19m from a windows-22 shard. That is
stale. Measured on `next` with none of this PR's changes present: 26m18s (run
32614439702, windows-latest/24 shard 3/3), 23m36s and 23m17s on shard 2/3. So the
lane costs ~26m and the 30-minute cap carried 1.14x headroom, not 1.5x. The gate
had been out of compliance with its own rule; this PR was merely the file
addition that reshuffled shard 3 past the cliff.

Fixed as that file prescribes: measuredMinutes 19 -> 27 with fresh evidence, and
test-full timeout-minutes 30 -> 45. The rule's minimum for 27m is 41; 45 is
deliberately above it because the reshuffle means per-shard worst case moves run
to run, and a budget pinned to the exact minimum would be re-breached by the next
test file anyone adds. Only that one job's timeout changed; test.yml's scope,
matrix and steps are untouched, so #764's saving is unaffected.

Raising that cap let the Windows shard finish (28m45s, inside 45) and uncovered
a real failure the 30-minute cancel had been masking:
`new quick-task branch branches off origin/main (#2916)` died with
`outcome=timed_out exitCode=null`, SIGTERM, at the 15000ms bound.

tests/quick-branching.test.cjs:149 `runStep` runs a `#!/usr/bin/env bash` script
executing MULTIPLE git commands, but was bound to GIT_TIMEOUT_MS (15000) -- the
norm for a SINGLE git plumbing call. tests/helpers/timeouts.cjs already documents
this exact failure and exists to fix it: HOOK_FANOUT_TIMEOUT_MS was created after
PR #3285 recorded "outcome=timed_out exitCode=null at exactly the 15000ms probe
bound while every other lane passed the same commit", and calls that "a bound
sized for the wrong class, not a slow machine". Our failure is that case
verbatim, so both sites move to the class norm rather than to a bigger number.

The same class also failed on `next` itself 21 hours earlier -- run 32608945654,
windows-latest/24 shard 1/3, `plan touching only src/ in a submodule project
keeps worktree isolation ENABLED` -- where tests/worktree-safety.test.cjs:5845
`runGate` fans out to `git config --file .gitmodules` under a hardcoded 30000.
Fixed too, since it is a defect in the tree regardless of which branch surfaced
it.

A survey of the whole tests/ tree found the same class-mismatch at further
bash fan-out sites bound under 60000ms, and the maintainer approved sweeping
them rather than leaving them latent to surface the same way one at a time. 16
fan-out sites across 16 files now use the class norm.

The sweep is class-correctness, not raising numbers until things pass. Sites
were moved ONLY where the bash body demonstrably spawns something (git, node,
npm, a CLI); self-contained shell snippets were left where they are, and are
listed as deliberately unchanged: pure if/printf bodies (copilot-install), pure
array/case builtins (code-review-pipeline-regression:638), a documented
pure-shell gsd_run stub (host-integration), single-process hook calls
(workflow-guard:222/271/302), and a deliberately tight 5000ms fast-check hook
(gsd-write-guard.property). Nothing was lowered. process-seam.test.cjs:513
(literal 300) is untouched on purpose -- it tests timeout BEHAVIOR, so raising
it would destroy what it asserts.

Shared file-level constants were the trap here, and were handled per file rather
than by redefinition: GIT_TIMEOUT_MS has ~15 users in git-base-branch and only 1
is a fan-out; WORKTREE_TIMEOUT_MS has 16 users in worktree.test.cjs and 3 are;
PROBE_TIMEOUT_MS has several in three more files. In each the CALL SITE was
changed and the constant left alone, so no single-plumbing-call site silently
inherited a 60s bound. The one exception is hooks-opt-in.test.cjs, where
HOOK_TIMEOUT_MS has exactly one consumer -- spawnHook, the fan-out itself -- so
redefining it is identical in effect and reads better.

Only two of these sites have actually been observed failing. The rest cite that
shared class and those two run ids rather than inventing evidence of their own.

Co-authored-by: sim <sim@local>
2026-08-23 21:21:21 -04:00

316 lines
12 KiB
JavaScript

// docs-guard-exempt: 'docs/adr/0174-...md' and 'docs/' are synthetic fixture path/prefix values, never read as content.
'use strict';
const { describe, test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const fc = require('fast-check');
const { runHook } = require('./helpers/process-seam.cjs');
const { throwIfFailed } = require('./helpers/git-fixture.cjs');
const { createTempDir, cleanup } = require('./helpers.cjs');
const { HOOK_FANOUT_TIMEOUT_MS } = require('./helpers/timeouts.cjs');
const { stagedSourcePaths } = require('../scripts/lib/alias-drift-families.cjs');
const ROOT = path.resolve(__dirname, '..');
const HOOK_PATH = path.join(ROOT, '.githooks', 'pre-commit');
/**
* Derived, never restated: the sources `scripts/check-alias-drift.cjs` actually
* reads. The hook's watched list and the checker's family table are parallel
* surfaces over one constant set, and their silent divergence is exactly what
* made the guard inert (#2725) — so this test asserts the hook against the
* checker's own table rather than against a second copy of it.
*/
const DRIFT_SOURCES = stagedSourcePaths();
/** The two script paths the hook additionally watches, beyond the sources above. */
const WATCHED_SCRIPTS = [
'scripts/check-alias-drift.cjs',
'scripts/lib/alias-drift-families.cjs',
];
const WATCHED_PATHS = new Set([...DRIFT_SOURCES, ...WATCHED_SCRIPTS]);
/**
* Write a mock bash script to a .sh file in tmpDir and return its absolute path.
* The hook invokes it via GIT_OVERRIDE / NPM_OVERRIDE — bash executes the path
* directly, so no PATH manipulation or NTFS execute-ACL fight is needed.
*/
function writeMock(tmpDir, name, content) {
const filePath = path.join(tmpDir, `${name}.sh`);
fs.writeFileSync(filePath, content, { mode: 0o755 });
return filePath;
}
/**
* Run the hook with a mock `git diff --cached --name-only` that emits
* `stagedLines` verbatim, and a mock `npm` that appends one line to a marker
* file per invocation.
*
* `stagedLines` is a raw string, not an array, so a row can exercise the exact
* byte shape git produces — including a CR-terminated line. Every other row
* builds it from LF-joined paths, which is what git actually emits.
*
* Returns `{ result, npmCalls }`. Counting invocations (rather than testing for
* file existence) is what lets the many-staged-files row assert the check runs
* exactly once.
*/
function runPreCommit(t, stagedLines) {
const tmpDir = createTempDir('gsd-precommit-hook-');
t.after(() => cleanup(tmpDir));
const marker = path.join(tmpDir, 'npm-calls.txt');
// The payload goes through a FILE that the mock `cat`s, never through printf.
// `printf '%s' "…\n"` emits a literal backslash-n — bash does not expand escapes
// in a double-quoted string and printf does not expand them in a %s argument — so
// the hook saw one unterminated line and no whole-line match could ever succeed.
// `cat` reproduces bytes verbatim, which is also what lets the CR-terminated row
// and the empty-staged-list row mean what they say.
const stagedFile = path.join(tmpDir, 'staged-paths.txt');
fs.writeFileSync(stagedFile, stagedLines);
const mockGit = writeMock(
tmpDir,
'git',
`#!/usr/bin/env bash\ncat ${JSON.stringify(stagedFile)}\n`,
);
const mockNpm = writeMock(
tmpDir,
'npm',
`#!/usr/bin/env bash\nprintf 'call %s\\n' "$*" >> "$GSD_TEST_NPM_MARKER"\n`,
);
// This IS the fan-out class HOOK_FANOUT_TIMEOUT_MS documents: the
// pre-commit hook runs under `bash` and shells out to `git diff`, `tr`,
// `grep`, and conditionally `npm` (which itself runs node). Same class as
// the observed CI failures in tests/quick-branching.test.cjs (PR #3787 run
// 32668773524) and tests/worktree-safety.test.cjs (`next` run
// 32608945654). See HOOK_FANOUT_TIMEOUT_MS in ./helpers/timeouts.cjs for
// the class rationale.
const result = runHook(HOOK_PATH, [], {
interpreter: 'bash',
cwd: ROOT,
env: {
...process.env,
GIT_OVERRIDE: mockGit,
NPM_OVERRIDE: mockNpm,
GSD_TEST_NPM_MARKER: marker,
},
timeoutMs: HOOK_FANOUT_TIMEOUT_MS,
});
const npmCalls = fs.existsSync(marker)
? fs.readFileSync(marker, 'utf8').split(/\r?\n/).filter(Boolean).length
: 0;
return { result, npmCalls };
}
/** Join paths the way `git diff --cached --name-only` emits them. */
function staged(...paths) {
return paths.length === 0 ? '' : `${paths.join('\n')}\n`;
}
describe('.githooks/pre-commit alias drift guard', () => {
test('runs the drift check when the alias table source is staged', (t) => {
const { result, npmCalls } = runPreCommit(t, staged('src/command-aliases.cts'));
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(
npmCalls,
1,
'staging the tracked alias source must invoke check:alias-drift — ' +
'the guard previously watched gitignored build output, which git never stages (#2725)',
);
});
test('fires when the drift checker itself is staged', (t) => {
const { result, npmCalls } = runPreCommit(t, staged('scripts/check-alias-drift.cjs'));
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(npmCalls, 1, 'editing the checker must re-run it');
});
test('fires when the shared family table is staged', (t) => {
const { result, npmCalls } = runPreCommit(
t,
staged('scripts/lib/alias-drift-families.cjs'),
);
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(npmCalls, 1, 'editing the family table must re-run the check');
});
test('fires for every source the drift check actually reads', (t) => {
assert.ok(DRIFT_SOURCES.length > 0, 'the drift surface must not be empty');
for (const source of DRIFT_SOURCES) {
const { npmCalls } = runPreCommit(t, staged(source));
assert.equal(
npmCalls,
1,
`${source} is in the drift checker's family table but .githooks/pre-commit ` +
'does not watch it — the two surfaces have diverged again (#2725)',
);
}
});
test('does not watch routers the drift check dropped', (t) => {
// The reverse direction of the parity row above. That row catches the hook
// UNDER-watching; this one catches it OVER-watching, using every
// `src/*-command-router.cts` on disk as the universe. Drop a family from
// scripts/lib/alias-drift-families.cjs without narrowing the hook and this
// fails — which is the half of the divergence #2725 would otherwise leave open.
const allRouters = fs
.readdirSync(path.join(ROOT, 'src'))
.filter((name) => name.endsWith('-command-router.cts'))
.map((name) => `src/${name}`);
const unwatched = allRouters.filter((routerPath) => !WATCHED_PATHS.has(routerPath));
assert.ok(
allRouters.length > DRIFT_SOURCES.length - 1,
'expected more routers on disk than the drift check reads — otherwise this row proves nothing',
);
assert.ok(unwatched.length > 0, 'expected at least one router outside the drift surface');
for (const routerPath of unwatched) {
const { npmCalls } = runPreCommit(t, staged(routerPath));
assert.equal(
npmCalls,
0,
`${routerPath} is not in the drift checker's family table, but .githooks/pre-commit ` +
'still watches it — the hook over-watches relative to the module (#2725)',
);
}
});
test('does not run the drift check for unrelated staged files', (t) => {
const { result, npmCalls } = runPreCommit(t, staged('README.md'));
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(npmCalls, 0, 'expected npm check to be skipped for unrelated staged files');
});
test('does not fire for a src file outside the drift surface', (t) => {
const outsider = 'src/milestone.cts';
// Guards the row against going vacuous if milestone ever joins the family.
assert.ok(
!WATCHED_PATHS.has(outsider),
`${outsider} joined the drift surface — pick a different outsider for this row`,
);
const { result, npmCalls } = runPreCommit(t, staged(outsider));
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(
npmCalls,
0,
'a guard that fires on every src/ edit trains contributors to bypass it',
);
});
test('does not invoke a missing npm script for retired sdk paths', (t) => {
const { result, npmCalls } = runPreCommit(t, staged('sdk/src/query/state-document.ts'));
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(
npmCalls,
0,
'the retired sdk/ guards called npm scripts that do not exist, aborting the commit (#2725)',
);
});
test('does not watch the gitignored build output', (t) => {
const { result, npmCalls } = runPreCommit(
t,
staged('gsd-core/bin/lib/command-aliases.cjs'),
);
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(
npmCalls,
0,
'build outputs are gitignored and can never be staged — watching them is what made the guard inert',
);
});
test('exits clean when nothing is staged', (t) => {
const { result, npmCalls } = runPreCommit(t, staged());
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(npmCalls, 0);
});
test('runs the check once when one of many staged files matches', (t) => {
const { result, npmCalls } = runPreCommit(
t,
staged(
'README.md',
'docs/adr/0174-retire-gsd-sdk-package-boundary.md',
'src/command-aliases.cts',
'tests/helpers.cjs',
),
);
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(npmCalls, 1, 'expected exactly one check:alias-drift invocation');
});
test('matches a CR-terminated staged path', (t) => {
const { result, npmCalls } = runPreCommit(t, 'src/command-aliases.cts\r\n');
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(
npmCalls,
1,
'a $-anchored grep fails on a CR-terminated line — the hook must strip \\r first',
);
});
describe('anchors the pattern exactly (limit-1 / limit / limit+1)', () => {
const cases = [
['src/command-aliases.ct', 0, 'limit-1: one character short of the extension'],
['src/command-aliases.cts', 1, 'limit: the exact tracked source'],
['src/command-aliases.ctsx', 0, 'limit+1: one character past the extension'],
['src/command-aliases.cts.bak', 0, 'suffix past the end anchor'],
['notsrc/command-aliases.cts', 0, 'prefix before the start anchor'],
];
for (const [stagedPath, expectedCalls, label] of cases) {
test(label, (t) => {
const { result, npmCalls } = runPreCommit(t, staged(stagedPath));
throwIfFailed(result, `bash ${HOOK_PATH}`);
assert.equal(npmCalls, expectedCalls, `${stagedPath} -> ${expectedCalls} npm call(s)`);
});
}
});
test('property: never fires for a path outside the watched set', (t) => {
// Biased toward near-misses (src/-prefixed, .cts-suffixed) because that is
// where over-matching actually hides. numRuns is held low: every sample
// spawns bash.
const nearMiss = fc
.tuple(
fc.constantFrom('src/', 'srcx/', 'notsrc/', 'docs/', 'tests/', ''),
fc.stringMatching(/^[a-z][a-z0-9-]{0,20}$/),
fc.constantFrom('.cts', '.cjs', '.ts', '.md', '.cts.bak', ''),
)
.map(([dir, stem, ext]) => `${dir}${stem}${ext}`)
.filter((p) => !WATCHED_PATHS.has(p));
fc.assert(
fc.property(nearMiss, (stagedPath) => {
const { result, npmCalls } = runPreCommit(t, staged(stagedPath));
throwIfFailed(result, `bash ${HOOK_PATH}`);
return npmCalls === 0;
}),
{ numRuns: 20 },
);
});
});