From 5fa09a59f4808bf5dceb82ab53a04057ea2fd52e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 2 Nov 2026 17:35:10 +0000 Subject: [PATCH] chore(ci): remove three root scripts with no consumer scripts/measure-graph-routes.ts, scripts/replay-ci-consumers.ts and scripts/generated-inputs.ts (with its test) have no reader in the tree and their driving issues are closed. Drop the stale shard-cost entry for the removed test and record the last main commit that holds them under "Considered and left alone" in the measurement-archive record. Refs #2510 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/measurement-archive.md | 15 +++ scripts/generated-inputs.ts | 56 --------- scripts/measure-graph-routes.ts | 161 -------------------------- scripts/replay-ci-consumers.ts | 30 ----- scripts/test-shard-costs.json | 1 - tests/generated-inputs.test.ts | 59 ---------- 6 files changed, 15 insertions(+), 307 deletions(-) delete mode 100644 scripts/generated-inputs.ts delete mode 100644 scripts/measure-graph-routes.ts delete mode 100644 scripts/replay-ci-consumers.ts delete mode 100644 tests/generated-inputs.test.ts diff --git a/docs/decisions/measurement-archive.md b/docs/decisions/measurement-archive.md index a46dc1e86d..0ec9d3aff3 100644 --- a/docs/decisions/measurement-archive.md +++ b/docs/decisions/measurement-archive.md @@ -275,6 +275,21 @@ lists 240 of them, and the triage answers file under suggestions documents and one to the site-model spike's README. It links them at the pinned commit `c577320cb4b9e3224a84a374e975ef5910db1edd`, which still contains them, so those links stay valid and were not changed. +- Three root scripts lost their last consumer once their driving issues closed, + and were removed from `main` by + [#2510](https://github.com/schlessera/brain-kit/issues/2510). They are + harnesses, not measurement output, so they were not added to the archive + branch. Main commit `a62db8f27a22fd2df744308e9b1ee12bc50f3da2` is the last + to contain all four files; read them there: + - `scripts/measure-graph-routes.ts` timed graph reads for + [#1030](https://github.com/schlessera/brain-kit/issues/1030), after #697 + moved them onto `./queries`. + - `scripts/replay-ci-consumers.ts` replayed root-proof consumer selection + for #2149 (closing #2123). It read a 100-PR snapshot that was never + committed. + - `scripts/generated-inputs.ts` and its test `tests/generated-inputs.test.ts` + came from #2178 (refs #2126 and #2190). It was library code with no + production caller, so only its own test ran it. ## Pointers moved to the archive diff --git a/scripts/generated-inputs.ts b/scripts/generated-inputs.ts deleted file mode 100644 index 1861f8caa0..0000000000 --- a/scripts/generated-inputs.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** Audited ephemeral producers. A producer receipt alone never resolves a consumer root. */ -import { createHash } from "node:crypto"; -import { readFileSync, realpathSync } from "node:fs"; -import { resolve } from "node:path"; -import ts from "typescript"; -export interface GeneratedProducer { - owner: string; root: string; expression: string; -} -export interface ProducerReceipt { - owner: string; root: string; relativePath: string; contentDigest: string; - producerDigest: string; consumerBound: false; -} -/** Only fixed literal bytes in a newly owned temp root; external/parameter roots do not qualify. */ -export function inspectGeneratedProducer(root: string, binding: GeneratedProducer): ProducerReceipt { - if (binding.owner.includes("..") || binding.owner.startsWith("/") || !/^[A-Za-z_$][\w$]*$/.test(binding.root)) throw Error("Invalid generated producer identity"); - const path = resolve(root, binding.owner); - if (!/\.[cm]?[jt]sx?$/.test(binding.owner) || realpathSync(path) !== path) throw Error("Unsupported generated producer source"); - const source = readFileSync(path, "utf8"), ast = ts.createSourceFile(binding.owner, source, ts.ScriptTarget.Latest, true); - if ((ast as ts.SourceFile & { parseDiagnostics: readonly ts.Diagnostic[] }).parseDiagnostics.length) throw Error("Invalid generated producer source"); - const imports = new Map(), declarations: ts.VariableDeclaration[] = [], calls: ts.CallExpression[] = []; - for (const statement of ast.statements) if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) { - const module = statement.moduleSpecifier.text.replace(/^node:/, ""), names = statement.importClause?.namedBindings; - if (names && ts.isNamedImports(names)) for (const element of names.elements) imports.set(element.name.text, `${module}:${element.propertyName?.text ?? element.name.text}`); - } - const walk = (node: ts.Node) => { if (ts.isVariableDeclaration(node)) declarations.push(node); if (ts.isCallExpression(node)) calls.push(node); ts.forEachChild(node, walk); }; - walk(ast); - const named = (node: ts.Node | undefined, name: string) => Boolean(node && ts.isIdentifier(node) && node.text === name); - const imported = (node: ts.Node | undefined, identity: string) => Boolean(node && ts.isIdentifier(node) && imports.get(node.text) === identity); - const rootDeclarations = declarations.filter(node => named(node.name, binding.root)); - const rootDeclaration = rootDeclarations[0], initializer = rootDeclaration?.initializer; - if (rootDeclarations.length !== 1 || !initializer || !ts.isCallExpression(initializer) || !imported(initializer.expression, "fs:mkdtempSync") || initializer.arguments.length !== 1) throw Error("Generated producer requires one owned mkdtemp root"); - if (!(rootDeclaration.parent.flags & ts.NodeFlags.Const)) throw Error("Generated root must be immutable"); - const temp = initializer.arguments[0]; - if (!temp || !ts.isCallExpression(temp) || !imported(temp.expression, "path:join") || temp.arguments.length !== 2 || !ts.isCallExpression(temp.arguments[0]!) || !imported(temp.arguments[0]!.expression, "os:tmpdir") || !ts.isStringLiteral(temp.arguments[1]!) || !/^[A-Za-z0-9-]+$/.test(temp.arguments[1]!.text)) throw Error("Generated root is not a bounded fresh temporary directory"); - const matching = calls.filter(node => node.getText(ast) === binding.expression); - if (matching.length !== 1) throw Error("Missing or ambiguous generated producer call"); - const call = matching[0]!; - const functionOwner = (node: ts.Node) => { for (let parent = node.parent; parent; parent = parent.parent) if (ts.isFunctionDeclaration(parent) || ts.isFunctionExpression(parent) || ts.isArrowFunction(parent)) return parent; }; - if (functionOwner(call) !== functionOwner(rootDeclaration)) throw Error("Generated producer call has another root scope"); - if (!ts.isIdentifier(call.expression) || call.arguments.length !== 2 || !ts.isStringLiteral(call.arguments[0]!) || !ts.isStringLiteral(call.arguments[1]!)) throw Error("Generated producer must write literal path and bytes"); - const relativePath = call.arguments[0]!.text, content = call.arguments[1]!.text; - if (!relativePath || relativePath.startsWith("/") || relativePath.split("/").some(part => !part || part === "." || part === "..") || /[\\\r\n\0]/.test(relativePath)) throw Error("Generated path escapes its owned root"); - const writers = declarations.filter(node => named(node.name, call.expression.getText(ast))); - const writer = writers[0]?.initializer; - if (writers.length !== 1 || !writer || !ts.isArrowFunction(writer) || writer.parameters.length !== 2 || !ts.isIdentifier(writer.parameters[0]!.name) || !ts.isIdentifier(writer.parameters[1]!.name)) throw Error("Unsupported generated writer binding"); - if (writers[0]!.parent.parent.parent !== rootDeclaration.parent.parent.parent || !(writers[0]!.parent.flags & ts.NodeFlags.Const)) throw Error("Generated writer and root have different lexical owners"); - if (writer.parameters.some(parameter => named(parameter.name, binding.root))) throw Error("Generated writer shadows its owned root"); - const writes: ts.CallExpression[] = []; - const collect = (node: ts.Node) => { if (ts.isCallExpression(node) && imported(node.expression, "fs:writeFileSync")) writes.push(node); ts.forEachChild(node, collect); }; - collect(writer.body); - const write = writes[0], target = write?.arguments[0]; - if (writes.length !== 1 || !write || write.arguments.length !== 2 || !named(write.arguments[1], writer.parameters[1]!.name.text) || !target || !ts.isCallExpression(target) || !imported(target.expression, "path:join") || target.arguments.length !== 2 || !named(target.arguments[0], binding.root) || !named(target.arguments[1], writer.parameters[0]!.name.text)) throw Error("Generated writer does not preserve its root/path/bytes binding"); - return { owner: binding.owner, root: binding.root, relativePath, - contentDigest: createHash("sha256").update(content).digest("hex"), - producerDigest: createHash("sha256").update(source).digest("hex"), consumerBound: false }; -} diff --git a/scripts/measure-graph-routes.ts b/scripts/measure-graph-routes.ts deleted file mode 100644 index 8d30098f95..0000000000 --- a/scripts/measure-graph-routes.ts +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Route latency of the graph view and the keyterm build, before and after - * #697 moved them onto core's supported query results. - * - * bun scripts/measure-graph-routes.ts [--cold-runs 10] [--warm-runs 50] - * - * Both implementations answer through real Hono routes (`routes.request`) over - * the same two CLI-produced indexes: the Odysseus fixture corpus, and a - * generated cap-sized graph (5,100 markdown notes, ~27,500 links) that - * exercises every node/edge cap. The baseline is the frozen pre-migration - * reader under tests/helpers/legacy-ui; the replacement is the shipped - * ui-server route with its lazily resolved core peer. - * - * Cold: the first request in a fresh process (module load, peer resolution, - * first open), one process per sample. Warm: requests after five warm-ups in - * one process. Keyless and offline; no network, no paid model. - */ -import { Database } from "bun:sqlite"; -import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "fs"; -import { cpus, tmpdir } from "os"; -import { join, resolve } from "path"; - -const ROOT = resolve(import.meta.dir, ".."); -const ROUTES = [ - "/graph/meta", - "/graph/clusters", - "/graph/neighborhood?center=CENTER", - "/graph/discovery", - "/graph/maintenance", - "keyterms", -] as const; -type Impl = "baseline" | "replacement"; - -function arg(name: string, fallback: number): number { - const i = process.argv.indexOf(name); - return i === -1 ? fallback : Number(process.argv[i + 1]); -} - -async function load(impl: Impl, brainPath: string) { - if (impl === "baseline") { - const { createGraphRoutes } = await import("../tests/helpers/legacy-ui/graph-routes.js"); - const { buildKeyterms } = await import("../tests/helpers/legacy-ui/keyterm-builder.js"); - return { routes: createGraphRoutes({ brainRoot: brainPath }), keyterms: () => buildKeyterms({ brainPath, cacheDir: brainPath, limit: 500 }) }; - } - const { createGraphRoutes } = await import("../packages/ui-server/src/routes/graph.js"); - const { buildKeyterms } = await import("../packages/ui-server/src/voice/keyterm-builder.js"); - const { createCoreQueryAccess } = await import("../packages/ui-server/src/core-queries.js"); - const queries = createCoreQueryAccess(); - return { routes: createGraphRoutes({ brainRoot: brainPath, queries }), keyterms: () => buildKeyterms({ brainPath, cacheDir: brainPath, limit: 500, queries }) }; -} - -async function once(target: Awaited>, route: string, center: string): Promise { - const start = Bun.nanoseconds(); - if (route === "keyterms") { - const cache = target.keyterms(); - if (cache.degraded || cache.count === 0) throw new Error("empty keyterms"); - } else { - const response = await target.routes.request(route.replace("CENTER", encodeURIComponent(center))); - if (response.status !== 200) throw new Error(`${route}: ${response.status}`); - await response.arrayBuffer(); - } - return (Bun.nanoseconds() - start) / 1e6; -} - -// Child mode: one cold sample. -if (process.argv[2] === "--child") { - const [, , , impl, brainPath, route, center] = process.argv; - const t0 = Bun.nanoseconds(); - const target = await load(impl as Impl, brainPath); - const ms = await once(target, route, center); - console.log(JSON.stringify({ ms, withLoad: (Bun.nanoseconds() - t0) / 1e6 })); - process.exit(0); -} - -const pct = (values: number[], p: number) => { - const sorted = [...values].sort((a, b) => a - b); - return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]; -}; - -async function cliIndex(source: string): Promise { - const dir = mkdtempSync(join(tmpdir(), "measure-graph-routes-")); - cpSync(source, dir, { recursive: true }); - for (const suffix of ["", "-wal", "-shm"]) rmSync(join(dir, ".brain-index", `brain.db${suffix}`), { force: true }); - symlinkSync(join(ROOT, "node_modules"), join(dir, "node_modules")); - const env: Record = { ...process.env, BRAIN_ROOT: dir }; - for (const name of ["GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "TYPESAFE_API_KEY", "BRAIN_RERANK_MODE"]) delete env[name]; - const child = Bun.spawn([process.execPath, join(ROOT, "packages/core/src/cli/brain.ts"), "index", "--force", "--json"], { env, stdout: "pipe", stderr: "pipe" }); - if (await child.exited !== 0) throw new Error(await new Response(child.stderr).text()); - const db = new Database(join(dir, ".brain-index", "brain.db")); - db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); - db.close(true); - return dir; -} - -/** The fixture index, rewritten to a graph that hits every cap. */ -function capSized(fixture: string): string { - const dir = mkdtempSync(join(tmpdir(), "measure-graph-routes-cap-")); - mkdirSync(join(dir, ".brain-index")); - cpSync(join(fixture, ".brain-index", "brain.db"), join(dir, ".brain-index", "brain.db")); - const db = new Database(join(dir, ".brain-index", "brain.db")); - db.exec("DELETE FROM links; DELETE FROM graph_metrics; DELETE FROM graph_layouts; DELETE FROM graph_communities; DELETE FROM graph_root_distances; DELETE FROM documents"); - const doc = db.query("INSERT INTO documents (id,path,title,type,status,created,updated,content,indexed_at,asset_type) VALUES (?,?,?,'note','active','2026-01-01','2026-01-01',?,'2026-01-01T00:00:00Z','markdown')"); - const metric = db.query("INSERT INTO graph_metrics (document_id,in_degree,out_degree,component,pagerank,community) VALUES (?,5,5,1,?,?)"); - const layout = db.query("INSERT INTO graph_layouts (mode,document_id,x,y) VALUES ('clusters',?,?,?)"); - const distance = db.query("INSERT INTO graph_root_distances (document_id,distance,parent_id) VALUES (?,?,NULL)"); - const link = db.query("INSERT INTO links (source_id,target,target_id) VALUES (?,?,?)"); - db.transaction(() => { - for (let i = 0; i < 5100; i++) { - doc.run(10000 + i, `notes/ithaca-${i}.md`, `Ithaca ${i}`, `**Penelope Icarius** waits on Ithaca ${i}. MCP log.`); - metric.run(10000 + i, i, i % 12); - layout.run(10000 + i, i % 100, Math.floor(i / 100)); - distance.run(10000 + i, 1 + (i % 8)); - } - for (let i = 0; i < 5100; i++) for (let j = 1; j <= 5; j++) link.run(10000 + i, `notes/ithaca-${(i + j) % 5100}.md`, 10000 + ((i + j) % 5100)); - for (let i = 6; i < 2000; i++) link.run(10000, `notes/ithaca-${i}.md`, 10000 + i); - db.run("INSERT INTO graph_communities (community,size,label,top_terms) SELECT DISTINCT community, 425, 'ithaca', '[\"ithaca\"]' FROM graph_metrics"); - db.run("INSERT OR REPLACE INTO index_metadata (key,value) VALUES ('graph_root','notes/ithaca-0.md')"); - })(); - db.close(true); - return dir; -} - -const coldRuns = arg("--cold-runs", 10); -const warmRuns = arg("--warm-runs", 50); -const fixture = await cliIndex(join(ROOT, "packages/core/fixtures/corpus")); -const cap = capSized(fixture); -const corpora = [ - { name: "fixture corpus", dir: fixture, center: "studies/star-bearings.md" }, - { name: "cap-sized graph", dir: cap, center: "notes/ithaca-0.md" }, -]; -console.log(`Bun ${Bun.version}, ${process.platform}/${process.arch}, ${cpus()[0]?.model ?? "unknown CPU"} x${cpus().length}`); -for (const corpus of corpora) { - const db = new Database(join(corpus.dir, ".brain-index", "brain.db"), { readonly: true }); - const counts = db.query<{ d: number; l: number }, []>("SELECT (SELECT COUNT(*) FROM documents) AS d, (SELECT COUNT(*) FROM links) AS l").get()!; - db.close(); - console.log(`\n## ${corpus.name}: ${counts.d} documents, ${counts.l} links; cold n=${coldRuns}, warm n=${warmRuns} (ms)\n`); - console.log("| route | baseline cold p50/p95 | replacement cold p50/p95 | baseline warm p50/p95 | replacement warm p50/p95 |"); - console.log("| --- | --- | --- | --- | --- |"); - const warm: Record>> = { baseline: await load("baseline", corpus.dir), replacement: await load("replacement", corpus.dir) }; - for (const route of ROUTES) { - const row: string[] = [route.replace("CENTER", corpus.center)]; - const cold: Record = { baseline: [], replacement: [] }; - for (let i = 0; i < coldRuns; i++) { - for (const impl of ["baseline", "replacement"] as const) { - const child = Bun.spawn([process.execPath, import.meta.path, "--child", impl, corpus.dir, route, corpus.center], { stdout: "pipe", stderr: "inherit" }); - const out = await new Response(child.stdout).text(); - if (await child.exited !== 0) throw new Error(`cold ${impl} ${route} failed`); - cold[impl].push(JSON.parse(out).ms); - } - } - const warmSamples: Record = { baseline: [], replacement: [] }; - for (const impl of ["baseline", "replacement"] as const) for (let i = 0; i < 5; i++) await once(warm[impl], route, corpus.center); - for (let i = 0; i < warmRuns; i++) { - for (const impl of ["baseline", "replacement"] as const) warmSamples[impl].push(await once(warm[impl], route, corpus.center)); - } - const fmt = (v: number[]) => `${pct(v, 50).toFixed(2)} / ${pct(v, 95).toFixed(2)}`; - row.push(fmt(cold.baseline), fmt(cold.replacement), fmt(warmSamples.baseline), fmt(warmSamples.replacement)); - console.log(`| ${row.join(" | ")} |`); - } -} -for (const corpus of corpora) rmSync(corpus.dir, { recursive: true, force: true }); diff --git a/scripts/replay-ci-consumers.ts b/scripts/replay-ci-consumers.ts deleted file mode 100644 index a61b5dcc2f..0000000000 --- a/scripts/replay-ci-consumers.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** Offline replay of the audited #1741–#2071 PR snapshot; no provider/network calls. */ -import { resolve } from "node:path"; -import { planChecks, rootConsumers, workspaces } from "./ci-plan"; -interface ReplaySnapshot { cutoff: string; order: string; prs: { number: number; changed: string[]; mergeCommit: string }[]; } - -export function replayConsumers(root: string, snapshot: ReplaySnapshot) { - if (snapshot.prs.length !== 100 || new Set(snapshot.prs.map(pr => pr.number)).size !== 100 || - snapshot.prs.some(pr => !/^[a-f0-9]{40}$/.test(pr.mergeCommit) || !pr.changed.length)) throw new Error("Expected 100 immutable merged PR diffs"); - const packages = workspaces(root); - const rows = snapshot.prs.map(({ number, changed, mergeCommit }) => { - const diff = Bun.spawnSync(["git", "diff", "--name-only", "--no-renames", "-z", `${mergeCommit}^`, mergeCommit], { cwd: root, stdout: "pipe", stderr: "pipe" }); - const actual = diff.stdout.toString().split("\0").filter(Boolean).sort(); - if (diff.exitCode || JSON.stringify(actual) !== JSON.stringify([...changed].sort())) throw new Error(`PR #${number}: snapshot does not match immutable merge diff`); - const before = planChecks(changed, packages, root, false); - const after = planChecks(changed, packages, root); - const hard = changed.filter(path => ["bun.lock", "package.json", ".changeset/config.json"].includes(path) || path.startsWith(".github/workflows/")); - const unknown = changed.filter(path => !/^(?:packages|template|api-report|docs|scripts|tests|experiments|website)\//.test(path) && !/\.(?:md|mdx|txt)$/.test(path) && !path.startsWith(".changeset/") && path !== "LICENSE"); - return { number, mergeCommit, beforeGlobal: before.global, afterGlobal: after.global, - unitFiles: after.unitTests, local: after.local, - reason: after.global ? hard.length ? `Global policy inputs: ${hard.join(", ")}` : unknown.length ? `Unknown roots: ${unknown.join(", ")}` : - rootConsumers(root, changed.filter(path => /^(?:scripts|tests|experiments|website)\//.test(path))).reason ?? "Unknown package ownership" : undefined }; - }); - return { cutoff: snapshot.cutoff, order: snapshot.order, count: rows.length, - beforeGlobal: rows.filter(row => row.beforeGlobal).length, - afterGlobal: rows.filter(row => row.afterGlobal).length, rows }; -} -if (import.meta.main) { - if (process.argv.length !== 3) throw new Error("usage: bun scripts/replay-ci-consumers.ts "); - console.log(JSON.stringify(replayConsumers(resolve(import.meta.dir, ".."), await Bun.file(process.argv[2]!).json()), null, 2)); -} diff --git a/scripts/test-shard-costs.json b/scripts/test-shard-costs.json index 25b363907d..f3c0bfeece 100644 --- a/scripts/test-shard-costs.json +++ b/scripts/test-shard-costs.json @@ -1083,7 +1083,6 @@ "tests/frontmatter-parse-gate.test.ts": 4.853, "tests/generated-audio-input.test.ts": 0.103, "tests/generated-build-inputs.test.ts": 0.552, - "tests/generated-inputs.test.ts": 0.196, "tests/generated-theme-inputs.test.ts": 1.463, "tests/geo-render.test.ts": 2.895, "tests/haiku-model-selection.test.ts": 0.1, diff --git a/tests/generated-inputs.test.ts b/tests/generated-inputs.test.ts deleted file mode 100644 index 315f55a1b3..0000000000 --- a/tests/generated-inputs.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { afterEach, expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; -import { inspectGeneratedProducer } from "../scripts/generated-inputs"; -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -const expression = `write("brain.config.ts", "export default {};\\n")`; -const source = `import {mkdtempSync,writeFileSync} from "node:fs"; -import {tmpdir} from "node:os"; import {join} from "node:path"; -const root = mkdtempSync(join(tmpdir(), "producer-proof-")); -const write = (path:string,bytes:string) => { writeFileSync(join(root,path),bytes); }; -${expression};`; -function fixture(contents: string) { const root = mkdtempSync(join(tmpdir(), "generated-inputs-")); roots.push(root); writeFileSync(join(root, "producer.ts"), contents); return root; } -test("fixed generated producer runs in an owned temporary root; receipt never claims a consumer binding", async () => { - const root = fixture(source), receipt = inspectGeneratedProducer(root, { owner: "producer.ts", root: "root", expression }); - expect(receipt.relativePath).toBe("brain.config.ts"); expect(receipt.consumerBound).toBe(false); - writeFileSync(join(root, "producer.ts"), source + `console.log(JSON.stringify({root}));`); - const child = Bun.spawn([process.execPath, join(root, "producer.ts")], { stdout: "pipe", stderr: "pipe" }); - const [output, error, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); - expect(code, error).toBe(0); - const generated = JSON.parse(output).root; - expect(generated.startsWith(join(tmpdir(), "producer-proof-"))).toBe(true); roots.push(generated); - expect(readFileSync(join(generated, "brain.config.ts"), "utf8")).toBe("export default {};\n"); -}); -test("redirected roots, producer drift, escaping paths and unbounded bytes cannot qualify", () => { - for (const changed of [source.replace(`mkdtempSync(join(tmpdir(), "producer-proof-"))`, "process.env.REDIRECT_ROOT"), source.replace("join(root,path)", "join(external,path)"), source.replace(expression, `write("../brain.config.ts", "fixed")`), source.replace(expression, `write("brain.config.ts", process.env.PAYLOAD)`), source + expression + ";"]) { - const root = fixture(changed); - const current = changed.includes(expression) ? expression : changed.includes("../brain") ? `write("../brain.config.ts", "fixed")` : `write("brain.config.ts", process.env.PAYLOAD)`; - expect(() => inspectGeneratedProducer(root, { owner: "producer.ts", root: "root", expression: current })).toThrow(); - } -}); -test("actual hygiene-loop config producer is verified but its CLI consumer stays unbound", () => { - const root = resolve(import.meta.dir, ".."), owner = "packages/ui-react/tests/browser/hygiene-loop-command.ts"; - const expression = /^\s*(write\("brain\.config\.ts", [^\n]+\));$/m.exec(readFileSync(join(root, owner), "utf8"))?.[1]; - expect(expression).toBeDefined(); - const receipt = inspectGeneratedProducer(root, { owner, root: "root", expression: expression! }); - expect(receipt.relativePath).toBe("brain.config.ts"); expect(receipt.producerDigest).toMatch(/^[0-9a-f]{64}$/); expect(receipt.consumerBound).toBe(false); -}); - - -test("actual core config resolves the generated CLI cwd only when root redirects are absent", async () => { - const generated = mkdtempSync(join(tmpdir(), "producer-cli-root-")); roots.push(generated); - writeFileSync(join(generated, "brain.config.ts"), "export default { taxonomy: { types: { note: { dir: \"journeys\", orphanExempt: true } } } };\n"); - const redirect = mkdtempSync(join(tmpdir(), "producer-cli-redirect-")); roots.push(redirect); - writeFileSync(join(redirect, "brain.config.ts"), "export default { taxonomy: { types: { note: { dir: \"other\" } } } };\n"); - const module = resolve(import.meta.dir, "../packages/core/src/lib/config.ts"); - const code = `import {resolveRoot,loadUserConfig} from ${JSON.stringify(module)}; const root=resolveRoot(); const loaded=await loadUserConfig(root); console.log(JSON.stringify({root,path:loaded.path,dir:loaded.config?.taxonomy?.types?.note?.dir}));`; - const env = { ...process.env }; - for (const name of ["BRAIN_ROOT", "BRAIN_WORKER_DATA_ROOT", "BRAIN_WORKER_CONFIG_ROOT"]) delete env[name]; - async function read(overrides: Record) { - const child = Bun.spawn([process.execPath, "-e", code], { cwd: generated, env: { ...env, ...overrides }, stdout: "pipe", stderr: "pipe" }); - const [output, error, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); - expect(exit,error).toBe(0); return JSON.parse(output); - } - expect(await read({})).toEqual({ root: generated, path: join(generated,"brain.config.ts"), dir:"journeys" }); - expect(await read({ BRAIN_ROOT: redirect })).toEqual({ root: redirect, path: join(redirect,"brain.config.ts"), dir:"other" }); - expect(await read({ BRAIN_WORKER_DATA_ROOT: generated, BRAIN_WORKER_CONFIG_ROOT: redirect })).toEqual({ root: generated, path: join(generated,"brain.config.ts"), dir:"other" }); -});