Skip to content

Commit 64b52a5

Browse files
committed
feat: enforce import-direction DAG (Phase-5 layering lint)
Generalize the inline CI "Layering Guard" grep into a structured import-direction lint (scripts/layering/check.ts) over the resolved import graph, per plans/perfect-shape.md §5.5. The full target DAG (kernel ◄ platforms ◄ core ◄ commands ◄ {cli, client, daemon/server}; client ◄ daemon/client) is only partly realized — the client/remote/metro extraction, the daemon/server split, and the utils dissolution are still pending Phase-5 moves, so the tree still holds legitimate back-edges (platforms→core, commands→cli, utils→*). Enforcing the whole DAG today would need a mass import rewrite that Phase 5 defers. The lint therefore enforces the three invariants the completed moves (kernel/, daemon/client/) already guarantee and that are green today: R1 kernel-sink — nothing under src/kernel/ imports another zone, except the one type-only kernel→contracts re-export. R2 commands-floor — nothing below the command surface (kernel, platforms, core, daemon) imports src/commands/. Generalizes the former guard (daemon + platforms). R3 platforms-seam — platforms/ is statically imported only at the core interactor seam (src/core/interactors/) and by the daemon server; elsewhere use a dynamic import() or a type-only import, preserving CLI cold-start. Dynamic import('../platforms/*') and `import type` stay allowed. Fixes the three pre-existing R3 violations by converting static platforms value imports to dynamic imports (all in already-async call sites, behavior-preserving and cold-start-improving): - src/client/client.ts debug.symbols → lazy symbolicateCrashArtifact - src/cli/commands/web.ts setup/doctor → lazy agent-browser-tool - src/core/dispatch-interactions.ts runner-sequence → lazy (matches the file's own dynamic-import pattern) Wire the check into the Layering Guard CI job and add a check:layering package.json script (also folded into check:tooling). scripts/layering/** is excluded from fallow (untested CI script, like scripts/perf/**).
1 parent 62b3eb5 commit 64b52a5

7 files changed

Lines changed: 276 additions & 36 deletions

File tree

‎.fallowrc.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"ignorePatterns": [
2828
"examples/test-app/**",
2929
"scripts/perf/**",
30+
"scripts/layering/**",
3031
"ios-runner/AgentDeviceRunner/AgentDeviceRunnerUITests.xctestplan",
3132
"scripts/write-xcuitest-cache-metadata.mjs"
3233
],

‎.github/workflows/ci.yml‎

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -96,24 +96,17 @@ jobs:
9696
- name: Checkout
9797
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
9898

99-
- name: Reject commands/ imports below the CLI surface layer
100-
run: |
101-
# daemon/ and platforms/ should not directly depend on the CLI commands layer.
102-
# This grep is a direct-import guard; deeper type-only transitive imports are handled
103-
# by keeping shared daemon/client contracts outside src/commands.
104-
set +e
105-
matches=$(git grep -n -E "from '.*commands/" -- src/daemon src/platforms ':!src/**/__tests__/**' ':!*.test.ts')
106-
grep_status=$?
107-
set -e
108-
if [ "$grep_status" -gt 1 ]; then
109-
exit "$grep_status"
110-
fi
111-
if [ -n "$matches" ]; then
112-
echo "$matches"
113-
count=$(printf '%s\n' "$matches" | wc -l)
114-
echo "::error title=Layering drift::$count import(s) of src/commands/* from src/daemon or src/platforms. Depend on shared contracts instead."
115-
exit 1
116-
fi
99+
- name: Setup toolchain
100+
uses: ./.github/actions/setup-node-pnpm
101+
with:
102+
install-deps: false
103+
104+
- name: Check import-direction DAG (kernel-sink, commands-floor, platforms-seam)
105+
# Generalizes the former inline commands/-import grep into a structured
106+
# import-direction lint over the resolved graph. See scripts/layering/check.ts
107+
# and plans/perfect-shape.md §5.5. Invoked directly (no deps needed) so the
108+
# job stays fast and does not require a pnpm install.
109+
run: node --experimental-strip-types scripts/layering/check.ts
117110

118111
fallow:
119112
name: Fallow Code Quality

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,12 @@
108108
"fallow:all": "fallow --summary",
109109
"fallow:baseline": "(fallow dead-code --save-baseline fallow-baselines/dead-code.json --summary || true) && (fallow health --save-baseline fallow-baselines/health.json --summary || true)",
110110
"check:fallow": "fallow audit",
111+
"check:layering": "node --experimental-strip-types scripts/layering/check.ts",
111112
"check:quick": "pnpm lint && pnpm typecheck",
112113
"sync:mcp-metadata": "node scripts/sync-mcp-metadata.mjs",
113114
"check:mcp-metadata": "node scripts/sync-mcp-metadata.mjs --check",
114115
"version": "node scripts/sync-mcp-metadata.mjs && git add server.json",
115-
"check:tooling": "pnpm lint && pnpm typecheck && pnpm check:mcp-metadata && pnpm build",
116+
"check:tooling": "pnpm lint && pnpm typecheck && pnpm check:layering && pnpm check:mcp-metadata && pnpm build",
116117
"check:unit": "pnpm test:unit && pnpm test:smoke",
117118
"check": "pnpm check:tooling && pnpm check:fallow && pnpm check:unit",
118119
"prepack": "pnpm check:mcp-metadata && pnpm build:all && pnpm package:android-snapshot-helper:npm && pnpm package:android-multitouch-helper:npm",

‎scripts/layering/check.ts‎

Lines changed: 249 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
// Import-direction lint — enforces the folder DAG established by the Phase-5
2+
// folder moves (see plans/perfect-shape.md §5.5).
3+
//
4+
// This generalizes the former inline "Layering Guard" CI grep (which only
5+
// checked that src/daemon and src/platforms do not import src/commands) into a
6+
// structured check over the resolved import graph.
7+
//
8+
// Target DAG (imports point DOWN, toward the kernel sink):
9+
// kernel ◄ platforms ◄ core ◄ commands ◄ { cli, client, daemon/server }
10+
// client ◄ daemon/client remote, metro ◄ daemon/client
11+
// sdk = re-export barrels only
12+
//
13+
// That full DAG is a *target*. Several Phase-5 folder moves are still pending
14+
// (the client/remote/metro extraction, the daemon/server split, and the utils
15+
// dissolution), so the tree still contains legitimate back-edges between
16+
// folders that have not yet been separated (e.g. platforms→core, commands→cli,
17+
// utils→*). Enforcing the whole DAG today would require a mass import rewrite,
18+
// which Phase 5 explicitly defers. This lint therefore enforces only the three
19+
// invariants that the *completed* moves (kernel/, daemon/client/) already
20+
// guarantee and that hold green today:
21+
//
22+
// R1 kernel is the dependency sink — nothing under src/kernel/ imports
23+
// another zone, except a type-only re-export from src/contracts/ (the one
24+
// documented kernel→contracts type seam).
25+
// R2 the command surface is a floor — nothing below it (kernel, platforms,
26+
// core, daemon) imports src/commands/. Generalizes the former guard,
27+
// which covered only daemon + platforms.
28+
// R3 platforms/ is statically imported only at the interactor seam
29+
// (src/core/interactors/) and by the daemon server (src/daemon/ minus
30+
// src/daemon/client/). Everywhere else must reach platforms via a dynamic
31+
// import() or a type-only import, which preserves CLI cold-start.
32+
//
33+
// Dynamic `import('../platforms/*')` and `import type` are always allowed by R3.
34+
//
35+
// Run: node --experimental-strip-types scripts/layering/check.ts
36+
37+
import { execFileSync } from 'node:child_process';
38+
import fs from 'node:fs';
39+
import path from 'node:path';
40+
41+
type ImportEdge = {
42+
spec: string;
43+
dynamic: boolean;
44+
typeOnly: boolean;
45+
line: number;
46+
};
47+
48+
type EdgeContext = {
49+
file: string;
50+
fromTop: string;
51+
toTop: string;
52+
imp: ImportEdge;
53+
};
54+
55+
type Violation = {
56+
rule: string;
57+
file: string;
58+
line: number;
59+
message: string;
60+
};
61+
62+
const repoRoot = execFileSync('git', ['rev-parse', '--show-toplevel'], {
63+
encoding: 'utf8',
64+
}).trim();
65+
66+
function listSourceFiles(): string[] {
67+
const out = execFileSync('git', ['ls-files', 'src/**/*.ts'], {
68+
cwd: repoRoot,
69+
encoding: 'utf8',
70+
});
71+
return out
72+
.split('\n')
73+
.filter(Boolean)
74+
.filter((f) => !/(?:^|\/)__tests__\//.test(f) && !/\.test\.ts$/.test(f));
75+
}
76+
77+
// The DAG node ("zone") a src-relative path belongs to: its first path segment
78+
// under src/, e.g. src/core/interactors/apple.ts → "core".
79+
function topFolder(rel: string): string {
80+
const match = /^src\/([^/]+)\//.exec(rel);
81+
return match ? match[1] : '(root)';
82+
}
83+
84+
function isCoreInteractor(rel: string): boolean {
85+
return rel.startsWith('src/core/interactors/');
86+
}
87+
88+
function isDaemonServer(rel: string): boolean {
89+
return rel.startsWith('src/daemon/') && !rel.startsWith('src/daemon/client/');
90+
}
91+
92+
// ── Import extraction ───────────────────────────────────────────────────────
93+
94+
function scanDynamicImports(line: string, lineNo: number): ImportEdge[] {
95+
const edges: ImportEdge[] = [];
96+
const re = /import\s*\(\s*['"]([^'"]+)['"]/g;
97+
let match: RegExpExecArray | null;
98+
while ((match = re.exec(line))) {
99+
edges.push({ spec: match[1]!, dynamic: true, typeOnly: false, line: lineNo });
100+
}
101+
return edges;
102+
}
103+
104+
function scanSideEffectImport(line: string, lineNo: number): ImportEdge | null {
105+
const match = /^\s*import\s+['"]([^'"]+)['"]/.exec(line);
106+
return match ? { spec: match[1]!, dynamic: false, typeOnly: false, line: lineNo } : null;
107+
}
108+
109+
// A `from '...'` clause on lines[i] (possibly the tail of a multi-line import).
110+
// Walk back to the statement start to read the import/export keyword and whether
111+
// it is a whole-statement `type` import.
112+
function scanFromImport(lines: string[], i: number): ImportEdge | null {
113+
const fromMatch = /(?:^|[\s;}])from\s+['"]([^'"]+)['"]/.exec(lines[i]!);
114+
if (!fromMatch) return null;
115+
116+
let start = i;
117+
while (start >= 0 && !/^\s*(?:import|export)\b/.test(lines[start]!)) {
118+
start--;
119+
}
120+
if (start < 0) return null;
121+
122+
const typeOnly = /^\s*(?:import|export)\s+type\b/.test(lines[start]!);
123+
return { spec: fromMatch[1]!, dynamic: false, typeOnly, line: start + 1 };
124+
}
125+
126+
function parseImports(source: string): ImportEdge[] {
127+
const lines = source.split('\n');
128+
const edges: ImportEdge[] = [];
129+
for (let i = 0; i < lines.length; i++) {
130+
edges.push(...scanDynamicImports(lines[i]!, i + 1));
131+
const sideEffect = scanSideEffectImport(lines[i]!, i + 1);
132+
if (sideEffect) {
133+
edges.push(sideEffect);
134+
continue;
135+
}
136+
const fromImport = scanFromImport(lines, i);
137+
if (fromImport) edges.push(fromImport);
138+
}
139+
return edges;
140+
}
141+
142+
function resolveTargetZone(fromFile: string, spec: string): string | null {
143+
if (!spec.startsWith('.')) return null; // bare / external specifier
144+
const resolved = path.normalize(path.join(path.dirname(fromFile), spec));
145+
if (!resolved.startsWith('src/')) return null; // escapes src/
146+
return resolved;
147+
}
148+
149+
// ── Rules ───────────────────────────────────────────────────────────────────
150+
151+
// R1 — kernel is the dependency sink.
152+
function ruleKernelSink(ctx: EdgeContext): Violation | null {
153+
if (ctx.fromTop !== 'kernel') return null;
154+
if (ctx.toTop === 'contracts' && ctx.imp.typeOnly) return null;
155+
return {
156+
rule: 'R1 kernel-sink',
157+
file: ctx.file,
158+
line: ctx.imp.line,
159+
message:
160+
`kernel must not import ${ctx.toTop}/ (imports '${ctx.imp.spec}'). ` +
161+
`The only allowed kernel out-edge is a type-only re-export from contracts/.`,
162+
};
163+
}
164+
165+
// R2 — the command surface is a floor.
166+
const BELOW_COMMANDS = new Set(['kernel', 'platforms', 'core', 'daemon']);
167+
function ruleCommandsFloor(ctx: EdgeContext): Violation | null {
168+
if (ctx.toTop !== 'commands' || !BELOW_COMMANDS.has(ctx.fromTop)) return null;
169+
return {
170+
rule: 'R2 commands-floor',
171+
file: ctx.file,
172+
line: ctx.imp.line,
173+
message:
174+
`${ctx.fromTop}/ must not import the command surface commands/ ` +
175+
`(imports '${ctx.imp.spec}'). Depend on shared kernel/contracts instead.`,
176+
};
177+
}
178+
179+
// R3 — platforms/ static value imports only at the interactor seam and the
180+
// daemon server; everywhere else use a dynamic import() or a type-only import.
181+
function rulePlatformsSeam(ctx: EdgeContext): Violation | null {
182+
if (ctx.toTop !== 'platforms' || ctx.imp.dynamic || ctx.imp.typeOnly) return null;
183+
if (isCoreInteractor(ctx.file) || isDaemonServer(ctx.file)) return null;
184+
return {
185+
rule: 'R3 platforms-seam',
186+
file: ctx.file,
187+
line: ctx.imp.line,
188+
message:
189+
`static value import of platforms/ from ${ctx.fromTop}/ (imports '${ctx.imp.spec}'). ` +
190+
`Only src/core/interactors/ and the daemon server may statically import platforms/; ` +
191+
`elsewhere use a dynamic import() or a type-only import to preserve CLI cold-start.`,
192+
};
193+
}
194+
195+
const RULES = [ruleKernelSink, ruleCommandsFloor, rulePlatformsSeam];
196+
197+
function checkFile(file: string): Violation[] {
198+
const source = fs.readFileSync(path.join(repoRoot, file), 'utf8');
199+
const fromTop = topFolder(file);
200+
const violations: Violation[] = [];
201+
for (const imp of parseImports(source)) {
202+
const target = resolveTargetZone(file, imp.spec);
203+
if (target === null) continue;
204+
const toTop = topFolder(target);
205+
if (toTop === fromTop) continue; // intra-zone imports are always fine
206+
const ctx: EdgeContext = { file, fromTop, toTop, imp };
207+
for (const rule of RULES) {
208+
const violation = rule(ctx);
209+
if (violation) violations.push(violation);
210+
}
211+
}
212+
return violations;
213+
}
214+
215+
// ── Report ──────────────────────────────────────────────────────────────────
216+
217+
function report(files: string[], violations: Violation[]): number {
218+
if (violations.length === 0) {
219+
process.stdout.write(
220+
`Layering guard: OK — ${files.length} source files satisfy the import-direction DAG ` +
221+
`(R1 kernel-sink, R2 commands-floor, R3 platforms-seam).\n`,
222+
);
223+
return 0;
224+
}
225+
226+
const byRule = new Map<string, Violation[]>();
227+
for (const v of violations) {
228+
const bucket = byRule.get(v.rule) ?? [];
229+
bucket.push(v);
230+
byRule.set(v.rule, bucket);
231+
}
232+
233+
process.stderr.write(`Layering guard: ${violations.length} import-direction violation(s)\n\n`);
234+
for (const [rule, group] of byRule) {
235+
process.stderr.write(` [${rule}] ${group.length} violation(s):\n`);
236+
for (const v of group) {
237+
process.stderr.write(` ${v.file}:${v.line} — ${v.message}\n`);
238+
process.stderr.write(
239+
`::error file=${v.file},line=${v.line},title=Layering drift (${v.rule})::${v.message}\n`,
240+
);
241+
}
242+
process.stderr.write('\n');
243+
}
244+
return 1;
245+
}
246+
247+
const sourceFiles = listSourceFiles();
248+
const allViolations = sourceFiles.flatMap(checkFile);
249+
process.exit(report(sourceFiles, allViolations));

‎src/cli/commands/web.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import {
2-
doctorManagedAgentBrowser,
3-
setupManagedAgentBrowser,
4-
type AgentBrowserToolStatus,
5-
} from '../../platforms/web/agent-browser-tool.ts';
1+
import type { AgentBrowserToolStatus } from '../../platforms/web/agent-browser-tool.ts';
62
import { AppError } from '../../kernel/errors.ts';
73
import type { CliFlags } from '../parser/cli-flags.ts';
84
import { printJson } from '../../utils/output.ts';
@@ -17,13 +13,17 @@ export async function runWebCommand(
1713
switch (action) {
1814
case 'setup': {
1915
printWebSetupStart(options.flags.json);
16+
const { setupManagedAgentBrowser } =
17+
await import('../../platforms/web/agent-browser-tool.ts');
2018
const status = await setupManagedAgentBrowser({
2119
stateDir: options.stateDir,
2220
});
2321
printWebSetupResult(options.flags.json, status);
2422
return 0;
2523
}
2624
case 'doctor': {
25+
const { doctorManagedAgentBrowser } =
26+
await import('../../platforms/web/agent-browser-tool.ts');
2727
const result = await doctorManagedAgentBrowser({
2828
stateDir: options.stateDir,
2929
});
@@ -44,10 +44,7 @@ function printWebSetupStart(json: boolean | undefined): void {
4444
process.stdout.write('Setting up managed agent-browser backend (downloads if needed)...\n');
4545
}
4646

47-
function printWebSetupResult(
48-
json: boolean | undefined,
49-
status: Awaited<ReturnType<typeof setupManagedAgentBrowser>>,
50-
): void {
47+
function printWebSetupResult(json: boolean | undefined, status: AgentBrowserToolStatus): void {
5148
if (json) {
5249
printJson({ success: true, data: { status: toPublicAgentBrowserToolStatus(status) } });
5350
return;

‎src/client/client.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { sendToDaemon } from '../daemon/client/daemon-client.ts';
22
import { prepareMetroRuntime, reloadMetro } from '../metro/client-metro.ts';
33
import { resolveDaemonPaths } from '../daemon/config.ts';
4-
import { symbolicateCrashArtifact } from '../platforms/apple/core/debug-symbols.ts';
54
import { INTERNAL_COMMANDS } from '../command-catalog.ts';
65
import {
76
prepareDaemonCommandRequest,
@@ -332,8 +331,11 @@ export function createAgentDeviceClient(
332331
network: async (options = {}) => await executeCommand('network', options),
333332
},
334333
debug: {
335-
symbols: async (options) =>
336-
await symbolicateCrashArtifact({ cwd: options.cwd ?? config.cwd, ...options }),
334+
symbols: async (options) => {
335+
const { symbolicateCrashArtifact } =
336+
await import('../platforms/apple/core/debug-symbols.ts');
337+
return symbolicateCrashArtifact({ cwd: options.cwd ?? config.cwd, ...options });
338+
},
337339
},
338340
recording: {
339341
record: async (options) => await executeCommand('record', options),

‎src/core/dispatch-interactions.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,6 @@ import {
4141
computeDeterministicJitter,
4242
runRepeatedSeries,
4343
} from './dispatch-series.ts';
44-
import {
45-
MAX_RUNNER_SEQUENCE_STEPS,
46-
buildRunnerSequenceCommand,
47-
parseRunnerSequenceResult,
48-
} from '../platforms/apple/core/runner/runner-sequence.ts';
4944
import type { RunnerSequenceStep } from '../platforms/apple/core/runner/runner-contract.ts';
5045
import type { DispatchContext } from './dispatch-context.ts';
5146
import type { Interactor, RunnerCallOptions } from './interactor-types.ts';
@@ -347,6 +342,8 @@ async function runIosSequenceChunks(
347342
context: DispatchContext | undefined,
348343
): Promise<Record<string, unknown>> {
349344
const { runIosRunnerCommand } = await import('../platforms/apple/core/runner/runner-client.ts');
345+
const { MAX_RUNNER_SEQUENCE_STEPS, buildRunnerSequenceCommand, parseRunnerSequenceResult } =
346+
await import('../platforms/apple/core/runner/runner-sequence.ts');
350347
const chunks = chunkRunnerSequenceStepsByBudget(steps, MAX_RUNNER_SEQUENCE_STEPS);
351348

352349
let firstChunkRunnerResult: Record<string, unknown> | undefined;

0 commit comments

Comments
 (0)