Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
5 changes: 3 additions & 2 deletions packages/ui-server/tests/capture-outcome.test.ts
Original file line number Diff line number Diff line change
@@ -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();

Expand All @@ -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<string[]>(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.
Expand Down
13 changes: 13 additions & 0 deletions packages/ui-server/tests/helpers/json-lines.ts
Original file line number Diff line number Diff line change
@@ -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<T = unknown>(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);
}
23 changes: 23 additions & 0 deletions packages/ui-server/tests/helpers/private-tmpdir.ts
Original file line number Diff line number Diff line change
@@ -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 });
},
};
}
3 changes: 2 additions & 1 deletion packages/ui-server/tests/host-version-requirements.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>)[] = [];
afterEach(async () => { for (const close of closeNative.splice(0)) await close(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
Expand All @@ -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<string[]>(calls);
return { root, bin, install, config, observability, registry, invocations, boundary };
}

Expand Down
4 changes: 2 additions & 2 deletions packages/ui-server/tests/http-object-bodies.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<string[]>(callsPath)
.filter((args) => args[0] === "add");
}

Expand Down
3 changes: 2 additions & 1 deletion packages/ui-server/tests/http-supported-mounts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) });
Expand Down Expand Up @@ -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<string[]>(join(t.brainPath, CLI_LOG));
expect(args.some((a) => a[0] === (command === "history" ? "stats" : command))).toBe(true);
}
}
Expand Down
7 changes: 3 additions & 4 deletions packages/ui-server/tests/http-validation.test.ts
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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<string[]>(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<string[]>(join(t.brainPath, CLI_LOG)).map(args => args[0])).toContain("add");
} finally { await t.close(); }
});

Expand Down
3 changes: 2 additions & 1 deletion packages/ui-server/tests/hygiene-review.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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<string[]>(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 };
}
Expand Down
22 changes: 22 additions & 0 deletions packages/ui-server/tests/json-lines.test.ts
Original file line number Diff line number Diff line change
@@ -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" }]);
});
10 changes: 9 additions & 1 deletion packages/ui-server/tests/turn-data-tree-placement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>> = [];
afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });
Expand Down Expand Up @@ -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)),
Expand Down
Loading
Loading