Files
msd-core/tests/lint-hooks-runtime-build-seam.test.cjs
Tom Boucher bf2332e67c fix(#3582): route every hook's compiled-module require through the self-heal build seam (#3629)
* test(3582): failing-first cold-tree coverage and the seam drift lint

On a plugin-channel install the compiled gsd-core/bin/lib/*.cjs are legitimately
absent (ADR-457 build-at-publish; the npm package builds before publishing, a raw
tree materialization never does). gsd-tools.cjs calls ensureRuntimeBuild() before
requiring ./lib; no hook does, so the isolation guard's Cannot-find-module lands in
its fail-closed catch and is misreported as an unreadable dispatch-isolation
configuration, blocking every executor dispatch.

These tests fail on that: cold-tree runs of the isolation guard, statusline, cursor
guard and update worker, plus the seam's actionable build error surfacing instead of
the generic misreport.

Also adds the drift lint the acceptance criteria require, with a fixture proving it
CAN fail — a guard never shown to fail is worthless. It is red here by design: it
flags today's unfixed hooks, which is exactly the defect.

* fix(3582): route every hook's compiled-module require through the self-heal seam

RED proven at 5b174b0d: 11 failures — the cold-tree runs for the isolation guard,
cursor guard and update worker, the fail-closed-with-actionable-message assertion, and
the lint's own real-tree check.

The compiled runtime library is produced by build:lib and gitignored (ADR-457,
build-at-publish). The npm package builds before publishing; a plugin-marketplace or
git-clone install materializes the raw tree and never does, so on that channel those
modules are legitimately absent. The self-heal seam added by #2002 exists to heal exactly
this, and the CLI entrypoint already calls it — no hook did. The isolation guard's
Cannot-find-module therefore landed in its fail-closed catch and was reported as
'could not read or resolve dispatch-isolation configuration', so an ARTIFACT ABSENCE was
misdiagnosed as an unreadable project config and every executor dispatch was blocked.

All SEVEN affected files now call the seam before their first compiled require. The issue
named four; a scan found six; implementing it surfaced a seventh — the shared isolation
sentinel helper, used by BOTH guards, which requires two compiled modules itself and
would have defeated the guards' own fix on a genuinely cold tree. Same defect class, so
fixed here rather than left as a known-broken remainder.

Failure posture is deliberately split by hook kind:
- Gates (agent isolation guard, cursor subagent start) surface the seam's actionable
  build error distinctly instead of swallowing it into the generic text, and stay
  fail-closed — a genuinely unreadable project config still DENIES exactly as before.
- Cosmetic and detached hooks (statusline, update worker, update check, update banner)
  DEGRADE rather than crash: the statusline draws on every render and the worker is a
  detached process, so a build failure there must not take down the prompt.

The npm path is untouched: the seam's already-built fast path returns immediately, so
prebuilt installs pay nothing and behave bit-for-bit as before.

Adds a drift lint, wired into the CI lint chain, so the invariant is enforced rather than
remembered — without it the next hook to add a compiled require reintroduces the class
silently. It is proven able to fail: a fixture hook requiring a compiled module without
the seam is flagged, and one that uses the seam is not. Verified directly — on the
unfixed tree it named all seven offenders; with the fix it passes.

While writing the lint's comment stripper, a naive whole-text block-comment regex ate its
own fixture, because this repo's comments legitimately spell the compiled-lib glob whose
star-slash reads as a comment opener. Rewritten as a line-based scanner with a regression
test pinning that case.

* fix(3582): test the three untested seam call sites and assert typed reason codes

Two independent reviews converged on the same major gap: the fix wired the seam into
seven files but only four had cold-tree tests. The adversarial pass put it plainly —
deleting the shared isolation-sentinel helper's seam call would not have failed any test
in the diff. That file was my own addition beyond the issue's four, so it shipped
untested; that is now closed.

- Shared isolation-sentinel helper: its seam call is only reached when .planning is NOT
  directly under cwd, and every existing cold-tree fixture puts it there, so the early
  return always fired first. Now covered, and proven load-bearing by mutation: with the
  call removed the spy records zero seam invocations and the test fails.
- update-check hook and update-banner hook: cold-tree tests added asserting the DEGRADED
  VERDICT — the fallback cache filename, and silent suppression when the package name
  degrades to null — rather than merely 'did not throw'. The banner hook previously had
  no test file at all.

Standards violation fixed: two tests asserted on free-form prose via assert.match against
a JSON reason string, which CONTRIBUTING bans by name — its own BAD example is exactly
that. The ESLint rule only covers readFileSync/spawnSync text, so tooling did not catch
it. Both isolation guards now emit a machine-readable reason_code from a frozen enum,
following the repo's existing REASON convention, and the tests assert that instead. The
human-readable message is unchanged for operators; only the assertion target moved.

The duplicated degrade boilerplate across the three cosmetic hooks was deliberately NOT
extracted, and the reason is recorded at each site: both viable shapes — a
path-parameterized helper, or a ceremony-only wrapper — defeat the drift lint's per-file
literal co-occurrence check, so extracting would require the lint to special-case its own
helper. Triplication is the lesser evil while the lint stays a co-occurrence scan.

The lint's header now states what it does and does not catch (literal quoted requires
only; hooks/ scan root), so a future reader does not over-trust a guard that a
concatenated path or a require inside a non-hooks helper would evade.

* chore(3582): regenerate the committed install-tree fixtures

Adding a new shipped hook helper changed the install tree, and those fixtures are
committed-and-derived (regen:derived / gen:install-tree), so 12 'install tree — <runtime>'
tests failed on 541a1913. Regenerated rather than hand-edited.

The delta across all 15 runtime fixtures is exactly two lines — the new helper under both
its hooks/ and gsd-hooks/ install paths — and nothing else, so the regeneration pulled in
no unrelated drift.

This is the bookkeeping ripple a new file under hooks/ carries; it was not visible from
lint:ci, which passed both before and after.

* chore(3582): backfill changeset PR number (#3629)

---------

Co-authored-by: sim <sim@local>
2026-08-18 14:11:23 -04:00

256 lines
10 KiB
JavaScript

'use strict';
/**
* Tests for `scripts/lint-hooks-runtime-build-seam.cjs` — the CI guard that
* every `hooks/**` file requiring a compiled `gsd-core/bin/lib/*.cjs` module
* must also self-heal via `ensureRuntimeBuild()` first (#3582).
*
* Mirrors the sibling `lint-*-drift.cjs` test convention (see e.g.
* `tests/lint-planning-artifact-writer-drift.test.cjs`): pure-function unit
* tests against in-memory strings for the fast cases, plus an on-disk
* fixture-tree test (via `scanRepo`) proving the guard genuinely detects a
* real violating file — "a ratchet that has never been proven to fail is
* worthless" (CLAUDE.md).
*/
const { test, describe } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {
scanFile,
scanRepo,
stripComments,
} = require('../scripts/lint-hooks-runtime-build-seam.cjs');
const { createTempDir, cleanup } = require('./helpers.cjs');
const REPO_ROOT = path.join(__dirname, '..');
// ─── Case 1: the guard passes clean against the REAL hooks/ tree ───────────
describe('scanRepo — real hooks/ tree', () => {
test('reports zero violations against the actual hooks/ tree', () => {
const violations = scanRepo(REPO_ROOT);
assert.deepStrictEqual(
violations,
[],
`unexpected hooks/ runtime-build-seam violation(s): ${JSON.stringify(violations, null, 2)}`,
);
});
test('the real tree has REAL compiled-lib requires (the detector is not silently inert)', () => {
// A detector that never matches anything would also report zero
// violations. Prove it actually found the six #3582 hook files' real
// gsd-core/bin/lib/*.cjs requires and confirmed each is seam-wired.
const hookFiles = [
'gsd-agent-isolation-guard.js',
'gsd-cursor-subagent-start.js',
'gsd-statusline.js',
'gsd-check-update-worker.js',
'gsd-check-update.js',
'gsd-update-banner.js',
];
for (const name of hookFiles) {
const text = fs.readFileSync(path.join(REPO_ROOT, 'hooks', name), 'utf8');
const { compiledLibRequires, hasSeamRequire, hasSeamCall } = scanFile(text);
assert.ok(compiledLibRequires.length > 0, `${name}: expected at least one compiled-lib require`);
assert.ok(hasSeamRequire, `${name}: expected a require of ensure-runtime-build.cjs`);
assert.ok(hasSeamCall, `${name}: expected an ensureRuntimeBuild(...) call`);
}
});
});
// ─── Case 2: pure-function unit tests (in-memory strings) ─────────────────
describe('scanFile — pure detection', () => {
test('a file with no compiled-lib require has nothing to check', () => {
const text = "'use strict';\nconst fs = require('fs');\nmodule.exports = {};\n";
const { compiledLibRequires } = scanFile(text);
assert.deepStrictEqual(compiledLibRequires, []);
});
test('a compiled-lib require with NO seam require/call is detected', () => {
const text = [
"'use strict';",
"const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');",
'module.exports = { runtimes };',
'',
].join('\n');
const { compiledLibRequires, hasSeamRequire, hasSeamCall } = scanFile(text);
assert.deepStrictEqual(compiledLibRequires, ['../gsd-core/bin/lib/capability-registry.cjs']);
assert.equal(hasSeamRequire, false);
assert.equal(hasSeamCall, false);
});
test('a compiled-lib require WITH a seam require + call is not flagged', () => {
const text = [
"'use strict';",
"const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');",
'function f() {',
' ensureRuntimeBuild();',
" const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');",
' return runtimes;',
'}',
'module.exports = { f };',
'',
].join('\n');
const { compiledLibRequires, hasSeamRequire, hasSeamCall } = scanFile(text);
assert.deepStrictEqual(compiledLibRequires, ['../gsd-core/bin/lib/capability-registry.cjs']);
assert.equal(hasSeamRequire, true);
assert.equal(hasSeamCall, true);
});
test('a seam REQUIRE with no CALL still counts as missing (import-only bypass)', () => {
const text = [
"'use strict';",
// Imported but never invoked — must not satisfy the guard.
"const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');",
"const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');",
'module.exports = { runtimes, ensureRuntimeBuild };',
'',
].join('\n');
const { hasSeamRequire, hasSeamCall } = scanFile(text);
assert.equal(hasSeamRequire, true);
assert.equal(hasSeamCall, false);
});
test('a real require() inside a // comment is NOT counted (comment-only mention)', () => {
const text = [
"'use strict';",
"// example: require('../gsd-core/bin/lib/capability-registry.cjs')",
"const fs = require('fs');",
'',
].join('\n');
const { compiledLibRequires } = scanFile(text);
assert.deepStrictEqual(compiledLibRequires, []);
});
// Regression: this repo's own hook comments legitimately spell the glob
// `gsd-core/bin/lib/*.cjs` inside a `//` line — a `/` immediately followed
// by `*` forms a bare `/*` token. A naive whole-text
// `/\*[\s\S]*?\*\//g` block-comment stripper reads that as an OPENING
// block comment and silently deletes everything up to the next unrelated
// `*/` later in the file — including real require() lines. Caught while
// authoring this guard (it ate its own seam require in
// hooks/gsd-agent-isolation-guard.js); locked here so it cannot regress.
test('a `//` comment containing a glob like lib/*.cjs does not swallow later real code', () => {
const text = [
"'use strict';",
'// gsd-core/bin/lib/*.cjs (foo.cjs, bar.cjs) are compiled artifacts.',
"const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');",
'function f() {',
' ensureRuntimeBuild();',
" const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');",
' return runtimes;',
'}',
'/* a real, later, unrelated block comment */',
'module.exports = { f };',
'',
].join('\n');
const stripped = stripComments(text);
assert.ok(
stripped.includes("require('../gsd-core/bin/ensure-runtime-build.cjs')"),
'the seam require must survive comment-stripping',
);
assert.ok(stripped.includes('ensureRuntimeBuild();'), 'the seam call must survive comment-stripping');
const { compiledLibRequires, hasSeamRequire, hasSeamCall } = scanFile(text);
assert.deepStrictEqual(compiledLibRequires, ['../gsd-core/bin/lib/capability-registry.cjs']);
assert.equal(hasSeamRequire, true);
assert.equal(hasSeamCall, true);
});
test('a genuine multi-line block comment is still stripped (no false-positive require inside it)', () => {
const text = [
"'use strict';",
'/**',
" * Example: require('../gsd-core/bin/lib/capability-registry.cjs') is",
' * mentioned here only as documentation prose.',
' */',
"const fs = require('fs');",
'',
].join('\n');
const { compiledLibRequires } = scanFile(text);
assert.deepStrictEqual(compiledLibRequires, []);
});
});
// ─── Case 3: on-disk fixture tree via scanRepo — proves the guard CAN fail ─
describe('scanRepo — on-disk fixture tree (proves the guard is not vacuous)', () => {
function writeFixtureTree(dir, { withSeam }) {
const hooksDir = path.join(dir, 'hooks');
fs.mkdirSync(hooksDir, { recursive: true });
const badLines = [
"'use strict';",
"const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');",
'module.exports = { runtimes };',
'',
];
fs.writeFileSync(path.join(hooksDir, 'bad-hook.js'), badLines.join('\n'));
const goodLines = withSeam
? [
"'use strict';",
"const { ensureRuntimeBuild } = require('../gsd-core/bin/ensure-runtime-build.cjs');",
'ensureRuntimeBuild();',
"const { runtimes } = require('../gsd-core/bin/lib/capability-registry.cjs');",
'module.exports = { runtimes };',
'',
]
: [
"'use strict';",
"const fs = require('fs');",
'module.exports = { fs };',
'',
];
fs.writeFileSync(path.join(hooksDir, 'good-hook.js'), goodLines.join('\n'));
// hooks/dist/ is the generated build-output copy — never scanned, even
// when it contains an identical un-sealed require.
const distDir = path.join(hooksDir, 'dist');
fs.mkdirSync(distDir, { recursive: true });
fs.writeFileSync(path.join(distDir, 'bad-hook.js'), badLines.join('\n'));
}
test('a fixture hook requiring a compiled module with NO seam is FLAGGED', (t) => {
const dir = createTempDir('gsd-lint-hooks-seam-');
t.after(() => cleanup(dir));
writeFixtureTree(dir, { withSeam: true });
const violations = scanRepo(dir);
const files = violations.map((v) => v.file);
assert.ok(files.includes('hooks/bad-hook.js'), `expected hooks/bad-hook.js flagged, got: ${JSON.stringify(files)}`);
assert.ok(
!files.includes('hooks/good-hook.js'),
`hooks/good-hook.js (seam-wired) must NOT be flagged, got: ${JSON.stringify(files)}`,
);
const bad = violations.find((v) => v.file === 'hooks/bad-hook.js');
assert.deepStrictEqual(bad.compiledLibRequires, ['../gsd-core/bin/lib/capability-registry.cjs']);
assert.ok(bad.missing.length > 0);
});
test('hooks/dist/ (generated build-output copy) is never scanned, even with the same violation', (t) => {
const dir = createTempDir('gsd-lint-hooks-seam-dist-');
t.after(() => cleanup(dir));
writeFixtureTree(dir, { withSeam: true });
const violations = scanRepo(dir);
const files = violations.map((v) => v.file);
assert.ok(
!files.some((f) => f.startsWith('hooks/dist/')),
`hooks/dist/ must be excluded from the scan, got: ${JSON.stringify(files)}`,
);
});
test('a fixture tree with NO offending hooks reports zero violations (no false positive)', (t) => {
const dir = createTempDir('gsd-lint-hooks-seam-clean-');
t.after(() => cleanup(dir));
writeFixtureTree(dir, { withSeam: false });
fs.unlinkSync(path.join(dir, 'hooks', 'bad-hook.js'));
const violations = scanRepo(dir);
assert.deepStrictEqual(violations, []);
});
});