Files
msd-core/scripts/lint-health-diagnostic-rule-table.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

405 lines
18 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/**
* lint-health-diagnostic-rule-table.cjs — gate: enforces ADR-3180 §8.2's 1:1
* rule-code invariant and §8.5's fixture-proof invariant for
* `src/health-diagnostic.cts`'s RULES table (Phase 11, #3309).
*
* ## What this enforces
*
* 1. (§8.2 rule 1 — 1:1 code invariant) Every `rule.code` in RULES (exported
* from the compiled `gsd-core/bin/lib/health-diagnostic.cjs`) is unique,
* and every rule's `severity` is one of `SEVERITY`'s values. The severity
* check exists only to confirm the compiled artifact was not hand-edited
* to bypass the `Rule.severity` required field TypeScript already
* enforces at compile time — "severity is a property of the RULE, never
* the emit call."
* 2. (§8.5 — fixture-proof invariant) Every code in RULES has a paired test:
* the code string (e.g. `'W001'`) appears as a literal AND within a
* `describe(`/`test(` block whose title also names that exact code, in
* one of the health-diagnostic test files
* (`tests/health-diagnostic-rules/*.test.cjs`,
* `tests/health-diagnostic.test.cjs`). A mere comment/string mention
* outside a titled block does not count as coverage.
*
* EXCEPTION — `PERMANENTLY_INERT_CODES` (below): a rule whose `check`
* always returns `[]` BY DESIGN (the real check lives outside the rule
* table entirely, because it needs ambient I/O `Rule.check` cannot
* perform — §8.1 rule 1) can never satisfy a real fixture-proof, no
* matter how many tests reference its code. Before this exception
* existed, W024 "passed" this guard only because an unrelated test title
* (the RULES-array shape assertion, "exports exactly 5 rules: W024, ...")
* happened to contain the string "W024" — accidental coverage, not proof
* the rule can fire. `PERMANENTLY_INERT_CODES` makes that exemption
* explicit and auditable instead of relying on a coincidental title
* match, and the PASS output now reports exempted codes SEPARATELY from
* genuinely fixture-covered ones rather than folding them together.
* 3. (Phase 12, #3310 — S0NN pass) `cmdStateValidate` (src/state.cts) emits
* 7 coded diagnostics (S001-S007) built inline via a local
* `stateDiagnostic()` helper — NOT `Rule`-table entries, so they are not
* read from the compiled module the way RULES/CONSISTENCY_RULES are.
* This third pass hardcodes that code list (`STATE_VALIDATE_CODES`,
* below) and applies the SAME §8.5 fixture-proof check against
* `tests/state.test.cjs`, reported in its own PASS/FAIL section —
* mirroring the C0NN pass's structure, just with a hardcoded list
* instead of a `Rule[]` array as the code source.
*
* Design: .gsd/phase/refactor-3309-health-diagnostic-rule-table/40-design.md
* ("The lint guard (§8.2 1:1 invariant + §8.5 fixture proof)").
*
* ## Deviation from the design doc's original plan
*
* The design doc assumed fixtures would live as separate files at
* `tests/fixtures/health-diagnostic/<code>.*`. That did not happen during
* implementation — all 8 rule-group test files
* (`tests/health-diagnostic-rules/*.test.cjs`) build fixtures INLINE via
* real temp directories (`createTempDir()` from `tests/helpers.cjs`) and a
* real, non-mocked `buildPlanningSnapshot(tmpCwd)` call (see
* `tests/health-diagnostic-rules/root-existence.test.cjs`). This guard
* therefore verifies the fixture-proof invariant STATICALLY against the
* test files' own text — mirroring `scripts/lint-fix-has-regression-tests.cjs`'s
* house style — rather than dynamically re-running fixture-building code
* this guard does not own.
*/
const fs = require('node:fs');
const path = require('node:path');
const { ExitError, runMain } = require('./lib/cli-exit.cjs');
const REPO_ROOT = path.join(__dirname, '..');
const COMPILED_MODULE_REL = 'gsd-core/bin/lib/health-diagnostic.cjs';
const COMPILED_MODULE_PATH = path.join(REPO_ROOT, COMPILED_MODULE_REL);
const TEST_GROUP_DIR = path.join(REPO_ROOT, 'tests', 'health-diagnostic-rules');
const SKELETON_TEST_FILE = path.join(REPO_ROOT, 'tests', 'health-diagnostic.test.cjs');
// Phase 12 (#3310, ADR-3180 §8.4) — the C0NN namespace's own fixture-proof
// test file. §8.5 extends to `CONSISTENCY_RULES`'s NEW codes only (C001-C004
// — W006/W007 are already fixture-proofed above, against the SAME `Rule`
// objects; re-checking them here would be redundant, not additional
// coverage).
const CONSISTENCY_TEST_FILE = path.join(REPO_ROOT, 'tests', 'health-diagnostic-rules', 'consistency.test.cjs');
const CONSISTENCY_CODE_PREFIX_RE = /^C\d{3}$/;
// Phase 12 (#3310, ADR-3180 §8.5 extension) — the S0NN namespace's own
// fixture-proof pass. These 7 codes are NOT collected in any exported
// `Rule[]` array: `cmdStateValidate` (src/state.cts) builds `Diagnostic[]`
// directly via a local `stateDiagnostic()` helper, not via the rule-table
// evaluator (out of scope for the RULES/CONSISTENCY_RULES-keyed passes
// above). The list is therefore hardcoded here instead of read from the
// compiled module.
const STATE_VALIDATE_TEST_FILE = path.join(REPO_ROOT, 'tests', 'state.test.cjs');
const STATE_VALIDATE_CODES = ['S001', 'S002', 'S003', 'S004', 'S005', 'S006', 'S007'];
// Matches `describe(`/`test(`/`it(` calls whose first argument is a string
// literal, capturing that literal as the block's title. Line/regex-based
// (not full AST) per this repo's existing lint-guard house style
// (scripts/lint-planning-snapshot-bypass-drift.cjs's scanCode precedent).
const TITLED_BLOCK_RE = /\b(describe|test|it)\(\s*(['"`])((?:\\.|(?!\2)[^\\])*)\2/g;
// Rule codes whose `check` is a documented PERMANENT no-op (always returns
// `[]`) because the real check requires ambient I/O forbidden inside a
// `Rule.check(snapshot)` (§8.1 rule 1) — the real check runs elsewhere,
// outside the rule table. These can never be proven via a real
// diagnostic-firing fixture, so they are exempted from the §8.5 fixture-proof
// invariant explicitly here rather than via an accidental test-title match.
// Adding an entry is a deliberate, reviewed decision — see each reason.
const PERMANENTLY_INERT_CODES = new Map([
[
'W024',
'readStateHeadFreshness requires a git-log shell-out, forbidden ambient I/O for Rule.check ' +
'(§8.1 rule 1) — the real check runs in cmdValidateHealth itself, outside the rule table ' +
'(src/verify.cts). This rule-table entry is a permanent no-op by design, not a fixture gap.',
],
]);
/**
* Load the compiled health-diagnostic module. Throws a clear ExitError
* (not a raw MODULE_NOT_FOUND) if `npm run build:lib` has not run.
*/
function loadCompiledModule(compiledPath = COMPILED_MODULE_PATH) {
if (!fs.existsSync(compiledPath)) {
throw new ExitError(
2,
`lint-health-diagnostic-rule-table: compiled artifact not found at ${COMPILED_MODULE_REL}.\n` +
'Run `npm run build:lib` first.',
);
}
return require(compiledPath);
}
/**
* §8.2 rule 1 — 1:1 code invariant: every rule.code is unique, and every
* rule's severity is a member of SEVERITY's values.
*
* @param {Array<{code: string, severity: string}>} rules
* @param {Record<string, string>} severity SEVERITY export (code -> value)
* @returns {{duplicates: Array<{code: string, count: number}>, badSeverities: Array<{code: string, severity: unknown}>}}
*/
function checkOneToOneInvariant(rules, severity) {
const severityValues = new Set(Object.values(severity));
const counts = new Map();
const badSeverities = [];
for (const rule of rules) {
counts.set(rule.code, (counts.get(rule.code) || 0) + 1);
if (!severityValues.has(rule.severity)) {
badSeverities.push({ code: rule.code, severity: rule.severity });
}
}
const duplicates = [...counts.entries()]
.filter(([, count]) => count > 1)
.map(([code, count]) => ({ code, count }));
return { duplicates, badSeverities };
}
/**
* Extracts every `describe(`/`test(`/`it(` block title found in `text`.
*
* @param {string} text
* @returns {string[]}
*/
function extractTitledBlocks(text) {
const titles = [];
TITLED_BLOCK_RE.lastIndex = 0;
let match;
while ((match = TITLED_BLOCK_RE.exec(text)) !== null) {
titles.push(match[3]);
}
return titles;
}
/**
* True iff `code` appears verbatim, as a whole token, inside at least one of
* `titles`. Whole-token match guards against a shorter code accidentally
* substring-matching inside an unrelated longer token.
*
* @param {string} code
* @param {string[]} titles
*/
function codeAppearsInTitle(code, titles) {
const codeRe = new RegExp(`(?:^|[^A-Za-z0-9])${code}(?:$|[^A-Za-z0-9])`);
return titles.some((title) => codeRe.test(`|${title}|`));
}
/**
* Locates every health-diagnostic test file this guard scans for §8.5
* fixture-proof coverage.
*
* @param {string} repoRoot
* @returns {string[]} absolute paths, sorted
*/
function findHealthDiagnosticTestFiles(repoRoot = REPO_ROOT) {
const groupDir = path.join(repoRoot, 'tests', 'health-diagnostic-rules');
const files = [];
if (fs.existsSync(groupDir)) {
for (const entry of fs.readdirSync(groupDir)) {
if (entry.endsWith('.test.cjs')) {
files.push(path.join(groupDir, entry));
}
}
}
const skeletonTestFile = path.join(repoRoot, 'tests', 'health-diagnostic.test.cjs');
if (fs.existsSync(skeletonTestFile)) {
files.push(skeletonTestFile);
}
return files.sort();
}
/**
* §8.5 — fixture-proof invariant: for every code in `rules`, confirm at
* least one test file in `testFiles` has a `describe(`/`test(`/`it(` block
* whose title names that exact code — UNLESS the code is listed in
* `PERMANENTLY_INERT_CODES`, in which case it is reported separately as
* `exempted` (visibly, not folded into "covered") and never fails the guard
* regardless of test coverage.
*
* @param {Array<{code: string}>} rules
* @param {string[]} testFiles absolute paths to *.test.cjs files to scan
* @param {Map<string, string>} inertCodes PERMANENTLY_INERT_CODES (injectable for tests)
* @returns {{uncovered: string[], exempted: string[], testFilesScanned: string[]}}
*/
function checkFixtureProofInvariant(rules, testFiles, inertCodes = PERMANENTLY_INERT_CODES) {
const allTitles = [];
for (const file of testFiles) {
const text = fs.readFileSync(file, 'utf8');
allTitles.push(...extractTitledBlocks(text));
}
const uncovered = [];
const exempted = [];
for (const rule of rules) {
if (inertCodes.has(rule.code)) {
exempted.push(rule.code);
continue;
}
if (!codeAppearsInTitle(rule.code, allTitles)) {
uncovered.push(rule.code);
}
}
return { uncovered, exempted, testFilesScanned: testFiles };
}
function formatRepoRelative(absPath) {
return path.relative(REPO_ROOT, absPath).split(path.sep).join('/');
}
function main() {
const { RULES, CONSISTENCY_RULES, SEVERITY } = loadCompiledModule();
const { duplicates, badSeverities } = checkOneToOneInvariant(RULES, SEVERITY);
const testFiles = findHealthDiagnosticTestFiles(REPO_ROOT);
const { uncovered, exempted } = checkFixtureProofInvariant(RULES, testFiles);
// ─── C0NN check pass (Phase 12, #3310) — separate from the W/E/I pass
// above, own reporting section, does NOT re-check W006/W007's fixture
// proof (already covered above against the same `Rule` objects).
const consistencyNewRules = CONSISTENCY_RULES.filter((r) => CONSISTENCY_CODE_PREFIX_RE.test(r.code));
const { duplicates: consistencyDuplicates, badSeverities: consistencyBadSeverities } = checkOneToOneInvariant(
consistencyNewRules,
SEVERITY,
);
const consistencyTestFiles = fs.existsSync(CONSISTENCY_TEST_FILE) ? [CONSISTENCY_TEST_FILE] : [];
const { uncovered: consistencyUncovered } = checkFixtureProofInvariant(
consistencyNewRules,
consistencyTestFiles,
new Map(),
);
// ─── S0NN check pass (Phase 12, #3310) — separate from the W/E/I and C0NN
// passes above, own reporting section. Hardcoded code list (see the
// STATE_VALIDATE_CODES comment above) rather than read from a Rule[] array.
const stateValidateTestFiles = fs.existsSync(STATE_VALIDATE_TEST_FILE) ? [STATE_VALIDATE_TEST_FILE] : [];
const { uncovered: stateValidateUncovered } = checkFixtureProofInvariant(
STATE_VALIDATE_CODES.map((code) => ({ code })),
stateValidateTestFiles,
new Map(),
);
const problems = [];
if (duplicates.length > 0) {
const list = duplicates.map((d) => ` ${d.code} (${d.count} occurrences)`).join('\n');
problems.push(
`§8.2 rule 1 violated: ${duplicates.length} duplicated rule code(s) in RULES ` +
`(${COMPILED_MODULE_REL}):\n${list}\n` +
' remedy: codes are append-only and 1:1 with a single Rule — rename or remove the duplicate.',
);
}
if (badSeverities.length > 0) {
const list = badSeverities
.map((b) => ` ${b.code}: severity=${JSON.stringify(b.severity)}`)
.join('\n');
problems.push(
`§8.2 rule 3 violated: ${badSeverities.length} rule(s) with a severity not in SEVERITY's values:\n${list}\n` +
' remedy: severity is a property of the RULE — set it to SEVERITY.ERROR/WARNING/INFO.',
);
}
if (uncovered.length > 0) {
const scannedList = testFiles.map(formatRepoRelative).join('\n ');
problems.push(
`§8.5 violated: ${uncovered.length} rule code(s) with no describe()/test() block naming them ` +
`(a comment or bare string mention does not count):\n ${uncovered.join(', ')}\n\n` +
` Searched these test files:\n ${scannedList}\n\n` +
' remedy: add or extend a describe()/test() title in the matching ' +
'tests/health-diagnostic-rules/<group>.test.cjs file so the block title ' +
`names the code verbatim (e.g. describe('${uncovered[0]} — ...', () => { ... })), ` +
'and drive the rule to fire against a real fixture built via createTempDir() + buildPlanningSnapshot() ' +
'(see tests/health-diagnostic-rules/root-existence.test.cjs).',
);
}
if (consistencyDuplicates.length > 0) {
const list = consistencyDuplicates.map((d) => ` ${d.code} (${d.count} occurrences)`).join('\n');
problems.push(
`§8.2 rule 1 violated (C0NN namespace): ${consistencyDuplicates.length} duplicated rule code(s) in ` +
`CONSISTENCY_RULES (${COMPILED_MODULE_REL}):\n${list}\n` +
' remedy: codes are append-only and 1:1 with a single Rule — rename or remove the duplicate.',
);
}
if (consistencyBadSeverities.length > 0) {
const list = consistencyBadSeverities
.map((b) => ` ${b.code}: severity=${JSON.stringify(b.severity)}`)
.join('\n');
problems.push(
`§8.2 rule 3 violated (C0NN namespace): ${consistencyBadSeverities.length} rule(s) with a severity not ` +
`in SEVERITY's values:\n${list}\n` +
' remedy: severity is a property of the RULE — set it to SEVERITY.ERROR/WARNING/INFO.',
);
}
if (consistencyUncovered.length > 0) {
problems.push(
`§8.5 violated (C0NN namespace): ${consistencyUncovered.length} rule code(s) with no describe()/test() ` +
`block naming them (a comment or bare string mention does not count):\n ${consistencyUncovered.join(', ')}\n\n` +
` Searched: ${formatRepoRelative(CONSISTENCY_TEST_FILE)}` +
(consistencyTestFiles.length === 0 ? ' (file not found)' : '') +
'\n\n remedy: add or extend a describe()/test() title in tests/health-diagnostic-rules/consistency.test.cjs ' +
`so the block title names the code verbatim (e.g. describe('${consistencyUncovered[0]} — ...', () => { ... })), ` +
'and drive the rule to fire against a real fixture built via createTempDir() + buildPlanningSnapshot().',
);
}
if (stateValidateUncovered.length > 0) {
problems.push(
`§8.5 violated (S0NN namespace): ${stateValidateUncovered.length} code(s) with no describe()/test() ` +
`block naming them (a comment or bare string mention does not count):\n ${stateValidateUncovered.join(', ')}\n\n` +
` Searched: ${formatRepoRelative(STATE_VALIDATE_TEST_FILE)}` +
(stateValidateTestFiles.length === 0 ? ' (file not found)' : '') +
'\n\n remedy: add or extend a describe()/test() title in tests/state.test.cjs ' +
`so the block title names the code verbatim (e.g. test('${stateValidateUncovered[0]}: ...', () => { ... })), ` +
'mirroring the existing `#3310 state validate — S0NN coded diagnostics` describe block.',
);
}
if (problems.length > 0) {
throw new ExitError(1, `${problems.join('\n\n')}\n`);
}
const coveredCount = RULES.length - exempted.length;
const exemptedDetail = exempted
.map((code) => `${code} (${PERMANENTLY_INERT_CODES.get(code)})`)
.join('; ');
console.log(
`lint-health-diagnostic-rule-table: PASS — ${RULES.length} rule code(s): ${coveredCount} covered by a ` +
`real fixture, ${exempted.length} exempted across ${testFiles.length} test file(s).` +
(exempted.length > 0 ? `\n Exempted: ${exemptedDetail}` : ''),
);
console.log(
`lint-health-diagnostic-rule-table: PASS (C0NN namespace) — ${consistencyNewRules.length} new rule code(s) ` +
`(${consistencyNewRules.map((r) => r.code).join(', ')}), all fixture-covered in ` +
`${formatRepoRelative(CONSISTENCY_TEST_FILE)}.`,
);
console.log(
`lint-health-diagnostic-rule-table: PASS (S0NN namespace) — ${STATE_VALIDATE_CODES.length} code(s) ` +
`(${STATE_VALIDATE_CODES.join(', ')}), all fixture-covered in ` +
`${formatRepoRelative(STATE_VALIDATE_TEST_FILE)}.`,
);
}
runMain(main);
module.exports = {
loadCompiledModule,
checkOneToOneInvariant,
extractTitledBlocks,
codeAppearsInTitle,
findHealthDiagnosticTestFiles,
checkFixtureProofInvariant,
PERMANENTLY_INERT_CODES,
COMPILED_MODULE_PATH,
TEST_GROUP_DIR,
SKELETON_TEST_FILE,
CONSISTENCY_TEST_FILE,
STATE_VALIDATE_TEST_FILE,
STATE_VALIDATE_CODES,
};