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>
449 lines
20 KiB
JavaScript
449 lines
20 KiB
JavaScript
// docs-guard-exempt: docs/CONTEXT-INDEX.json is mentioned only in module-doc comments; the test reads root CONTEXT.md and mocked fs, never a real docs/ path.
|
|
'use strict';
|
|
|
|
/**
|
|
* Integration tests for scripts/gen-context-index.cjs — the CI gate that
|
|
* keeps docs/CONTEXT-INDEX.json in sync with the predicates declared in the
|
|
* repo-root CONTEXT.md (ADR-1671, #2928 Phase 1, rows F1-F17).
|
|
*
|
|
* The committed artifact is plain JSON (not a `.cjs` CommonJS module): a
|
|
* shipped runtime module is the wrong place for ~120 KB of arbitrary
|
|
* CONTEXT.md prose, and embedding it there tripped both
|
|
* tests/cline-install.test.cjs (leaked `.claude/hooks/...` path literals) and
|
|
* tests/package-name-single-source.test.cjs (hardcoded package-name
|
|
* literals) — both true positives against runtime-code content scanning.
|
|
* docs/CONTEXT-INDEX.json mirrors docs/INVENTORY-MANIFEST.json's precedent:
|
|
* a committed, generated, `--check`-guarded JSON manifest that is not
|
|
* runtime code.
|
|
*
|
|
* Fixture isolation (ADR-1671 Phase 1 commit 3): gen-context-index.cjs now
|
|
* accepts `--context-path <p>` / `--index-path <p>` CLI overrides (and the
|
|
* same-named parameters on the exported `checkReport`/`buildFreshIndex`
|
|
* pure functions), so every test here spawns the real CLI (spawnSync, not an
|
|
* engine-direct call — an engine-direct call is false-green for CLI behavior
|
|
* per the design's own risk analysis) pointed directly at temp fixture
|
|
* files, with NO fs monkeypatching. The prior `--require` preload
|
|
* (tests/helpers/gen-context-index-fs-fixture.cjs) redirected two hardcoded
|
|
* absolute paths by patching fs.readFileSync/existsSync/writeFileSync — that
|
|
* indirection is no longer needed now that the paths are directly
|
|
* injectable, and the preload has been deleted.
|
|
*
|
|
* Prohibited: Raw Text Matching on Test Outputs (CONTRIBUTING.md). This
|
|
* generator's `--check --json` mode emits a typed `{ ok, reason, duplicates,
|
|
* count, classes }` report — `reason` is always one of the frozen `REASON`
|
|
* enum values. Rows F7-F10 assert on `report.reason === REASON.FAIL_X`
|
|
* (and, for F7, that `report.duplicates` names the duplicate id) instead of
|
|
* exit-code-only / stderr-substring assertions.
|
|
*/
|
|
|
|
const { describe, test, beforeEach, afterEach } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { execFileSync } = require('node:child_process');
|
|
|
|
const { createTempDir, cleanup } = require('./helpers.cjs');
|
|
const { serializeIndex, buildFreshIndex, checkReport, REASON } = require('../scripts/gen-context-index.cjs');
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
const SCRIPT = path.join(ROOT, 'scripts', 'gen-context-index.cjs');
|
|
const REAL_CONTEXT_PATH = path.join(ROOT, 'CONTEXT.md');
|
|
|
|
const STACK_FRAME_RE = /\n\s+at\s+\S+\s+\(.*:\d+:\d+\)/;
|
|
|
|
/**
|
|
* Spawn the real gen-context-index.cjs CLI with explicit `--context-path` /
|
|
* `--index-path` overrides — no fs monkeypatching, no `--require` preload.
|
|
*
|
|
* @param {string[]} args - CLI args (e.g. ['--check', '--json']).
|
|
* @param {{contextPath?: string, indexPath?: string}} [paths] - absolute
|
|
* fixture paths to pass via `--context-path`/`--index-path`. Omit a key to
|
|
* leave that seam at its real-repo default (read-only, untouched).
|
|
* @returns {{code: number, stdout: string, stderr: string}}
|
|
*/
|
|
function runGenContextIndex(args, paths = {}) {
|
|
const fullArgs = [...args];
|
|
if (paths.contextPath !== undefined) fullArgs.push('--context-path', paths.contextPath);
|
|
if (paths.indexPath !== undefined) fullArgs.push('--index-path', paths.indexPath);
|
|
|
|
try {
|
|
const stdout = execFileSync(process.execPath, [SCRIPT, ...fullArgs], {
|
|
cwd: ROOT,
|
|
encoding: 'utf8',
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
timeout: 30000,
|
|
});
|
|
return { code: 0, stdout, stderr: '' };
|
|
} catch (err) {
|
|
return {
|
|
code: err.status ?? 1,
|
|
stdout: err.stdout ? err.stdout.toString() : '',
|
|
stderr: err.stderr ? err.stderr.toString() : '',
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Parse the single JSON line `--check --json` writes to stdout.
|
|
*
|
|
* @param {string} stdout
|
|
* @returns {object}
|
|
*/
|
|
function parseJsonReport(stdout) {
|
|
return JSON.parse(stdout.trim());
|
|
}
|
|
|
|
describe('gen-context-index.cjs REASON enum (three-coordinated-changes lock)', () => {
|
|
test('REASON key set is exactly the documented set', () => {
|
|
// Locks the documented enum shape (CONTRIBUTING.md three-coordinated-
|
|
// changes pattern): adding a reason requires updating this assertion
|
|
// too, so the typed surface cannot silently drift from what tests expect.
|
|
assert.deepEqual(Object.keys(REASON).sort(), [
|
|
'FAIL_CONTEXT_MISSING',
|
|
'FAIL_CONTEXT_UNREADABLE',
|
|
'FAIL_DUPLICATE_IDS',
|
|
'FAIL_INDEX_MISSING',
|
|
'FAIL_INDEX_UNPARSEABLE',
|
|
'FAIL_LIB_NOT_BUILT',
|
|
'FAIL_STALE',
|
|
'OK_UP_TO_DATE',
|
|
]);
|
|
});
|
|
|
|
test('REASON is frozen', () => {
|
|
assert.ok(Object.isFrozen(REASON));
|
|
});
|
|
});
|
|
|
|
describe('gen-context-index.cjs --check (F)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempDir('gen-context-index-');
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('checkExitsZeroWhenIndexIsFresh', () => {
|
|
// Read-only against the real, already-fresh repo state — no override
|
|
// needed, and nothing is mutated.
|
|
const r = runGenContextIndex(['--check']);
|
|
assert.equal(r.code, 0);
|
|
});
|
|
|
|
test('checkExitsZeroAfterPureLineShift', () => {
|
|
// S5: the committed artifact carries no `line` field, so a pure line
|
|
// shift in CONTEXT.md must not perturb the byte-identical serialization.
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
const lines = real.split(/\r?\n/);
|
|
const shifted = [lines[0], '', '', ...lines.slice(1)].join('\n');
|
|
const shiftedPath = path.join(tmpDir, 'CONTEXT-shifted.md');
|
|
fs.writeFileSync(shiftedPath, shifted, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check'], { contextPath: shiftedPath });
|
|
assert.equal(r.code, 0, 'a pure line shift must not fail the gate (Q4 resolution, S5)');
|
|
});
|
|
|
|
test('checkExitsOneWhenPredicateValueChanged', () => {
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
const modified = real.replace(
|
|
// eslint-disable-next-line local/no-unbounded-quantifier -- parses this repo's own maintainer-authored CONTEXT.md, bounded, not adversarial input
|
|
/`RULESET\.PR-SCOPE\.one-concern-per-pr=[^`]*`/,
|
|
'`RULESET.PR-SCOPE.one-concern-per-pr=CHANGED VALUE FOR TEST`',
|
|
);
|
|
assert.notEqual(modified, real, 'fixture setup sanity: the substitution must actually apply');
|
|
const modifiedPath = path.join(tmpDir, 'CONTEXT-value-changed.md');
|
|
fs.writeFileSync(modifiedPath, modified, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check'], { contextPath: modifiedPath });
|
|
assert.equal(r.code, 1);
|
|
});
|
|
|
|
test('checkExitsOneWhenPredicateAdded', () => {
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
const added = real + '\n`ZZZTEST.added-by-test=value`\n';
|
|
const addedPath = path.join(tmpDir, 'CONTEXT-added.md');
|
|
fs.writeFileSync(addedPath, added, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check'], { contextPath: addedPath });
|
|
assert.equal(r.code, 1);
|
|
});
|
|
|
|
test('checkExitsOneWhenPredicateRemoved', () => {
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
// eslint-disable-next-line local/no-unbounded-quantifier -- parses this repo's own maintainer-authored CONTEXT.md, bounded, not adversarial input
|
|
const removed = real.replace(/`RULESET\.PR-SCOPE\.one-concern-per-pr=[^`]*`\r?\n/, '');
|
|
assert.notEqual(removed, real, 'fixture setup sanity: the removal must actually apply');
|
|
const removedPath = path.join(tmpDir, 'CONTEXT-removed.md');
|
|
fs.writeFileSync(removedPath, removed, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check'], { contextPath: removedPath });
|
|
assert.equal(r.code, 1);
|
|
});
|
|
|
|
test('checkExitsOneWhenClassSetChanged', () => {
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
const classGained = real + '\n`BRANDNEWCLASSFORTEST.x=y`\n';
|
|
const classGainedPath = path.join(tmpDir, 'CONTEXT-class-gained.md');
|
|
fs.writeFileSync(classGainedPath, classGained, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check'], { contextPath: classGainedPath });
|
|
assert.equal(r.code, 1);
|
|
});
|
|
|
|
test('checkExitsOneAndNamesDuplicateIdentifier (F7)', () => {
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
const dupPath = path.join(tmpDir, 'CONTEXT-dup.md');
|
|
const dupIntroduced = real + '\n`RULESET.PR-SCOPE.one-concern-per-pr=duplicate copy for test`\n';
|
|
fs.writeFileSync(dupPath, dupIntroduced, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check', '--json'], { contextPath: dupPath });
|
|
assert.equal(r.code, 1);
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'no bare stack trace in non-debug failure output');
|
|
|
|
const report = parseJsonReport(r.stdout);
|
|
assert.equal(report.ok, false);
|
|
assert.equal(report.reason, REASON.FAIL_DUPLICATE_IDS);
|
|
assert.ok(
|
|
report.duplicates.some((d) => d.id === 'RULESET.PR-SCOPE.one-concern-per-pr'),
|
|
'report.duplicates must name the duplicate id',
|
|
);
|
|
});
|
|
|
|
test('checkExitsOneWithRemedyWhenIndexMissing (F8)', () => {
|
|
const missingIndexPath = path.join(tmpDir, 'does-not-exist.json');
|
|
const r = runGenContextIndex(['--check', '--json'], { indexPath: missingIndexPath });
|
|
assert.equal(r.code, 1);
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE);
|
|
|
|
const report = parseJsonReport(r.stdout);
|
|
assert.equal(report.ok, false);
|
|
assert.equal(report.reason, REASON.FAIL_INDEX_MISSING);
|
|
});
|
|
|
|
test('checkExitsOneWithNamedReasonWhenIndexCorrupt (F9)', () => {
|
|
const corruptIndexPath = path.join(tmpDir, 'corrupt-index.json');
|
|
fs.writeFileSync(corruptIndexPath, 'this is not { valid javascript', 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check', '--json'], { indexPath: corruptIndexPath });
|
|
assert.equal(r.code, 1);
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'no bare stack trace for a corrupt committed index');
|
|
|
|
const report = parseJsonReport(r.stdout);
|
|
assert.equal(report.ok, false);
|
|
assert.equal(report.reason, REASON.FAIL_INDEX_UNPARSEABLE);
|
|
});
|
|
|
|
test('checkExitsOneWhenContextMdMissing (F10)', () => {
|
|
const missingContextPath = path.join(tmpDir, 'does-not-exist.md');
|
|
const r = runGenContextIndex(['--check', '--json'], { contextPath: missingContextPath });
|
|
assert.equal(r.code, 1);
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'no bare stack trace when CONTEXT.md is missing');
|
|
|
|
const report = parseJsonReport(r.stdout);
|
|
assert.equal(report.ok, false);
|
|
assert.equal(report.reason, REASON.FAIL_CONTEXT_MISSING);
|
|
});
|
|
|
|
test('checkExitsOneWhenContextMdUnreadable', () => {
|
|
// Fault injection via the mandated technique (CONTRIBUTING.md /
|
|
// CLAUDE.md cross-platform IO-failure rule): monkeypatch fs.readFileSync
|
|
// to throw an injected EACCES for one specific fixture path, restore in
|
|
// `finally`. Never chmod 0o000 (root bypasses mode bits). This is an
|
|
// in-process call to the exported `checkReport` pure function rather
|
|
// than a subprocess spawn — a subprocess's fs cannot be monkeypatched
|
|
// from the parent test process without a `--require` preload, and
|
|
// `checkReport` IS the typed surface under test here, so calling it
|
|
// directly is not an engine-direct false-green for CLI *argv* behavior
|
|
// (that risk is covered by the spawned-CLI tests above); it is the
|
|
// correct level to exercise a fault the CLI itself cannot inject.
|
|
const fixtureContextPath = path.join(tmpDir, 'unreadable-context.md');
|
|
fs.writeFileSync(fixtureContextPath, '`FOO=bar`\n', 'utf8');
|
|
|
|
const origReadFileSync = fs.readFileSync;
|
|
fs.readFileSync = function patchedReadFileSync(p, ...rest) {
|
|
if (p === fixtureContextPath) {
|
|
const err = new Error(`EACCES: permission denied, open '${p}' (injected by test, never a real fs fault)`);
|
|
err.code = 'EACCES';
|
|
throw err;
|
|
}
|
|
return origReadFileSync.call(fs, p, ...rest);
|
|
};
|
|
try {
|
|
const report = checkReport(fixtureContextPath, path.join(tmpDir, 'unused-index.json'));
|
|
assert.equal(report.ok, false);
|
|
assert.equal(report.reason, REASON.FAIL_CONTEXT_UNREADABLE);
|
|
} finally {
|
|
fs.readFileSync = origReadFileSync;
|
|
}
|
|
});
|
|
|
|
test('checkIsCrlfAgnostic (F17)', () => {
|
|
// F17: a CRLF-committed index compared against the (LF) fresh real
|
|
// CONTEXT.md must still exit 0 — comparison is CRLF-normalized.
|
|
const freshSerialized = serializeIndex(buildFreshIndex());
|
|
const crlfSerialized = freshSerialized.replace(/\n/g, '\r\n');
|
|
const crlfIndexPath = path.join(tmpDir, 'context-index-crlf.json');
|
|
fs.writeFileSync(crlfIndexPath, crlfSerialized, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check'], { indexPath: crlfIndexPath });
|
|
assert.equal(r.code, 0, 'CRLF-vs-LF committed/fresh comparison must be normalized, not a false failure');
|
|
});
|
|
});
|
|
|
|
describe('gen-context-index.cjs --write / default / usage (F)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempDir('gen-context-index-');
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('writeThenCheckIsClean', () => {
|
|
const writeTarget = path.join(tmpDir, 'write-target.json');
|
|
const w = runGenContextIndex(['--write'], { indexPath: writeTarget });
|
|
assert.equal(w.code, 0);
|
|
assert.ok(fs.existsSync(writeTarget), '--write must create the fixture-redirected index file');
|
|
|
|
const c = runGenContextIndex(['--check'], { indexPath: writeTarget });
|
|
assert.equal(c.code, 0, '--check must be clean immediately after --write');
|
|
});
|
|
|
|
test('writeIsByteIdenticalAcrossRuns', () => {
|
|
const target1 = path.join(tmpDir, 'w1.json');
|
|
const target2 = path.join(tmpDir, 'w2.json');
|
|
assert.equal(runGenContextIndex(['--write'], { indexPath: target1 }).code, 0);
|
|
assert.equal(runGenContextIndex(['--write'], { indexPath: target2 }).code, 0);
|
|
|
|
const content1 = fs.readFileSync(target1, 'utf8');
|
|
const content2 = fs.readFileSync(target2, 'utf8');
|
|
assert.equal(content1, content2, '--write must be deterministic across independent runs');
|
|
});
|
|
|
|
test('writtenIndexContainsNoLineField', () => {
|
|
const target = path.join(tmpDir, 'no-line-field.json');
|
|
assert.equal(runGenContextIndex(['--write'], { indexPath: target }).code, 0);
|
|
const content = fs.readFileSync(target, 'utf8');
|
|
assert.equal(content.includes('"line"'), false, 'the committed artifact must carry no `line` field anywhere (S5)');
|
|
});
|
|
|
|
test('defaultInvocationPrintsIndexToStdout', () => {
|
|
// Fully safe against the real repo: default mode only reads CONTEXT.md
|
|
// and the compiled predicates lib (read-only) and writes nothing.
|
|
const r = runGenContextIndex([]);
|
|
assert.equal(r.code, 0);
|
|
assert.ok(r.stdout.length > 0);
|
|
// Compare against the exact expected serialization (computed the same
|
|
// way the CLI does, via the exported pure functions) rather than
|
|
// hand-parsing the rendered text — avoids brittle delimiter-scanning
|
|
// over a JSON payload that legitimately contains ';' inside string values.
|
|
const expected = serializeIndex(buildFreshIndex()) + '\n';
|
|
assert.equal(r.stdout, expected);
|
|
});
|
|
|
|
test('unknownFlagExitsWithUsage', () => {
|
|
// Safe against the real repo: the unknown-flag branch never reads
|
|
// CONTEXT.md or the committed index at all.
|
|
const r = runGenContextIndex(['--totally-bogus-flag']);
|
|
assert.notEqual(r.code, 0);
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'usage output must never be a bare stack trace');
|
|
});
|
|
|
|
// ─── DEFECT.GEN-CONTEXT-INDEX-PARSEARGS-GATE-BYPASS (MAJOR review finding):
|
|
// conflicting `--check --write` must be a hard usage error, not a silent
|
|
// `--write` win, and a missing/flag-shaped path value must never resolve
|
|
// to the cwd (which previously leaked a raw EISDIR stack trace). ────────
|
|
|
|
test('checkAndWriteTogetherIsUsageErrorNotASilentWrite (a)', () => {
|
|
const target = path.join(tmpDir, 'should-not-be-written.json');
|
|
const r = runGenContextIndex(['--check', '--write'], { indexPath: target });
|
|
assert.notEqual(r.code, 0, '--check --write together must not silently exit 0 as a write');
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'usage output must never be a bare stack trace');
|
|
assert.equal(fs.existsSync(target), false, '--write must never win over --check and rewrite the index');
|
|
});
|
|
|
|
test('writeAndCheckReversedOrderIsAlsoAUsageError (a)', () => {
|
|
const target = path.join(tmpDir, 'should-also-not-be-written.json');
|
|
const r = runGenContextIndex(['--write', '--check'], { indexPath: target });
|
|
assert.notEqual(r.code, 0, 'conflicting mode flags must be a usage error regardless of order');
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE);
|
|
assert.equal(fs.existsSync(target), false);
|
|
});
|
|
|
|
test('missingTrailingValueForContextPathIsUsageErrorNotEisdirStackTrace (b)', () => {
|
|
const target = path.join(tmpDir, 'should-not-be-written-2.json');
|
|
// `--context-path` is the LAST arg: argv[i+1] is undefined, which used
|
|
// to resolve to the cwd via `path.resolve(undefined ?? '')`.
|
|
const r = runGenContextIndex(['--write', '--index-path', target, '--context-path']);
|
|
assert.notEqual(r.code, 0, 'a missing --context-path value must be a usage error');
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE, 'must never leak a raw EISDIR (or any) stack trace');
|
|
assert.equal(fs.existsSync(target), false, 'no write must happen when the path argument is rejected');
|
|
});
|
|
|
|
test('flagShapedValueForIndexPathIsUsageErrorNotSwallowedAsALiteralPath (b)', () => {
|
|
// `--index-path` is immediately followed by another flag rather than a
|
|
// path — must be rejected, not silently swallowed as the literal path
|
|
// "--json".
|
|
const r = runGenContextIndex(['--write', '--index-path', '--json']);
|
|
assert.notEqual(r.code, 0, 'a flag-shaped --index-path value must be a usage error');
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE);
|
|
});
|
|
});
|
|
|
|
// ─── DEFECT.GEN-CONTEXT-INDEX-DUPLICATE-GATE-UNPROVEN (MAJOR review finding):
|
|
// `FAIL_DUPLICATE_IDS` was only ever proven against synthetic fixtures — this
|
|
// branch hand-deleted the ONE live duplicate
|
|
// (`RULESET.WORKFLOW_MARKDOWN.FENCES`) from the real CONTEXT.md, so the
|
|
// committed docs/CONTEXT-INDEX.json ships `duplicates: []` and the gate has
|
|
// never been shown to catch a REAL duplicate in the real document. This
|
|
// suite re-inserts the exact deleted line (recovered from
|
|
// `git show origin/next:CONTEXT.md`) into a copy of the REAL CONTEXT.md and
|
|
// runs the real generator CLI against it. ───────────────────────────────────
|
|
|
|
describe('gen-context-index.cjs --check against a real-CONTEXT.md duplicate (real-data proof)', () => {
|
|
let tmpDir;
|
|
|
|
beforeEach(() => {
|
|
tmpDir = createTempDir('gen-context-index-real-dup-');
|
|
});
|
|
|
|
afterEach(() => {
|
|
cleanup(tmpDir);
|
|
});
|
|
|
|
test('reinsertingTheDeletedRulesetWorkflowMarkdownFencesLineFailsWithNamedDuplicate', () => {
|
|
// The exact line this branch deleted from the real CONTEXT.md (does NOT
|
|
// mention MD040 — the live line that replaced it does).
|
|
const deletedLine =
|
|
'`RULESET.WORKFLOW_MARKDOWN.FENCES=when editing shell snippets inside workflow markdown, preserve the opening language fence; malformed fence can create fresh CodeRabbit threads`';
|
|
|
|
const real = fs.readFileSync(REAL_CONTEXT_PATH, 'utf8');
|
|
assert.ok(
|
|
real.includes('RULESET.WORKFLOW_MARKDOWN.FENCES'),
|
|
'sanity: the real CONTEXT.md must still carry the live (MD040) FENCES line',
|
|
);
|
|
assert.ok(!real.includes(deletedLine), 'sanity: the deleted line must not already be present verbatim');
|
|
|
|
const reinserted = real + '\n' + deletedLine + '\n';
|
|
const fixturePath = path.join(tmpDir, 'CONTEXT-real-with-reinserted-duplicate.md');
|
|
fs.writeFileSync(fixturePath, reinserted, 'utf8');
|
|
|
|
const r = runGenContextIndex(['--check', '--json'], { contextPath: fixturePath });
|
|
assert.equal(r.code, 1, 'a real duplicate reintroduced into the real CONTEXT.md must fail the gate');
|
|
assert.doesNotMatch(r.stderr, STACK_FRAME_RE);
|
|
|
|
const report = parseJsonReport(r.stdout);
|
|
assert.equal(report.ok, false);
|
|
assert.equal(report.reason, REASON.FAIL_DUPLICATE_IDS);
|
|
assert.ok(
|
|
report.duplicates.some((d) => d.id === 'RULESET.WORKFLOW_MARKDOWN.FENCES'),
|
|
'report.duplicates must name RULESET.WORKFLOW_MARKDOWN.FENCES as the real duplicate',
|
|
);
|
|
});
|
|
});
|