Skip to content

Commit 01da41e

Browse files
committed
refactor(layering): register guard rules in a keyed table
Replaces the AST wiring guard with a construction that cannot express the defect, per review on #1746. The parser was the wrong instrument: it reconstructed one array's shape from TypeScript syntax, so it only recognised top-level function declarations and imports whose local name matched /^check[A-Z]/. A const-defined or aliased rule was invisible to it, a helper named checkX was a false positive, and naming and syntax became part of the interface — all to detect a mistake rather than prevent it. Rules now live in a keyed table over a shared context, executed once via Object.values. An object cannot hold a key twice, so double registration is unrepresentable rather than merely detected, and oxlint's no-dupe-keys rejects the attempt at the source. LayeringRuleId makes a missing key a type error, and LAYERING_RULE_IDS gives the catalog to check exhaustiveness against. Call sites and order are unchanged, so grouped output and the success line are byte-identical. One regression test remains, through the production interface: scripts/ is outside tsconfig.json's `include`, so the Record's exhaustiveness is an editor signal rather than a CI gate, and the catalog assertion is what fails the build when wiring goes missing. Verified by mutation: dropping an entry and registering an uncatalogued one both fail the test, a duplicated key fails oxlint, and re-planting the original contracts violation reports it exactly once. Net -133 LOC.
1 parent 390d13a commit 01da41e

3 files changed

Lines changed: 87 additions & 220 deletions

File tree

Lines changed: 11 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -1,93 +1,20 @@
11
// The seam bin-alias-fast-path.test.ts calls out as untested — "the check.ts wiring that turns it
2-
// into a violation" — checked directly: fixtures pin what each wiring mistake reports, and the last
3-
// test holds the real check.ts to the same rule.
2+
// into a violation." The registry makes duplicate registration unrepresentable on its own (an
3+
// object holds a key once, and oxlint's no-dupe-keys rejects the attempt), so what is left to check
4+
// is the other direction: that the catalog and the registry still describe the same set of rules.
5+
// scripts/ is outside tsconfig.json's `include`, so the Record's exhaustiveness is an editor
6+
// signal, not a CI gate — this test is what fails the build when wiring goes missing.
47

58
import assert from 'node:assert/strict';
6-
import { readFileSync } from 'node:fs';
7-
import path from 'node:path';
89
import { test } from 'node:test';
9-
import { fileURLToPath } from 'node:url';
10-
import { ruleWiringViolations } from './check-wiring.ts';
10+
import { LAYERING_RULE_IDS, LAYERING_RULES } from './check.ts';
1111

12-
const GUARD_FILE = path.join(fileURLToPath(new URL('.', import.meta.url)), 'check.ts');
13-
14-
/**
15-
* The shape of check.ts's rule wiring, minus everything the guard does not read: one imported rule
16-
* and one local rule, spread into main()'s violation list. Fixtures vary one thing against this
17-
* baseline, so a test's subject is the line it changed.
18-
*/
19-
function guardFixture(violationList: string, prelude = ''): string {
20-
return `
21-
import { checkPackageBoundaries } from './package-boundaries.ts';
22-
${prelude}
23-
function checkCycles(edges) {
24-
return [];
25-
}
26-
27-
export function main() {
28-
const violations = [
29-
${violationList}
30-
];
31-
return report(violations);
32-
}
33-
`;
34-
}
35-
36-
test('wiring each in-scope rule exactly once is clean', () => {
37-
const source = guardFixture(' ...checkCycles(edges),\n ...checkPackageBoundaries(root),');
38-
assert.deepEqual(ruleWiringViolations(source), []);
39-
});
40-
41-
test('a rule spread twice is named with its multiplier', () => {
42-
const source = guardFixture(
43-
' ...checkCycles(edges),\n' +
44-
' ...checkPackageBoundaries(root),\n' +
45-
' ...checkCycles(edges),',
46-
);
47-
assert.deepEqual(ruleWiringViolations(source), [
48-
"checkCycles is spread into main()'s violation list 2 times, so every finding it reports is " +
49-
'printed and ::error-annotated 2 times. Keep one.',
50-
]);
51-
});
52-
53-
test('a rule that is never spread is reported as silently unenforced', () => {
54-
const source = guardFixture(' ...checkCycles(edges),');
55-
assert.deepEqual(ruleWiringViolations(source), [
56-
"checkPackageBoundaries is in scope but never spread into main()'s violation list, so the " +
57-
'rule it owns is silently unenforced — the guard still prints OK. Wire it in, delete it, ' +
58-
'or rename it if it is a helper rather than a rule.',
59-
]);
12+
test('every catalogued rule is registered, and nothing else is', () => {
13+
assert.deepEqual(Object.keys(LAYERING_RULES), [...LAYERING_RULE_IDS]);
6014
});
6115

62-
test('an unwired rule is caught whether it is imported or declared here', () => {
63-
const source = guardFixture(' ...checkPackageBoundaries(root),', 'function checkNothing() {}');
64-
assert.deepEqual(
65-
ruleWiringViolations(source).map((message) => message.split(' ')[0]),
66-
['checkNothing', 'checkCycles'],
67-
);
68-
});
69-
70-
test('a type-only import carries no wiring obligation', () => {
71-
const source = guardFixture(
72-
' ...checkCycles(edges),\n ...checkPackageBoundaries(root),',
73-
"import type { checkShape } from './model.ts';",
74-
);
75-
assert.deepEqual(ruleWiringViolations(source), []);
76-
});
77-
78-
test('the guard fails closed when the violation list is not where it looks', () => {
79-
const renamedList = ruleWiringViolations(
80-
guardFixture(' ...checkCycles(edges),').replace('const violations', 'const findings'),
81-
);
82-
const renamedMain = ruleWiringViolations(
83-
guardFixture(' ...checkCycles(edges),').replace('function main', 'function run'),
84-
);
85-
for (const violations of [renamedList, renamedMain]) {
86-
assert.equal(violations.length, 1);
87-
assert.match(violations[0]!, /cannot read the rule list/);
16+
test('every registered rule is callable, so no entry is a stale reference', () => {
17+
for (const id of LAYERING_RULE_IDS) {
18+
assert.equal(typeof LAYERING_RULES[id], 'function', `${id} is not callable`);
8819
}
8920
});
90-
91-
test('check.ts wires every rule it has into main() exactly once', () => {
92-
assert.deepEqual(ruleWiringViolations(readFileSync(GUARD_FILE, 'utf8')), []);
93-
});

‎scripts/layering/check-wiring.ts‎

Lines changed: 0 additions & 112 deletions
This file was deleted.

‎scripts/layering/check.ts‎

Lines changed: 76 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,74 @@ function report(
646646
return 1;
647647
}
648648

649+
/** Everything the guard reads once per run, so a rule takes one argument whatever it needs. */
650+
export type LayeringContext = Readonly<{
651+
sourceFiles: readonly string[];
652+
sources: ReadonlyMap<string, string>;
653+
allTypeScriptSources: ReadonlyMap<string, string>;
654+
edges: readonly ResolvedImportEdge[];
655+
typeCycleMembers: readonly string[];
656+
}>;
657+
658+
export type LayeringRule = (context: LayeringContext) => LayeringViolation[];
659+
660+
/**
661+
* The rules this guard runs. Registering one is writing a key here, which is why the list is data
662+
* rather than a hand-written array of spreads: an object cannot hold the same key twice, so a rule
663+
* cannot be run — and reported, and ::error-annotated — twice by a copy-paste. `LayeringRuleId`
664+
* then makes a missing key a type error rather than a silently retired rule.
665+
*
666+
* Order is the reporting order: report() groups by rule in first-seen order.
667+
*/
668+
export const LAYERING_RULE_IDS = [
669+
'zone-policies',
670+
'value-import-cycles',
671+
'logs-runtime-cutover',
672+
'contracts-implementation-authority',
673+
'network-runtime-cutover',
674+
'record-runtime-cutover',
675+
'back-edges',
676+
'type-spine-inversions',
677+
'session-state-ownership',
678+
'daemon-modularity-ratchets',
679+
'zero-dep-job-closure',
680+
'bin-alias-fast-path',
681+
'package-boundaries',
682+
'platform-package-policy',
683+
'device-inventory-cutover',
684+
] as const;
685+
686+
export type LayeringRuleId = (typeof LAYERING_RULE_IDS)[number];
687+
688+
export const LAYERING_RULES: Readonly<Record<LayeringRuleId, LayeringRule>> = {
689+
'zone-policies': (context) => checkLayeringRules(context.edges),
690+
'value-import-cycles': (context) => checkCycles(context.edges),
691+
'logs-runtime-cutover': (context) => checkLogsRuntimeCutover(context.sources),
692+
'contracts-implementation-authority': (context) =>
693+
checkContractsImplementationAuthority(context.sources),
694+
'network-runtime-cutover': (context) => checkNetworkRuntimeCutover(context.sources),
695+
'record-runtime-cutover': (context) => checkRecordRuntimeCutover(context.sources),
696+
'back-edges': (context) => checkBackEdges(context.edges),
697+
'type-spine-inversions': (context) => checkTypeInversions(context.edges),
698+
'session-state-ownership': (context) => checkSessionStateOwnership(context.sources),
699+
'daemon-modularity-ratchets': (context) =>
700+
checkDaemonModularityRatchets(context.edges, context.typeCycleMembers),
701+
'zero-dep-job-closure': () => checkZeroDepJobs(),
702+
'bin-alias-fast-path': (context) => checkBinAliasFastPath(context.sources),
703+
'package-boundaries': () =>
704+
checkPackageBoundaries(
705+
repoRoot,
706+
zeroDepClosureFiles(repoZeroDepJobs(), readSourceOrNull, fileExists),
707+
),
708+
'platform-package-policy': (context) =>
709+
checkPlatformPackagePolicy(
710+
context.allTypeScriptSources,
711+
readTrackedPlatformPackageDeclarations(repoRoot),
712+
{ untrackedProductionFiles: listUntrackedProductionTypeScriptFiles(repoRoot) },
713+
),
714+
'device-inventory-cutover': (context) => checkDeviceInventoryCutover(context.sources),
715+
};
716+
649717
export function main(): number {
650718
const sourceFiles = listSourceFiles();
651719
const sources = readSources(sourceFiles);
@@ -654,30 +722,14 @@ export function main(): number {
654722
// Computed once and threaded: the rule and the success line must report the same number.
655723
const typeCycleMembers = largestTypeCycleMembers(edges);
656724
const typeCycle = typeCycleMembers.length;
657-
const violations = [
658-
...checkLayeringRules(edges),
659-
...checkCycles(edges),
660-
...checkLogsRuntimeCutover(sources),
661-
...checkContractsImplementationAuthority(sources),
662-
...checkNetworkRuntimeCutover(sources),
663-
...checkRecordRuntimeCutover(sources),
664-
...checkBackEdges(edges),
665-
...checkTypeInversions(edges),
666-
...checkSessionStateOwnership(sources),
667-
...checkDaemonModularityRatchets(edges, typeCycleMembers),
668-
...checkZeroDepJobs(),
669-
...checkBinAliasFastPath(sources),
670-
...checkPackageBoundaries(
671-
repoRoot,
672-
zeroDepClosureFiles(repoZeroDepJobs(), readSourceOrNull, fileExists),
673-
),
674-
...checkPlatformPackagePolicy(
675-
allTypeScriptSources,
676-
readTrackedPlatformPackageDeclarations(repoRoot),
677-
{ untrackedProductionFiles: listUntrackedProductionTypeScriptFiles(repoRoot) },
678-
),
679-
...checkDeviceInventoryCutover(sources),
680-
];
725+
const context: LayeringContext = {
726+
sourceFiles,
727+
sources,
728+
allTypeScriptSources,
729+
edges,
730+
typeCycleMembers,
731+
};
732+
const violations = Object.values(LAYERING_RULES).flatMap((rule) => rule(context));
681733
return report(sourceFiles, violations, typeCycle);
682734
}
683735

0 commit comments

Comments
 (0)