Merge build/106-import-direction: imports:check enforces the package matrix, host-free Worker code and adapter subpaths
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents e30ceed, 328a649 · Browse files · 3 files·+1609 added−70 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+1609 added−70 removed
- tests:+520 added−0 removed
- other:+1089 added−70 removed
Provenance
- Commit
f6da76a- Tree
c507b14- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
e30ceed- Parent 2
328a649
3 files changed+1609 added−70 removed
added:packages/config/test/imports.test.ts+520 added
1+import { describe, expect, it } from "@effect/vitest";2+3+import {4+ findViolations,5+ formatViolation,6+ importsOf,7+ Matrix,8+} from "../../../scripts/lib/imports.ts";9+import type {10+ ImportRule,11+ SourceFile,12+ Workspace,13+} from "../../../scripts/lib/imports.ts";14+15+// Every package exports its modules by subpath, as `package.json`'s16+// `"./*": "./src/*.ts"` does.17+const bySubpath = { "./*": ["./src/*.ts"] };18+19+const workspace = (20+ name: string,21+ dir: string,22+ dependencies: readonly string[]23+): Workspace => ({ dependencies, dir, exports: bySubpath, name });24+25+/** The tree's workspaces, shaped like the repo's. */26+const workspaces: readonly Workspace[] = [27+ {28+ dependencies: ["@repo/brand", "@repo/protocol"],29+ dir: "",30+ name: "@repo/root",31+ },32+ workspace("@repo/brand", "packages/brand", ["@repo/config"]),33+ workspace("@repo/config", "packages/config", []),34+ workspace("@repo/protocol", "packages/protocol", [35+ "@repo/brand",36+ "@repo/config",37+ ]),38+ workspace("@repo/sdk", "packages/sdk", ["@repo/brand", "@repo/protocol"]),39+ workspace("@repo/checks", "packages/checks", [40+ "@repo/brand",41+ "@repo/protocol",42+ ]),43+ // `@repo/project` is declared, so only the matrix can refuse the edge.44+ workspace("@repo/gate", "packages/gate", [45+ "@repo/checks",46+ "@repo/project",47+ "@repo/protocol",48+ ]),49+ workspace("@repo/artifacts", "packages/artifacts", ["@repo/protocol"]),50+ // `@repo/brand` is left out: the matrix allows it, the manifest doesn't.51+ workspace("@repo/git", "packages/git", [52+ "@repo/artifacts",53+ "@repo/config",54+ "@repo/protocol",55+ ]),56+ workspace("@repo/project", "packages/project", ["@repo/protocol"]),57+ workspace("@repo/testkit", "packages/testkit", ["@repo/protocol"]),58+ workspace("@repo/platform", "apps/platform", [59+ "@repo/brand",60+ "@repo/checks",61+ "@repo/protocol",62+ ]),63+ workspace("@repo/web", "apps/web", ["@repo/brand", "@repo/protocol"]),64+ workspace("@repo/cli", "apps/cli", [65+ "@repo/checks",66+ "@repo/config",67+ "@repo/protocol",68+ "@repo/testkit",69+ ]),70+];71+72+const file = (path: string, ...lines: readonly string[]): SourceFile => ({73+ content: lines.join("\n"),74+ path,75+});76+77+/** A tree that keeps every rule: each case below plants one fault in it. */78+const clean: readonly SourceFile[] = [79+ file(80+ "apps/platform/src/worker.ts",81+ 'import { Contracts } from "@repo/protocol/contracts";',82+ 'import { isJudged } from "@repo/checks/judge";',83+ 'import { Buffer } from "node:buffer";',84+ 'import { serve } from "./surfaces.ts";'85+ ),86+ file("apps/platform/src/surfaces.ts", 'import { Brand } from "@repo/brand";'),87+ file(88+ "apps/cli/src/main.ts",89+ 'import { CheckRunnerLocal } from "@repo/checks/check-runner/local";'90+ ),91+ file(92+ "apps/cli/test/stdio.ts",93+ 'import { asTester } from "@repo/protocol/testing";',94+ 'import { aProject } from "@repo/testkit/scenario";',95+ 'import { NodeServices } from "@effect/platform-node";'96+ ),97+ file(98+ "packages/protocol/src/contracts.ts",99+ 'import { AskId } from "./ids.ts";'100+ ),101+ file("packages/protocol/src/ids.ts", 'import { Schema } from "effect";'),102+ file(103+ "packages/protocol/src/testing.ts",104+ 'import { Handle } from "./ids.ts";'105+ ),106+ // Test-only itself: its consumers are tests.107+ file(108+ "packages/testkit/src/scenario.ts",109+ 'export { asTester } from "@repo/protocol/testing";'110+ ),111+ file(112+ "packages/protocol/test/examples.ts",113+ 'import { AskId } from "@repo/protocol/ids";',114+ 'export { asTester } from "../src/testing.ts";'115+ ),116+ file(117+ "packages/sdk/src/kinds.ts",118+ 'import { Ask } from "@repo/protocol/domain/ask";'119+ ),120+ file(121+ "packages/checks/src/judge.ts",122+ 'import type { RepoPath } from "@repo/protocol/ids";'123+ ),124+ file(125+ "packages/checks/src/check-runner.ts",126+ 'import { Context } from "effect";'127+ ),128+ file(129+ "packages/checks/src/check-runner/local.ts",130+ 'import { BunServices } from "@effect/platform-bun";',131+ 'import { CheckRunner } from "../check-runner.ts";'132+ ),133+ file(134+ "packages/gate/src/shape.ts",135+ 'import { matchGlob } from "@repo/checks/judge";'136+ ),137+ file(138+ "packages/artifacts/src/repo-host.ts",139+ 'import { CommitSha } from "@repo/protocol/ids";'140+ ),141+ file(142+ "packages/artifacts/src/repo-host/memory.ts",143+ 'import { RepoHost } from "../repo-host.ts";',144+ 'import { memoryFs } from "./memory-fs.ts";'145+ ),146+ file("packages/artifacts/src/repo-host/memory-fs.ts"),147+ // A file in a port's folder that isn't an adapter.148+ file(149+ "packages/project/src/lander.ts",150+ 'export { LandWire } from "./lander/wire.ts";'151+ ),152+ file("packages/project/src/lander/wire.ts"),153+ file(154+ "packages/git/test/git.ts",155+ 'import { spawn } from "node:child_process";'156+ ),157+ file(158+ "packages/git/vitest.config.ts",159+ 'export { preset as default } from "@repo/config/vitest";'160+ ),161+ // Config's tests drive the root's fence: its scripts, tools and config.162+ file(163+ "packages/config/test/imports.test.ts",164+ 'import { findViolations } from "../../../scripts/lib/imports.ts";',165+ 'import oxlintConfig from "../../../oxlint.config.ts";'166+ ),167+ file("scripts/gen.ts", 'import { groups } from "@repo/protocol/refusal";'),168+ file("infra/deploy.ts", 'import alchemy from "alchemy";'),169+];170+171+/** The clean tree with `planted` added, each replacing a file at its path. */172+const plant = (...planted: readonly SourceFile[]) => [173+ ...clean.filter((kept) => planted.every((other) => other.path !== kept.path)),174+ ...planted,175+];176+177+interface Case {178+ readonly name: string;179+ readonly planted: readonly SourceFile[];180+ readonly path: string;181+ readonly specifier: string;182+ readonly rule: ImportRule;183+}184+185+const refused = (186+ name: string,187+ rule: ImportRule,188+ planted: SourceFile,189+ specifier: string190+): Case => ({ name, path: planted.path, planted: [planted], rule, specifier });191+192+describe("import direction", () => {193+ it("passes a tree that keeps every rule", () => {194+ expect(findViolations(clean, workspaces)).toStrictEqual([]);195+ });196+197+ it.each<Case>([198+ refused(199+ "an app imports an app",200+ "app-imports-app",201+ file("apps/web/src/x.ts", 'import { platform } from "@repo/platform";'),202+ "@repo/platform"203+ ),204+ refused(205+ "an app imports an app by a type-only import",206+ "app-imports-app",207+ file(208+ "apps/web/src/x.ts",209+ 'import type { Services } from "@repo/platform/surfaces";'210+ ),211+ "@repo/platform/surfaces"212+ ),213+ refused(214+ "Worker code imports a host builtin",215+ "worker-host",216+ file(217+ "apps/platform/src/x.ts",218+ 'import { spawn } from "node:child_process";'219+ ),220+ "node:child_process"221+ ),222+ refused(223+ "Worker code imports a node builtin nodejs_compat doesn't serve",224+ "worker-host",225+ file("apps/platform/src/x.ts", 'import { readFile } from "node:fs";'),226+ "node:fs"227+ ),228+ refused(229+ "Worker code imports OpenTUI",230+ "worker-host",231+ file("apps/web/src/x.ts", 'import { render } from "@opentui/react";'),232+ "@opentui/react"233+ ),234+ refused(235+ "a package imports host code outside a /local or /bun adapter",236+ "worker-host",237+ file(238+ "packages/checks/src/finder.ts",239+ 'import { spawn } from "node:child_process";'240+ ),241+ "node:child_process"242+ ),243+ refused(244+ "a port imports its adapter",245+ "adapter-through-port",246+ file(247+ "packages/artifacts/src/repo-host.ts",248+ 'import { RepoHostMemory } from "./repo-host/memory.ts";'249+ ),250+ "./repo-host/memory.ts"251+ ),252+ refused(253+ "a port re-exports its adapter",254+ "adapter-through-port",255+ file(256+ "packages/artifacts/src/repo-host.ts",257+ 'export * from "./repo-host/memory.ts";'258+ ),259+ "./repo-host/memory.ts"260+ ),261+ refused(262+ "a port re-exports an adapter that runs in process",263+ "adapter-through-port",264+ file(265+ "packages/project/src/answer-runs.ts",266+ 'export { AnswerRunsInline } from "./answer-runs/inline.ts";'267+ ),268+ "./answer-runs/inline.ts"269+ ),270+ refused(271+ "a package reaches the root's scripts by a relative path",272+ "adapter-through-port",273+ file(274+ "packages/gate/src/x.ts",275+ 'import { findViolations } from "../../../scripts/lib/imports.ts";'276+ ),277+ "../../../scripts/lib/imports.ts"278+ ),279+ refused(280+ "a file reaches into another package by a relative path",281+ "adapter-through-port",282+ file(283+ "apps/cli/src/x.ts",284+ 'import { AskId } from "../../../packages/protocol/src/ids.ts";'285+ ),286+ "../../../packages/protocol/src/ids.ts"287+ ),288+ refused(289+ "gate imports project",290+ "matrix",291+ file(292+ "packages/gate/src/x.ts",293+ 'import { Project } from "@repo/project";'294+ ),295+ "@repo/project"296+ ),297+ refused(298+ "gate imports a checks subpath that runs processes",299+ "matrix",300+ file(301+ "packages/gate/src/x.ts",302+ 'import { CheckRunnerLocal } from "@repo/checks/check-runner/local";'303+ ),304+ "@repo/checks/check-runner/local"305+ ),306+ refused(307+ "a package's src imports the test config",308+ "matrix",309+ file(310+ "packages/brand/src/x.ts",311+ 'import { preset } from "@repo/config/vitest";'312+ ),313+ "@repo/config/vitest"314+ ),315+ refused(316+ "sdk imports protocol outside domain/*",317+ "matrix",318+ file(319+ "packages/sdk/src/x.ts",320+ 'import { Contracts } from "@repo/protocol/contracts";'321+ ),322+ "@repo/protocol/contracts"323+ ),324+ refused(325+ "a package imports a workspace its package.json doesn't declare",326+ "undeclared",327+ file("packages/git/src/x.ts", 'import { Brand } from "@repo/brand";'),328+ "@repo/brand"329+ ),330+ refused(331+ "a script imports a workspace the root doesn't declare",332+ "undeclared",333+ file("scripts/x.ts", 'import { gate } from "@repo/gate";'),334+ "@repo/gate"335+ ),336+ refused(337+ "src imports the test principal",338+ "test-only",339+ file(340+ "packages/git/src/x.ts",341+ 'import { asTester } from "@repo/protocol/testing";'342+ ),343+ "@repo/protocol/testing"344+ ),345+ refused(346+ "protocol's own src imports the test principal by a relative path",347+ "test-only",348+ file(349+ "packages/protocol/src/x.ts",350+ 'import { asTester } from "./testing.ts";'351+ ),352+ "./testing.ts"353+ ),354+ refused(355+ "src imports testkit",356+ "test-only",357+ file(358+ "apps/cli/src/x.ts",359+ 'import { aProject } from "@repo/testkit/scenario";'360+ ),361+ "@repo/testkit/scenario"362+ ),363+ refused(364+ "a script imports alchemy",365+ "infra-only",366+ file("scripts/x.ts", 'import alchemy from "alchemy/cloudflare";'),367+ "alchemy/cloudflare"368+ ),369+ ])("refuses $name as $rule", ({ path, planted, rule, specifier }) => {370+ expect(findViolations(plant(...planted), workspaces)).toStrictEqual([371+ { line: 1, path, rule, specifier },372+ ]);373+ });374+375+ it("refuses Worker code that reaches host code through a package, and names the chain", () => {376+ const violations = findViolations(377+ plant(378+ file(379+ "apps/platform/src/x.ts",380+ 'import { Schema } from "effect";',381+ 'import { CheckRunnerLocal } from "@repo/checks/check-runner/local";'382+ )383+ ),384+ workspaces385+ );386+387+ expect(violations).toStrictEqual([388+ {389+ line: 2,390+ path: "apps/platform/src/x.ts",391+ rule: "worker-host",392+ specifier: "@repo/checks/check-runner/local",393+ via: [394+ "packages/checks/src/check-runner/local.ts",395+ "@effect/platform-bun",396+ ],397+ },398+ ]);399+ expect(violations.map(formatViolation)).toStrictEqual([400+ "apps/platform/src/x.ts:2: worker-host: @repo/checks/check-runner/local → packages/checks/src/check-runner/local.ts → @effect/platform-bun",401+ ]);402+ });403+404+ it("follows relative imports out of Worker code, and reports each fault once", () => {405+ expect(406+ findViolations(407+ plant(408+ file("apps/platform/src/a.ts", 'import { b } from "./b.ts";'),409+ file(410+ "apps/platform/src/b.ts",411+ 'import { harness } from "../test/harness.ts";'412+ ),413+ file(414+ "apps/platform/test/harness.ts",415+ 'import { NodeServices } from "@effect/platform-node";'416+ )417+ ),418+ workspaces419+ )420+ ).toStrictEqual([421+ {422+ line: 1,423+ path: "apps/platform/src/b.ts",424+ rule: "worker-host",425+ specifier: "../test/harness.ts",426+ via: ["apps/platform/test/harness.ts", "@effect/platform-node"],427+ },428+ ]);429+ });430+431+ it("reports the first rule an import breaks, and only that one", () => {432+ // Undeclared, off the matrix and an app: the app rule comes first.433+ expect(434+ findViolations(435+ plant(436+ file(437+ "apps/platform/src/x.ts",438+ 'import { mcp } from "@repo/cli/surfaces";'439+ )440+ ),441+ workspaces442+ ).map((violation) => violation.rule)443+ ).toStrictEqual(["app-imports-app"]);444+ });445+446+ it("lists every row of the import matrix, absent packages included", () => {447+ expect(Object.keys(Matrix).toSorted()).toStrictEqual([448+ "@repo/agent-kit",449+ "@repo/artifacts",450+ "@repo/brand",451+ "@repo/checks",452+ "@repo/cli",453+ "@repo/gate",454+ "@repo/git",455+ "@repo/platform",456+ "@repo/project",457+ "@repo/protocol",458+ "@repo/rules",459+ "@repo/sandbox",460+ "@repo/sdk",461+ "@repo/testkit",462+ "@repo/visibility",463+ "@repo/web",464+ ]);465+ expect(Matrix["@repo/gate"]).toStrictEqual([466+ "@repo/checks",467+ "@repo/protocol",468+ ]);469+ expect(Matrix["@repo/brand"]).toStrictEqual([]);470+ });471+});472+473+describe("reading imports", () => {474+ it("reads every import form, type-only ones too, with its line", () => {475+ const content = [476+ 'import { Effect } from "effect";',477+ 'import type { Ask } from "@repo/protocol/domain/ask";',478+ "import {",479+ " a,",480+ " b,",481+ '} from "./multi.ts";',482+ 'export { c } from "./c.ts";',483+ 'export type { D } from "./d.ts";',484+ 'export * as e from "./e.ts";',485+ 'import "./side-effect.ts";',486+ 'const later = await import("./later.ts");',487+ 'type Worker = typeof import("./worker.ts");',488+ ].join("\n");489+490+ expect(importsOf({ content, path: "packages/x/src/a.ts" })).toStrictEqual([491+ { line: 1, specifier: "effect", typeOnly: false },492+ { line: 2, specifier: "@repo/protocol/domain/ask", typeOnly: true },493+ { line: 6, specifier: "./multi.ts", typeOnly: false },494+ { line: 7, specifier: "./c.ts", typeOnly: false },495+ { line: 8, specifier: "./d.ts", typeOnly: true },496+ { line: 9, specifier: "./e.ts", typeOnly: false },497+ { line: 10, specifier: "./side-effect.ts", typeOnly: false },498+ { line: 11, specifier: "./later.ts", typeOnly: false },499+ { line: 12, specifier: "./worker.ts", typeOnly: true },500+ ]);501+ });502+503+ it("skips import syntax inside strings, templates, regexes and comments", () => {504+ const content = [505+ '// import { x } from "@repo/cli";',506+ "/* export * from '@repo/cli';",507+ ' import("@repo/cli") */',508+ "const quoted = 'import { mcp } from \"@repo/cli/surfaces\";';",509+ "const doubled = \"export { a } from '@repo/cli'\";",510+ // A template, with a template inside its `${…}`.511+ `const template = \`import { b } from "@repo/cli" \${\`import("@repo/cli")\`}\`;`,512+ 'const pattern = /["\']import\\("@repo\\/cli"\\)/u;',513+ 'import { real } from "./real.ts";',514+ ].join("\n");515+516+ expect(importsOf({ content, path: "packages/x/src/a.ts" })).toStrictEqual([517+ { line: 8, specifier: "./real.ts", typeOnly: false },518+ ]);519+ });520+});modified:scripts/lib/imports.ts+1007 added-43 removed
1 /**2- * Import direction's pure core: which imports cross a line the workspace3- * graph forbids. `scripts/imports.ts` feeds it the committable TypeScript4- * files and the workspaces; tests feed it fixture files.2+ * Import direction's pure core: which imports cross a line AGENTS.md3+ * principle 6 draws. `scripts/imports.ts` feeds it the committable TypeScript4+ * files and the workspaces; tests feed it fixture trees.5 *6- * The first rule: apps never import apps (AGENTS.md principle 6).6+ * The rules, in order. An import reports the first one it breaks:7+ *8+ * 1. `app-imports-app`: apps never import apps, by name or by path.9+ * 2. `undeclared`: a workspace imports only the `@repo/*` packages its10+ * `package.json` lists. The root's `scripts/` and `infra/` are the root's.11+ * 3. `matrix`: a workspace imports only the packages its `Matrix` row names12+ * (and only the subpaths `OnlySubpaths` names, where it names any).13+ * 4. `adapter-through-port`: a port file never imports or re-exports its own14+ * adapters, and nothing reaches into another workspace by a relative path15+ * (the root's files only from config's tests).16+ * 5. `worker-host`: Worker code, and everything it imports, stays free of host17+ * code; in packages, host code lives only in `/local` and `/bun` adapters.18+ * 6. `test-only`: the test kit and the test principal are imported only from19+ * `test/` directories.20+ * 7. `infra-only`: `alchemy` stays in `infra/`.21 */22+import { Option } from "effect";23 24 export interface SourceFile {25 readonly path: string;26 readonly content: string;27 }28 29 export interface Workspace {15- /** The workspace's folder, relative to the repo root: `apps/platform`. */30+ /** The workspace's folder, relative to the repo root: `apps/platform`. The root's is `""`. */31 readonly dir: string;32 readonly name: string;33 /** Every package named in `dependencies` and `devDependencies`. */34 readonly dependencies: readonly string[];35+ /**36+ * `package.json`'s `exports`: each subpath (`.`, `./ids`, `./*`) and the37+ * files it names, relative to `dir`, with conditions flattened.38+ */39+ readonly exports?: Readonly<Record<string, readonly string[]>>;40 }41 42+export type ImportRule =43+ | "app-imports-app"44+ | "undeclared"45+ | "matrix"46+ | "adapter-through-port"47+ | "worker-host"48+ | "test-only"49+ | "infra-only";50+51 export interface ImportViolation {52 readonly path: string;53 /** 1-based: the line the specifier is on. */54 readonly line: number;55 readonly specifier: string;27- readonly rule: string;56+ readonly rule: ImportRule;57+ /**58+ * For Worker code that reaches host code through other files: each file59+ * the import leads through, then the host specifier it ends at.60+ */61+ readonly via?: readonly string[];62 }63 30-// The specifier of a static import or re-export (`… from "x"`), a bare31-// `import "x"`, or a dynamic `import("x")`. A `from` clause may span lines.32-const IMPORT =33- /\b(?:import|export)\s[^;]*?\bfrom\s*(?<quote>["'])(?<from>[^"'\n]+)\k<quote>|\bimport\s*(?<bareQuote>["'])(?<bare>[^"'\n]+)\k<bareQuote>|\bimport\s*\(\s*(?<dynamicQuote>["'])(?<dynamic>[^"'\n]+)\k<dynamicQuote>\s*\)/gu;34-35-interface Found {64+export interface Import {65 readonly specifier: string;66+ /** 1-based: the line the specifier is on. */67 readonly line: number;68+ /** `import type`, `export type` or `typeof import(…)`. These count too. */69+ readonly typeOnly: boolean;70 }71 40-const importsIn = (content: string): readonly Found[] =>41- [...content.matchAll(IMPORT)].flatMap((match) => {42- const specifier =43- match.groups?.from ?? match.groups?.bare ?? match.groups?.dynamic;72+/** Every package in the direction table: what the test kit may import. */73+const EVERY_PACKAGE: readonly string[] = [74+ "@repo/agent-kit",75+ "@repo/artifacts",76+ "@repo/brand",77+ "@repo/checks",78+ "@repo/gate",79+ "@repo/git",80+ "@repo/project",81+ "@repo/protocol",82+ "@repo/rules",83+ "@repo/sdk",84+ "@repo/visibility",85+];86 87+/**88+ * Which workspace packages each workspace may import, by workspace name. A89+ * row for a package that doesn't exist yet matches nothing; a workspace with90+ * no row may import none. Files outside a workspace's `src/` (tests, config)91+ * may also import `@repo/config`. Where `@repo/testkit` may appear is the92+ * `test-only` rule's to say.93+ *94+ * Narrower than a row: `OnlySubpaths`. `@repo/web`'s dev backend (the95+ * artifacts and project memory adapters) and `@repo/cli`'s narrower edges96+ * (`rules/bun`, `artifacts/local`, visibility's parser) are added here when97+ * the work that imports them (401, 501) builds those subpaths.98+ */99+export const Matrix = {100+ "@repo/agent-kit": ["@repo/brand", "@repo/checks", "@repo/protocol"],101+ "@repo/artifacts": ["@repo/protocol"],102+ "@repo/brand": [],103+ "@repo/checks": ["@repo/brand", "@repo/protocol"],104+ "@repo/cli": [105+ "@repo/agent-kit",106+ "@repo/artifacts",107+ "@repo/brand",108+ "@repo/checks",109+ "@repo/gate",110+ "@repo/git",111+ "@repo/protocol",112+ "@repo/rules",113+ "@repo/sdk",114+ "@repo/visibility",115+ ],116+ "@repo/gate": ["@repo/checks", "@repo/protocol"],117+ "@repo/git": ["@repo/artifacts", "@repo/brand", "@repo/protocol"],118+ "@repo/platform": [119+ "@repo/agent-kit",120+ "@repo/artifacts",121+ "@repo/brand",122+ "@repo/checks",123+ "@repo/gate",124+ "@repo/git",125+ "@repo/project",126+ "@repo/protocol",127+ "@repo/rules",128+ "@repo/visibility",129+ ],130+ "@repo/project": [131+ "@repo/artifacts",132+ "@repo/brand",133+ "@repo/checks",134+ "@repo/gate",135+ "@repo/git",136+ "@repo/protocol",137+ "@repo/rules",138+ "@repo/visibility",139+ ],140+ "@repo/protocol": ["@repo/brand"],141+ "@repo/rules": ["@repo/protocol", "@repo/sdk"],142+ "@repo/sandbox": [143+ "@repo/brand",144+ "@repo/checks",145+ "@repo/git",146+ "@repo/protocol",147+ "@repo/rules",148+ "@repo/visibility",149+ ],150+ "@repo/sdk": ["@repo/brand", "@repo/protocol"],151+ // Its own consumers are tests only.152+ "@repo/testkit": EVERY_PACKAGE,153+ "@repo/visibility": [154+ "@repo/artifacts",155+ "@repo/brand",156+ "@repo/checks",157+ "@repo/git",158+ "@repo/protocol",159+ ],160+ "@repo/web": ["@repo/brand", "@repo/protocol"],161+} as const satisfies Readonly<Record<string, readonly string[]>>;162+163+/**164+ * The subpaths of `@repo/checks` that are pure: no port, no process, no I/O.165+ * `check-runner` (a port) and `check-runner/local` (a process) are not.166+ */167+export const ChecksPureSubpaths: readonly string[] = [168+ "classify",169+ "finder",170+ "judge",171+ "kinds",172+ "kinds/*",173+ "phases",174+ "red-first",175+ "weak-shapes",176+];177+178+/**179+ * `Matrix` edges that allow only some subpaths of the imported package, by180+ * importer, then imported package. `*` matches the rest of a subpath.181+ */182+export const OnlySubpaths = {183+ "@repo/gate": { "@repo/checks": ChecksPureSubpaths },184+ "@repo/sdk": { "@repo/protocol": ["domain/*"] },185+} as const satisfies Readonly<186+ Record<string, Readonly<Record<string, readonly string[]>>>187+>;188+189+/** The folders whose files run in a Worker. */190+export const WorkerRoots: readonly string[] = [191+ "apps/platform/src/",192+ "apps/sandbox/src/",193+ "apps/web/src/",194+];195+196+/**197+ * The `node:*` builtins Worker code may import: those Workers' `nodejs_compat`198+ * serves. Widen with a reason.199+ */200+export const WorkerNodeAllowed: readonly string[] = [201+ "node:async_hooks",202+ "node:buffer",203+ "node:crypto",204+ "node:events",205+ "node:path",206+ "node:stream",207+ "node:util",208+];209+210+/**211+ * Specifiers that need a host process (Bun or Node). A trailing `/*` matches a212+ * whole scope; any other entry matches itself and its subpaths.213+ */214+export const HostOnly: readonly string[] = [215+ "@effect/platform-bun",216+ "@effect/platform-node",217+ "@opentui/*",218+ "child_process",219+ "node:child_process",220+];221+222+/**223+ * What a file under `src/<port>/` is called when it is an adapter224+ * (AGENTS.md "Nouns"), plus the adapters later ports name. `memory-fs` is a225+ * `memory` adapter's.226+ */227+export const AdapterNames: readonly string[] = [228+ "binding",229+ "bun",230+ "env-spec",231+ "inline",232+ "isogit",233+ "json",234+ "local",235+ "memory",236+ "r2",237+ "repo-host",238+ "rest",239+ "sqlite",240+ "webcrypto",241+ "worker",242+];243+244+/** Host code in a package lives only in these adapters, as files or folders. */245+const HOST_ADAPTERS = new Set(["bun", "local"]);246+247+const TESTKIT = "@repo/testkit";248+249+const TEST_ONLY = [TESTKIT, "@repo/protocol/testing"] as const;250+251+const CONFIG = "@repo/config";252+253+/**254+ * The one place a workspace may reach the root's files by a relative path:255+ * config's tests drive the root's fence (`scripts/`, `tools/oxlint/`,256+ * `oxlint.config.ts`).257+ */258+const FENCE_TESTS = "packages/config/test/";259+260+/** What a reader can do about each rule, one line each. */261+export const RuleHints: Readonly<Record<ImportRule, string>> = {262+ "adapter-through-port":263+ "import an adapter by its own subpath (@repo/<package>/<port>/<adapter>), never through its port file, and reach another workspace by its name, never by a relative path (only packages/config/test reaches the root's files).",264+ "app-imports-app":265+ "apps import packages only; move what both need into a package.",266+ "infra-only": "alchemy stays in infra/.",267+ matrix:268+ "this workspace may not import that package or subpath; Matrix and OnlySubpaths in scripts/lib/imports.ts are the allow-list.",269+ "test-only":270+ "@repo/testkit and @repo/protocol/testing are imported only from test/ directories.",271+ undeclared:272+ "list the package in this workspace's package.json, if Matrix allows the edge.",273+ "worker-host":274+ "Worker code, and every module it imports, stays host-free: host code lives only in a package's /local or /bun adapter, which Worker code never imports.",275+};276+277+// ---------------------------------------------------------------- reading278+279+/** Punctuation after which a `/` starts a regex rather than a division. */280+const BEFORE_REGEX = new Set("(,=:[!&|?{};+-*%<>~^");281+282+const KEYWORDS_BEFORE_REGEX = new Set([283+ "await",284+ "case",285+ "delete",286+ "do",287+ "else",288+ "in",289+ "instanceof",290+ "new",291+ "of",292+ "return",293+ "throw",294+ "typeof",295+ "void",296+ "yield",297+]);298+299+const WORD = /[\w$]/u;300+301+const SPACE = /\s/u;302+303+/**304+ * A pass over one file's source. `chars` starts as the source and ends with305+ * comments and the insides of strings, regexes and templates blanked.306+ */307+interface Lexer {308+ readonly content: string;309+ readonly chars: string[];310+ /** Each string literal's contents, by the offset of its opening quote. */311+ readonly strings: Map<number, string>;312+ /** The brace depth outside each enclosing template's `${`, innermost last. */313+ readonly outer: number[];314+ depth: number;315+ inTemplate: boolean;316+ /** The last code token read: a punctuation character or a word. */317+ previous: string;318+ at: number;319+}320+321+/** Blanks `[from, to)`, keeping line breaks. */322+const blank = (lexer: Lexer, from: number, to: number) => {323+ for (let at = from; at < Math.min(to, lexer.chars.length); at += 1) {324+ if (lexer.chars[at] !== "\n") {325+ lexer.chars[at] = " ";326+ }327+ }328+};329+330+/** The offset of the `/` that closes the regex opening at `start`, or -1 when its line ends first. */331+const regexEnd = (content: string, start: number) => {332+ let inClass = false;333+ let at = start + 1;334+335+ while (at < content.length && content[at] !== "\n") {336+ const char = content[at];337+338+ if (char === "/" && !inClass) {339+ return at;340+ }341+342+ if (char === "[" || char === "]") {343+ inClass = char === "[";344+ }345+346+ at += char === "\\" ? 2 : 1;347+ }348+349+ return -1;350+};351+352+/** A template's text, up to its closing backtick or its next `${`. */353+const templateText = (lexer: Lexer) => {354+ const { content } = lexer;355+ const start = lexer.at;356+357+ while (358+ lexer.at < content.length &&359+ content[lexer.at] !== "`" &&360+ !content.startsWith("${", lexer.at)361+ ) {362+ lexer.at += content[lexer.at] === "\\" ? 2 : 1;363+ }364+365+ blank(lexer, start, lexer.at);366+ lexer.inTemplate = false;367+368+ if (content.startsWith("${", lexer.at)) {369+ lexer.outer.push(lexer.depth);370+ lexer.depth = 0;371+ lexer.previous = "{";372+ lexer.at += 2;373+ } else {374+ lexer.previous = "`";375+ lexer.at += 1;376+ }377+};378+379+/** Each step reads one token of code if it starts at `at`, and says whether it did. */380+type Step = (lexer: Lexer) => boolean;381+382+const comment: Step = (lexer) => {383+ const { at, content } = lexer;384+ const line = content.startsWith("//", at);385+386+ if (!line && !content.startsWith("/*", at)) {387+ return false;388+ }389+390+ const end = line ? content.indexOf("\n", at) : content.indexOf("*/", at + 2);391+ const stop = end === -1 ? content.length : end + (line ? 0 : 2);392+393+ blank(lexer, at, stop);394+ lexer.at = stop;395+396+ return true;397+};398+399+// A string stops at its line's end, so a stray quote (an apostrophe in JSX400+// text) blanks one line at most.401+const quoted: Step = (lexer) => {402+ const { at, content } = lexer;403+ const quote = content[at] ?? "";404+405+ if (quote !== '"' && quote !== "'") {406+ return false;407+ }408+409+ let end = at + 1;410+411+ while (412+ end < content.length &&413+ content[end] !== quote &&414+ content[end] !== "\n"415+ ) {416+ end += content[end] === "\\" ? 2 : 1;417+ }418+419+ lexer.strings.set(at, content.slice(at + 1, end));420+ blank(lexer, at + 1, end);421+ lexer.previous = quote;422+ lexer.at = end + 1;423+424+ return true;425+};426+427+const templateStart: Step = (lexer) => {428+ if (lexer.content[lexer.at] !== "`") {429+ return false;430+ }431+432+ lexer.inTemplate = true;433+ lexer.at += 1;434+435+ return true;436+};437+438+const regex: Step = (lexer) => {439+ const { at, content, previous } = lexer;440+441+ const mayStart =442+ content[at] === "/" &&443+ (previous === "" ||444+ BEFORE_REGEX.has(previous) ||445+ KEYWORDS_BEFORE_REGEX.has(previous));446+447+ const end = mayStart ? regexEnd(content, at) : -1;448+449+ if (end === -1) {450+ return false;451+ }452+453+ blank(lexer, at + 1, end);454+ lexer.previous = "/";455+ lexer.at = end + 1;456+457+ return true;458+};459+460+/** The `}` that closes a template's `${`. */461+const templateResume: Step = (lexer) => {462+ if (463+ lexer.content[lexer.at] !== "}" ||464+ lexer.depth > 0 ||465+ lexer.outer.length === 0466+ ) {467+ return false;468+ }469+470+ lexer.depth = lexer.outer.pop() ?? 0;471+ lexer.inTemplate = true;472+ lexer.at += 1;473+474+ return true;475+};476+477+const word: Step = (lexer) => {478+ const { content } = lexer;479+ const start = lexer.at;480+481+ while (lexer.at < content.length && WORD.test(content[lexer.at] ?? "")) {482+ lexer.at += 1;483+ }484+485+ lexer.previous = content.slice(start, lexer.at) || lexer.previous;486+487+ return lexer.at > start;488+};489+490+const punctuation: Step = (lexer) => {491+ const char = lexer.content[lexer.at] ?? "";492+493+ lexer.depth += Number(char === "{") - Number(char === "}");494+495+ if (!SPACE.test(char)) {496+ lexer.previous = char;497+ }498+499+ lexer.at += 1;500+501+ return true;502+};503+504+const STEPS: readonly Step[] = [505+ comment,506+ quoted,507+ templateStart,508+ regex,509+ templateResume,510+ word,511+ punctuation,512+];513+514+/**515+ * The source with comments, and the insides of strings, regexes and516+ * templates, blanked, keeping every offset and line break, so import syntax517+ * inside them is never read. It knows TypeScript's lexical grammar as far as518+ * imports need, not further.519+ */520+const mask = (content: string) => {521+ const lexer: Lexer = {522+ at: 0,523+ chars: content.split(""),524+ content,525+ depth: 0,526+ inTemplate: false,527+ outer: [],528+ previous: "",529+ strings: new Map(),530+ };531+532+ while (lexer.at < content.length) {533+ if (lexer.inTemplate) {534+ templateText(lexer);535+ } else {536+ for (const step of STEPS) {537+ if (step(lexer)) {538+ break;539+ }540+ }541+ }542+ }543+544+ return { code: lexer.chars.join(""), strings: lexer.strings };545+};546+547+// Over masked code, each alternative ends at a specifier's opening quote: a548+// static import or re-export (`… from "x"`, maybe across lines), a bare549+// `import "x"`, or a dynamic `import("x")`.550+const IMPORT =551+ /(?<![.\w$])(?<keyword>import|export)(?<clause>[\s{*][^;]*?)\bfrom\s*["']|(?<![.\w$])import\s*["']|(?<typeOf>\btypeof\s+)?(?<![.\w$])import\s*\(\s*["']/gu;552+553+const TYPE_CLAUSE = /^\s+type[\s{*]/u;554+555+/** `import type from "x"`: a default import named `type`. */556+const DEFAULT_NAMED_TYPE = /^\s+type\s+$/u;557+558+/** Every import, re-export and dynamic import in a file, in source order. */559+export const importsOf = (file: SourceFile): readonly Import[] => {560+ const { code, strings } = mask(file.content);561+562+ return [...code.matchAll(IMPORT)].flatMap((match) => {563+ const quote = match.index + match[0].length - 1;564+ const specifier = strings.get(quote);565+45- if (specifier === undefined) {566+ if (specifier === undefined || specifier.length === 0) {567 return [];568 }569 49- const at = match.index + match[0].lastIndexOf(specifier);570+ const clause = match.groups?.clause;571 51- return [{ line: content.slice(0, at).split("\n").length, specifier }];572+ const typeOnly =573+ match.groups?.typeOf !== undefined ||574+ (clause !== undefined &&575+ TYPE_CLAUSE.test(clause) &&576+ !DEFAULT_NAMED_TYPE.test(clause));577+578+ return [579+ {580+ line: file.content.slice(0, quote).split("\n").length,581+ specifier,582+ typeOnly,583+ },584+ ];585 });586+};587 588+// --------------------------------------------------------------- resolving589+590 /** `a/b/../c/./d` as `a/c/d`; `undefined` when it climbs out of the repo. */591 const normalize = (path: string): string | undefined => {592 const parts: string[] = [];593 14 unmodified lines608 609 const dirname = (path: string) => path.slice(0, path.lastIndexOf("/") + 1);610 611 const isInside = (dir: string, path: string) =>76- path === dir || path.startsWith(`${dir}/`);612+ dir === "" || path === dir || path.startsWith(`${dir}/`);613 614+const isUnder = (roots: readonly string[], path: string) =>615+ roots.some((root) => path.startsWith(root));616+617+const isRelative = (specifier: string) =>618+ specifier === "." ||619+ specifier === ".." ||620+ specifier.startsWith("./") ||621+ specifier.startsWith("../");622+623+/** `@scope/name/sub` → `@scope/name`; `name/sub` → `name`. */624+const packageOf = (specifier: string) =>625+ specifier626+ .split("/")627+ .slice(0, specifier.startsWith("@") ? 2 : 1)628+ .join("/");629+630+/** Whether `name` or one of its subpaths is what `specifier` imports. */631+const names = (name: string, specifier: string) =>632+ specifier === name || specifier.startsWith(`${name}/`);633+634+const STAR = "*";635+636+/** A subpath pattern against a subpath: `domain/*` matches `domain/ask`. */637+const matchesPattern = (pattern: string, subpath: string) => {638+ const star = pattern.indexOf(STAR);639+640+ if (star === -1) {641+ return pattern === subpath;642+ }643+644+ const prefix = pattern.slice(0, star);645+ const suffix = pattern.slice(star + 1);646+647+ return (648+ subpath.length > prefix.length + suffix.length &&649+ subpath.startsWith(prefix) &&650+ subpath.endsWith(suffix)651+ );652+};653+654+/**655+ * The files a package subpath (`.`, `./ids`) names, through the exports map:656+ * an exact key first, then the `*` pattern with the longest prefix.657+ */658+const exportTargets = (workspace: Workspace, subpath: string) => {659+ const exports = workspace.exports ?? {};660+ const exact = exports[subpath];661+662+ const within = (target: string) =>663+ normalize(workspace.dir === "" ? target : `${workspace.dir}/${target}`);664+665+ if (exact !== undefined) {666+ return exact.flatMap((target) => within(target) ?? []);667+ }668+669+ const [pattern] = Object.keys(exports)670+ .filter((key) => key.includes(STAR) && matchesPattern(key, subpath))671+ .toSorted((a, b) => b.indexOf(STAR) - a.indexOf(STAR));672+673+ if (pattern === undefined) {674+ return [];675+ }676+677+ const star = pattern.indexOf(STAR);678+679+ const matched = subpath.slice(680+ star,681+ subpath.length - (pattern.length - star - 1)682+ );683+684+ return (exports[pattern] ?? []).flatMap(685+ (target) => within(target.replace(STAR, matched)) ?? []686+ );687+};688+689 /** The workspace a repo path belongs to: the deepest one that holds it. */690 const owner = (path: string, workspaces: readonly Workspace[]) =>691 workspaces692 .filter((workspace) => isInside(workspace.dir, path))693 .toSorted((a, b) => b.dir.length - a.dir.length)[0];694 84-/** The workspace an import reaches, by package name or by relative path. */85-const target = (86- file: SourceFile,695+const namedWorkspace = (specifier: string, workspaces: readonly Workspace[]) =>696+ workspaces.find((workspace) => names(workspace.name, specifier));697+698+/**699+ * The repo paths an import reaches, without extensions guessed: a relative700+ * path as written, a workspace package through its exports map. Empty for701+ * anything else.702+ */703+const pathsOf = (704+ from: string,705 specifier: string,706 workspaces: readonly Workspace[]707+): readonly string[] => {708+ if (isRelative(specifier)) {709+ const resolved = normalize(`${dirname(from)}${specifier}`);710+711+ return resolved === undefined ? [] : [resolved];712+ }713+714+ const workspace = namedWorkspace(specifier, workspaces);715+716+ return workspace === undefined717+ ? []718+ : exportTargets(719+ workspace,720+ specifier === workspace.name721+ ? "."722+ : `.${specifier.slice(workspace.name.length)}`723+ );724+};725+726+/** The file in the tree a path names, trying TypeScript's extensions. */727+const fileAt = (path: string, files: ReadonlySet<string>) =>728+ [729+ path,730+ path.replace(/\.js$/u, ".ts"),731+ `${path}.ts`,732+ `${path}.tsx`,733+ `${path}/index.ts`,734+ `${path}/index.tsx`,735+ ].find((candidate) => files.has(candidate));736+737+// ------------------------------------------------------------------ hosts738+739+const isHostOnly = (specifier: string) =>740+ HostOnly.some((entry) =>741+ entry.endsWith(`/${STAR}`)742+ ? specifier.startsWith(entry.slice(0, -1))743+ : names(entry, specifier)744+ );745+746+/** What Worker code may not import: host-only code, or a builtin Workers don't serve. */747+const isHostForWorkers = (specifier: string) =>748+ isHostOnly(specifier) ||749+ (specifier.startsWith("node:") &&750+ !WorkerNodeAllowed.includes(specifier.split("/")[0] ?? specifier));751+752+const PACKAGE_SRC = /^packages\/[^/]+\/src\/(?<inner>.+)$/u;753+754+const EXTENSION = /\.(?:ts|tsx|mts|cts|js)$/u;755+756+/** A package file host code may live in: `…/local.ts`, `…/bun/…`. */757+const isHostAdapter = (inner: string) =>758+ inner759+ .replace(EXTENSION, "")760+ .split("/")761+ .some((segment) => HOST_ADAPTERS.has(segment));762+763+/** Whether `target` is one of the port file `port`'s own adapters. */764+const isAdapterOf = (port: string, target: string) => {765+ const base = port.replace(EXTENSION, "");766+767+ if (!target.startsWith(`${base}/`)) {768+ return false;769+ }770+771+ const [first = ""] = target772+ .slice(base.length + 1)773+ .replace(EXTENSION, "")774+ .split("/");775+776+ return AdapterNames.some(777+ (name) => first === name || first.startsWith(`${name}-`)778+ );779+};780+781+// ------------------------------------------------------------------- rules782+783+interface Verdict {784+ readonly rule: ImportRule;785+ readonly via?: readonly string[];786+}787+788+interface Tree {789+ readonly workspaces: readonly Workspace[];790+ readonly paths: ReadonlySet<string>;791+ /** The files the test-only specifiers name, so a relative path to one counts too. */792+ readonly testOnlyFiles: ReadonlySet<string>;793+ readonly importsAt: (path: string) => readonly Import[];794+ /** The shortest chain from a file to a specifier Workers can't import. */795+ readonly hostChain: (path: string) => Option.Option<readonly string[]>;796+}797+798+interface Site {799+ readonly path: string;800+ readonly from: Workspace | undefined;801+ readonly specifier: string;802+}803+804+type Rule = (site: Site, tree: Tree) => Option.Option<Verdict>;805+806+const breaks = (rule: ImportRule, broken: boolean): Option.Option<Verdict> =>807+ broken ? Option.some({ rule }) : Option.none();808+809+const ROWS = new Map<string, readonly string[]>(Object.entries(Matrix));810+811+const NARROWED = new Map(812+ Object.entries(OnlySubpaths).map(([importer, edges]) => [813+ importer,814+ new Map(Object.entries(edges)),815+ ])816+);817+818+const isApp = (workspace: Workspace | undefined) =>819+ workspace?.dir.startsWith("apps/") === true;820+821+/** The workspace an import reaches, by package name or by relative path. */822+const reached = (site: Site, workspaces: readonly Workspace[]) => {823+ if (!isRelative(site.specifier)) {824+ return namedWorkspace(site.specifier, workspaces);825+ }826+827+ const resolved = normalize(`${dirname(site.path)}${site.specifier}`);828+829+ return resolved === undefined ? undefined : owner(resolved, workspaces);830+};831+832+/** The `@repo/*` package an import names, unless it names its own workspace. */833+const otherRepoPackage = (site: Site) => {834+ const name = packageOf(site.specifier);835+836+ return name.startsWith("@repo/") && name !== site.from?.name837+ ? name838+ : undefined;839+};840+841+const appImportsApp: Rule = (site, tree) => {842+ const to = reached(site, tree.workspaces);843+844+ return breaks(845+ "app-imports-app",846+ isApp(site.from) && isApp(to) && to !== site.from847+ );848+};849+850+const undeclared: Rule = (site) => {851+ const name = otherRepoPackage(site);852+853+ return breaks(854+ "undeclared",855+ name !== undefined &&856+ site.from !== undefined &&857+ !site.from.dependencies.includes(name)858+ );859+};860+861+/** Whether `from`'s file at `path` may import `specifier`, of package `name`. */862+const allows = (863+ from: Workspace,864+ path: string,865+ name: string,866+ specifier: string867 ) => {90- if (specifier.startsWith(".")) {91- const resolved = normalize(`${dirname(file.path)}${specifier}`);868+ const inSrc = isInside(`${from.dir}/src`, path);869+ const only = NARROWED.get(from.name)?.get(name);870+ const subpath = specifier.slice(name.length + 1);871 93- return resolved === undefined ? undefined : owner(resolved, workspaces);872+ const listed =873+ name === TESTKIT ||874+ (name === CONFIG && !inSrc) ||875+ (ROWS.get(from.name) ?? []).includes(name);876+877+ return (878+ listed &&879+ (only === undefined ||880+ only.some((pattern) => matchesPattern(pattern, subpath)))881+ );882+};883+884+// The root is tooling, with no row: `undeclared` holds it.885+const matrix: Rule = (site) => {886+ const name = otherRepoPackage(site);887+ const { from } = site;888+889+ return breaks(890+ "matrix",891+ name !== undefined &&892+ from !== undefined &&893+ from.dir !== "" &&894+ !allows(from, site.path, name, site.specifier)895+ );896+};897+898+const adapterThroughPort: Rule = (site, tree) => {899+ const reachesOwnAdapter =900+ PACKAGE_SRC.test(site.path) &&901+ pathsOf(site.path, site.specifier, tree.workspaces).some((target) =>902+ isAdapterOf(site.path, target)903+ );904+905+ const to = isRelative(site.specifier)906+ ? reached(site, tree.workspaces)907+ : undefined;908+909+ const reachesAcross =910+ to !== undefined &&911+ to !== site.from &&912+ (to.dir !== "" || !site.path.startsWith(FENCE_TESTS));913+914+ return breaks("adapter-through-port", reachesOwnAdapter || reachesAcross);915+};916+917+/** In a package, host code only in a `/local` or `/bun` adapter. */918+const hostOutsideAdapter = (site: Site) => {919+ const inner = PACKAGE_SRC.exec(site.path)?.groups?.inner;920+921+ return (922+ inner !== undefined && isHostOnly(site.specifier) && !isHostAdapter(inner)923+ );924+};925+926+const workerHost: Rule = (site, tree) => {927+ const inWorker = isUnder(WorkerRoots, site.path);928+929+ if (930+ hostOutsideAdapter(site) ||931+ (inWorker && isHostForWorkers(site.specifier))932+ ) {933+ return Option.some({ rule: "worker-host" });934 }935 96- return workspaces.find(97- (workspace) =>98- specifier === workspace.name || specifier.startsWith(`${workspace.name}/`)936+ // A Worker file this one imports answers for its own imports.937+ const targets = inWorker938+ ? pathsOf(site.path, site.specifier, tree.workspaces)939+ .flatMap((target) => fileAt(target, tree.paths) ?? [])940+ .filter((target) => !isUnder(WorkerRoots, target))941+ : [];942+943+ return Option.map(944+ Option.firstSomeOf(targets.map(tree.hostChain)),945+ (via): Verdict => ({ rule: "worker-host", via })946 );947 };948 102-const isApp = (workspace: Workspace) => workspace.dir.startsWith("apps/");949+const testOnly: Rule = (site, tree) => {950+ const named = TEST_ONLY.some((name) => names(name, site.specifier));951 104-/** Every import that breaks a rule, in file order, then line order. */105-export const findViolations = (952+ const reachedByPath =953+ isRelative(site.specifier) &&954+ pathsOf(site.path, site.specifier, tree.workspaces).some((target) =>955+ tree.testOnlyFiles.has(fileAt(target, tree.paths) ?? target)956+ );957+958+ return breaks(959+ "test-only",960+ (named || reachedByPath) &&961+ !`/${site.path}`.includes("/test/") &&962+ site.from?.name !== TESTKIT963+ );964+};965+966+const infraOnly: Rule = (site) =>967+ breaks(968+ "infra-only",969+ names("alchemy", site.specifier) && !site.path.startsWith("infra/")970+ );971+972+const RULES: readonly Rule[] = [973+ appImportsApp,974+ undeclared,975+ matrix,976+ adapterThroughPort,977+ workerHost,978+ testOnly,979+ infraOnly,980+];981+982+const treeOf = (983 files: readonly SourceFile[],984 workspaces: readonly Workspace[]108-): readonly ImportViolation[] =>109- files.flatMap((file) => {110- const from = owner(file.path, workspaces);985+): Tree => {986+ const byPath = new Map(files.map((file) => [file.path, file]));987+ const paths: ReadonlySet<string> = new Set(byPath.keys());988+ const imports = new Map<string, readonly Import[]>();989+ const chains = new Map<string, Option.Option<readonly string[]>>();990 112- if (from === undefined || !isApp(from)) {113- return [];991+ const importsAt = (path: string) => {992+ const file = byPath.get(path);993+994+ if (!imports.has(path)) {995+ imports.set(path, file === undefined ? [] : importsOf(file));996 }997 116- return importsIn(file.content).flatMap(({ line, specifier }) => {117- const to = target(file, specifier, workspaces);998+ return imports.get(path) ?? [];999+ };1000 119- return to !== undefined && to !== from && isApp(to)120- ? [{ line, path: file.path, rule: "app-imports-app", specifier }]121- : [];122- });1001+ const reachableFrom = (path: string) =>1002+ importsAt(path).flatMap(({ specifier }) =>1003+ pathsOf(path, specifier, workspaces).flatMap(1004+ (target) => fileAt(target, paths) ?? []1005+ )1006+ );1007+1008+ // Breadth first, so the chain reported is a shortest one.1009+ const search = (start: string): Option.Option<readonly string[]> => {1010+ const seen = new Set([start]);1011+ const queue: (readonly string[])[] = [[start]];1012+1013+ for (const chain of queue) {1014+ const path = chain.at(-1) ?? start;1015+1016+ const host = importsAt(path).find((found) =>1017+ isHostForWorkers(found.specifier)1018+ );1019+1020+ if (host !== undefined) {1021+ return Option.some([...chain, host.specifier]);1022+ }1023+1024+ for (const reachable of reachableFrom(path)) {1025+ if (!seen.has(reachable)) {1026+ seen.add(reachable);1027+ queue.push([...chain, reachable]);1028+ }1029+ }1030+ }1031+1032+ return Option.none();1033+ };1034+1035+ const hostChain = (path: string) => {1036+ const known = chains.get(path) ?? search(path);1037+1038+ chains.set(path, known);1039+1040+ return known;1041+ };1042+1043+ const testOnlyFiles = new Set(1044+ TEST_ONLY.flatMap((specifier) => pathsOf("", specifier, workspaces))1045+ );1046+1047+ return { hostChain, importsAt, paths, testOnlyFiles, workspaces };1048+};1049+1050+/** The first rule an import breaks, if it breaks one. */1051+const firstBroken = (site: Site, tree: Tree) => {1052+ for (const rule of RULES) {1053+ const verdict = rule(site, tree);1054+1055+ if (Option.isSome(verdict)) {1056+ return verdict;1057+ }1058+ }1059+1060+ return Option.none<Verdict>();1061+};1062+1063+/** Every import that breaks a rule, in file order, then line order. */1064+export const findViolations = (1065+ files: readonly SourceFile[],1066+ workspaces: readonly Workspace[]1067+): readonly ImportViolation[] => {1068+ const tree = treeOf(files, workspaces);1069+1070+ return files.flatMap((file) => {1071+ const from = owner(file.path, workspaces);1072+1073+ return tree.importsAt(file.path).flatMap(({ line, specifier }) =>1074+ Option.match(firstBroken({ from, path: file.path, specifier }, tree), {1075+ onNone: () => [],1076+ onSome: (verdict) => [{ line, path: file.path, specifier, ...verdict }],1077+ })1078+ );1079 });1080+};1081+1082+/** One violation as `path:line: rule: specifier`, then its chain, if any. */1083+export const formatViolation = (violation: ImportViolation) =>1084+ [1085+ `${violation.path}:${violation.line}: ${violation.rule}: ${violation.specifier}`,1086+ ...(violation.via ?? []),1087+ ].join(" → ");modified:scripts/imports.ts+82 added-27 removed
123423456789101011121314151617171819201819202122232425262725282930313233343536373839404142434445464748495051525354555657585960616229 unmodified lines9293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129731301311321331342 unmodified lines1371381391408414114214387888990919293949514414514614714814915015115215315415510115615715815916011 unmodified lines172173174175121122123176177178126127128179180181182183184185186187188/** * imports:check: fails when an import crosses a line the workspace graph * forbids (AGENTS.md principle 6). Files come from git, so ignored files are * never opened. * imports:check: fails when an import crosses a line AGENTS.md principle 6 * draws: the package direction, the Worker host rules, adapters through their * own subpaths, test-only and infra-only imports. Files come from git, so * ignored files are never opened. The rules live in `lib/imports.ts`. */import { BunRuntime, BunServices } from "@effect/platform-bun";import { Console, Data, Effect, FileSystem, pipe, Schema } from "effect";import { ChildProcess, ChildProcessSpawner } from "effect/process";
import { findViolations } from "./lib/imports.ts";import { findViolations, formatViolation, RuleHints } from "./lib/imports.ts";import type { Workspace } from "./lib/imports.ts";
class ImportsCrossed extends Data.TaggedError("ImportsCrossed")<{ readonly count: number;}> {}
const RootPackage = Schema.Struct({ workspaces: Schema.Struct({ packages: Schema.Array(Schema.String) }),});
const Dependencies = Schema.optionalKey( Schema.Record(Schema.String, Schema.String));
/** An `exports` target: a path, or a path per condition. */const Target = Schema.Union([ Schema.String, Schema.Record(Schema.String, Schema.String),]);
const WorkspacePackage = Schema.Struct({const Manifest = Schema.Struct({ dependencies: Dependencies, devDependencies: Dependencies, exports: Schema.optionalKey( Schema.Union([Schema.String, Schema.Record(Schema.String, Target)]) ), name: Schema.String,});
const RootManifest = Schema.Struct({ ...Manifest.fields, workspaces: Schema.Struct({ packages: Schema.Array(Schema.String) }),});
const SOURCE = /\.(?:ts|tsx|mts|cts)$/u;
/** Vendored, fixture, example and generated code: not ours to direct. */const SKIPPED = [ "tools/oxlint/anti-slop/", "tools/oxlint/fence/fixtures/", "examples/", ".agent_sources/",];
const GENERATED = /(?:^|\/)worker-configuration\.d\.ts$/u;
const isChecked = (path: string) => SOURCE.test(path) && !GENERATED.test(path) && !SKIPPED.some((prefix) => path.startsWith(prefix));
/** `apps/*` as a test of a folder path: `*` is one path segment. */const matchesGlob = (glob: string) => { const parts = glob.split("/");
29 unmodified lines .readFileString(file) .pipe(Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema)))) );
/** Each subpath's files, with conditions flattened. */const exportsOf = (exports: (typeof Manifest.Type)["exports"]) => { if (exports === undefined) { return {}; }
if (Schema.is(Schema.String)(exports)) { return { ".": [exports] }; }
return Object.fromEntries( Object.entries(exports).map(([subpath, target]) => [ subpath, Schema.is(Schema.String)(target) ? [target] : Object.values(target), ]) );};
const workspaceOf = ( dir: string, manifest: typeof Manifest.Type): Workspace => ({ dependencies: Object.keys({ ...manifest.dependencies, ...manifest.devDependencies, }).toSorted(), dir, exports: exportsOf(manifest.exports), name: manifest.name,});
const check = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const paths = yield* listCommittable; const root = yield* readJson("package.json", RootPackage); const root = yield* readJson("package.json", RootManifest); const globs = root.workspaces.packages.map(matchesGlob);
const manifests = paths.filter((path) => { const dir = path.slice(0, -"/package.json".length);2 unmodified lines path.endsWith("/package.json") && globs.some((matches) => matches(dir)) ); });
const workspaces: readonly Workspace[] = yield* pipe( const members = yield* pipe( manifests, Effect.forEach((manifest) => readJson(manifest, WorkspacePackage).pipe( Effect.map((pkg) => ({ dependencies: Object.keys({ ...pkg.dependencies, ...pkg.devDependencies, }).toSorted(), dir: manifest.slice(0, -"/package.json".length), name: pkg.name, })) readJson(manifest, Manifest).pipe( Effect.map((decoded) => workspaceOf(manifest.slice(0, -"/package.json".length), decoded) ) ) ) );
// The root's own files (`scripts/`, `infra/`) belong to the root workspace. const workspaces = [workspaceOf("", root), ...members];
const files = yield* pipe( paths.filter((path) => SOURCE.test(path)), paths.filter(isChecked), Effect.forEach((path) => fs.exists(path).pipe( Effect.flatMap((exists) => exists ? fs.readFileString(path) : Effect.succeed("")11 unmodified lines ); }
for (const violation of violations) { yield* Console.error( `${violation.path}:${violation.line}: ${violation.rule}: ${violation.specifier}` ); yield* Console.error(formatViolation(violation)); }
yield* Console.error( "imports:check: apps import packages only; move what both need into a package." ); const broken = [...new Set(violations.map((violation) => violation.rule))];
for (const rule of broken) { yield* Console.error(`imports:check: ${rule}: ${RuleHints[rule]}`); }
return yield* new ImportsCrossed({ count: violations.length });});
BunRuntime.runMain(check.pipe(Effect.provide(BunServices.layer)));