Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions docs/code-standards.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
51 changes: 51 additions & 0 deletions scripts/arch-boundaries.mjs
Original file line number Diff line number Diff line change
@@ -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`,
)
47 changes: 47 additions & 0 deletions scripts/lib/arch-boundaries.d.mts
Original file line number Diff line number Diff line change
@@ -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<string, number>
maxLines?: number
}): Violation[]
export function checkArchitecture(input: {
files: SourceFile[]
grandfather?: Record<string, number>
maxLines?: number
rules?: BoundaryRule[]
}): {
violations: Violation[]
checked: { files: number; imports: number; grandfathered: number }
}
208 changes: 208 additions & 0 deletions scripts/lib/arch-boundaries.mjs
Original file line number Diff line number Diff line change
@@ -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,
},
}
}
7 changes: 7 additions & 0 deletions scripts/lib/arch-grandfather.json
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading