Skip to content

Commit e53f083

Browse files
committed
fix(ci): install deps for the layering guard, and gate the zero-dep contract
The Layering Guard job failed with ERR_MODULE_NOT_FOUND on `oxc-parser`. The job ran with `install-deps: false` — no `pnpm install`, so no `node_modules` — and R7 had started parsing the daemon with oxc-parser instead of matching assignment operators with a regex. `pnpm check:layering` passed on every local run, because locally `node_modules` is always there. The job now installs dependencies. The alternative was to put R7 back on a regex, which cannot see `??=` or a computed `session[key] =` write, so it would trade a correct rule for a fast job. That leaves the interesting part: the zero-dep contract is real for the jobs that keep it, and it is invisible to every local run, which is the worst combination a constraint can have. R8 makes it checkable. It reads the zero-dep job list out of `.github/workflows/` rather than restating it — declaring a job zero-dep is what puts it under the rule — walks each job's entry scripts and their whole relative-import closure, and requires every specifier to be a Node builtin or another repo file. A zero-dep job whose entry scripts the scan cannot identify fails too, so the rule cannot be escaped by changing how the job invokes them. Specifiers come from oxc-parser's module record, not a line scan. The closures include `--test` files, and a test about imports naturally embeds import syntax in a fixture string; the line scanner reported two such phantom violations in model.test.ts before the switch, which is how a gate stops being trusted. Verified by re-running the real gate against three injected regressions: the layering job back on `install-deps: false` (reproduces the exact CI failure, pointing at session-state.ts:24), a package import added to the still-zero-dep affected-selector closure, and a zero-dep job whose run step names no script. Also corrects the CONTEXT.md spine paragraph, which still described the satellite zones as deliberately unranked after they had all joined the ranked spine. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Bfu8HofkhybiAm5LECfqur
1 parent 250570f commit e53f083

5 files changed

Lines changed: 412 additions & 18 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,16 +96,19 @@ jobs:
9696
- name: Checkout
9797
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
9898

99+
# This job used to run with install-deps: false, and R8 still holds every
100+
# remaining zero-dep job to that contract. The layering guard itself opted out
101+
# when R7 (SessionState ownership) started parsing the daemon with `oxc-parser`
102+
# instead of matching assignment operators with a regex: a regex cannot see
103+
# `??=` or a computed `session[key] =` write, so the choice was a real parser or
104+
# a rule with holes in it. Keep install-deps enabled.
99105
- name: Setup toolchain
100106
uses: ./.github/actions/setup-node-pnpm
101-
with:
102-
install-deps: false
103107

104108
- name: Check import-direction DAG
105109
# Generalizes the former inline commands/-import grep into a structured
106110
# import-direction lint over the resolved graph. See scripts/layering/check.ts
107-
# and CONTEXT.md (Architecture: folder DAG + layering lint). Invoked directly
108-
# (no deps needed) so the job stays fast and does not require a pnpm install.
111+
# and CONTEXT.md (Architecture: folder DAG + layering lint).
109112
run: |
110113
node --experimental-strip-types --test scripts/layering/model.test.ts
111114
node --experimental-strip-types scripts/layering/check.ts

‎CONTEXT.md‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -249,23 +249,25 @@ The perfect-shape refactor is complete and merged. Its end-state:
249249
hardware evidence validates discovery, lifecycle, and the complete remote-control contract.
250250
Vega capture, selector, inventory, install, logging, and performance backends remain separate
251251
follow-up surfaces.
252-
- Folder DAG + layering lint. `scripts/layering/check.ts` enforces four different scopes in CI.
252+
- Folder DAG + layering lint. `scripts/layering/check.ts` enforces five rules across four scopes in CI.
253253
GLOBALLY, across every production source file, it enforces the R1-R3 move rules (kernel-sink,
254254
commands-floor, platforms-seam) and rejects all production static value-import cycles. Separately,
255255
it ranks an explicit target spine — as rank groups, lowest (kernel sink) to highest, where `A ◄ B`
256256
means B may not be outranked by A (the back-edge order the gate rejects), NOT that every displayed
257257
import exists:
258-
`kernel ◄ { contracts, request, selectors, platforms, utils } ◄ core ◄ { commands, cli-schema } ◄ { client, daemon-server } ◄ daemon-client ◄ cli` —
259-
and rejects every back-edge within it. Root entrypoints and peripheral zones (`mcp`, `compat`,
260-
`remote`, `metro`, `replay`, `recording`, `snapshot`, `screenshot-diff`, `cloud-webdriver`, `sdk`)
261-
are deliberately unranked (`UNRANKED_ZONES` in `scripts/layering/model.ts`): they still
262-
obey R1-R4, but the gate asserts no total back-edge order over them. It is not a claim that every
263-
folder is arranged in one DAG. `model.test.ts` guards that no new zone escapes this classification
264-
silently. Thirdly, R6 ratchets the SAME inversion measured over TYPE-ONLY edges, which R5 ignores
265-
by design: a type-only import is free at runtime, but "zone A is declared in terms of zone B" is
266-
still a boundary claim, and ranking type edges surfaced 61 inversions the gate had never seen.
267-
`TYPE_INVERSION_BASELINE` in `check.ts` holds the remaining pairs with their counts; the numbers
268-
may only shrink, and a new pair fails outright.
258+
`kernel ◄ { contracts, request, selectors, platforms, utils, replay, recording, snapshot, screenshot-diff, cloud-webdriver } ◄ { core, providers } ◄ { commands, cli-schema, mcp } ◄ { client, daemon-server, compat, remote, metro, sdk } ◄ daemon-client ◄ cli` —
259+
and rejects every back-edge within it. Only `(root)` is unranked (`UNRANKED_ZONES` in
260+
`scripts/layering/model.ts`): it holds the entrypoints and the composition roots that wire the
261+
command surface into the daemon, and R2 forbids `daemon/` from importing `commands/`, so those
262+
files sit outside the spine by construction. The satellite zones used to be unranked too, on the
263+
grounds that ranking them would invent an order the architecture had not committed to; once
264+
`utils` joined the spine and `(root)` was emptied of shared contracts, every one of them turned
265+
out to have a consistent rank already. `model.test.ts` guards that no new zone escapes this
266+
classification silently. Thirdly, R6 ratchets the SAME inversion measured over TYPE-ONLY edges,
267+
which R5 ignores by design: a type-only import is free at runtime, but "zone A is declared in
268+
terms of zone B" is still a boundary claim, and ranking type edges surfaced 61 inversions the gate
269+
had never seen. `TYPE_INVERSION_BASELINE` in `check.ts` holds the remaining pairs with their
270+
counts; the numbers may only shrink, and a new pair fails outright.
269271
- SessionState ownership (R7). `SessionStore.get()` returns the live record out of a private Map
270272
and `set()` re-puts the same reference, so any `session.<field> = …` in the daemon is a durable
271273
write to store-owned state — persistence depends on aliasing, not on an API call. That is
@@ -276,6 +278,16 @@ The perfect-shape refactor is complete and merged. Its end-state:
276278
read out of the `SessionState` declaration, so a daemon module with an unrelated local named
277279
`session` cannot trip it. ADR 0014's ref frame is the worked example — its four fields moved
278280
together across two modules until `activateRefFrame` took the transition.
281+
- Zero-dep CI jobs (R8). Some jobs run scripts straight from a checkout with `install-deps: false`,
282+
so they have no `node_modules`. Nothing local can feel that constraint — every dev machine has
283+
`node_modules` sitting right there — so a script grows a package import, passes locally, and fails
284+
the runner on the resolve. R8 reads the zero-dep job list out of `.github/workflows/` (declaring a
285+
job zero-dep is what puts it under the rule; there is no second list to update), walks each job's
286+
entry scripts and their whole relative-import closure, and requires every specifier to be a Node
287+
builtin or another repo file. A zero-dep job whose entry scripts the scan cannot identify fails
288+
too, so the rule cannot be escaped by changing how the job invokes them. Specifiers come from
289+
`oxc-parser`'s module record rather than a line scan, because these closures include `--test`
290+
files whose fixtures legitimately contain import syntax inside strings.
279291
- Agent-cost. Responses carry a cost block and MCP `outputSchema`, rendered through a leveled
280292
`ResponseView`.
281293

‎scripts/layering/check.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77
// ◄ { client, daemon-server } ◄ daemon-client ◄ cli
88
// (authoritative ranks: `TARGET_DAG_RANK` in model.ts)
99
//
10-
// This gate enforces four things, across three scopes:
10+
// This gate enforces five things, across four scopes:
1111
// - GLOBALLY, across every production source file: the R1-R3 move rules and
1212
// rejection of all production static value-import cycles (R4).
1313
// - Over the RANKED SPINE only: rejection of every spine back-edge (R5), i.e.
1414
// an import whose source zone outranks its target zone, plus a ratchet on the
1515
// same inversion measured over TYPE-ONLY edges (R6).
1616
// - Over the DAEMON only: SessionState field ownership (R7), because the session
1717
// record is store-owned mutable state that any daemon module can write.
18+
// - Over the ZERO-DEP CI JOBS only: their scripts may import nothing that needs
19+
// installing (R8), a constraint no local run can feel because `node_modules` is
20+
// always there locally and never there in those jobs.
1821
// Only `(root)` is unranked (see `UNRANKED_ZONES` in model.ts): it holds the
1922
// entrypoints and the composition roots that wire the command surface into the
2023
// daemon, which R2 forbids the daemon from importing, so they sit outside the
@@ -29,6 +32,7 @@ import {
2932
sessionStateFields,
3033
SESSION_STATE_FIELD_OWNERS,
3134
} from './session-state.ts';
35+
import { uninstallableImports, zeroDepJobs } from './zero-dep-jobs.ts';
3236
import {
3337
backEdgePair,
3438
findValueImportCycles,
@@ -72,6 +76,14 @@ function readSources(files: readonly string[]): Map<string, string> {
7276
return new Map(files.map((file) => [file, fs.readFileSync(path.join(repoRoot, file), 'utf8')]));
7377
}
7478

79+
function fileExists(file: string): boolean {
80+
return fs.existsSync(path.join(repoRoot, file)) && fs.statSync(path.join(repoRoot, file)).isFile();
81+
}
82+
83+
function readSourceOrNull(file: string): string | null {
84+
return fileExists(file) ? fs.readFileSync(path.join(repoRoot, file), 'utf8') : null;
85+
}
86+
7587
function isProductionSourceFile(file: string): boolean {
7688
return file.endsWith('.ts') && !/(?:^|\/)__tests__\//.test(file) && !/\.test\.ts$/.test(file);
7789
}
@@ -339,14 +351,56 @@ function checkSessionStateOwnership(sources: ReadonlyMap<string, string>): Viola
339351
return violations;
340352
}
341353

354+
// R8: a CI job that runs with `install-deps: false` has no `node_modules`, so every script it
355+
// reaches must import only Node builtins and other repo files. Locally the opposite is true —
356+
// `node_modules` is always present — which is why this needs a gate rather than a convention.
357+
function checkZeroDepJobs(): Violation[] {
358+
const workflows = readSources(
359+
execFileSync('git', ['ls-files', '.github/workflows/*.yml'], { cwd: repoRoot, encoding: 'utf8' })
360+
.split('\n')
361+
.filter(Boolean),
362+
);
363+
364+
const violations: Violation[] = [];
365+
for (const job of zeroDepJobs(workflows, fileExists)) {
366+
// Fail closed: a zero-dep job whose commands the entry scan cannot recognize would
367+
// otherwise be silently exempt from the rule it is the whole reason for.
368+
if (job.entries.length === 0) {
369+
violations.push({
370+
rule: 'R8 zero-dep-job-closure',
371+
file: job.workflow,
372+
line: 1,
373+
message:
374+
`job '${job.job}' runs with install-deps: false but no entry script was found in its ` +
375+
`run steps, so its import closure cannot be checked. Invoke the script by path, or ` +
376+
`let the job install dependencies.`,
377+
});
378+
continue;
379+
}
380+
for (const bare of uninstallableImports(job, readSourceOrNull, fileExists)) {
381+
violations.push({
382+
rule: 'R8 zero-dep-job-closure',
383+
file: bare.file,
384+
line: bare.line,
385+
message:
386+
`'${bare.spec}' is a package, and job '${bare.job}' (${bare.workflow}) runs with ` +
387+
`install-deps: false — nothing installs it, so this resolves locally and fails in CI. ` +
388+
`Use a Node builtin, inline what you need, or drop install-deps: false from the job.`,
389+
});
390+
}
391+
}
392+
return violations;
393+
}
394+
342395
function report(files: readonly string[], violations: readonly Violation[]): number {
343396
if (violations.length === 0) {
344397
process.stdout.write(
345398
`Layering guard: OK — ${files.length} source files satisfy R1-R3 and contain no ` +
346399
`value-import cycles (both checked globally); the ranked target spine contains no ` +
347400
`back-edges (only the composition root is unranked), and its type-only ` +
348401
`inversions match the R6 ratchet (${Object.values(TYPE_INVERSION_BASELINE).reduce((sum, count) => sum + count, 0)} remaining); ` +
349-
`every SessionState write is inside its declared owner (R7).\n`,
402+
`every SessionState write is inside its declared owner (R7); and every zero-dep CI ` +
403+
`job resolves without node_modules (R8).\n`,
350404
);
351405
return 0;
352406
}
@@ -382,6 +436,7 @@ export function main(): number {
382436
...checkBackEdges(edges),
383437
...checkTypeInversions(edges),
384438
...checkSessionStateOwnership(sources),
439+
...checkZeroDepJobs(),
385440
];
386441
return report(sourceFiles, violations);
387442
}

‎scripts/layering/model.test.ts‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import assert from 'node:assert/strict';
2+
import { existsSync, readFileSync, statSync } from 'node:fs';
3+
import path from 'node:path';
24
import { test } from 'node:test';
35
import { listSourceFiles } from './check.ts';
46
import {
57
findSessionStateWrites,
68
sessionStateFields,
79
SESSION_STATE_FIELD_OWNERS,
810
} from './session-state.ts';
11+
import { uninstallableImports, zeroDepJobs } from './zero-dep-jobs.ts';
912
import {
1013
RANKED_ZONES,
1114
typeInversionPair,
@@ -273,3 +276,126 @@ test('every declared session-state owner is a real file path under src/daemon',
273276
assert.deepEqual([...owners], [...owners].sort(), `${field} owners must be sorted`);
274277
}
275278
});
279+
280+
// R8: the zero-dep CI job contract. These tests use synthetic workflows and a synthetic tree,
281+
// because the point of the rule is to catch a shape that does not exist in the repo yet.
282+
283+
const ZERO_DEP_WORKFLOW = `
284+
name: CI
285+
jobs:
286+
installs-deps:
287+
steps:
288+
- uses: ./.github/actions/setup-node-pnpm
289+
- run: node scripts/needs-packages/entry.ts
290+
zero-dep:
291+
steps:
292+
- uses: ./.github/actions/setup-node-pnpm
293+
with:
294+
install-deps: false
295+
- run: |
296+
node --experimental-strip-types --test scripts/probe/entry.test.ts
297+
node --experimental-strip-types scripts/probe/entry.ts
298+
`;
299+
300+
test('a zero-dep job is discovered from the workflow, and a dep-installing one is not', () => {
301+
const present = new Set(['scripts/probe/entry.ts', 'scripts/probe/entry.test.ts']);
302+
const jobs = zeroDepJobs(new Map([['.github/workflows/probe.yml', ZERO_DEP_WORKFLOW]]), (file) =>
303+
present.has(file),
304+
);
305+
assert.deepEqual(jobs, [
306+
{
307+
workflow: '.github/workflows/probe.yml',
308+
job: 'zero-dep',
309+
// Sorted, deduplicated, and filtered to paths that exist — `scripts/needs-packages`
310+
// belongs to the job that installs deps and must not leak in.
311+
entries: ['scripts/probe/entry.test.ts', 'scripts/probe/entry.ts'],
312+
},
313+
]);
314+
});
315+
316+
test('install-deps: false counts whether YAML parsed it as a boolean or a string', () => {
317+
const quoted = ZERO_DEP_WORKFLOW.replace('install-deps: false', "install-deps: 'false'");
318+
const jobs = zeroDepJobs(new Map([['w.yml', quoted]]), () => true);
319+
assert.deepEqual(
320+
jobs.map(({ job }) => job),
321+
['zero-dep'],
322+
);
323+
});
324+
325+
test('a job with no recognizable entry script is reported rather than exempted', () => {
326+
// Fail-closed: `entries: []` is what check.ts turns into a violation, so a job that
327+
// invokes its script in some way the scan cannot read never escapes the rule silently.
328+
const jobs = zeroDepJobs(new Map([['w.yml', ZERO_DEP_WORKFLOW]]), () => false);
329+
assert.deepEqual(jobs, [{ workflow: 'w.yml', job: 'zero-dep', entries: [] }]);
330+
});
331+
332+
test('a package import anywhere in a zero-dep closure is rejected, builtins are not', () => {
333+
const tree = new Map([
334+
[
335+
'scripts/probe/entry.ts',
336+
"import fs from 'node:fs';\nimport path from 'path';\nimport { helper } from './helper.ts';\n",
337+
],
338+
// One hop deeper than the entry: the failure that motivated R8 was exactly this shape —
339+
// the entry script itself imported nothing external, its helper did.
340+
['scripts/probe/helper.ts', "import { parseSync } from 'oxc-parser';\nimport './deep.js';\n"],
341+
['scripts/probe/deep.ts', "const lazy = await import('yaml');\n"],
342+
]);
343+
const found = uninstallableImports(
344+
{ workflow: 'w.yml', job: 'zero-dep', entries: ['scripts/probe/entry.ts'] },
345+
(file) => tree.get(file) ?? null,
346+
(file) => tree.has(file),
347+
);
348+
assert.deepEqual(
349+
found.map(({ file, spec }) => `${file}:${spec}`),
350+
// `node:fs` and bare `path` are builtins; `./helper.ts` and `./deep.js` resolve into the
351+
// tree (including the .js -> .ts rewrite); a dynamic package import fails just the same.
352+
['scripts/probe/deep.ts:yaml', 'scripts/probe/helper.ts:oxc-parser'],
353+
);
354+
});
355+
356+
test('an import written inside a string is not a package import', () => {
357+
// A zero-dep job runs test files, and a test about imports naturally embeds import syntax as
358+
// a fixture string. R8 parses instead of scanning lines precisely so those stay invisible —
359+
// this file itself contains such fixtures, and reported two phantom violations before the
360+
// switch. A type-only package import, by contrast, is still a resolve at runtime under
361+
// --experimental-strip-types only because the type is erased; it is listed to prove the
362+
// parser sees it, since erasure is a compiler detail and not something to lean on.
363+
const tree = new Map([
364+
[
365+
'scripts/probe/entry.ts',
366+
[
367+
'const fixture = "import real from \'not-a-package\'";',
368+
"const also = ['export { x } from \\'nope\\''];",
369+
"import type { T } from 'is-a-package';",
370+
'export type Alias = T;',
371+
].join('\n'),
372+
],
373+
]);
374+
const found = uninstallableImports(
375+
{ workflow: 'w.yml', job: 'zero-dep', entries: ['scripts/probe/entry.ts'] },
376+
(file) => tree.get(file) ?? null,
377+
(file) => tree.has(file),
378+
);
379+
assert.deepEqual(
380+
found.map(({ spec, line }) => `${line}:${spec}`),
381+
['3:is-a-package'],
382+
);
383+
});
384+
385+
test("the repo's own zero-dep jobs resolve without node_modules", () => {
386+
const repoRoot = path.resolve(import.meta.dirname, '../..');
387+
const read = (file: string): string | null => {
388+
const absolute = path.join(repoRoot, file);
389+
return existsSync(absolute) && statSync(absolute).isFile()
390+
? readFileSync(absolute, 'utf8')
391+
: null;
392+
};
393+
const exists = (file: string): boolean => read(file) !== null;
394+
395+
const jobs = zeroDepJobs(new Map([['.github/workflows/ci.yml', read('.github/workflows/ci.yml')!]]), exists);
396+
assert.ok(jobs.length > 0, 'expected ci.yml to still declare at least one zero-dep job');
397+
for (const job of jobs) {
398+
assert.ok(job.entries.length > 0, `${job.job} must name an entry script`);
399+
assert.deepEqual(uninstallableImports(job, read, exists), [], `${job.job} must reach no package`);
400+
}
401+
});

0 commit comments

Comments
 (0)