Files
msd-core/scripts/lint-removed-but-needed.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

321 lines
13 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/**
* lint-removed-but-needed.cjs — DEFECT.REMOVED-BUT-NEEDED (CONTEXT.md).
*
* ## Why
*
* A file/key gets removed because "no longer used" without verifying every
* consumer (workflows, docs, manifests, npm scripts, tests). #3316: root
* `package-lock.json` was deleted while `package.json` still declares deps
* and workflows still use `cache: 'npm'` + `npm ci` (which require a
* lockfile). e3b52c70: docs referenced a removed `/gsd-new-workspace`
* workflow after it was deleted. #3560: a deleted workflow was pinned by an
* existence assertion in `tests/phase.test.cjs` — the lint passed clean and
* the breakage surfaced only as four red tests on the remote runner,
* because `tests/` was not scanned at all.
*
* ## What this checks
*
* For every file deleted (`git diff --name-status <base>...HEAD`, status
* `D`), grep the post-diff tree for the deleted file's basename:
*
* - `.github/workflows/`, `gsd-core/`, `docs/`, `package.json` — ANY
* surviving reference fails (the original rule).
* - `tests/` — scanned with a discriminator (#3565): a reference that PINS
* existence (`fs.existsSync(path)`, `readFileSync`, `require`, or the
* basename as a quoted object key) fails; a reference that ASSERTS
* ABSENCE (`assert.ok(!content.includes('x.md'))`, `!fs.existsSync(...)`)
* is the correct post-deletion state and passes. The naive widening —
* flagging every mention — was tried in #3560 and reverted: an absence
* assertion must contain the basename to assert the file is gone, so
* without the two kinds separated the guard fires on correct code and
* gets disabled. A mention that is neither a pin nor an absence
* assertion (prose, a path assembled on another line) is not flagged —
* a documented known limit, chosen because a false violation reds a
* correct tree while a missed prose mention only loses one detection
* channel.
*
* `package-lock.json` deletions additionally fail if any workflow still
* uses `npm ci` or `cache: 'npm'`/`cache: "npm"` — those depend on a
* lockfile even though they never spell out its filename.
*
* ## False-positive risk (moderate, per audit)
*
* A common basename (`index.js`, `config.json`) can coincidentally match an
* unrelated file, and this only catches LITERAL string references — not a
* variable holding the filename or a glob that happened to match it.
*/
const fs = require('node:fs');
const path = require('node:path');
const cp = require('node:child_process');
const { ExitError, runMain } = require('./lib/cli-exit.cjs');
const { escapeRegex } = require('../gsd-core/bin/lib/pattern.cjs');
const { sanitizeEcho } = require('./command-contract-helpers.cjs');
const ROOT = path.join(__dirname, '..');
const SCAN_ROOTS = ['.github/workflows', 'gsd-core', 'docs'];
const EXTRA_FILES = ['package.json'];
const TESTS_ROOT = 'tests';
// Skip these when walking SCAN_ROOTS — binary/generated content that can
// never carry a meaningful basename reference, and is often large.
const SKIP_EXT = new Set(['.png', '.jpg', '.jpeg', '.gif', '.ico', '.woff', '.woff2', '.ttf', '.zip']);
/**
* Pure: does `content` contain a literal reference to `basename`, delimited
* by non-identifier/non-path characters on both sides (so "foo.json" doesn't
* match inside "old-foo.json.bak" style names but does match in a normal
* path/prose context)?
* @param {string} content
* @param {string} basename
* @returns {boolean}
*/
function referencesBasename(content, basename) {
const re = new RegExp(`(^|[^\\w.-])${escapeRegex(basename)}($|[^\\w.-])`);
return re.test(content);
}
/**
* Pure: given the deleted file's basename, does content contain a
* lockfile-dependent idiom (`npm ci`, `cache: 'npm'` / `cache: "npm"`)?
* Only meaningful for package-lock.json deletions.
* @param {string} content
* @returns {boolean}
*/
function referencesNpmLockfileDependency(content) {
return /\bnpm ci\b/.test(content) || /cache:\s*['"]npm['"]/.test(content);
}
function walk(dir) {
const out = [];
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) out.push(...walk(full));
else if (entry.isFile() && !SKIP_EXT.has(path.extname(entry.name))) out.push(full);
}
return out;
}
/**
* Pure: given a list of deleted basenames and a `{ file, content }[]` corpus
* of the post-diff tree, find every surviving reference.
* @param {string[]} deletedFiles - repo-relative deleted paths
* @param {{ file: string, content: string }[]} corpus
* @returns {{ deletedFile: string, referencedIn: string, reason: string }[]}
*/
function findSurvivingReferences(deletedFiles, corpus) {
const violations = [];
for (const deletedFile of deletedFiles) {
const basename = path.basename(deletedFile);
for (const { file, content } of corpus) {
if (referencesBasename(content, basename)) {
violations.push({ deletedFile, referencedIn: file, reason: `basename '${basename}' still referenced` });
}
}
if (basename === 'package-lock.json') {
for (const { file, content } of corpus) {
if (file.startsWith('.github/workflows') && referencesNpmLockfileDependency(content)) {
violations.push({
deletedFile,
referencedIn: file,
reason: '`npm ci` / `cache: \'npm\'` still present — both require a lockfile',
});
}
}
}
}
return violations;
}
/**
* Pure: classify ONE line of a test file that references `basename`.
* Returns 'asserts-absence' | 'pins-existence' | null.
*
* - asserts-absence: a NEGATED check carrying the basename —
* `assert.ok(!content.includes('x.md'))`, `!fs.existsSync(p)`,
* `!/x\.md/.test(s)`. The basename must appear for the assertion to
* work, so this is the CORRECT post-deletion state (#3560's reverted
* naive widening fired exactly here).
* - pins-existence: a direct dependency on the file existing —
* `fs.existsSync/readFileSync/statSync/readdirSync/require(...)` on the
* same line, or the basename as a quoted object key (`'x.md': ...`,
* the allowlist trap — a key means the test resolves against the file).
* - null: neither (prose mention, path assembled on another line). Not a
* violation — see the header's known-limit note.
*
* @param {string} line
* @param {string} basename
* @returns {'asserts-absence'|'pins-existence'|null}
*/
function classifyTestReference(line, basename) {
const negatedCheck =
/!\s*[A-Za-z_$][\w.$]*\.(includes|indexOf|search|startsWith|endsWith|match)\s*\(/.test(line) ||
/!\s*(fs\.)?(existsSync|statSync)\s*\(/.test(line) ||
// [^/\n]* (not .*) so an adversarial line cannot backtrack the regex
/!\s*\/[^/\n]*\/\s*\.(test|match)\s*\(/.test(line);
if (negatedCheck) return 'asserts-absence';
const pinsByCall =
/\b(existsSync|readFileSync|statSync|readdirSync|require|accessSync)\s*\(/.test(line) ||
/\brequire\s*\(?['"]/.test(line);
if (pinsByCall) return 'pins-existence';
// Template literal needs \\s so the RegExp constructor receives \s — a
// bare \s in a template literal collapses to 's' and silently matches a
// literal 's' instead of whitespace.
if (new RegExp(`['"\`]${escapeRegex(basename)}['"\`]\\s*:`).test(line)) return 'pins-existence';
return null;
}
/**
* Pure: for every deleted basename, scan the tests corpus line by line and
* report each `pins-existence` reference as a violation. `asserts-absence`
* references are explicitly NOT violations; unclassifiable mentions are
* skipped (known limit). Violations are per-reference — one test file
* carrying both an absence assertion and an existence pin reports the pin.
*
* @param {string[]} deletedFiles - repo-relative deleted paths
* @param {{ file: string, content: string }[]} testsCorpus
* @returns {{ deletedFile: string, referencedIn: string, reason: string }[]}
*/
function findSurvivingTestReferences(deletedFiles, testsCorpus) {
const violations = [];
for (const deletedFile of deletedFiles) {
const basename = path.basename(deletedFile);
const refRe = new RegExp(`(^|[^\\w.-])${escapeRegex(basename)}($|[^\\w.-])`);
for (const { file, content } of testsCorpus) {
for (const line of content.split(/\r?\n/)) {
if (!refRe.test(line)) continue;
const kind = classifyTestReference(line, basename);
if (kind === 'pins-existence') {
violations.push({
deletedFile,
referencedIn: file,
// control-char-stripped + capped: this text is echoed into lint
// output that AI agents read as trusted instructions
reason: `pins-existence: test depends on deleted basename '${basename}' — ${sanitizeEcho(line.trim())}`,
});
}
// 'asserts-absence' is correct post-deletion state; null is a
// documented known limit — neither is a violation.
}
}
}
return violations;
}
function getDeletedFiles(root, baseRef) {
// Deliberately let a git failure (unresolvable ref, no merge base, etc.)
// propagate as a plain Error — main() treats ANY scan() failure as "cannot
// resolve this base ref in this environment" and degrades to a skip,
// matching lint-fix-has-regression-tests.cjs. There is no failure mode here
// that should hard-exit non-zero; a real drift is only ever reported once
// the diff succeeds and findSurvivingReferences finds a violation.
const out = cp.execFileSync('git', ['diff', '--name-status', `${baseRef}...HEAD`], {
cwd: root,
encoding: 'utf8',
timeout: 15000,
});
return out
.trim()
.split('\n')
.filter(Boolean)
.filter((line) => line.startsWith('D\t'))
.map((line) => line.slice(2));
}
function buildCorpus(root) {
const corpus = [];
for (const rel of SCAN_ROOTS) {
for (const abs of walk(path.join(root, rel))) {
try {
corpus.push({ file: path.relative(root, abs).replace(/\\/g, '/'), content: fs.readFileSync(abs, 'utf8') });
} catch {
// unreadable (broken symlink, binary that slipped past SKIP_EXT) — skip
}
}
}
for (const rel of EXTRA_FILES) {
const abs = path.join(root, rel);
try {
corpus.push({ file: rel, content: fs.readFileSync(abs, 'utf8') });
} catch {
// optional file absent — skip
}
}
return corpus;
}
function scan(root, baseRef) {
const deletedFiles = getDeletedFiles(root, baseRef);
if (deletedFiles.length === 0) return [];
const corpus = buildCorpus(root);
const violations = findSurvivingReferences(deletedFiles, corpus);
// tests/ arm (#3565): same deletions, discriminated references. A bare
// mention that pins nothing is skipped; an absence assertion is the
// correct post-deletion state; only a pin on a deleted file fails.
const testsCorpus = [];
for (const abs of walk(path.join(root, TESTS_ROOT))) {
try {
testsCorpus.push({
file: path.relative(root, abs).replace(/\\/g, '/'),
content: fs.readFileSync(abs, 'utf8'),
});
} catch {
// unreadable (broken symlink, binary that slipped past SKIP_EXT) — skip
}
}
violations.push(...findSurvivingTestReferences(deletedFiles, testsCorpus));
return violations;
}
function main() {
const baseRef = `origin/${process.env.GSD_REMOVED_BUT_NEEDED_BASE || process.env.GITHUB_BASE_REF || 'next'}`;
let violations;
try {
violations = scan(ROOT, baseRef);
} catch (e) {
// origin/<base> unreachable in this environment (e.g. a shallow local
// clone with no matching remote-tracking ref) — degrade to a skip rather
// than a false failure, matching lint-fix-has-regression-tests.cjs.
console.log(`lint-removed-but-needed: could not resolve ${baseRef}, skipping (${e.message})`);
return;
}
if (violations.length > 0) {
const detail = violations
.map((v) => ` ${v.deletedFile} deleted, but still referenced in ${v.referencedIn}: ${v.reason}`)
.join('\n');
throw new ExitError(
1,
'lint-removed-but-needed: a deleted file is still referenced by a live consumer\n'
+ '(DEFECT.REMOVED-BUT-NEEDED). Either restore the file or update every consumer in the\n'
+ 'same commit — do not paper over with a workaround that loses reproducibility:\n'
+ detail,
);
}
console.log('ok lint-removed-but-needed: no deleted file has a surviving reference');
}
module.exports = {
referencesBasename,
referencesNpmLockfileDependency,
findSurvivingReferences,
classifyTestReference,
findSurvivingTestReferences,
getDeletedFiles,
buildCorpus,
scan,
SCAN_ROOTS,
EXTRA_FILES,
TESTS_ROOT,
};
if (require.main === module) runMain(main);