diff --git a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts index 379a73809a..843dfa5561 100644 --- a/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts +++ b/packages/ui-backend-claude/tests/fixtures/server-host-relay-probe.ts @@ -196,6 +196,11 @@ try { }); const view = activeView = manager ? await prepareNativeWorkerStartupView(brainPath, manager) : undefined; const beforeRunnerListeners = new Set(tracked); + // The diff below lists the temp directory, which is this probe's own: + // native-route-qualification starts it under bwrap with a fresh tmpfs on + // /tmp, and the identity proof starts it in a container of its own, one + // step at a time. A launcher that shares /tmp with other test processes + // must give it a private TMPDIR first (#4252). const relayDirectories = readdirSync(tmpdir()).filter(name => name.startsWith("brain-inference-")); try { await runner.startTurn({ prompt: turn ? "Continue the Ithaca plan." : "Plan the return to Ithaca.", diff --git a/packages/ui-server/tests/capture-outcome.test.ts b/packages/ui-server/tests/capture-outcome.test.ts index 75ccfe563e..a7d1d4e405 100644 --- a/packages/ui-server/tests/capture-outcome.test.ts +++ b/packages/ui-server/tests/capture-outcome.test.ts @@ -1,9 +1,10 @@ import { expect, test } from "bun:test"; -import { chmodSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { chmodSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { installNativeBrainClientFixtures } from "./helpers/native-brain-client-fixture.js"; import { createBrainRoutes } from "../src/routes/brain"; +import { completeJsonLines } from "./helpers/json-lines.js"; const { createFixtureBrainClient: createBrainClient } = installNativeBrainClientFixtures(); @@ -25,7 +26,7 @@ test("capture keeps partial success and retry runs only index through the actual expect(await saved.json()).toMatchObject({ success: true, path: "notes/topic.md", indexed: false, indexError: "database is locked" }); const retries = await Promise.all(Array.from({ length: 3 }, () => app.request("/brain/index", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }))); for (const retry of retries) expect(await retry.json()).toEqual({ success: true }); - expect(readFileSync(calls, "utf8").trim().split("\n").map(line => JSON.parse(line)[0])).toEqual(["add", "index"]); + expect(completeJsonLines(calls).map(args => args[0])).toEqual(["add", "index"]); const refused = await app.request("/brain/index", { method: "POST" }); expect(refused.status).toBe(415); // A failed index never retries capture, and a later retry is not latched. diff --git a/packages/ui-server/tests/helpers/json-lines.ts b/packages/ui-server/tests/helpers/json-lines.ts new file mode 100644 index 0000000000..975860846b --- /dev/null +++ b/packages/ui-server/tests/helpers/json-lines.ts @@ -0,0 +1,13 @@ +/** + * Read the records another process appends to a JSON-lines file, one + * `appendFileSync` per record. The writer creates the file before it writes + * the line, so a read in between sees an empty file, and a read during the + * write sees a partial line. Only lines ended by a newline are complete: the + * rest is dropped, and the next poll reads it whole (#4247). + */ +import { existsSync, readFileSync } from "node:fs"; + +export function completeJsonLines(path: string): T[] { + if (!existsSync(path)) return []; + return readFileSync(path, "utf8").split("\n").slice(0, -1).filter(line => line.trim() !== "").map(line => JSON.parse(line) as T); +} diff --git a/packages/ui-server/tests/helpers/private-tmpdir.ts b/packages/ui-server/tests/helpers/private-tmpdir.ts new file mode 100644 index 0000000000..52c7daec2c --- /dev/null +++ b/packages/ui-server/tests/helpers/private-tmpdir.ts @@ -0,0 +1,23 @@ +/** + * Point `TMPDIR` at a directory of this process's own while a test runs. + * Other test processes create directories with the same prefixes in the + * shared temp directory at the same time, so a test that lists it to prove + * what it created or removed must list one nobody else writes to (#4252). + */ +import { chmodSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +export function usePrivateTmpdir(prefix: string): { path: string; restore(): void } { + const shared = process.env.TMPDIR; + const path = mkdtempSync(join(tmpdir(), prefix)); + chmodSync(path, 0o755); + process.env.TMPDIR = path; + return { + path, + restore() { + if (shared === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = shared; + rmSync(path, { recursive: true, force: true }); + }, + }; +} diff --git a/packages/ui-server/tests/host-version-requirements.test.ts b/packages/ui-server/tests/host-version-requirements.test.ts index 1473cecf86..64e3189c33 100644 --- a/packages/ui-server/tests/host-version-requirements.test.ts +++ b/packages/ui-server/tests/host-version-requirements.test.ts @@ -16,6 +16,7 @@ import { hostProcessAlive, waitForHostProcesses } from "./helpers/host-processes import { makeFakeBackend } from "./helpers/fake-backend"; import { registeredVersionDeadline } from "../../ui-sdk/tests/helpers/registered-version-deadline"; import { MIN_BRAIN_CLI_VERSION } from "../src/brain/client"; +import { completeJsonLines } from "./helpers/json-lines.js"; const roots: string[] = []; const closeNative: (() => Promise)[] = []; afterEach(async () => { for (const close of closeNative.splice(0)) await close(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); @@ -38,7 +39,7 @@ function fixture(version = MIN_BRAIN_CLI_VERSION) { const boundary = (exec: import("@schlessera/brain-ui-sdk/server").ExecWrapperConfig = {}) => createHostBoundary({ brainPath: root, dbPath: config.dbPath, exec, nativeManager }); const observability = createRecordingObservability(); const registry = createStaticBackendRegistry([makeFakeBackend({ id: "fake" })]); - const invocations = () => existsSync(calls) ? readFileSync(calls, "utf8").trim().split("\n").map(line => JSON.parse(line) as string[]) : []; + const invocations = () => completeJsonLines(calls); return { root, bin, install, config, observability, registry, invocations, boundary }; } diff --git a/packages/ui-server/tests/http-object-bodies.test.ts b/packages/ui-server/tests/http-object-bodies.test.ts index ac3cf32ebb..15ff4083b6 100644 --- a/packages/ui-server/tests/http-object-bodies.test.ts +++ b/packages/ui-server/tests/http-object-bodies.test.ts @@ -8,6 +8,7 @@ import { resetVerificationReservations } from "../src/middleware/auth"; import { createRecordingObservability } from "../src/observability"; import { makeFakeBackend } from "./helpers/fake-backend"; import { createTestApp, type TestApp } from "./helpers/test-app"; +import { completeJsonLines } from "./helpers/json-lines.js"; const PASSWORD = "odyssey-fixture-password"; const SECRET = "fixture-cookie-secret-0123456789abcdef"; @@ -20,8 +21,7 @@ let callsPath: string; let contentPath: string; function addCalls(): string[][] { - return readFileSync(callsPath, "utf8").trim().split("\n") - .filter(Boolean).map((line) => JSON.parse(line) as string[]) + return completeJsonLines(callsPath) .filter((args) => args[0] === "add"); } diff --git a/packages/ui-server/tests/http-supported-mounts.test.ts b/packages/ui-server/tests/http-supported-mounts.test.ts index 5e1d31dca4..b858d9355a 100644 --- a/packages/ui-server/tests/http-supported-mounts.test.ts +++ b/packages/ui-server/tests/http-supported-mounts.test.ts @@ -12,6 +12,7 @@ import { closeHttpMountFixture, createHttpMountPool, httpMountAgentKey } from ". import { observeMountTimers } from "./helpers/http-mount-timers"; import { mountLifetimes } from "./helpers/http-mount-lifetimes"; import { documentedRoutes, httpCoverageMatrix } from "./helpers/http-spec"; +import { completeJsonLines } from "./helpers/json-lines.js"; const SECRET = "http-contract-fixture-secret-0123456789"; const json = (method: string, body: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); @@ -218,7 +219,7 @@ async function checkHandler(operation: string, check: Check, t: HttpContractApp, await check.verify?.(response, t); if (operation.includes("/api/brain/") && operation !== "POST /api/brain/sync") { const command = operation.split("/").at(-1)!; - const args = readFileSync(join(t.brainPath, CLI_LOG), "utf8").trim().split("\n").map((l) => JSON.parse(l) as string[]); + const args = completeJsonLines(join(t.brainPath, CLI_LOG)); expect(args.some((a) => a[0] === (command === "history" ? "stats" : command))).toBe(true); } } diff --git a/packages/ui-server/tests/http-validation.test.ts b/packages/ui-server/tests/http-validation.test.ts index 765b01c99c..1da6183a5f 100644 --- a/packages/ui-server/tests/http-validation.test.ts +++ b/packages/ui-server/tests/http-validation.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; -import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { CLI_LOG, httpContractApp } from "./helpers/http-contract-app"; +import { completeJsonLines } from "./helpers/json-lines.js"; test("mounted capture rejects incorrect JSON media, oversized bytes and missing content without invoking add", async () => { const t = await httpContractApp(); @@ -19,13 +19,12 @@ test("mounted capture rejects incorrect JSON media, oversized bytes and missing 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)) : []; + const calls = completeJsonLines(join(t.brainPath, CLI_LOG)); 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 }); - expect(readFileSync(join(t.brainPath, CLI_LOG), "utf8").trim().split("\n").map(l => JSON.parse(l)[0])).toContain("add"); + expect(completeJsonLines(join(t.brainPath, CLI_LOG)).map(args => args[0])).toContain("add"); } finally { await t.close(); } }); diff --git a/packages/ui-server/tests/hygiene-review.test.ts b/packages/ui-server/tests/hygiene-review.test.ts index 1d759b15af..3cd75aa37f 100644 --- a/packages/ui-server/tests/hygiene-review.test.ts +++ b/packages/ui-server/tests/hygiene-review.test.ts @@ -17,6 +17,7 @@ import { Hono } from "hono"; import type { AppEnv } from "../src/app-env.js"; import type { InboxActionItem, InboxDelta, ServerMessage } from "@schlessera/brain-ui-sdk/protocol"; import { parseServerMessage } from "@schlessera/brain-ui-sdk/schemas"; +import { completeJsonLines } from "./helpers/json-lines.js"; const { createFixtureBrainClient: createBrainClient } = installNativeBrainClientFixtures(); @@ -51,7 +52,7 @@ function setup(body = "Odysseus sees [[Eumaeus hut]].", missingTitle = false) { const brain = createBrainClient({ brainPath: root, exec: {} }); const review = createHygieneReview(db, { brain }); const store = createInboxStore(db); - const argv = () => existsSync(join(root, "argv.jsonl")) ? readFileSync(join(root, "argv.jsonl"), "utf8").trim().split("\n").map(s => JSON.parse(s) as string[]) : []; + const argv = () => completeJsonLines(join(root, "argv.jsonl")); const applies = () => argv().filter(a => a.includes("resolve") && !a.includes("--dry-run")); return { root, db, principal, brain, review, store, argv, applies }; } diff --git a/packages/ui-server/tests/json-lines.test.ts b/packages/ui-server/tests/json-lines.test.ts new file mode 100644 index 0000000000..8f1f22a30d --- /dev/null +++ b/packages/ui-server/tests/json-lines.test.ts @@ -0,0 +1,22 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { completeJsonLines } from "./helpers/json-lines.js"; + +let dir = "", files = 0; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "odysseus-json-lines-")); }); +afterEach(() => { rmSync(dir, { recursive: true, force: true }); }); +const file = (text?: string) => { + const path = join(dir, `calls-${++files}.jsonl`); + if (text !== undefined) writeFileSync(path, text); + return path; +}; + +test("a JSON-lines read in the middle of an append gives only the complete records (#4247)", () => { + expect(completeJsonLines(file()), "MISSING_FILE_HAS_NO_RECORDS").toEqual([]); + expect(completeJsonLines(file("")), "CREATED_BUT_UNWRITTEN_FILE_HAS_NO_RECORDS").toEqual([]); + expect(completeJsonLines(file('{"tool":"web_se')), "PARTIAL_FIRST_LINE_IS_DROPPED").toEqual([]); + expect(completeJsonLines(file('{"tool":"web_search"}\n{"tool":"web_fe')), "UNTERMINATED_LAST_LINE_IS_DROPPED").toEqual([{ tool: "web_search" }]); + expect(completeJsonLines(file('{"tool":"web_search"}\n{"tool":"web_fetch"}\n')), "COMPLETE_LINES_ARE_ALL_READ").toEqual([{ tool: "web_search" }, { tool: "web_fetch" }]); +}); diff --git a/packages/ui-server/tests/turn-data-tree-placement.test.ts b/packages/ui-server/tests/turn-data-tree-placement.test.ts index 7e8048b861..30c3ef0a25 100644 --- a/packages/ui-server/tests/turn-data-tree-placement.test.ts +++ b/packages/ui-server/tests/turn-data-tree-placement.test.ts @@ -16,6 +16,7 @@ import * as startup from "../../ui-sdk/src/server/worker-startup-view"; import { prepareNativeWorkerStartupView } from "../../ui-sdk/src/server/worker-startup-view"; import { createFixtureWorkerStartupView } from "../../ui-sdk/tests/helpers/worker-startup-view-fixture"; import { createTurnDataTree, TURN_TREE_EFFECT_BYTES, turnTreeAllowance } from "../src/brain/turn-data-tree"; +import { usePrivateTmpdir } from "./helpers/private-tmpdir.js"; const cleanups: Array<() => void | Promise> = []; afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); @@ -67,7 +68,14 @@ async function fixture(options: { tree?: boolean } = {}) { await copy(from, to, (mode & ~fs.constants.COPYFILE_FICLONE_FORCE) | fs.constants.COPYFILE_FICLONE); }) as typeof fsp.copyFile); cleanups.push(() => spy.mockRestore()); - const tmpTrees = () => fs.readdirSync(tmpdir()).filter(name => name.startsWith("brain-turn-data-")); + // A temporary copy would land in the temp directory, where other processes + // create trees of their own: list one only this fixture writes to (#4252). + const tmp = usePrivateTmpdir("odysseus-tree-placement-tmp-"); + cleanups.push(() => tmp.restore()); + const tmpTrees = () => { + expect(tmpdir(), "TREES_ARE_LISTED_IN_THIS_FIXTURES_OWN_TEMP_DIRECTORY").toBe(tmp.path); + return fs.readdirSync(tmpdir()).filter(name => name.startsWith("brain-turn-data-")); + }; const before = new Set(tmpTrees()); return { store, brain, view, calls, flags, refuse(code?: string) { refuse = code; }, newTmpTrees: () => tmpTrees().filter(name => !before.has(name)), diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index e72131b95f..2b5863890b 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -11,6 +11,28 @@ import { createTurnScope, SCOPE_DISCONNECTED_MS } from "../src/brain/turn-scope. import { scopeFixture } from "./helpers/scope-fixture.js"; import { registeredInterval } from "./helpers/registered-interval.js"; async function wait(check: () => boolean, timeout = 5000) { const end = Date.now() + timeout; while (!check()) { if (Date.now() > end) throw Error("Scope fixture timed out"); await Bun.sleep(10); } } +/** Process names below `pid`, read from the host's /proc, which sees into the worker's PID namespace. */ +function descendantNames(pid: number): string[] { + const parents = new Map(), names = new Map(); + for (const entry of readdirSync("/proc")) { + if (!/^\d+$/.test(entry)) continue; + let stat: string; try { stat = readFileSync(`/proc/${entry}/stat`, "utf8"); } catch { continue; } + const close = stat.lastIndexOf(")"), ppid = Number(stat.slice(close + 2).split(" ")[1]); + names.set(Number(entry), stat.slice(stat.indexOf("(") + 1, close)); + parents.set(ppid, [...(parents.get(ppid) ?? []), Number(entry)]); + } + const found: string[] = [], queue = [...(parents.get(pid) ?? [])]; + while (queue.length) { const next = queue.shift()!; found.push(names.get(next) ?? ""); queue.push(...(parents.get(next) ?? [])); } + return found; +} +/** + * Wait until a `while :; do sleep 1; done` worker is really running. Its + * sandbox's PID 1 forks the shell after launch, and a freeze before then + * cannot confirm a stopped tree: on a loaded runner the first observation + * outran the fork and failed "did not confirm its frozen state". The wait is + * a hang catch-all, not a timing claim. + */ +async function sleeping(child: { pid: number }) { await wait(() => descendantNames(child.pid).includes("sleep"), 60_000); } test("real process tree freezes, resumes once per dimension, then stops with event-bound replay and independent grants", async () => { const f = scopeFixture({ max_tool_calls: 2, max_bytes_written: 8 }); let child: ReturnType | undefined; @@ -68,7 +90,7 @@ test("real process tree freezes, resumes once per dimension, then stops with eve test("shared snapshots count ignored scratch, workspace bytes and repeated observed bytes, with independent finite grant", async () => { const f = scopeFixture({ max_bytes_written: 8, max_files_changed: 3 }); let child: ReturnType | undefined; try { - await f.begin(); child = f.worker('while :; do sleep 1; done'); + await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); writeFileSync(join(f.brain, ".brain/scratch/loom"), "12345678"); await f.journal.observe(); expect(f.receipt()).toMatchObject({ dimension: "turn_bytes", count: 8, cap: 8, newCap: 16 }); expect((await f.scope.decide(f.message("continue"), true)).state).toBe("accepted"); @@ -83,24 +105,26 @@ test("shared snapshots count ignored scratch, workspace bytes and repeated obser }); test("files_changed leaves out a reference clone under workspaces/ but counts every path outside it (#3793)", async () => { - const f = scopeFixture({ max_files_changed: 1000 }); let child: ReturnType | undefined; + // The cap is small so the file volume stays small: a 30 s hang limit on a + // loaded worker is no budget for writing thousands of files (#4249). + const f = scopeFixture({ max_files_changed: 20 }); let child: ReturnType | undefined; try { - await f.begin(); child = f.worker('while :; do sleep 1; done'); - // A fetch and checkout of a mid-sized repository, and nothing in the brain. + await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); + // A checkout far larger than the cap, and nothing in the brain. mkdirSync(join(f.brain, "workspaces/argo/src"), { recursive: true }); - for (let index = 0; index < 1500; index++) writeFileSync(join(f.brain, "workspaces/argo/src", `oar-${index}.ts`), `export const oar = ${index};\n`); + for (let index = 0; index < 150; index++) writeFileSync(join(f.brain, "workspaces/argo/src", `oar-${index}.ts`), `export const oar = ${index};\n`); await f.journal.observe(); const scope = () => f.journal.summary("voyage").scope!; expect(scope().receipts, "WORKSPACE_CLONE_DOES_NOT_PAUSE_FILES_CHANGED").toEqual([]); - expect(scope().changedPaths, "SUMMARY_STILL_DISCLOSES_WORKSPACE_PATHS").toBeGreaterThanOrEqual(1500); - for (let index = 0; index < 999; index++) writeFileSync(join(f.brain, `ithaca-${index}.md`), `Day ${index}\n`); + expect(scope().changedPaths, "SUMMARY_STILL_DISCLOSES_WORKSPACE_PATHS").toBeGreaterThanOrEqual(150); + for (let index = 0; index < 19; index++) writeFileSync(join(f.brain, `ithaca-${index}.md`), `Day ${index}\n`); await f.journal.observe(); expect(scope().receipts, "BRAIN_PATHS_BELOW_THE_CAP_DO_NOT_PAUSE").toEqual([]); // A sibling sharing the prefix is outside workspaces/ and counts. mkdirSync(join(f.brain, "workspaces-old")); writeFileSync(join(f.brain, "workspaces-old/x.md"), "Old raft\n"); - writeFileSync(join(f.brain, "ithaca-999.md"), "Day 999\n"); + writeFileSync(join(f.brain, "ithaca-19.md"), "Day 19\n"); await f.journal.observe(); - expect(f.receipt(), "BRAIN_PATHS_PAST_THE_CAP_STILL_PAUSE").toMatchObject({ dimension: "files_changed", count: 1001, cap: 1000, state: "paused", frozen: true }); + expect(f.receipt(), "BRAIN_PATHS_PAST_THE_CAP_STILL_PAUSE").toMatchObject({ dimension: "files_changed", count: 21, cap: 20, state: "paused", frozen: true }); await f.scope.decide(f.message("stop"), true); await child.exited; } finally { child?.kill("SIGKILL"); if (child) await child.exited; await f.close(); } }); @@ -108,7 +132,7 @@ test("files_changed leaves out a reference clone under workspaces/ but counts ev test("workspace writes still count toward turn_bytes and pause the turn there (#3793)", async () => { const f = scopeFixture({ max_files_changed: 1, max_bytes_written: 1024 }); let child: ReturnType | undefined; try { - await f.begin(); child = f.worker('while :; do sleep 1; done'); + await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); mkdirSync(join(f.brain, "workspaces/argo")); writeFileSync(join(f.brain, "workspaces/argo/hull.bin"), Buffer.alloc(1024, 1)); writeFileSync(join(f.brain, "workspaces/argo/keel.bin"), Buffer.alloc(1024, 2)); await f.journal.observe(); @@ -201,7 +225,7 @@ test("the disposable index counts once at its largest size, ignored or not, and test("connected pause has no scope expiry; disconnect lifetime, reconnect and restart never resume automatically", async () => { let clock = Date.now(); const f = scopeFixture({ max_tool_calls: 1 }, () => clock); let child: ReturnType | undefined; try { - await f.begin(); child = f.worker('while :; do sleep 1; done'); f.scope.toolCall("voyage", "loom"); + await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); f.scope.toolCall("voyage", "loom"); clock += SCOPE_DISCONNECTED_MS * 2; await f.journal.observe(); expect(f.receipt().state).toBe("paused"); f.disconnect(); await f.journal.observe(); clock += SCOPE_DISCONNECTED_MS - 1; await f.journal.observe(); expect(f.receipt().state).toBe("paused"); f.reconnect(); await f.journal.observe(); expect(f.receipt().state, "SCOPE_RECONNECT_NEVER_RESUMES").toBe("paused"); @@ -418,7 +442,7 @@ test("real host restart kills its paused namespace, records interruption and nev test("wall time uses the frozen policy independently of later edits and hard limits, then allows only one finite grant", async () => { let clock = Date.now(); const f = scopeFixture({ max_minutes: .25 }, () => clock); let child: ReturnType | undefined; try { - await f.begin(); child = f.worker('while :; do sleep 1; done'); f.policy.scope.max_minutes = 90; clock += 15_001; await f.journal.observe(); + await f.begin(); child = f.worker('while :; do sleep 1; done'); await sleeping(child); f.policy.scope.max_minutes = 90; clock += 15_001; await f.journal.observe(); expect(f.receipt()).toMatchObject({ dimension: "minutes", cap: .25, newCap: .5, frozen: true }); expect((await f.scope.decide(f.message("continue"), true)).state).toBe("accepted"); clock += 15_001; await f.journal.observe(); expect(f.receipt()).toMatchObject({ cap: .5, state: "paused" }); expect(f.receipt().newCap).toBeUndefined(); diff --git a/packages/ui-server/tests/web-pi-worker.test.ts b/packages/ui-server/tests/web-pi-worker.test.ts index 0945431c99..7570224d15 100644 --- a/packages/ui-server/tests/web-pi-worker.test.ts +++ b/packages/ui-server/tests/web-pi-worker.test.ts @@ -8,7 +8,7 @@ */ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; @@ -17,6 +17,7 @@ import { createPiBackend } from "../../ui-backend-pi/src/backend.js"; import { createWebBroker, type WebBroker, type WebReceipt } from "../src/web-tools/broker.js"; import { createChildWebExecutor } from "../src/web-tools/child-executor.js"; import { createWebAccess } from "../src/ws/bridge-capabilities/web.js"; +import { completeJsonLines } from "./helpers/json-lines.js"; let root: string, brain: string, executorDir: string, broker: WebBroker, receipts: WebReceipt[]; beforeEach(() => { @@ -31,8 +32,7 @@ beforeEach(() => { }); afterEach(async () => { await broker.close(); rmSync(root, { recursive: true, force: true }); }); -const executed = () => existsSync(join(executorDir, "calls.jsonl")) - ? readFileSync(join(executorDir, "calls.jsonl"), "utf8").trim().split("\n").map(line => JSON.parse(line)) : []; +const executed = () => completeJsonLines(join(executorDir, "calls.jsonl")); async function piTurn(mode: string) { const previous = process.env.PI_CODING_AGENT_DIR; diff --git a/packages/ui-server/tests/web-tools-broker.test.ts b/packages/ui-server/tests/web-tools-broker.test.ts index f86683d2c5..62b336b426 100644 --- a/packages/ui-server/tests/web-tools-broker.test.ts +++ b/packages/ui-server/tests/web-tools-broker.test.ts @@ -14,6 +14,7 @@ import { WEB_SEARCH_PROVIDERS } from "@schlessera/brain-ui-sdk/internal"; import { WEB_TOOL_PROVIDERS } from "@schlessera/brain-ui-sdk/tool-contracts"; import { createWebBroker, type WebBroker, type WebBrokerLimits, type WebCallScope, type WebReceipt } from "../src/web-tools/broker.js"; import { createChildWebExecutor } from "../src/web-tools/child-executor.js"; +import { completeJsonLines } from "./helpers/json-lines.js"; let dir: string, broker: WebBroker, receipts: WebReceipt[]; const FIXTURE = join(import.meta.dir, "fixtures/web-executor.ts"); @@ -34,8 +35,7 @@ const scope = (sessionId = "s-ithaca", principalId = "p-penelope", turnId = "t-v function call(at: WebCallScope, tool: WebToolCall["tool"], input: Record, options: { signal?: AbortSignal; current?: () => boolean } = {}): Promise { return broker.call(at, { tool, input, toolCallId: at.toolCallId }, options.signal ?? new AbortController().signal, options.current ?? (() => true)); } -const calls = () => existsSync(join(dir, "calls.jsonl")) - ? readFileSync(join(dir, "calls.jsonl"), "utf8").trim().split("\n").map(line => JSON.parse(line)) : []; +const calls = () => completeJsonLines(join(dir, "calls.jsonl")); const executorReceipts = () => receipts.filter((receipt): receipt is Extract => receipt.kind === "executor"); const groupGone = (pid: number) => { try { process.kill(pid, 0); return false; } catch { return true; } }; async function until(condition: () => boolean, label = "condition not met", ms = 3_000) {