From 2764f606b92c7e60f8c7d29b0ddb44c3f4421a95 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 20:53:45 +0100 Subject: [PATCH 1/8] 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 2/8] 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 3/8] 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 4/8] 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 5/8] 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 75aeb3cce69c56987a0ca869433f236df7a3db99 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 21:29:06 +0100 Subject: [PATCH 6/8] 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 7/8] 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 be59d52f238c9da29d2bbfc60797c96a0970c3b2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 22:14:26 +0100 Subject: [PATCH 8/8] 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"); });