/** * The `utils/` boundary, enforced rather than agreed. * * `utils` is the one folder every codebase has and every codebase lets rot, * because "utility" has no membership test — a function that reads a context and * causes a side effect is *arguably* a utility, and once one lands the folder * means nothing. * * So the membership test is a property: **a utility is a function of its * arguments.** No context, no globals, no I/O. This test is what makes that true * rather than aspirational — it fails the build, the way this file's "the * client bundle reaches nothing host-only" block already fails it for a * client module reaching host-only code. * * @module test/architecture.test */ import { existsSync, readdirSync, readFileSync } from "node:fs"; import { join, posix } from "node:path"; import { describe, expect, it } from "vitest"; import { blankCommentLines } from "./support/strip-comments.ts"; const SRC_DIR = join(import.meta.dirname, "..", "src"); const UTILS_DIR = join(SRC_DIR, "utils"); /** * Every `.ts`/`.tsx` file under `dir`, at any depth, relative to `dir`. * * Recursive on purpose: a utility in a subfolder is still a utility, and a walk * that read one level would let `utils/nested/` hold anything at all. */ const filesUnder = (dir: string): string[] => { const files: string[] = []; const walk = (current: string): void => { for (const entry of readdirSync(current, { withFileTypes: true })) { const full = join(current, entry.name); if (entry.isDirectory()) { walk(full); } else if (/\.tsx?$/u.test(entry.name)) { files.push(full.slice(dir.length + 1).replaceAll("\\", "/")); } } }; walk(dir); return files.toSorted(); }; /** Every utility, at any depth under `src/utils/`. */ const utilityFiles = (): string[] => filesUnder(UTILS_DIR); /** * The source with its comments blanked, keeping line structure: comment lines * through {@link blankCommentLines}, which only ever errs loudly, then a * trailing `// …` after code. The trailing strip needs a space before the * `//`, so a `"https://…"` string is not cut short. */ const stripComments = (source: string): string => blankCommentLines(source).replaceAll(/(?<=\s)\/\/.*$/gmu, ""); /** * Runtime imports of one file. A type-only import is erased by the compiler, * so it is no edge in the bundle and is skipped; a mixed one is a real edge. */ const runtimeImportsOf = (source: string): string[] => { const specifiers: string[] = []; for (const match of source.matchAll( /\b(?:import|export)\s+(type\s+)?(?:[^;"']*?\sfrom\s+)?"([^"]+)"/gu )) { if (match[1] === undefined && match[2] !== undefined) { specifiers.push(match[2]); } } return specifiers; }; /** * Every `src/` file `entry` reaches at runtime, entry included, mapped to its * source with comments stripped. */ const runtimeGraph = (entry: string): Map => { const seen = new Map(); const visit = (file: string): void => { if (seen.has(file)) { return; } const source = stripComments(readFileSync(join(SRC_DIR, file), "utf8")); seen.set(file, source); for (const specifier of runtimeImportsOf(source)) { if (specifier.startsWith("./") || specifier.startsWith("../")) { visit(join(file, "..", specifier).replaceAll("\\", "/")); } } }; visit(entry); return seen; }; /** The module specifiers one file imports. */ const importsOf = (source: string): string[] => { const specifiers: string[] = []; const patterns = [/from\s+"([^"]+)"/gu, /import\s+"([^"]+)"/gu]; for (const pattern of patterns) { let match: RegExpExecArray | null; while ((match = pattern.exec(source)) !== null) { if (match[1] !== undefined) { specifiers.push(match[1]); } } } return specifiers; }; /** What a utility may not reach. Each entry names the rule it breaks. */ const FORBIDDEN: readonly { readonly matches: (specifier: string) => boolean; readonly because: string; }[] = [ { because: "a node built-in is I/O: the utility would need the filesystem or a stream to answer", matches: (s) => s.startsWith("node:"), }, { because: "a cordis context is the world: a utility takes its inputs as arguments instead", matches: (s) => s.startsWith("@deepseek-ai/cordis"), }, ]; /** * Why a relative import from the utility at `file` (a path relative to * `src/utils/`) leaves the folder, or `undefined` when it stays inside. * * The specifier is resolved against the importing file's own directory, so a * nested utility's `../guards.ts` is a sibling, not an escape. Comparing the raw * specifier would flag every `../` — which, once the walk is recursive, rejects * exactly the nested utilities the recursion admits. */ const escapesUtils = (file: string, specifier: string): string | undefined => { if (!specifier.startsWith("./") && !specifier.startsWith("../")) { return undefined; } // Resolved under a root named for the folder, so a path that leaves and // re-enters it (`../../utils/guards.ts`) is judged by where it lands. const target = posix.join("/utils", posix.dirname(file), specifier); return target.startsWith("/utils/") ? undefined : "only guards.ts and other utilities may be imported; anything else is an effect module"; }; describe("architecture · a property read is a declared dependency", () => { const SRC = join(import.meta.dirname, "..", "src"); /** * Cordis's own framework members, mixed onto every context. Reading these * needs no declaration — they are not services. */ const FRAMEWORK = new Set([ "baseUrl", "effect", "fiber", "get", "inject", "logger", "on", "plugin", "provide", "registry", "root", "waterfall", ]); /** * The CLIENT half's context, which is a different object from the host's. * * Every read there is optional (`ctx.remote === undefined`, * `ctx.slots?.inject?.(…)`), which is the pattern the host half must use for * its optional services and does. They are not `inject` declarations because * the host plugin declares nothing at its root — see the next test. */ const CLIENT_OPTIONAL = new Set([ "configForms", "locale", "modelDirectories", "remote", "slots", ]); /** * The services the plugin DECLARES at its root, so reading one as a property * is right: none. `llm` and `settings` are reached through `ctx.inject` * child scopes, as `scope.llm`. */ const DECLARED = new Set(); /** Every `ctx.` in a file, excluding `ctx.get("name")`. */ const serviceReads = (file: string): string[] => { const source = stripComments(readFileSync(join(SRC, file), "utf8")); const names = new Set(); // Two shapes are the same bug: `ctx.loader` and `(ctx as {loader}).loader`. // The cast form is what a "quick fix" looks like, and matching only the // first let a planted regression pass. for (const match of source.matchAll( /\bctx\.([A-Za-z][A-Za-z0-9_]*)|\bctx as [^\n]*\}\)\.([A-Za-z][A-Za-z0-9_]*)/gu )) { const name = match[1] ?? match[2]; if ( name === undefined || FRAMEWORK.has(name) || CLIENT_OPTIONAL.has(name) || DECLARED.has(name) ) { continue; } names.add(name); } return [...names]; }; const sourceFiles = (): string[] => filesUnder(SRC); it("reads no host service as a property: the root declares none", () => { // Cordis THROWS `cannot get property "X" without inject` for an undeclared // name, and its `inject` form has no required/optional split: a declared // service is REQUIRED, so declaring the optional ones would stop the plugin // activating on a headless host — a silent total failure. // // Consequence: every optional host service must be read through `ctx.get`, // which reads the store without consulting `inject`. This shipped as two // real bugs: `isLoaderHost` — which exists to answer "is there a loader?" — // read `ctx.loader` and threw, and `loaderOf` read it before its own // guarded fallback. Both failed the mount. const offenders: string[] = []; for (const file of sourceFiles()) { for (const name of serviceReads(file)) { offenders.push(`${file}: ctx.${name}`); } } expect(offenders).toEqual([]); }); it("declares no service at the root, so its config listener attaches before `llm` exists", async () => { const { inject } = await import("./support/src.ts"); expect(inject).toEqual([]); }); }); describe("architecture · no source module imports a test library", () => { const SRC = join(import.meta.dirname, "..", "src"); it("keeps vitest and testing-library out of everything in src/", () => { // Wider than `utils/`: an effect module importing `vitest` would be just as // fatal to a published package, and just as invisible in review. The gate on // `lib/client.js`'s requires catches it only if the import survives to the // bundle, which a type-only import does not. const violations: string[] = []; const walk = (dir: string): void => { for (const entry of readdirSync(dir, { withFileTypes: true })) { const full = join(dir, entry.name); if (entry.isDirectory()) { walk(full); continue; } if (!/\.tsx?$/u.test(entry.name)) { continue; } const source = stripComments(readFileSync(full, "utf8")); if (/from\s+"(?:vitest|@testing-library[^"]*)"/u.test(source)) { violations.push(full.slice(SRC.length + 1)); } } }; walk(SRC); expect(violations).toEqual([]); }); }); describe("architecture · src never reads what the desktop's patched pi changes", () => { /** * The harness's own pi patch, which only the desktop app ships, removes pi's * per-delta re-parse of streamed tool-call arguments and round-trips a model's * thought signature on OpenAI-compatible completions. An npm install runs pi * unpatched. The plugin supports both because it reads neither (D14''): * this case fails the day a module starts to, so the difference stays * invisible to the plugin instead of becoming a channel-dependent bug. * * The names are the patch's own, and one shape that names none of them: * the patch deletes the line that refreshes an unfinished tool-call block's * `arguments`, and a caller reaches that block through the `partial` * message pi attaches to every streaming event (text and thinking deltas * included). So a `.partial` property read (dotted, optional-chained or * bracketed) counts too; a `.partial()` call and the `Partial<…>` type do * not, since neither touches a stream event. */ const PATCHED_SURFACE = /\b(?:partialJson|partial_json|partialArgs|toolcall_delta|toolCallDelta|parseStreamingJson|thought_signature|thoughtSignature)\b|\.partial\b(?!\s*\()|\[\s*["'`]partial["'`]\s*\]/u; const readsPatchedSurface = (source: string): boolean => PATCHED_SURFACE.test(stripComments(source)); it("no src module reads a streamed tool-call delta, partial arguments or a thought signature", () => { const files = filesUnder(SRC_DIR); expect(files.length).toBeGreaterThan(10); expect( files.filter((file) => readsPatchedSurface(readFileSync(join(SRC_DIR, file), "utf8")) ) ).toEqual([]); }); it("flags a planted read, in code but not in a comment, so a pass means something", () => { expect( readsPatchedSurface('if (event.type === "toolcall_delta") {}\n') ).toBe(true); expect(readsPatchedSurface("const json = block.partialJson;\n")).toBe(true); expect(readsPatchedSurface("part.thoughtSignature ??= signature;\n")).toBe( true ); expect( readsPatchedSurface("// a comment may name partialJson\nconst a = 1;\n") ).toBe(false); // The in-progress arguments through the event's `partial` message, which // read parsed on an npm install and `{}` on the desktop's patched pi. expect( readsPatchedSurface("const args = event.partial.content[0].arguments;\n") ).toBe(true); expect( readsPatchedSurface("const blocks = event?.partial?.content ?? [];\n") ).toBe(true); expect(readsPatchedSurface('const message = event["partial"];\n')).toBe( true ); // Neither a `.partial()` call nor the `Partial<…>` type is a stream read. expect(readsPatchedSurface("const loose = schema.partial();\n")).toBe( false ); expect( readsPatchedSurface("const row: Partial> = {};\n") ).toBe(false); }); }); describe("architecture · utils/ holds only pure functions", () => { it("has utilities to check", () => { // Without this the suite passes vacuously on an empty folder — the exact // "a grep over a directory that does not exist" failure. expect(utilityFiles().length).toBeGreaterThan(0); }); it("strips comments without cutting code short, keeping the line count", () => { // Stripping only ever removes text and every gate asserts an empty list, // so over-stripping can never fail a gate; these answers pin the rule. expect(stripComments('const u = "https://x"; process.env.A')).toContain( "process.env.A" ); expect(stripComments("f(); // process.env")).not.toMatch(/process\.env/u); expect( stripComments("/**\n * process.env\n */\nconst a = 1;").split("\n") ).toEqual(["", "", "", "const a = 1;"]); expect(stripComments("/* a */ fetch(x)")).toContain("fetch("); expect(stripComments("f(/* process.env */ 1)")).toContain("process.env"); }); it("imports nothing host-only, and nothing outside utils/", () => { const violations: string[] = []; for (const file of utilityFiles()) { const source = readFileSync(join(UTILS_DIR, file), "utf8"); for (const specifier of importsOf(source)) { for (const rule of FORBIDDEN) { if (rule.matches(specifier)) { violations.push(`${file} imports "${specifier}" — ${rule.because}`); } } // `guards.ts` lives in utils/ and is dependency-free by construction, // so it resolves inside the folder like any other utility. const escape = escapesUtils(file, specifier); if (escape !== undefined) { violations.push(`${file} imports "${specifier}" — ${escape}`); } } } expect(violations).toEqual([]); }); it("resolves an import from the importing file's folder, at any depth", () => { // Known answers, so the rule is seen to allow and to reject. expect(escapesUtils("retry.ts", "./guards.ts")).toBeUndefined(); expect(escapesUtils("nested/a.ts", "../guards.ts")).toBeUndefined(); expect(escapesUtils("nested/a.ts", "./b.ts")).toBeUndefined(); expect(escapesUtils("nested/a.ts", "../retry.ts")).toBeUndefined(); expect(escapesUtils("retry.ts", "../config.ts")).toBeDefined(); expect(escapesUtils("retry.ts", "./../config.ts")).toBeDefined(); expect(escapesUtils("nested/a.ts", "../../config.ts")).toBeDefined(); expect( escapesUtils("nested/a.ts", "../../utils/guards.ts") ).toBeUndefined(); expect(escapesUtils("retry.ts", "../utils/guards.ts")).toBeUndefined(); expect(escapesUtils("nested/a.ts", "../../utilsx/a.ts")).toBeDefined(); }); it("never reads process.env, a global the arguments could have carried", () => { // Comments are stripped first: prose ABOUT the environment is exactly what // a rule explaining itself looks like, and a rule that flags its own // explanation would push the explanation out of the code. const violations = utilityFiles().filter((file) => /process\.env/u.test( stripComments(readFileSync(join(UTILS_DIR, file), "utf8")) ) ); expect(violations).toEqual([]); }); it("never calls fetch, which is I/O by definition", () => { const violations = utilityFiles().filter((file) => { // `fetch(` / `globalThis.fetch(` — but not the word inside a comment or a // longer identifier like `fetchPatch`. const source = stripComments(readFileSync(join(UTILS_DIR, file), "utf8")); return /(?:^|[^.\w])(?:fetch|globalThis\.fetch)\s*\(/mu.test(source); }); expect(violations).toEqual([]); }); /** * A reference to the console or to a global timer, outside a comment — not * only a call: `timer = setTimeout` as a default parameter, `backoffOver(setTimeout)` * and `const log = console.warn` reach the global just as surely, and so do * the four spellings of the global object (`globalThis.`, `window.`, * `global.`, `self.`). A member of something else (`options.timer(`, * `x.setTimeout(`) is not the global. * * A tripwire for the honest spelling, not a sandbox: an alias * (`const g = globalThis; g.setTimeout(…)`) or bracket access on the global * object gets past it, and catching those is a type-aware lint's job. */ const AMBIENT_EFFECT = /(? { // A log line is output and a timer is a clock: both are the world, and a // utility that needs one takes it as a parameter, the way `retry.ts` takes // its `sleep` and its `warn` and leaves the timer to the caller. const violations: string[] = []; for (const file of utilityFiles()) { // Block comments are blanked rather than removed, so a line number in a // violation is the line in the file. const source = stripComments(readFileSync(join(UTILS_DIR, file), "utf8")); for (const [index, line] of source.split("\n").entries()) { const match = AMBIENT_EFFECT.exec(line); if (match !== null) { violations.push( `${file}:${index + 1} — ${match[0].trim()} is an effect the caller owns` ); } } } expect(violations).toEqual([]); }); it("knows a console call and a timer when it sees one, and walks every level", () => { // Known answers, so an empty violation list means the rule ran. expect(AMBIENT_EFFECT.test('console.warn("x")')).toBe(true); expect(AMBIENT_EFFECT.test("setTimeout(f, 1)")).toBe(true); expect(AMBIENT_EFFECT.test("globalThis.setInterval(f, 1)")).toBe(true); expect(AMBIENT_EFFECT.test("global.setTimeout(f, 1)")).toBe(true); expect(AMBIENT_EFFECT.test("self.console.warn(x)")).toBe(true); expect(AMBIENT_EFFECT.test("setImmediate(f)")).toBe(true); expect(AMBIENT_EFFECT.test("clearTimeout(handle)")).toBe(true); expect( AMBIENT_EFFECT.test("(timer: RetryTimer = setTimeout, baseMs = 300) =>") ).toBe(true); expect(AMBIENT_EFFECT.test("const sleep = backoffOver(setTimeout);")).toBe( true ); expect(AMBIENT_EFFECT.test("const log = console.warn;")).toBe(true); expect(AMBIENT_EFFECT.test("const { warn } = console;")).toBe(true); expect(AMBIENT_EFFECT.test('console["warn"](x)')).toBe(true); expect(AMBIENT_EFFECT.test("(options.warn ?? console.warn)(m, e)")).toBe( true ); expect(AMBIENT_EFFECT.test("options.timer(resolve, ms)")).toBe(false); expect(AMBIENT_EFFECT.test("x.setTimeout(f, 1)")).toBe(false); expect(AMBIENT_EFFECT.test("const consoleLike = 1;")).toBe(false); expect( AMBIENT_EFFECT.test( "type RetryTimer = (callback: () => void, delayMs: number) => unknown" ) ).toBe(false); expect(utilityFiles()).toContain("retry.ts"); expect(filesUnder(SRC_DIR)).toContain("utils/retry.ts"); }); }); describe("architecture · the client bundle reaches nothing host-only", () => { /** The client bundle's entry, as `vite.config.ts` names it. */ const ENTRY = "settings-page.tsx"; /** Every `src/` file the entry reaches at runtime, entry included. */ const clientGraph = (): Map => runtimeGraph(ENTRY); /** What a client module may not import, each with the reason it is host-only. */ const HOST_ONLY: readonly { readonly matches: (specifier: string) => boolean; readonly because: string; }[] = [ { because: "a node built-in does not exist in the browser", matches: (s) => s.startsWith("node:"), }, { because: "the cordis runtime is the host's, and the client gets its own context", matches: (s) => s === "@deepseek-ai/cordis", }, { because: "pi is loaded from the host's installation, never shipped to a page", matches: (s) => s.startsWith("@earendil-works/pi-ai"), }, ]; it("walks a graph that actually contains the client modules", () => { // A walker that resolved nothing would pass every rule below vacuously. const graph = clientGraph(); expect(graph.has(ENTRY)).toBe(true); expect(graph.has("usage-pill.tsx")).toBe(true); expect(graph.has("config-values.ts")).toBe(true); // And it must not wander into the host half through a type-only import. expect(graph.has("lifecycle.ts")).toBe(false); // The settings table does, and the schema module, and schemastery with // it, never reaches the browser. expect(graph.has("settings-table.ts")).toBe(true); expect(graph.has("config.ts")).toBe(false); }); it("walks into the remote contracts, so the rules below cover them (P9)", () => { // The contracts are client-safe by construction, and the bundle loads // every one of them: the walker must resolve a nested folder for the // HOST_ONLY and process.env rules to be seen to apply. const graph = clientGraph(); for (const file of [ "contracts/all.ts", "contracts/purge.ts", "contracts/remote.ts", "contracts/store.ts", "contracts/usage.ts", ]) { expect(graph.has(file), file).toBe(true); } expect(graph.has("utils/guards.ts")).toBe(true); }); it("imports no node built-in, no cordis runtime and no pi", () => { const violations: string[] = []; for (const [file, source] of clientGraph()) { for (const specifier of runtimeImportsOf(source)) { for (const rule of HOST_ONLY) { if (rule.matches(specifier)) { violations.push(`${file} imports "${specifier}" — ${rule.because}`); } } } } expect(violations).toEqual([]); }); it("never reads process.env, which the browser does not have", () => { // The bundle test runs the built file in a VM, so a read inside a function // that never runs there passes it. Reading the source closes that gap. const violations = [...clientGraph()] .filter(([, source]) => /\bprocess\.env\b/u.test(source)) .map(([file]) => file); expect(violations).toEqual([]); }); it("flags a planted violation, so a pass means something", () => { // The rule is run over a source string with a known answer. const planted = 'import { readFileSync } from "node:fs";\nimport type { X } from "node:os";'; expect(runtimeImportsOf(planted)).toEqual(["node:fs"]); expect(HOST_ONLY.some((rule) => rule.matches("node:fs"))).toBe(true); }); }); describe("architecture · one remote seam (P9)", () => { /** * Each spelling the seam owns lives in one module: the Remote marker's key * in `host/remote.ts` (`markRemote`), the envelope reads in * `settings-remote.ts` (the one unwrap), and the usage namespace's literal * in `contracts/usage.ts` (`USAGE_NAMESPACE`). Tripwires for the spellings * they name, as P7's scans are: comments are stripped first, and a read * spelled another way (a destructured `ok`, a computed key) escapes them. */ const RULES: readonly { readonly name: string; readonly owner: string; readonly matches: (source: string) => boolean; }[] = [ { matches: (source) => source.includes("@deepseek-ai/dsh-typert-protocol/remote-methods"), name: "the Remote marker key", owner: "host/remote.ts", }, { matches: (source) => /"value"\s+in\b|\.ok\s*===\s*false|typeof\s+[\w.]+\.ok\s*===\s*"boolean"/u.test( source ), name: "an envelope read", owner: "settings-remote.ts", }, { matches: (source) => source.includes('"opencodeGoUsage"'), name: "the usage namespace literal", owner: "contracts/usage.ts", }, ]; it("flags a planted spelling of each, so a pass means something", () => { const [marker, envelope, namespace] = RULES; expect( marker?.matches( 'const KEY = "@deepseek-ai/dsh-typert-protocol/remote-methods";' ) ).toBe(true); expect(envelope?.matches('if ("value" in answer) {}')).toBe(true); expect(envelope?.matches("if (res.ok === false) {}")).toBe(true); expect(envelope?.matches('if (typeof res.ok === "boolean") {}')).toBe(true); expect(envelope?.matches("const { ok } = res;")).toBe(false); expect( namespace?.matches('remoteNamespaceOf(ctx, "opencodeGoUsage")') ).toBe(true); expect(namespace?.matches("remote.opencodeGoUsage.read")).toBe(false); // And a comment is not code. expect( namespace?.matches(stripComments('// "opencodeGoUsage"\nconst a = 1;')) ).toBe(false); }); it.each(RULES)("$name occurs in $owner only", ({ matches, owner }) => { const holders = filesUnder(SRC_DIR).filter((file) => matches(stripComments(readFileSync(join(SRC_DIR, file), "utf8"))) ); expect(holders).toEqual([owner]); }); }); describe("architecture · the host bundle mutates no registry it does not own", () => { /** The host half's composition root: everything `apply()` can run. */ const ENTRY = "lifecycle.ts"; /** A write to an `adapters` map: the llm registry's private table. */ const REGISTRY_WRITE = /\badapters\??\.(?:delete|set|clear)\s*\(/u; it("walks a graph that actually contains the host modules", () => { const graph = runtimeGraph(ENTRY); expect(graph.has("stream-hook.ts")).toBe(true); expect(graph.has("host/route-claim.ts")).toBe(true); expect(graph.has("host/plane-provider.ts")).toBe(true); expect(graph.has("settings-page.tsx")).toBe(false); expect(REGISTRY_WRITE.test('llm.adapters.delete("opencode")')).toBe(true); expect(REGISTRY_WRITE.test('llm.adapters?.delete("opencode")')).toBe(true); expect(REGISTRY_WRITE.test("this.adapters.get(route)")).toBe(false); }); it("nothing reachable from lifecycle.ts deletes or sets an llm adapters entry", () => { // `registerAdapter` is all-or-nothing and only the owner's handle moves a // registration's routes. An entry deleted from outside leaves the owner // believing it holds the route, and its next dispose deletes ours. The // plugin keeps pi-ai off the planes through the config waterfall instead // (docs/engineering-notes.md, "Replacing another plugin's adapter // registration is not an API"). const violations = [...runtimeGraph(ENTRY)] .filter(([, source]) => REGISTRY_WRITE.test(source)) .map(([file]) => file); expect(violations).toEqual([]); }); }); describe("architecture · the request path reads no environment of its own (P6)", () => { /** * The fetch patch's stages (every module under `src/request/`, so a new * stage cannot escape), the lifecycle and the plane provider take every * value they need as a parameter or a service: the fill's one read of the * process environment lives in `credentials.ts`, and the plane adapter's in * the host's launch environment (D20). Comments are stripped first, as in * the utilities' rule. Textual, like the repository's other environment * rules: a read through an alias (`process["env"]`, `const { env } = * process`) escapes it. */ const FILES = [ ...filesUnder(SRC_DIR).filter((file) => file.startsWith("request/")), "lifecycle.ts", "host/plane-provider.ts", ]; const readsEnv = (source: string): boolean => /process\.env/u.test(stripComments(source)); it("flags a planted read, so a pass means something", () => { expect(readsEnv("const k = process.env.X;")).toBe(true); expect(readsEnv("// process.env.X\nconst k = 1;")).toBe(false); }); it("walks the request stages, so an empty folder is not a pass", () => { expect(FILES).toContain("request/patch-fetch.ts"); }); it.each(FILES)("%s never reads process.env", (file) => { expect(readsEnv(readFileSync(join(SRC_DIR, file), "utf8"))).toBe(false); }); /** Whether a source writes a capture store: a `.record(` call. */ const writesStore = (source: string): boolean => /\.record\(/u.test(stripComments(source)); it("flags a planted store write, so a pass means something", () => { expect( writesStore("captureStoreFor(ctx).record(key, provider, url);") ).toBe(true); expect(writesStore("store.record(k);")).toBe(true); expect(writesStore("// store.record(k)\nconst recorded = 1;")).toBe(false); }); it("a capture store is written from src/credentials.ts only", () => { const writers = filesUnder(SRC_DIR).filter((file) => writesStore(readFileSync(join(SRC_DIR, file), "utf8")) ); expect(writers).toEqual(["credentials.ts"]); }); }); describe("architecture · host methods are wrapped only through patchMethod", () => { /** The host half's composition root: everything `apply()` can run. */ const ENTRY = "lifecycle.ts"; /** The one module that may write a method onto a host object. */ const HELPER = "host/patch-method.ts"; /** * A write onto a host object by any route but the helper: a * `Reflect.set`/`defineProperty`/`deleteProperty`/`setPrototypeOf`; an * `Object.assign`/`defineProperty`/`defineProperties`/`setPrototypeOf` whose * target is `llm`, an adapter, `settings` (the next site, P-R1's * `settings.describe`) or `globalThis`, bare or reached through a property * path (`registration?.adapter`, `this.llm`); a dotted or bracketed * assignment onto one of the first three, through `?.` or `!` too; or * `globalThis.x =`. A prototype swap is listed because it shadows a method * without leaving the own property the behavioural half inspects. * A textual rule, so a write through a local alias or a cast receiver * escapes it. The behavioural half is the `apply()`-twice case in * `test/reload.test.ts`, which requires a patch record on every own function * `apply()` leaves on its stand-in `llm` and adapter (P-R1 adds `settings` to * the stand-in together with its site). */ const HOST_WRITES = [ /\bReflect\.(?:set|defineProperty|deleteProperty|setPrototypeOf)\s*\(/gu, /\bObject\.(?:assign|defineProperty|defineProperties|setPrototypeOf)\(\s*(?:[\w$]+[?!]?\.)*(?:llm|adapter|settings|globalThis)\b/gu, /\b(?:llm|adapter|settings)[!?]?\.\w+\s*=(?![=>])/gu, /\b(?:llm|adapter|settings)!?\[[^\]\n]+\]\s*=(?![=>])/gu, /\bglobalThis\.\w+\s*=(?![=>])/gu, ]; /** * Named exemptions, each `: `. The global `fetch` * patch is a global, not a host service method: P6 moved it into its own * installer, which reads the original inside the effect and unwinds through * disposed links in any order (`host/global-fetch.ts`). The exemption stays * while the patch keeps relays, listing enrichment, the credential fill, the * free-tier body fallback and the User-Agent (docs/improvement-plan.md). */ const EXEMPT = new Set(["host/global-fetch.ts: globalThis.fetch ="]); /** Every host write in `source`, as `: `. */ const hostWritesIn = (file: string, source: string): string[] => HOST_WRITES.flatMap((pattern) => [...source.matchAll(pattern)].map((match) => `${file}: ${match[0]}`) ); it("flags a planted violation of each kind, so a pass means something", () => { const planted = [ "llm.listModels = wrapped;", "ctx.llm.resolveModelInfo = async () => ({});", 'adapter["resolveModel"] = wrapped;', "settings.describe = describe;", "Reflect.set(llm, key, wrapped);", "Reflect.defineProperty(adapter, key, { value: wrapped });", "Reflect.deleteProperty(llm, key);", "globalThis.fetch = patched;", "ctx.llm!.listModels = wrapped;", "adapter![key] = wrapped;", 'Object.defineProperty(settings, "describe", { value: wrapped });', "Object.assign(ctx.llm, { listModels: wrapped });", "Object.defineProperties(adapter, { modelOf: { value: wrapped } });", // A prototype swap shadows a method without leaving an own property. "Reflect.setPrototypeOf(llm, proto);", "Object.setPrototypeOf(adapter, proto);", // The receiver reached through a property path, as the plane-adapter // decoration P-R1 deleted reached the adapter. "Object.assign(registration?.adapter, { modelOf: wrapped });", 'Object.defineProperty(this.llm, "listModels", { value: wrapped });', ].join("\n"); expect(hostWritesIn("planted.ts", planted)).toHaveLength(17); // Reads, comparisons and a define onto the plugin's own prototype are not // host writes. expect( hostWritesIn( "planted.ts", "if (llm.listModels === x) {}\nconst f = (adapter) => adapter.modelOf;\nconst g = llm.x == null;\n" + 'Object.defineProperty(UsageService.prototype, "inspect", marker);' ) ).toEqual([]); }); it("walks a graph that contains the helper and the sites it serves", () => { const graph = runtimeGraph(ENTRY); expect(graph.has(HELPER)).toBe(true); expect(graph.has("host/discovery.ts")).toBe(true); // The helper itself is what the rule exempts, and it does match it. expect(hostWritesIn(HELPER, graph.get(HELPER) ?? "")).not.toEqual([]); }); it("nothing reachable from lifecycle.ts but the helper writes a method onto a host object", () => { const violations = [...runtimeGraph(ENTRY)] .filter(([file]) => file !== HELPER) .flatMap(([file, source]) => hostWritesIn(file, source)) .filter((write) => !EXEMPT.has(write)); expect(violations).toEqual([]); }); it("every named exemption is still there, so a stale one is noticed", () => { const writes = new Set( [...runtimeGraph(ENTRY)].flatMap(([file, source]) => hostWritesIn(file, source) ) ); for (const exempt of EXEMPT) { expect(writes.has(exempt), exempt).toBe(true); } }); }); describe("architecture · tests reach src through one door", () => { const SUPPORT = join(import.meta.dirname, "support", "src.ts"); /** * Whether `source` DECLARES `name` — an `export const|function|class|…` * of it — rather than passing it on with `export { name } from "…"`. */ const declares = (source: string, name: string): boolean => new RegExp( String.raw`export (?:declare )?(?:abstract )?(?:async )?(?:const|let|function\*?|class|interface|type|enum) ${name}\b`, "u" ).test(source); /** Each `export { names } from "../../src/"` block, names unaliased. */ const reExportBlocks = ( source: string ): { readonly target: string; readonly names: readonly string[] }[] => [ ...source.matchAll( /^export (?:type )?\{([^}]*)\} from "\.\.\/\.\.\/src\/([^"]+)"/gmu ), ].map((match) => ({ names: (match[1] ?? "") .split(",") .map((entry) => entry .trim() .replace(/^type\s+/u, "") .replace(/\s+as\s+[\w$]+$/u, "") ) .filter((entry) => entry !== ""), target: match[2] ?? "", })); it("knows a declaration from a pass-through when it sees one", () => { // Known answers, so an empty miss list means the rule ran. const config = readFileSync(join(SRC_DIR, "config.ts"), "utf8"); expect(declares(config, "Config")).toBe(true); expect(declares('export { Config } from "./config.ts";', "Config")).toBe( false ); expect(declares("export type ConfigLike = 1;", "Config")).toBe(false); expect( reExportBlocks( 'export { a, type B, c as d } from "../../src/x.ts";\nexport type { E } from "../../src/y.ts";' ) ).toEqual([ { names: ["a", "B", "c"], target: "x.ts" }, { names: ["E"], target: "y.ts" }, ]); }); it("test/support/src.ts re-exports each name from the module that declares it", () => { // Re-exporting through `src/index.ts` would tie every test to the barrel, // which carries only the host's contract, and that coupling is what this // file exists to remove; and a name taken from a module that only passes // it on breaks when P10a moves the module that really defines it. const source = readFileSync(SUPPORT, "utf8"); expect(source).not.toMatch(/src\/index\.ts/u); const blocks = reExportBlocks(source); // Every `from "../../src/…"` in the file is one of the parsed blocks, and // there is one block per module, so the walk below is not vacuous. expect(blocks.length).toBe( source.match(/from "\.\.\/\.\.\/src\//gu)?.length ?? 0 ); expect(blocks.length).toBeGreaterThanOrEqual(40); const missing = blocks .map(({ target }) => target) .filter((target) => !existsSync(join(SRC_DIR, target))); expect(missing).toEqual([]); const notDeclared = blocks.flatMap(({ names, target }) => { const defining = readFileSync(join(SRC_DIR, target), "utf8"); return names .filter((name) => !declares(defining, name)) .map((name) => `${name} is not declared in src/${target}`); }); expect(notDeclared).toEqual([]); }); }); describe("architecture · every test reaches src through one door", () => { const TEST_DIR = import.meta.dirname; /** * A static `import`/`export … from "(../)+src/…"`, multi-line blocks * included, and a side-effect `import "(../)+src/…";`. A * `vi.mock("../src/x.ts")` target and its `importOriginal` * type are not statements of this shape: module identity is their subject, * so they keep their paths. */ const STATIC_SRC_IMPORT = /^(?:(?:import|export)\b[^;]*?\bfrom\s+|import\s+)"(?:\.\.\/)+src\/[^"]+"/gmu; /** * A dynamic `import("(../)+src/…")` that is not a `typeof import(…)` type. * It is allowed only as a fresh re-import, so only in a file that calls * `vi.resetModules(`; anywhere else it is the door bypassed at runtime. */ const DYNAMIC_SRC_IMPORT = /(? /@(?:vitest|jest)-environment\s+([\w-]+)\b/u.exec(source)?.[1] === "jsdom"; /** * Files whose subject is the `src` layout or the barrel, the door itself, * and the setup file that imports `src` directly — a setup file that loaded * the door would pull the host graph into every jsdom test. Every other * `support/` file is walked like a test. */ const exempt = (file: string): boolean => file === "support/src.ts" || file === "support/reset-process-state.ts" || file === "architecture.test.ts" || file === "public-api.test.ts"; /** A value import of the door: a client test must not load the host graph. */ const DOOR_VALUE_IMPORT = /^import\s+(?!type\b)[^;]*?\bfrom\s+"(?:\.\.\/)*(?:\.\/)?support\/src\.ts"/gmu; /** * Comments blanked out with their line breaks kept, so `file:line` is true. * Line by line, so a `/*` inside a string cannot open a fake block that * hides the code after it (see `support/strip-comments.ts`). */ const blankComments = blankCommentLines; /** The test tree the gate walks: every `.ts`/`.tsx` not exempt by name. */ const walked = (): string[] => filesUnder(TEST_DIR).filter((f) => !exempt(f)); it("knows a static import from a mock target or a fresh re-import", () => { const matches = (line: string): boolean => new RegExp(STATIC_SRC_IMPORT.source, "mu").test(line); expect(matches('import { a } from "../src/a.ts";')).toBe(true); expect(matches('import type { A } from "../../src/a.ts";')).toBe(true); expect(matches('import {\n a,\n b,\n} from "../src/a.ts";')).toBe(true); expect( matches('vi.mock("../src/a.ts", async (importOriginal) => ({}));') ).toBe(false); expect(matches('importOriginal()')).toBe( false ); expect(matches('const m = await import("../src/a.ts");')).toBe(false); // A side-effect import loads the module just the same. expect(matches('import "../src/a.ts";')).toBe(true); const dynamic = (text: string): boolean => new RegExp(DYNAMIC_SRC_IMPORT.source, "u").test(text); expect(dynamic('const m = await import("../src/a.ts");')).toBe(true); expect(dynamic('importOriginal()')).toBe( false ); // The pragma as vitest reads it, built so this file stays a node test. const pragma = ["@vitest", "environment jsdom"].join("-"); expect(isClientTest(`// ${pragma}\n`)).toBe(true); expect(isClientTest(`/** ${pragma} */\n`)).toBe(true); expect(isClientTest("// a node test\n")).toBe(false); expect(isClientTest(readFileSync(import.meta.filename, "utf8"))).toBe( false ); // The first pragma decides, as in vitest, and its name is read whole. const nodePragma = ["@vitest", "environment node"].join("-"); expect( isClientTest(`// ${nodePragma}\n// unlike the ${pragma} tests\n`) ).toBe(false); expect( isClientTest(`// ${pragma}\n// unlike the ${nodePragma} tests\n`) ).toBe(true); expect(isClientTest(`// ${pragma}-global\n`)).toBe(false); // A `/*` inside a string opens no comment: the import after it is seen. const tricky = 'x("a/*b");\nimport "../src/x.ts";\n// c */\n'; expect( new RegExp(STATIC_SRC_IMPORT.source, "mu").test(blankComments(tricky)) ).toBe(true); const trickyDynamic = 'x("a/*b");\nconst m = await import("../src/x.ts");\n// c */\n'; expect( new RegExp(DYNAMIC_SRC_IMPORT.source, "u").test( blankComments(trickyDynamic) ) ).toBe(true); const door = (text: string): boolean => new RegExp(DOOR_VALUE_IMPORT.source, "mu").test(text); expect(door('import { a } from "./support/src.ts";')).toBe(true); expect(door('import { a } from "../support/src.ts";')).toBe(true); expect(door('import type { A } from "./support/src.ts";')).toBe(false); // The walk is real: it reaches the suites, the mocks and the e2e tree, // and leaves the door itself out. const files = walked(); expect(files).toContain("catalog.test.ts"); expect(files).toContain("mock/helpers.ts"); expect(files).toContain("e2e/protocol-routing.e2e.ts"); expect(files).not.toContain("support/src.ts"); expect(files).toContain("support/catalogs.ts"); }); it("no static src import outside the exemptions", () => { // A test that names a `src` path breaks on every module move; the door, // test/support/src.ts, is the one file that knows where names live. const offenders = walked().flatMap((file) => { const raw = readFileSync(join(TEST_DIR, file), "utf8"); const source = blankComments(raw); const at = (match: RegExpExecArray, why: string): string => { const end = (match.index ?? 0) + match[0].length; const line = source.slice(0, end).split("\n").length; return `${file}:${String(line)} ${why}`; }; if (isClientTest(raw)) { // A client test may name its own `src` module; what it must not do // is load the door, which reaches the whole host graph. return [...source.matchAll(DOOR_VALUE_IMPORT)].map((match) => at(match, "jsdom test loads the door") ); } const dynamic = source.includes("vi.resetModules(") ? [] : [...source.matchAll(DYNAMIC_SRC_IMPORT)].map((match) => at(match, "dynamic src import without vi.resetModules()") ); return [ ...[...source.matchAll(STATIC_SRC_IMPORT)].map((match) => at(match, "static src import") ), ...dynamic, ]; }); expect(offenders).toEqual([]); }); }); describe("architecture · the unit run binds no socket", () => { const TEST_DIR = import.meta.dirname; /** A module whose only use in a test is a server or a raw socket. */ const SOCKET_MODULE = /^(?:node:)?(?:dgram|http|http2|https|net|tls)$/u; /** A call that binds or serves: a server, the mock gateway, a listen. */ const SOCKET_CALL = /\b(?:createServer|startMockGateway)\s*\(|\.listen\s*\(/gu; /** * Every socket use in one file's comment-blanked source: a runtime import * of a socket module (a type-only one is erased, so it binds nothing) and a * call that binds, each as `file:line why`. */ const socketUsesIn = (file: string, raw: string): string[] => { const source = stripComments(raw); const imports = runtimeImportsOf(source) .filter((specifier) => SOCKET_MODULE.test(specifier)) .map((specifier) => `${file} imports ${specifier}`); const calls = [...source.matchAll(SOCKET_CALL)].map((match) => { const line = source.slice(0, match.index).split("\n").length; return `${file}:${String(line)} ${match[0].trim()}`; }); return [...imports, ...calls]; }; /** * The files the unit run loads from `test/`: every unit test file and, * transitively, every module inside `test/` one of them imports at runtime * (a support module, a helper, a mock module a unit case borrows a pure * half from). This file is left out: its planted rows are its subject. */ const unitGraph = (): Map => { const seen = new Map(); const visit = (file: string): void => { if (seen.has(file) || !existsSync(join(TEST_DIR, file))) { return; } const raw = readFileSync(join(TEST_DIR, file), "utf8"); seen.set(file, raw); for (const specifier of runtimeImportsOf(stripComments(raw))) { if (!specifier.startsWith("./") && !specifier.startsWith("../")) { continue; } const target = posix.normalize( posix.join(posix.dirname(file), specifier) ); if (!target.startsWith("../")) { visit(target); } } }; for (const file of filesUnder(TEST_DIR)) { if (/\.test\.tsx?$/u.test(file) && file !== "architecture.test.ts") { visit(file); } } return seen; }; it("walks a graph that reaches the support modules and the borrowed mock half", () => { const files = [...unitGraph().keys()]; expect(files).toContain("support/host.ts"); expect(files).toContain("support/catalogs.ts"); // `keyed-probes.test.ts` borrows the gateway's pure request handler, so // the walk crosses into `mock/` and the gate reads what it loads there. expect(files).toContain("mock/opencode-gateway.ts"); expect(files).not.toContain("architecture.test.ts"); }); it("no unit test, nor any test module it loads, imports a socket module or binds one", () => { // The offline guard admits loopback, so it cannot hold this; a case that // needs a socket belongs to the mock suite (`test/mock/*.mock.ts`). const offenders = [...unitGraph()].flatMap(([file, raw]) => socketUsesIn(file, raw) ); expect(offenders).toEqual([]); }); it("flags a planted use of each kind, in code but not in a comment, so a pass means something", () => { const planted = [ 'import { createServer } from "node:http";', 'import net from "node:net";', 'import type { IncomingMessage } from "node:http";', "// createServer(() => {}).listen(0);", "const server = createServer(handler);", 'server.listen(0, "127.0.0.1");', "const gateway = await startMockGateway();", ].join("\n"); expect(socketUsesIn("planted.ts", planted)).toEqual([ "planted.ts imports node:http", "planted.ts imports node:net", "planted.ts:5 createServer(", "planted.ts:6 .listen(", "planted.ts:7 startMockGateway(", ]); }); }); describe("architecture · the coverage floors name files that exist", () => { it("every per-file threshold key in vite.config.ts is a source file", () => { // A floor on a file that moved or was deleted is a floor on nothing: the // threshold silently stops measuring. Read from the config's text, which is // what the coverage run reads. const config = readFileSync( join(import.meta.dirname, "..", "vite.config.ts"), "utf8" ); const keys = [...config.matchAll(/^\s*"(src\/[^"]+)":\s*\{/gmu)].map( (match) => match[1] ?? "" ); expect(keys.length, "the config must name per-file floors").toBeGreaterThan( 0 ); const ROOT = join(import.meta.dirname, ".."); expect(keys.filter((key) => !existsSync(join(ROOT, key)))).toEqual([]); // The pattern reads a planted key, so an empty answer above means something. expect( [...plantedFloor().matchAll(/^\s*"(src\/[^"]+)":\s*\{/gmu)].map( (match) => match[1] ) ).toEqual(["src/x.ts"]); }); }); /** A config fragment with one per-file floor, for the pattern's known answer. */ const plantedFloor = (): string => ["thresholds: {", ' "src/x.ts": {', " lines: 100,", " },", "}"].join( "\n" ); describe("architecture · the modules the plane routes replaced are gone", () => { it("no hidden-route mount, protocol table, Gemini bridge, pi model builder or replay translator is left in src", () => { // P-R1 (D13): the plugin serves each plane through its own adapter, so // the modules that mounted pi-ai a second time under hidden routes, and // the translators that kept a Gemini replay across two provider labels, // have nothing left to do. Their survivors live in `utils/protocols.ts`. const ROOT = join(import.meta.dirname, ".."); const replaced = [ "src/responses-provider.ts", "src/responses-routes.ts", "src/google-bridge.ts", "src/pi-provider.ts", "src/utils/google-replay.ts", ]; expect(replaced.filter((file) => existsSync(join(ROOT, file)))).toEqual([]); // The check reads the tree: the module that took their place is there. expect(existsSync(join(ROOT, "src/utils/protocols.ts"))).toBe(true); }); });