|
| 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)); |
0 commit comments