From 8ca3856d3ccf5fdb53131aa31e64a758df4ef96f Mon Sep 17 00:00:00 2001 From: HugoXK Date: Mon, 23 Nov 2026 13:18:42 +0800 Subject: [PATCH] test(arch): add import-boundary and file-size gates (#1228) --- .github/workflows/ci.yml | 2 + docs/code-standards.md | 15 +++ package.json | 1 + scripts/arch-boundaries.mjs | 51 ++++++++ scripts/lib/arch-boundaries.d.mts | 47 +++++++ scripts/lib/arch-boundaries.mjs | 208 ++++++++++++++++++++++++++++++ scripts/lib/arch-grandfather.json | 7 + test/archBoundaries.test.ts | 105 +++++++++++++++ 8 files changed, 436 insertions(+) create mode 100644 scripts/arch-boundaries.mjs create mode 100644 scripts/lib/arch-boundaries.d.mts create mode 100644 scripts/lib/arch-boundaries.mjs create mode 100644 scripts/lib/arch-grandfather.json create mode 100644 test/archBoundaries.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cfeafc58..b7f50e1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,6 +138,8 @@ jobs: # at a time with their own measured run (#646). - run: npm ci --ignore-scripts - run: npm run lint + - name: Architecture boundaries + run: npm run arch:check typecheck: name: typecheck diff --git a/docs/code-standards.md b/docs/code-standards.md index 9469a080..d2ea0049 100644 --- a/docs/code-standards.md +++ b/docs/code-standards.md @@ -37,6 +37,21 @@ not a conclusion. - Same-class reds tighten this file or LESSONS; do not paper over them with a special case. +## Architecture boundaries + +- `npm run arch:check` is a step in the `lint` CI job and a test in the suite. + It reads the tree, not the diff. +- A view may import `db` row types; it may not import the store. The store must + not import `app`, a view or a job. A job must not import a view. A view may + import only `src/jobs/continuity.ts` and `src/jobs/automationHealth.ts` from + the job layer; the job service and the bridge stay out of the view. +- A new source file is at most 1,200 lines. The five files that predate the limit + are recorded in `scripts/lib/arch-grandfather.json` at their current size; an + entry may not grow, and it must be deleted once the file is at or below 1,200 + lines. +- A type-only import is erased at build time and is allowed across a boundary; + the gate is about runtime coupling. + ## Silent catches - A `catch` that swallows an error says why in a comment inside the block, or diff --git a/package.json b/package.json index 70fb2442..fd7d4520 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,7 @@ "start": "node dist/index.js", "typecheck": "tsc --noEmit", "lint": "node scripts/lint-warnings.mjs src test scripts bridge", + "arch:check": "node scripts/arch-boundaries.mjs", "test": "tsx --test test/*.test.ts", "test:coverage": "tsx --test --experimental-test-coverage --test-coverage-lines=84 --test-coverage-include='src/**' test/*.test.ts", "coverage:diff": "node scripts/coverage-diff.mjs", diff --git a/scripts/arch-boundaries.mjs b/scripts/arch-boundaries.mjs new file mode 100644 index 00000000..7d00892f --- /dev/null +++ b/scripts/arch-boundaries.mjs @@ -0,0 +1,51 @@ +#!/usr/bin/env node +// Enforce the import-direction and file-size rules in `src/`. +// +// npm run arch:check +// +// Reads the tree, not a git diff: the gate is about the shape the next reader +// sees, not only the lines this pull request touched. + +import { existsSync, readFileSync, readdirSync } from 'node:fs' +import { join, relative } from 'node:path' +import { checkArchitecture } from './lib/arch-boundaries.mjs' + +function walk(dir, out = []) { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const absolute = join(dir, entry.name) + if (entry.isDirectory()) walk(absolute, out) + else if (entry.isFile() && entry.name.endsWith('.ts')) out.push(absolute) + } + return out +} + +const root = process.cwd() +const sourceRoot = join(root, 'src') +if (!existsSync(sourceRoot)) { + console.error(`arch: no src/ directory under ${root}`) + process.exit(1) +} + +const files = walk(sourceRoot) + .map((absolute) => ({ + path: relative(root, absolute).replaceAll('\\', '/'), + content: readFileSync(absolute, 'utf8'), + })) + .sort((left, right) => left.path.localeCompare(right.path)) + +const grandfatherPath = join(root, 'scripts/lib/arch-grandfather.json') +const grandfather = existsSync(grandfatherPath) + ? JSON.parse(readFileSync(grandfatherPath, 'utf8')) + : {} + +const result = checkArchitecture({ files, grandfather }) +for (const violation of result.violations) { + console.error(`${violation.file}:${String(violation.line)} ${violation.rule}: ${violation.reason}`) +} +if (result.violations.length > 0) { + console.error(`arch: ${String(result.violations.length)} violation(s)`) + process.exit(1) +} +console.log( + `arch: ${String(result.checked.files)} files, ${String(result.checked.imports)} imports, ${String(result.checked.grandfathered)} grandfathered`, +) diff --git a/scripts/lib/arch-boundaries.d.mts b/scripts/lib/arch-boundaries.d.mts new file mode 100644 index 00000000..feaa4bda --- /dev/null +++ b/scripts/lib/arch-boundaries.d.mts @@ -0,0 +1,47 @@ +export interface SourceFile { + path: string + content: string +} + +export interface Violation { + file: string + line: number + rule: string + reason: string +} + +export interface BoundaryRule { + id: string + from: RegExp + to: RegExp + runtimeOnly: boolean + allow?: string[] + reason: string +} + +export interface ParsedImport { + line: number + specifier: string + typeOnly: boolean +} + +export const MAX_FILE_LINES: number +export const DEFAULT_RULES: BoundaryRule[] + +export function parseImports(content: string): ParsedImport[] +export function checkImports(input: { files: SourceFile[]; rules?: BoundaryRule[] }): Violation[] +export function lineCount(content: string): number +export function checkFileSizes(input: { + files: SourceFile[] + grandfather?: Record + maxLines?: number +}): Violation[] +export function checkArchitecture(input: { + files: SourceFile[] + grandfather?: Record + maxLines?: number + rules?: BoundaryRule[] +}): { + violations: Violation[] + checked: { files: number; imports: number; grandfathered: number } +} diff --git a/scripts/lib/arch-boundaries.mjs b/scripts/lib/arch-boundaries.mjs new file mode 100644 index 00000000..1a01621c --- /dev/null +++ b/scripts/lib/arch-boundaries.mjs @@ -0,0 +1,208 @@ +// Import-direction and file-size gates for the source tree. +// +// The rules are intentionally small: they name the couplings that make a file +// impossible to review, not a full module system. Type-only imports are erased +// at build time and are allowed across a boundary; a runtime import is the +// coupling this gate refuses. +// +// The size rule is a ratchet. A file that predates the limit is recorded in +// `scripts/lib/arch-grandfather.json` at its current size and may not grow; once +// it is at or below the limit, its entry must be deleted. + +import { posix } from 'node:path' + +export const MAX_FILE_LINES = 1200 + +export const DEFAULT_RULES = [ + { + id: 'views-no-store', + from: /^src\/views\//, + to: /^src\/db(?:\.ts|\/)/, + runtimeOnly: true, + reason: 'a view may import db row types but not the store; pass data in through its page model', + }, + { + id: 'db-no-outer', + from: /^src\/db(?:\.ts|\/)/, + to: /^src\/(?:app\.ts$|views\/|jobs\/)/, + runtimeOnly: true, + reason: 'the store must not depend on the composition root, a view or a job', + }, + { + id: 'jobs-no-views', + from: /^src\/jobs\//, + to: /^src\/views\//, + runtimeOnly: true, + reason: 'a job must not render; it returns data and the view describes it', + }, + { + id: 'views-no-jobs-service', + from: /^src\/views\//, + to: /^src\/jobs\//, + runtimeOnly: true, + allow: ['src/jobs/continuity.ts', 'src/jobs/automationHealth.ts'], + reason: 'a view may use a pure presentation helper, not the job service or the bridge', + }, +] + +const STATIC_IMPORT = /(?:^|\n)[ \t]*(import|export)[ \t]+(type[ \t]+)?([\s\S]*?)\bfrom[ \t]*['"]([^'"]+)['"]/g +const SIDE_EFFECT_IMPORT = /(?:^|\n)[ \t]*import[ \t]*['"]([^'"]+)['"]/g +const DYNAMIC_IMPORT = /\b(?:import|require)[ \t]*\([ \t]*['"]([^'"]+)['"]/g + +function lineAt(text, index) { + let line = 1 + for (let position = 0; position < index; position += 1) { + if (text[position] === '\n') line += 1 + } + return line +} + +function keywordOffset(statement) { + const match = /\b(?:import|export)\b/.exec(statement) + return match === null ? 0 : match.index +} + +function allSpecifiersAreTypes(clause) { + const trimmed = clause.trim() + if (!trimmed.startsWith('{')) return false + const end = trimmed.lastIndexOf('}') + if (end === -1) return false + const parts = trimmed + .slice(1, end) + .split(',') + .map((part) => part.trim()) + .filter((part) => part !== '') + return parts.length > 0 && parts.every((part) => /^type\s+/.test(part)) +} + +export function parseImports(content) { + const imports = [] + const seen = new Set() + + for (const match of content.matchAll(STATIC_IMPORT)) { + const specifier = match[4] ?? '' + const prefix = match[2] ?? '' + const clause = match[3] ?? '' + const raw = match[0] ?? '' + const line = lineAt(content, (match.index ?? 0) + keywordOffset(raw)) + const key = `${String(line)}:${specifier}` + if (seen.has(key)) continue + seen.add(key) + imports.push({ line, specifier, typeOnly: prefix !== '' || allSpecifiersAreTypes(clause) }) + } + + for (const match of content.matchAll(SIDE_EFFECT_IMPORT)) { + const specifier = match[1] ?? '' + const raw = match[0] ?? '' + const line = lineAt(content, (match.index ?? 0) + keywordOffset(raw)) + const key = `${String(line)}:${specifier}` + if (seen.has(key)) continue + seen.add(key) + imports.push({ line, specifier, typeOnly: false }) + } + + for (const match of content.matchAll(DYNAMIC_IMPORT)) { + const specifier = match[1] ?? '' + const raw = match[0] ?? '' + const line = lineAt(content, (match.index ?? 0) + keywordOffset(raw)) + const key = `${String(line)}:${specifier}` + if (seen.has(key)) continue + seen.add(key) + imports.push({ line, specifier, typeOnly: false }) + } + + return imports.sort((left, right) => left.line - right.line) +} + +function resolveSpecifier(fromPath, specifier, known) { + if (!specifier.startsWith('.')) return null + const base = posix.normalize(posix.join(posix.dirname(fromPath), specifier)) + const candidates = [base] + if (base.endsWith('.js')) candidates.push(`${base.slice(0, -3)}.ts`) + if (base.endsWith('.mjs')) candidates.push(`${base.slice(0, -4)}.ts`) + if (posix.extname(base) === '') candidates.push(`${base}.ts`, `${base}/index.ts`) + const resolved = candidates.find((candidate) => known.has(candidate)) + if (resolved !== undefined) return resolved + // A file the caller did not include still has a conventional target. Judge it + // rather than silently ignoring a rule the path clearly crosses; the real + // gate reads every `src/` file, so this only affects a focused test. + if (base.endsWith('.js')) return `${base.slice(0, -3)}.ts` + if (base.endsWith('.mjs')) return `${base.slice(0, -4)}.ts` + return null +} + +export function checkImports({ files, rules = DEFAULT_RULES }) { + const known = new Set(files.map((file) => file.path)) + const violations = [] + for (const file of files) { + for (const parsed of parseImports(file.content)) { + const target = resolveSpecifier(file.path, parsed.specifier, known) + if (target === null) continue + for (const rule of rules) { + if (!rule.from.test(file.path) || !rule.to.test(target)) continue + if (Array.isArray(rule.allow) && rule.allow.includes(target)) continue + if (rule.runtimeOnly === true && parsed.typeOnly) continue + violations.push({ + file: file.path, + line: parsed.line, + rule: rule.id, + reason: rule.reason, + }) + } + } + } + return violations.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line) +} + +export function lineCount(content) { + if (content === '') return 0 + return content.split('\n').length - (content.endsWith('\n') ? 1 : 0) +} + +export function checkFileSizes({ files, grandfather = {}, maxLines = MAX_FILE_LINES }) { + const violations = [] + for (const file of files) { + const lines = lineCount(file.content) + if (Object.prototype.hasOwnProperty.call(grandfather, file.path)) { + const recorded = Number(grandfather[file.path]) + if (lines > recorded) { + violations.push({ + file: file.path, + line: 1, + rule: 'grandfathered-growth', + reason: `${String(lines)} lines, above its recorded ${String(recorded)}; split the file instead of raising the entry`, + }) + } else if (lines <= maxLines) { + violations.push({ + file: file.path, + line: 1, + rule: 'stale-grandfather', + reason: `${String(lines)} lines, at or below the ${String(maxLines)}-line limit; remove the entry from arch-grandfather.json`, + }) + } + continue + } + if (lines > maxLines) { + violations.push({ + file: file.path, + line: 1, + rule: 'file-too-large', + reason: `${String(lines)} lines, over the ${String(maxLines)}-line limit`, + }) + } + } + return violations.sort((left, right) => left.file.localeCompare(right.file)) +} + +export function checkArchitecture({ files, grandfather = {}, maxLines = MAX_FILE_LINES, rules = DEFAULT_RULES }) { + const imports = files.reduce((total, file) => total + parseImports(file.content).length, 0) + const violations = [...checkImports({ files, rules }), ...checkFileSizes({ files, grandfather, maxLines })] + return { + violations, + checked: { + files: files.length, + imports, + grandfathered: files.filter((file) => Object.prototype.hasOwnProperty.call(grandfather, file.path)).length, + }, + } +} diff --git a/scripts/lib/arch-grandfather.json b/scripts/lib/arch-grandfather.json new file mode 100644 index 00000000..9c190fa0 --- /dev/null +++ b/scripts/lib/arch-grandfather.json @@ -0,0 +1,7 @@ +{ + "src/app.ts": 7471, + "src/db.ts": 8722, + "src/jobs/service.ts": 5518, + "src/repos/github.ts": 1335, + "src/views/pages.ts": 6234 +} diff --git a/test/archBoundaries.test.ts b/test/archBoundaries.test.ts new file mode 100644 index 00000000..8cc187f2 --- /dev/null +++ b/test/archBoundaries.test.ts @@ -0,0 +1,105 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { checkArchitecture, checkFileSizes, checkImports } from '../scripts/lib/arch-boundaries.mjs' + +const ROOT = fileURLToPath(new URL('..', import.meta.url)) + +function files(...entries: Array<[string, string]>) { + return entries.map(([path, content]) => ({ path, content })) +} + +test('a view may import a db row type but not the store', () => { + assert.deepEqual( + checkImports({ files: files(['src/views/page.ts', "import type { JobRow } from '../db.js'\n"]) }), + [], + ) + const violations = checkImports({ files: files(['src/views/page.ts', "import { store } from '../db.js'\n"]) }) + assert.equal(violations.length, 1) + assert.equal(violations[0]?.rule, 'views-no-store') + assert.match(String(violations[0]?.reason), /row types/) +}) + +test('the store must not import the composition root, views or jobs', () => { + for (const target of ['src/app.ts', 'src/views/pages.ts', 'src/jobs/service.ts']) { + const specifier = `./${target.slice('src/'.length).replace(/\.ts$/, '.js')}` + const violations = checkImports({ files: files(['src/db.ts', `import { x } from '${specifier}'\n`]) }) + assert.equal(violations.length, 1, target) + assert.equal(violations[0]?.rule, 'db-no-outer') + } +}) + +test('jobs must not import views, and views may only use the allowed job helpers', () => { + const fromJobs = checkImports({ files: files(['src/jobs/x.ts', "import { page } from '../views/pages.js'\n"]) }) + assert.equal(fromJobs.length, 1) + assert.equal(fromJobs[0]?.rule, 'jobs-no-views') + + assert.deepEqual( + checkImports({ files: files(['src/views/x.ts', "import { carryOverHeaderText } from '../jobs/continuity.js'\n"]) }), + [], + ) + const fromService = checkImports({ files: files(['src/views/x.ts', "import { Jobs } from '../jobs/service.js'\n"]) }) + assert.equal(fromService.length, 1) + assert.equal(fromService[0]?.rule, 'views-no-jobs-service') +}) + +test('a type-only import from the job service is not runtime coupling', () => { + assert.deepEqual( + checkImports({ files: files(['src/views/x.ts', "import type { PlatformStopRecord } from '../jobs/service.js'\n"]) }), + [], + ) +}) + +test('external and unresolved imports are not judged', () => { + assert.deepEqual( + checkImports({ + files: files(['src/views/x.ts', "import { fastify } from 'fastify'\nimport { gone } from './not-there.js'\n"]), + }), + [], + ) +}) + +test('a new file over the line limit fails, and a grandfathered one may not grow', () => { + const body = (lines: number): string => 'x\n'.repeat(lines) + assert.deepEqual(checkFileSizes({ files: files(['src/new.ts', body(1200)]) }), []) + assert.equal(checkFileSizes({ files: files(['src/new.ts', body(1201)]) })[0]?.rule, 'file-too-large') + + assert.deepEqual( + checkFileSizes({ files: files(['src/db.ts', body(3)]), grandfather: { 'src/db.ts': 3 }, maxLines: 2 }), + [], + ) + assert.equal( + checkFileSizes({ files: files(['src/db.ts', body(4)]), grandfather: { 'src/db.ts': 3 }, maxLines: 2 })[0]?.rule, + 'grandfathered-growth', + ) +}) + +test('a grandfathered file at or below the limit must remove its entry', () => { + const stale = checkFileSizes({ files: files(['src/db.ts', 'x\n'.repeat(1200)]), grandfather: { 'src/db.ts': 1300 } }) + assert.equal(stale[0]?.rule, 'stale-grandfather') +}) + +test('a runtime import is found at the line that starts it', () => { + const violations = checkImports({ + files: files(['src/views/x.ts', "// header\n\nimport {\n store,\n} from '../db.js'\n"]), + }) + assert.equal(violations[0]?.line, 3) +}) + +test('the current tree passes the boundary and size gate', () => { + const run = spawnSync(process.execPath, ['scripts/arch-boundaries.mjs'], { cwd: ROOT, encoding: 'utf8' }) + assert.equal(run.status, 0, run.stderr || run.stdout) +}) + +test('checkArchitecture reports the sizes it checked', () => { + const result = checkArchitecture({ + files: files(['src/db.ts', 'x\n'.repeat(3)], ['src/app.ts', "import { x } from './db.js'\n"]), + grandfather: { 'src/db.ts': 3 }, + maxLines: 2, + }) + assert.deepEqual(result.violations, []) + assert.equal(result.checked.files, 2) + assert.equal(result.checked.imports, 1) + assert.equal(result.checked.grandfathered, 1) +})