Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Store: registry bench, golden shape test and readRegistry helper (#6188)

Milind Soni7ac4f4954a91
diff --git a/package.json b/package.json
index 45356e438c..c53e506122 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"test:electron": "node --test \"electron/*.node-test.mjs\"",
"bench:observation": "node --experimental-strip-types scripts/bench-observation.ts",
"bench:persistence": "node --experimental-strip-types scripts/bench-persistence.ts",
+ "bench:registry": "node --experimental-strip-types scripts/bench-registry.ts",
"bench:runtime-reads": "node --experimental-strip-types scripts/bench-runtime-reads.ts",
"bench:today": "node --experimental-strip-types scripts/bench-today.ts",
"bench:browser-stream": "node --experimental-strip-types scripts/bench-browser-stream.ts",
diff --git a/scripts/bench-registry.ts b/scripts/bench-registry.ts
new file mode 100644
index 0000000000..cacafc76cc
--- /dev/null
+++ b/scripts/bench-registry.ts
@@ -0,0 +1,160 @@
+// What one registry save costs as bots and threads grow: bots.json and groups.json rewritten whole, with fsync, by the
+// real Store. Synthetic data in a throwaway folder per cell; never the person's own. Opt-in only (pnpm bench:registry),
+// never part of the test suite.
+// pnpm bench:registry the default matrix
+// pnpm bench:registry 34x200 1x5 only these cells (bots x threads per bot)
+import { spawnSync } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { arch, cpus, platform, tmpdir, totalmem } from "node:os";
+import { join } from "node:path";
+import { performance } from "node:perf_hooks";
+import { fileURLToPath } from "node:url";
+
+const DEFAULT_CELLS = ["1x5", "5x50", "34x200", "100x200", "200x200"];
+const CELL = /^(\d+)x(\d+)$/;
+
+type Result = {
+ bots: number; threadsPerBot: number; rooms: number; threadsPerRoom: number;
+ botsJsonKb: number; groupsJsonKb: number; loadMs: number; heapMb: number;
+ serializeP50Ms: number;
+ saveP50Ms: number; saveP95Ms: number; saveMaxMs: number;
+ bookkeepingP50Ms: number; bookkeepingP95Ms: number;
+ roomSaveP50Ms: number;
+ samples: number;
+};
+
+const round = (value: number) => Number(value.toFixed(2));
+const percentile = (values: number[], p: number) => {
+ const sorted = [...values].sort((a, b) => a - b);
+ return round(sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))]!);
+};
+const timed = (samples: number, run: (i: number) => void): number[] => {
+ const out: number[] = [];
+ for (let i = 0; i < samples; i++) {
+ const at = performance.now();
+ run(i);
+ out.push(performance.now() - at);
+ }
+ return out;
+};
+
+/** One cell, in a child whose OMB_DATA_DIR is already a fresh folder: config reads it at import. */
+async function runCell(bots: number, threadsPerBot: number): Promise<Result> {
+ const dataDir = process.env.OMB_DATA_DIR!;
+ const { Store } = await import("../server/store.ts");
+ const selection = () => ({ instanceId: "claude", model: "claude-sonnet-5" });
+
+ // Template records written by the Store itself, so the clones carry today's fields.
+ const seed = new Store(selection);
+ const bot = seed.createBot({ name: "Template", title: "Researcher", description: "Synthetic bot for the registry bench" });
+ const thread = seed.createTask(bot.id, "Synthetic thread title of a usual length", false)!;
+ seed.setResumeCursor(bot.id, "claude", randomUUID(), thread.threadId);
+ seed.markTaskDispatched(bot.id, thread.threadId, "claude");
+ seed.setTaskAskedAt(bot.id, thread.threadId, Date.now());
+ const room = seed.createGroup("Template room", [bot.id], false, undefined, { bulletin: "Synthetic bulletin." });
+ const botTemplate = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"))[0];
+ const roomTemplate = JSON.parse(readFileSync(join(dataDir, "groups.json"), "utf8")).find((r: { id: string }) => r.id === room.id);
+ const taskTemplate = botTemplate.tasks.find((t: { threadId: string }) => t.threadId === thread.threadId);
+ const roomTaskTemplate = roomTemplate.tasks[0];
+
+ const rooms = Math.ceil(bots / 10);
+ const threadsPerRoom = Math.min(threadsPerBot, 20);
+ const now = Date.now();
+ const botRecords = Array.from({ length: bots }, (_, b) => {
+ const tasks = Array.from({ length: threadsPerBot }, (_, t) => ({
+ ...structuredClone(taskTemplate), threadId: randomUUID(), title: `Thread ${t} of bot ${b}`,
+ createdAt: now - t * 60_000, updatedAt: now - t * 60_000, resumeCursors: { claude: randomUUID() },
+ }));
+ return { ...structuredClone(botTemplate), id: randomUUID(), name: `Bot ${b}`, threadId: tasks[0]!.threadId, tasks };
+ });
+ const roomRecords = Array.from({ length: rooms }, (_, r) => {
+ const tasks = Array.from({ length: threadsPerRoom }, (_, t) => ({
+ ...structuredClone(roomTaskTemplate), threadId: randomUUID(), title: `Room thread ${t}`, createdAt: now - t * 60_000, updatedAt: now - t * 60_000,
+ }));
+ return { ...structuredClone(roomTemplate), id: randomUUID(), name: `Room ${r}`, threadId: tasks[0]!.threadId,
+ memberIds: botRecords.slice(0, 5).map((record) => record.id), tasks };
+ });
+ writeFileSync(join(dataDir, "bots.json"), JSON.stringify(botRecords), { mode: 0o600 });
+ writeFileSync(join(dataDir, "groups.json"), JSON.stringify(roomRecords), { mode: 0o600 });
+
+ const gc = (globalThis as { gc?: () => void }).gc;
+ gc?.();
+ const heapBefore = process.memoryUsage().heapUsed;
+ let at = performance.now();
+ const store = new Store(selection);
+ const loadMs = performance.now() - at;
+ gc?.();
+ const heapMb = (process.memoryUsage().heapUsed - heapBefore) / 1024 / 1024;
+
+ const samples = bots * threadsPerBot >= 20_000 ? 20 : 40;
+ const pick = (i: number) => {
+ const owner = store.bots[(i * 7919) % store.bots.length]!;
+ const tasks = owner.tasks!;
+ return { botId: owner.id, threadId: tasks[(i * 104_729) % tasks.length]!.threadId };
+ };
+ for (let i = 0; i < 3; i++) store.renameTask(pick(i).botId, pick(i).threadId, `Warm-up ${i}`);
+ const serialize = timed(samples, () => { JSON.stringify(store.bots); });
+ // A durable change: the thread's title, saved at once with fsync.
+ const save = timed(samples, (i) => { const { botId, threadId } = pick(i); store.renameTask(botId, threadId, `Renamed ${i}`); });
+ // Bookkeeping a turn leaves: the engine session id. Outside a batched pass it saves at once too.
+ const bookkeeping = timed(samples, (i) => { const { botId, threadId } = pick(i); store.setResumeCursor(botId, "claude", `cursor-${i}`, threadId); });
+ const groupSamples = Math.min(samples, 20);
+ const roomSave = timed(groupSamples, (i) => {
+ const group = store.groups[i % store.groups.length]!;
+ store.patchGroupTask(group.id, group.tasks![i % group.tasks!.length]!.threadId, { title: `Room renamed ${i}` });
+ });
+ return {
+ bots, threadsPerBot, rooms, threadsPerRoom,
+ botsJsonKb: Math.round(statSync(join(dataDir, "bots.json")).size / 1024),
+ groupsJsonKb: Math.round(statSync(join(dataDir, "groups.json")).size / 1024),
+ loadMs: round(loadMs), heapMb: round(heapMb),
+ serializeP50Ms: percentile(serialize, 0.5),
+ saveP50Ms: percentile(save, 0.5), saveP95Ms: percentile(save, 0.95), saveMaxMs: percentile(save, 1),
+ bookkeepingP50Ms: percentile(bookkeeping, 0.5), bookkeepingP95Ms: percentile(bookkeeping, 0.95),
+ roomSaveP50Ms: percentile(roomSave, 0.5),
+ samples,
+ };
+}
+
+function parent(cells: string[]) {
+ for (const cell of cells) if (!CELL.test(cell)) throw new Error(`not a cell: ${cell} (want BOTSxTHREADS, e.g. 34x200)`);
+ const cpu = cpus()[0]?.model ?? "unknown";
+ console.log(JSON.stringify({ benchmark: "registry-save", node: process.version, platform: platform(), arch: arch(), cpu,
+ memoryGb: Math.round(totalmem() / 1024 ** 3),
+ scope: "Real Store, synthetic bots and threads cloned from records the Store wrote; one room per ten bots. Not a full turn." }));
+ const results: Result[] = [];
+ for (const cell of cells) {
+ const home = mkdtempSync(join(tmpdir(), "omb-registry-bench-home-"));
+ const data = mkdtempSync(join(tmpdir(), "omb-registry-bench-data-"));
+ try {
+ const run = spawnSync(process.execPath, ["--experimental-strip-types", "--no-warnings", "--expose-gc", fileURLToPath(import.meta.url), "--cell", cell], {
+ env: { ...process.env, HOME: home, USERPROFILE: home, OMB_DATA_DIR: data, OMB_DISABLE_ANNOUNCEMENTS: "1", OMB_DISABLE_MODEL_MANIFEST_FETCH: "1" },
+ encoding: "utf8", maxBuffer: 64 * 1024 * 1024,
+ });
+ const line = run.stdout.split("\n").find((text) => text.startsWith("{\"bots\""));
+ if (run.status !== 0 || !line) throw new Error(`cell ${cell} failed (${run.status}):\n${run.stderr}`);
+ console.log(line);
+ results.push(JSON.parse(line));
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ rmSync(data, { recursive: true, force: true });
+ }
+ }
+ console.log("\n| bots × threads | bots.json | load | heap after load | save p50 / p95 / max | bookkeeping p50 / p95 | serialize p50 | room save p50 |");
+ console.log("|---|---|---|---|---|---|---|---|");
+ for (const r of results) {
+ console.log(`| ${r.bots} × ${r.threadsPerBot} | ${r.botsJsonKb} KB | ${r.loadMs} ms | ${r.heapMb} MB | ${r.saveP50Ms} / ${r.saveP95Ms} / ${r.saveMaxMs} ms | `
+ + `${r.bookkeepingP50Ms} / ${r.bookkeepingP95Ms} ms | ${r.serializeP50Ms} ms | ${r.roomSaveP50Ms} ms |`);
+ }
+}
+
+const cellFlag = process.argv.indexOf("--cell");
+if (cellFlag !== -1) {
+ const [, bots, threads] = CELL.exec(process.argv[cellFlag + 1] ?? "") ?? [];
+ if (!bots || !threads || !process.env.OMB_DATA_DIR) throw new Error("--cell needs BOTSxTHREADS and OMB_DATA_DIR");
+ console.log(JSON.stringify(await runCell(Number(bots), Number(threads))));
+} else {
+ const asked = process.argv.slice(2).filter((arg) => !arg.startsWith("-"));
+ parent(asked.length ? asked : DEFAULT_CELLS);
+}
diff --git a/server/app-settings.e2e.test.ts b/server/app-settings.e2e.test.ts
index e6ee1e046a..d61ec616a7 100644
--- a/server/app-settings.e2e.test.ts
+++ b/server/app-settings.e2e.test.ts
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, expect, it } from "vitest";
import { launchVerificationServer, verificationServerArgs, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";
import { waitForExit } from "./testing/cleanup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const SECRET = "sk-test-123";
const XAI_URL = "https://example.test/v1";
@@ -66,11 +67,11 @@ beforeAll(async () => {
// Fixture setup, not a production grant: the stopped fixture's own bot is put on Full access on disk.
await waitForExit(fixture.child, { signal: "SIGTERM" });
- const saved = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
+ const saved = readRegistry(dataDir).bots;
const setter = saved.find((one: any) => one.id === bot.id);
setter.approvalMode = "full"; setter.autoApprove = false;
for (const task of setter.tasks) { task.approvalMode = "full"; task.autoApprove = false; }
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(saved, null, 2));
+ writeRegistry(dataDir, { bots: saved });
const env = verificationServerEnvironment({}, dataDir, Number(new URL(url).port));
const log = openSync(fixture.info.logPath, "a", 0o600);
child = spawn(process.execPath, verificationServerArgs(env), { cwd: join(import.meta.dirname, ".."), env, stdio: ["ignore", log, log] });
diff --git a/server/chief-level-delegation.e2e.test.ts b/server/chief-level-delegation.e2e.test.ts
index fe005130c2..5184d3370d 100644
--- a/server/chief-level-delegation.e2e.test.ts
+++ b/server/chief-level-delegation.e2e.test.ts
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { readRegistry } from "./testing/registry.ts";
it("starts a thread a Chief opens with a teammate at the Chief's level, and a Chief on Ask raises nobody", async () => {
const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true });
@@ -20,7 +21,7 @@ it("starts a thread a Chief opens with a teammate at the Chief's level, and a Ch
};
const cli = (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;
const messages = async (threadId: string) => (await api("GET", `/api/threads/${threadId}/messages?limit=100`)).messages as any[];
- const persistedTask = (botId: string, threadId: string) => JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"))
+ const persistedTask = (botId: string, threadId: string) => readRegistry(dataDir).bots
.find((bot: any) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId);
/** The Chief brings `teammate` in from `threadId` (coordinate_bots opens a
* thread with them); resolves with the teammate's provider turn. */
diff --git a/server/cloud-chat-merge.test.ts b/server/cloud-chat-merge.test.ts
index 40caa1fb15..b6c14128cf 100644
--- a/server/cloud-chat-merge.test.ts
+++ b/server/cloud-chat-merge.test.ts
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
import { activePath, applyChatMerge, mergeStagedChats, mergeThread, planChatMerge, type ChatsSide, type ChatStore, type ThreadRows } from "./cloud-chat-merge.ts";
import { DATA_DIR } from "./config.ts";
import { Store, type Message, type TaskRecord } from "./store.ts";
+import { writeRegistry } from "./testing/registry.ts";
const line = (id: string, at: number, parentId: string | null, role: "user" | "bot" = "user", extra: Partial<Message> = {}): Message =>
({ id, at, parentId, role, kind: "text", text: `${id} says hi`, ...extra });
@@ -136,8 +137,8 @@ describe("applied to a live store", () => {
/** This computer's copy as a backup stages it: rosters, its message database and its uploads. */
function staged(bots: unknown[], groups: unknown[], threads: Record<string, Message[]>, files: Record<string, string> = {}) {
const data = mkdtempSync(join(tmpdir(), "omb-staged-chats-"));
- writeFileSync(join(data, "bots.json"), JSON.stringify(bots));
- writeFileSync(join(data, "groups.json"), JSON.stringify(groups));
+ writeRegistry(data, { bots });
+ writeRegistry(data, { rooms: groups });
const db = new DatabaseSync(join(data, "messages.db"));
db.exec("CREATE TABLE messages (thread_id TEXT NOT NULL, id TEXT NOT NULL, at INTEGER NOT NULL, role TEXT NOT NULL, kind TEXT NOT NULL, text TEXT, json TEXT NOT NULL, PRIMARY KEY (thread_id, id)); CREATE TABLE thread_state (thread_id TEXT PRIMARY KEY, active_leaf_id TEXT);");
const insert = db.prepare("INSERT INTO messages VALUES (?, ?, ?, ?, ?, ?, ?)");
diff --git a/server/cloud-credit.e2e.test.ts b/server/cloud-credit.e2e.test.ts
index fe8addc4c7..f23e0dae30 100644
--- a/server/cloud-credit.e2e.test.ts
+++ b/server/cloud-credit.e2e.test.ts
@@ -13,6 +13,7 @@ import { cloudPairingSignature } from "./cloud-home.ts";
import { CLOUD_CREDIT_INSTANCE } from "./cloud-credit-provider.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { freePortBlock } from "./testing/ports.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
import { TRIAL_CREDIT_OWN_AI, TRIAL_CREDIT_REFUSED } from "./trial-credit.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
@@ -245,14 +246,14 @@ describe("the free trial's Claude credit on a Cloud home", { timeout: 90_000 },
const seeded = (await bots()).find((bot) => bot.name !== "From the desktop")!;
await waitForExit(child, { signal: "SIGTERM" });
// What a desktop copy installs: the desktop's bots.json, verbatim, on the desktop's own engines.
- const records = JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as Array<{ id: string; modelSelection: unknown; tasks?: Array<{ threadId: string; modelSelection?: unknown }> }>;
+ const records = readRegistry(data).bots as Array<{ id: string; modelSelection: unknown; tasks?: Array<{ threadId: string; modelSelection?: unknown }> }>;
const restored = records.find((record) => record.id === seeded.id)!;
restored.modelSelection = { instanceId: "codex", model: "gpt-5.5" };
restored.tasks![0]!.modelSelection = { instanceId: "desktop-endpoint", model: "llama-3" };
- writeFileSync(join(data, "bots.json"), JSON.stringify(records, null, 2));
+ writeRegistry(data, { bots: records });
await boot();
await expect.poll(async () => (await bots()).find((bot) => bot.id === seeded.id)?.modelSelection, { timeout: 20_000, interval: 200 }).toEqual(SONNET);
- const tasks = (JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as typeof records).find((record) => record.id === seeded.id)!.tasks!;
+ const tasks = (readRegistry(data).bots as typeof records).find((record) => record.id === seeded.id)!.tasks!;
expect(tasks.every((task) => task.modelSelection === undefined)).toBe(true);
expect(moved()[seeded.id]).toEqual({ instanceId: "codex", model: "gpt-5.5" });
expect(answered(await turn("still here?", seeded))).toBe(true);
diff --git a/server/cloud-lent-screen.e2e.test.ts b/server/cloud-lent-screen.e2e.test.ts
index 28ae43d9b0..4b6de7b5b1 100644
--- a/server/cloud-lent-screen.e2e.test.ts
+++ b/server/cloud-lent-screen.e2e.test.ts
@@ -16,6 +16,7 @@ import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { markLeftBehind } from "./testing/cloud-left-behind.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
import { freePortBlock } from "./testing/ports.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const HOST = "omb-t-0123456789ab.fly.dev";
@@ -157,12 +158,12 @@ it("lets an Auto conversation pinned to the cloud computer use the person's lent
// Stopped: an earlier Auto turn selected the cloud computer in this conversation (the pin a turn makes on its own), and
// a guest opened the other one before the Cloud was personal.
await waitForExit(child, { signal: "SIGTERM" });
- const bots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
- const record = (bots.bots ?? bots).find((bot: any) => bot.id === created.id);
+ const bots = readRegistry(dataDir).bots;
+ const record = bots.find((bot: any) => bot.id === created.id);
expect(record.computer).toBeUndefined();
const task = record.tasks.find((candidate: any) => candidate.threadId === created.threadId);
Object.assign(task, { surface: "cloud", surfaceSource: "auto" });
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(bots), { mode: 0o600 });
+ writeRegistry(dataDir, { bots });
markLeftBehind(dataDir, { threadIds: [guestThread] });
await boot();
await lendPc();
diff --git a/server/cloud-personal.e2e.test.ts b/server/cloud-personal.e2e.test.ts
index 62422d3fde..d0517693c5 100644
--- a/server/cloud-personal.e2e.test.ts
+++ b/server/cloud-personal.e2e.test.ts
@@ -13,6 +13,7 @@ import { afterAll, beforeAll, expect, it } from "vitest";
import { cloudPairingSignature } from "./cloud-home.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { freePortBlock } from "./testing/ports.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const HOST = "omb-t-0123456789ab.fly.dev";
@@ -225,13 +226,12 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl
const ownerKeyAtBoot = `p_${createHash("sha256").update("cloud-owner:3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93").digest("base64url").slice(0, 22)}`;
writeFileSync(join(dataDir, "lending-routines.json"), JSON.stringify({ version: 1, routines: { [before.stale]: "0".repeat(64) }, writers: { [before.stale]: ownerKeyAtBoot, [before.fullApproved]: ownerKeyAtBoot } }));
// A bot at Full access (set where only the desktop app can set it: its record).
- const bots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
- const record = Array.isArray(bots) ? bots : bots.bots;
- const full = record.find((bot: any) => bot.id === before.full.id);
+ const bots = readRegistry(dataDir).bots;
+ const full = bots.find((bot: any) => bot.id === before.full.id);
full.approvalMode = "full";
delete full.approvalGrant;
for (const task of full.tasks ?? []) { task.approvalMode = "full"; delete task.approvalGrant; delete task.autoApprove; }
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(bots));
+ writeRegistry(dataDir, { bots });
// A v0.1.91 Cloud home recorded who allowed a card by their device's key (a
// self-hosted server records no key): write it the way that release did.
const db = new DatabaseSync(join(dataDir, "messages.db"));
diff --git a/server/cloud-team-connections.e2e.test.ts b/server/cloud-team-connections.e2e.test.ts
index bcbef222dc..08f81eea39 100644
--- a/server/cloud-team-connections.e2e.test.ts
+++ b/server/cloud-team-connections.e2e.test.ts
@@ -14,6 +14,7 @@ import { startBrokerFake, type BrokerFake } from "./testing/broker-fake.ts";
import { startFakeHttpMcp, type FakeHttpMcp } from "./testing/fake-http-mcp-server.ts";
import { startFakeOAuth, type FakeOAuth } from "./testing/fake-oauth-server.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
+import { readRegistry } from "./testing/registry.ts";
const TOKEN = `ops_fake-team-${randomBytes(8).toString("hex")}`;
const OWNER = { email: "[email protected]", role: "owner" as const };
@@ -227,7 +228,7 @@ it("gives work her own message hands to another bot her own Gmail, and never wor
expect(created.status, JSON.stringify(created.body)).toBe(201);
const helper = created.body.bot as { id: string; mainThreadId: string };
const handOn = (who: string) => ({ name: "coordinate_bots", server: "agents", input: { bot_ids: [helper.id], message: `Fetch ${who}'s latest email.` } });
- const helperThreads = () => (JSON.parse(readFileSync(join(team.home, ".openmausbot", "bots.json"), "utf8")) as Array<{ id: string; tasks: Array<{ threadId: string }> }>)
+ const helperThreads = () => (readRegistry(join(team.home, ".openmausbot")).bots as Array<{ id: string; tasks: Array<{ threadId: string }> }>)
.find((entry) => entry.id === helper.id)!.tasks.map((task) => task.threadId).filter((threadId) => threadId !== helper.mainThreadId);
/** The Gmail step the helper ran in the work it was handed, once it has finished. */
const helperGmail = async (token: string, known: readonly string[]) => {
@@ -286,7 +287,7 @@ it("runs work her group-chat line hands on in the receiving bot's chat with her,
const created = await team.as(owner, "POST", "/api/bots", { name: "Clerk", visibility: "everyone" });
expect(created.status, JSON.stringify(created.body)).toBe(201);
const clerk = created.body.bot as { id: string; mainThreadId: string };
- const clerkWork = () => (JSON.parse(readFileSync(join(team.home, ".openmausbot", "bots.json"), "utf8")) as Array<{ id: string; tasks: Array<{ threadId: string }> }>)
+ const clerkWork = () => (readRegistry(join(team.home, ".openmausbot")).bots as Array<{ id: string; tasks: Array<{ threadId: string }> }>)
.find((entry) => entry.id === clerk.id)!.tasks.map((task) => task.threadId).filter((threadId) => threadId !== clerk.mainThreadId);
/** The room's row for Clerk's result: Scout is resumed with it in the room right after. */
const clerkReplied = async () => ((await messages(ada, roomThread)).body.messages as Array<{ roomRequest?: { phase?: string }; tool?: { name?: string } }>)
diff --git a/server/computer-engine-removal.e2e.test.ts b/server/computer-engine-removal.e2e.test.ts
index 3dfb1ae0b9..2de8ba34da 100644
--- a/server/computer-engine-removal.e2e.test.ts
+++ b/server/computer-engine-removal.e2e.test.ts
@@ -11,6 +11,7 @@ import { runControlOmb } from "../scripts/control-omb.ts";
import { SNAPSHOT_REUSE_MS } from "./harness/registry.ts";
import { freePortBlock } from "./testing/ports.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const ROOT = fileURLToPath(new URL("..", import.meta.url));
const FAKE_CLI = join(ROOT, "server/testing/fake-claude-cli.ts");
@@ -44,11 +45,11 @@ function install(home: string, boatPort: () => number) {
}).then(response => response.status);
const bots = async (): Promise<any[]> => (await api("GET", "/api/bots?messages=0")).bots;
const bot = async (botId: string) => (await bots()).find(entry => entry.id === botId);
- const savedBots = (): any[] => JSON.parse(readFileSync(join(data, "bots.json"), "utf8"));
+ const savedBots = (): any[] => readRegistry(data).bots;
const editSavedBot = (botId: string, edit: (bot: any) => void) => {
const saved = savedBots();
edit(saved.find(entry => entry.id === botId));
- writeFileSync(join(data, "bots.json"), JSON.stringify(saved, null, 2));
+ writeRegistry(data, { bots: saved });
};
const editConfig = (edit: (config: any) => void) => {
const path = join(data, "config.json");
diff --git a/server/context-compaction.e2e.test.ts b/server/context-compaction.e2e.test.ts
index 3d38b783c9..9af16773b9 100644
--- a/server/context-compaction.e2e.test.ts
+++ b/server/context-compaction.e2e.test.ts
@@ -6,6 +6,7 @@ import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";
import { request } from "../scripts/mcp-server.ts";
import { waitForExit } from "./testing/cleanup.ts";
+import { readRegistry } from "./testing/registry.ts";
async function fixture(test: (f: Awaited<ReturnType<typeof setup>>) => Promise<void>, hang = false, fakeEnv: NodeJS.ProcessEnv = {}) {
const f = await setup(hang, fakeEnv);
@@ -34,7 +35,7 @@ async function setup(hang: boolean, fakeEnv: NodeJS.ProcessEnv) {
const plan = join(session.info.dataDir, "room-plan.json");
writeFileSync(plan, JSON.stringify({ [bot.id]: { reply: "Acknowledged" } }));
const messages = async () => (await api(`/api/threads/${thread}/messages`)).messages as any[];
- const task = () => JSON.parse(readFileSync(join(session.info.dataDir, "bots.json"), "utf8"))
+ const task = () => readRegistry(session.info.dataDir).bots
.find((b: any) => b.id === bot.id).tasks.find((t: any) => t.threadId === thread);
const idle = () => expect.poll(async () => (await api("/api/bots?messages=0")).bots
.find((b: any) => b.id === bot.id).tasks.find((t: any) => t.threadId === thread).busy, { timeout: 15_000 }).toBe(false);
diff --git a/server/delta-context.e2e.test.ts b/server/delta-context.e2e.test.ts
index 6c0990bd74..8a15eb4a98 100644
--- a/server/delta-context.e2e.test.ts
+++ b/server/delta-context.e2e.test.ts
@@ -16,6 +16,7 @@ import { readHandoffs } from "./testing/handoff-rows.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
import { openSse } from "./testing/sse.ts";
import { withoutTurnClock } from "./testing/turn-clock-text.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const count = (text: string, needle: string) => text.split(needle).length - 1;
@@ -112,7 +113,7 @@ async function fixture(test: (f: any) => Promise<void>, options: { env?: NodeJS.
const messages = async (threadId = thread) => (await api(`/api/threads/${threadId}/messages`)).messages;
const nodes = () => readHandoffs(dataDir);
const root = () => nodes().filter((node: any) => !node.parentId && node.threadId === thread).at(-1);
- const task = (threadId = thread) => JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"))
+ const task = (threadId = thread) => readRegistry(dataDir).bots
.find((b: any) => b.id === chief.id).tasks.find((stored: any) => stored.threadId === threadId);
const handed = (threadId = thread) => task(threadId).handedMessages;
// A person-stopped or failed turn does not settle as "settled" for `wait`.
@@ -154,9 +155,9 @@ async function fixture(test: (f: any) => Promise<void>, options: { env?: NodeJS.
const open = (path: string) => writeFileSync(path, "open");
const restart = async (edit: (bots: any[]) => void, signal: NodeJS.Signals = "SIGTERM", extraEnv: NodeJS.ProcessEnv = {}) => {
await waitForExit(restarted ?? session.child, { signal });
- const bots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
+ const bots = readRegistry(dataDir).bots;
edit(bots);
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(bots, null, 2));
+ writeRegistry(dataDir, { bots });
const env = { ...verificationServerEnvironment(parentEnv, dataDir, Number(new URL(session.info.url).port)), ...extraEnv };
const log = openSync(session.info.logPath, "a", 0o600);
restarted = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))],
diff --git a/server/full-access-workflows.e2e.test.ts b/server/full-access-workflows.e2e.test.ts
index 02a826ac34..9683a41aa4 100644
--- a/server/full-access-workflows.e2e.test.ts
+++ b/server/full-access-workflows.e2e.test.ts
@@ -9,6 +9,7 @@ import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
import { waitForExit } from "./testing/cleanup.ts";
import { readHandoffs } from "./testing/handoff-rows.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
it("applies requested Full Access workflows through MCP without duplicate approvals, and the same changes apply in an Ask task with Undo", async () => {
const fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true });
@@ -110,7 +111,7 @@ it("applies requested Full Access workflows through MCP without duplicate approv
// This is fixture setup, not a production grant endpoint or bypass flag.
// Stop the exact owned server before changing its disposable persisted data.
await waitForExit(fixture.child, { signal: "SIGTERM" });
- const savedBots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
+ const savedBots = readRegistry(dataDir).bots;
const savedChief = savedBots.find((bot: any) => bot.id === chief.id);
savedChief.approvalMode = "full"; savedChief.autoApprove = false;
for (const task of savedChief.tasks) {
@@ -120,7 +121,7 @@ it("applies requested Full Access workflows through MCP without duplicate approv
const savedInverse = savedBots.find((bot: any) => bot.id === inverse.id);
savedInverse.approvalMode = "ask"; savedInverse.autoApprove = false;
savedInverse.tasks.find((task: any) => task.threadId === inverse.activeTaskId).approvalMode = "full";
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(savedBots, null, 2));
+ writeRegistry(dataDir, { bots: savedBots });
await restart();
expect((await api("GET", "/api/health")).capabilities).toMatchObject({ guardedFullAccess: 1 });
expect((await api("GET", "/api/health")).capabilities.sharedWorkspaceFullAccess).toBeUndefined();
@@ -241,7 +242,7 @@ it("applies requested Full Access workflows through MCP without duplicate approv
expect((await bots()).find(bot => bot.id === inverse.id)).toMatchObject({ title: "Applied from Full task", approvalMode: "ask" });
expect(await unanswered(chief.activeTaskId)).toHaveLength(0);
expect(providerTurns()).toHaveLength(7);
- const persisted = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
+ const persisted = readRegistry(dataDir).bots;
expect(persisted.find((bot: any) => bot.id === chief.id)).toMatchObject({ title: "Monthly reporting Chief", approvalMode: "full" });
expect(persisted.find((bot: any) => bot.id === chief.id).tasks.find((task: any) => task.threadId === ask.threadId).approvalMode).toBe("ask");
expect(persisted.find((bot: any) => bot.id === inverse.id)).toMatchObject({ title: "Applied from Full task", approvalMode: "ask" });
diff --git a/server/host-lazy-claim.e2e.test.ts b/server/host-lazy-claim.e2e.test.ts
index db3e77f4ca..adcc1c4c4b 100644
--- a/server/host-lazy-claim.e2e.test.ts
+++ b/server/host-lazy-claim.e2e.test.ts
@@ -12,6 +12,7 @@ import { freePortBlock } from "./testing/ports.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { answerYourComputer, openYourComputerCard, withAnswer } from "./testing/your-computer.ts";
import { YOUR_COMPUTER_WAITING } from "./your-computer-consent.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const ROOT = fileURLToPath(new URL("..", import.meta.url));
// A first screen call must clear within ACT_WITHIN_MS, the person's answer to its card and the seat's claim included.
@@ -75,7 +76,7 @@ describe("lazy host claim and pin on use (issue #1650)", () => {
const busy = (botId: string, threadId: string) => until(() => threadState(botId, threadId), Boolean);
const idle = (botId: string, threadId: string) => until(() => threadState(botId, threadId), task => !task?.busy);
const savedTask = (botId: string, threadId: string) =>
- (JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as any[])
+ (readRegistry(data).bots as any[])
.find((bot: any) => bot.id === botId)?.tasks.find((task: any) => task.threadId === threadId);
async function start(env: Record<string, string> = {}) {
@@ -446,10 +447,10 @@ describe("lazy host claim and pin on use (issue #1650)", () => {
await apiOk("PATCH", `/api/bots/${bot.id}`, { computer: "local" });
await stop();
// The pin an Auto turn left before the person set Works on to This computer, as bots.json keeps it.
- const bots = JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as any[];
+ const bots = readRegistry(data).bots as any[];
Object.assign(bots.find((one: any) => one.id === bot.id).tasks.find((one: any) => one.threadId === task.threadId),
{ surface: "local", surfaceSource: "auto" });
- writeFileSync(join(data, "bots.json"), JSON.stringify(bots, null, 2));
+ writeRegistry(data, { bots });
await start();
expect(savedTask(bot.id, task.threadId)).toMatchObject({ surface: "local", surfaceSource: "auto" });
resetTurn();
diff --git a/server/hosted-models-api.test.ts b/server/hosted-models-api.test.ts
index 406caa1dbb..0c7ed8528a 100644
--- a/server/hosted-models-api.test.ts
+++ b/server/hosted-models-api.test.ts
@@ -6,6 +6,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { launchVerificationServer, runControlOmb, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const ROOT = fileURLToPath(new URL("..", import.meta.url));
const TOKEN = `omb_workspace_${"s".repeat(43)}`;
@@ -146,8 +147,7 @@ beforeAll(async () => {
// Seed a prior release's saved selections only after the owned server exits.
await waitForExit(child, { signal: "SIGTERM" });
- const botsPath = join(fixture.info.dataDir, "bots.json");
- const saved = JSON.parse(readFileSync(botsPath, "utf8")) as SavedBot[];
+ const saved = readRegistry(fixture.info.dataDir).bots as SavedBot[];
// A prior release copied the bot's model onto every thread and had not run the one-time cleanup yet.
rmSync(join(fixture.info.dataDir, "thread-model-copies-cleared"), { force: true });
for (const bot of saved) for (const task of bot.tasks) {
@@ -164,7 +164,7 @@ beforeAll(async () => {
stale.tasks.find((task) => task.title === "Raw OpenRouter variant task")!.modelSelection = { instanceId: "opencode", model: INITIAL.openrouter[1], variant: "high" };
stale.tasks.find((task) => task.title === "Raw OpenRouter effort task")!.modelSelection = { instanceId: "opencode", model: INITIAL.openrouter[1], effort: "high" };
beforeTasks = structuredClone(stale.tasks);
- writeFileSync(botsPath, JSON.stringify(saved));
+ writeRegistry(fixture.info.dataDir, { bots: saved });
const configPath = join(fixture.info.dataDir, "config.json");
const config = JSON.parse(readFileSync(configPath, "utf8"));
config.defaultModelSelection = { instanceId: "opencode", model: INITIAL.openrouter[1], variant: "high" };
@@ -231,7 +231,7 @@ describe("hosted model policy in the full runtime", () => {
expect(JSON.parse(persisted).defaultModelSelection).toEqual({ instanceId: "opencode", model: INITIAL.openrouter[1] });
expect(persisted).not.toContain(TOKEN);
expect(persisted).not.toContain("/api/gateway/");
- const migrated = JSON.parse(readFileSync(join(fixture!.info.dataDir, "bots.json"), "utf8")) as SavedBot[];
+ const migrated = readRegistry(fixture!.info.dataDir).bots as SavedBot[];
for (const bot of migrated.filter((candidate) => candidate.id !== ids["Default hosted bot"])) {
for (const task of bot.tasks) {
expect(task.resumeCursors).toEqual({});
@@ -261,7 +261,7 @@ describe("hosted model policy in the full runtime", () => {
expect(after.messages.filter((message: { id: string }) => originalIds.has(message.id))).toEqual(history.messages);
expect(after.messages.length).toBeGreaterThan(history.messages.length);
history = after;
- const persisted = JSON.parse(readFileSync(join(fixture!.info.dataDir, "bots.json"), "utf8")) as SavedBot[];
+ const persisted = readRegistry(fixture!.info.dataDir).bots as SavedBot[];
const task = persisted.find((bot) => bot.id === primary.id)!.tasks.find((item) => item.threadId === primary.threadId)!;
expect(task.modelSelection).toEqual({ instanceId: "claude", model: INITIAL.anthropic[1] });
expect(task.resumeCursors.claude).toBeTruthy();
@@ -316,14 +316,13 @@ describe("hosted model policy in the full runtime", () => {
]) {
await control(["send", "--bot", bot.id, "--task", bot.threadId, "--text", "Remember this synthetic message before switching models."]);
expect(await control(["wait", "--bot", bot.id, "--task", bot.threadId, "--timeout", "15"])).toMatchObject({ status: "settled" });
- const botPath = join(fixture!.info.dataDir, "bots.json");
- const before = JSON.parse(readFileSync(botPath, "utf8")) as SavedBot[];
+ const before = readRegistry(fixture!.info.dataDir).bots as SavedBot[];
expect(before.find(row => row.id === bot.id)!.tasks[0].resumeCursors.claude).toBeTruthy();
const messages = (await api("GET", `/api/threads/${bot.threadId}/messages?limit=50`)).body;
const modelSelection = { instanceId: "claude", model };
const result = await api("PATCH", path, path.endsWith("/model") ? modelSelection : { modelSelection });
expect(result.status, JSON.stringify(result.body)).toBe(200);
- const after = JSON.parse(readFileSync(botPath, "utf8")) as SavedBot[];
+ const after = readRegistry(fixture!.info.dataDir).bots as SavedBot[];
const task = after.find(row => row.id === bot.id)!.tasks[0];
expect(task.modelSelection).toBeUndefined();
expect(after.find(row => row.id === bot.id)!.modelSelection).toEqual(modelSelection);
@@ -346,15 +345,14 @@ describe("hosted model policy in the full runtime", () => {
const first = await bots();
// A later managed session must survive an unchanged policy restart.
await waitForExit(child, { signal: "SIGTERM" });
- const botsPath = join(fixture!.info.dataDir, "bots.json");
- const persisted = JSON.parse(readFileSync(botsPath, "utf8")) as SavedBot[];
+ const persisted = readRegistry(fixture!.info.dataDir).bots as SavedBot[];
const validTask = persisted.find((bot) => bot.id === ids["Valid choice"])!.tasks[0];
validTask.resumeCursors = { codex: "synthetic-current-managed-session" };
validTask.lastInstanceId = "codex";
- writeFileSync(botsPath, JSON.stringify(persisted));
+ writeRegistry(fixture!.info.dataDir, { bots: persisted });
await restart(changed);
expect(await bots()).toEqual(first);
- const restarted = JSON.parse(readFileSync(botsPath, "utf8")) as SavedBot[];
+ const restarted = readRegistry(fixture!.info.dataDir).bots as SavedBot[];
expect(restarted.find((bot) => bot.id === ids["Valid choice"])!.tasks[0]).toMatchObject({
resumeCursors: { codex: "synthetic-current-managed-session" }, lastInstanceId: "codex",
});
diff --git a/server/independent-task-store.test.ts b/server/independent-task-store.test.ts
index 053d74b67d..2fef2ce578 100644
--- a/server/independent-task-store.test.ts
+++ b/server/independent-task-store.test.ts
@@ -7,10 +7,11 @@ import { DATA_DIR } from "./config.ts";
import type { ModelSelection } from "./contracts.ts";
import { isProjectEmoji, Store, type BotRecord, type GroupRecord, type TaskPatch } from "./store.ts";
import { ensureTaskWorkspace } from "./workspace.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const selection = (): ModelSelection => ({ instanceId: "claude", model: "default" });
-const savedBots = (): BotRecord[] => JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
-const savedGroups = (): GroupRecord[] => JSON.parse(readFileSync(join(DATA_DIR, "groups.json"), "utf8"));
+const savedBots = (): BotRecord[] => readRegistry(DATA_DIR).bots;
+const savedGroups = (): GroupRecord[] => readRegistry(DATA_DIR).rooms;
describe("independent bot task state", () => {
// The shared Vitest setup gives this file its own disposable home.
@@ -146,7 +147,7 @@ describe("independent bot task state", () => {
const hidden = saved.tasks!.find((task) => task.threadId === execution.threadId)!;
hidden.unread = true;
saved.unread = true;
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(raw));
+ writeRegistry(DATA_DIR, { bots: raw });
const reloaded = new Store(selection);
expect(reloaded.taskByThread(bot.id, execution.threadId)).toMatchObject({ routineRunId: "run-1", unread: false });
expect(reloaded.bot(bot.id)?.unread).toBe(false);
@@ -424,7 +425,7 @@ describe("independent bot task state", () => {
raw.rewound = true;
raw.pinnedMessageId = "legacy-pin";
raw.unread = true;
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(legacy));
+ writeRegistry(DATA_DIR, { bots: legacy });
const migrated = new Store(selection);
expect(migrated.tasks(bot.id)).toHaveLength(2);
expect(migrated.projectBotForTask(bot.id, first)).toMatchObject({
@@ -566,7 +567,7 @@ describe("independent bot task state", () => {
expect(store.patchProject(sibling.id, project.id, { name: "Wrong owner" })).toBeNull();
const saved = savedBots();
Object.assign(saved.find((entry) => entry.id === bot.id)!.projects![0], { modelSelection: { instanceId: "codex", model: "removed-folder-default" } });
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(saved));
+ writeRegistry(DATA_DIR, { bots: saved });
const reloaded = new Store(selection);
expect(reloaded.project(bot.id, project.id)).toEqual({ id: project.id, name: "General", emoji: "⭐" });
expect(reloaded.taskByThread(bot.id, bot.threadId)?.modelSelection).toEqual({ instanceId: "codex", model: "existing-thread" });
diff --git a/server/main-thread.e2e.test.ts b/server/main-thread.e2e.test.ts
index eabb604637..66bc0133d0 100644
--- a/server/main-thread.e2e.test.ts
+++ b/server/main-thread.e2e.test.ts
@@ -1,8 +1,9 @@
import { randomUUID } from "node:crypto";
-import { readFileSync, writeFileSync } from "node:fs";
+import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { readRegistry } from "./testing/registry.ts";
async function launch() {
const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
@@ -19,7 +20,7 @@ async function launch() {
const cli = (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;
const wire = async (botId: string) => (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === botId);
const tasks = async (botId: string) => (await wire(botId)).tasks as any[];
- const stamps = (botId: string) => Object.fromEntries((JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8")) as any[])
+ const stamps = (botId: string) => Object.fromEntries((readRegistry(dataDir).bots as any[])
.find((bot) => bot.id === botId).tasks.filter((task: any) => task.askedAt !== undefined).map((task: any) => [task.threadId, task.askedAt]));
const thread = async (botId: string, title: string) => {
await expect.poll(async () => (await tasks(botId)).some((task) => task.title === title), { timeout: 20_000 }).toBe(true);
diff --git a/server/outside-lineage.e2e.test.ts b/server/outside-lineage.e2e.test.ts
index f5a8ce4d35..dd94ae24ad 100644
--- a/server/outside-lineage.e2e.test.ts
+++ b/server/outside-lineage.e2e.test.ts
@@ -11,6 +11,7 @@ import { OUTSIDE_REFUSAL } from "./host/outside-fence.ts";
import { OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts";
import { markLeftBehind } from "./testing/cloud-left-behind.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const tag = randomBytes(6).toString("hex");
const dump = join(tmpdir(), `outside-${tag}.json`), release = join(tmpdir(), `outside-${tag}.release`), failing = join(tmpdir(), `outside-${tag}.fail`), notes = join(tmpdir(), `outside-${tag}.notes`),
@@ -459,10 +460,12 @@ describe("a Team Cloud", () => {
const scout = await newBot("Earlier bot");
const { thread } = await webhookTurn(scout.id, "Earlier hook", "marker-earlier");
await finish(scout.id);
- const file = join(team.home, ".openmausbot", "bots.json");
- const before = readFileSync(file, "utf8");
- expect(before).toContain('"outside":true');
- writeFileSync(file, before.replaceAll('"outside":true', '"unmarked":true'));
+ const dataDir = join(team.home, ".openmausbot");
+ const { bots } = readRegistry(dataDir);
+ const marked = bots.flatMap((bot: any) => bot.tasks ?? []).filter((task: any) => task.outside === true);
+ expect(marked.length).toBeGreaterThan(0);
+ for (const task of marked) { delete task.outside; task.unmarked = true; }
+ writeRegistry(dataDir, { bots });
await team.relaunch();
ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;
expect((await team.as(ada, "POST", `/api/bots/${scout.id}/messages`, { text: "person-line-earlier", threadId: thread })).status).toBe(202);
diff --git a/server/place-view.e2e.test.ts b/server/place-view.e2e.test.ts
index d626a77eee..973243bd60 100644
--- a/server/place-view.e2e.test.ts
+++ b/server/place-view.e2e.test.ts
@@ -1,13 +1,14 @@
// Real server, fake Claude CLI and a loopback Boat whose answers each journey sets; a restartable home lets a test seed an automatic pin.
import { spawn, type ChildProcess } from "node:child_process";
import { createServer, type Server } from "node:http";
-import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { freePortBlock } from "./testing/ports.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const ROOT = fileURLToPath(new URL("..", import.meta.url));
@@ -62,12 +63,12 @@ describe("a cloud computer that can't start, against the real server", () => {
async () => (await apiOk("GET", "/api/bots?messages=0")).bots.find((bot: any) => bot.id === botId),
(bot: any) => bot && !bot.busy, "idle bot");
const savedTask = (botId: string, threadId: string) =>
- (JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as any[])
+ (readRegistry(data).bots as any[])
.find((bot: any) => bot.id === botId)?.tasks.find((task: any) => task.threadId === threadId);
const editSavedBot = (botId: string, edit: (bot: any) => void) => {
- const bots = JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as any[];
+ const bots = readRegistry(data).bots as any[];
edit(bots.find((bot: any) => bot.id === botId));
- writeFileSync(join(data, "bots.json"), JSON.stringify(bots, null, 2));
+ writeRegistry(data, { bots });
};
const send = (botId: string, threadId: string, text: string) =>
apiOk("POST", `/api/bots/${botId}/messages`, { text, threadId });
diff --git a/server/registry-shape.test.ts b/server/registry-shape.test.ts
new file mode 100644
index 0000000000..4866761640
--- /dev/null
+++ b/server/registry-shape.test.ts
@@ -0,0 +1,95 @@
+// Pins what bots.json and groups.json hold today (format 1): every bot and room with its threads under `tasks`. A
+// change to either golden file is a change to what every existing data folder holds on disk, so it must be on purpose;
+// update the goldens with `npx vitest run server/registry-shape.test.ts -u` and say why in the PR.
+import { readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "./config.ts";
+import type { ModelSelection } from "./contracts.ts";
+import { Store } from "./store.ts";
+import { readRegistry, REGISTRY_FILES } from "./testing/registry.ts";
+
+const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });
+const GOLDEN = "./testing/fixtures/registry-format1";
+const START = Date.UTC(2026, 10, 16, 9, 0, 0);
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+/** Ids are random, so each becomes its order of first appearance; everything else is kept as written. */
+function normalized(value: unknown, ids = new Map<string, string>()): unknown {
+ if (typeof value === "string") {
+ if (!UUID.test(value)) return value;
+ if (!ids.has(value)) ids.set(value, `<id-${ids.size + 1}>`);
+ return ids.get(value);
+ }
+ if (Array.isArray(value)) return value.map((item) => normalized(item, ids));
+ if (value && typeof value === "object") {
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [normalized(key, ids) as string, normalized(item, ids)]));
+ }
+ return value;
+}
+
+/** A small folder with what a person makes in the first minutes: two bots, extra threads with the bookkeeping a turn
+ * leaves on them, a room with two threads and a direct chat. */
+function seedFolder(): { store: Store; ada: string; ben: string } {
+ const store = new Store(selection);
+ const ada = store.createBot({ name: "Ada", title: "Researcher", description: "Reads papers", soul: "Be brief." });
+ vi.advanceTimersByTime(1_000);
+ const ben = store.createBot({ name: "Ben", section: "Engineering" });
+ vi.advanceTimersByTime(1_000);
+ const second = store.createTask(ada.id, "Second thread", false)!;
+ vi.advanceTimersByTime(1_000);
+ const third = store.createTask(ada.id, "Third thread", true, undefined, undefined, "full")!;
+ store.renameTask(ada.id, second.threadId, "Renamed thread");
+ store.setResumeCursor(ada.id, "claude", "session-a", ada.threadId);
+ store.markTaskDispatched(ada.id, ada.threadId, "claude");
+ store.setTaskAskedAt(ada.id, ada.threadId, START + 500);
+ store.patchTask(ada.id, second.threadId, { pinned: true, unread: true, snoozedUntil: START + 86_400_000 });
+ store.patchTask(ada.id, third.threadId, { archivedAt: START + 3_000 });
+ vi.advanceTimersByTime(1_000);
+ const room = store.createGroup("Launch", [ada.id, ben.id], false, "Engineering", { bulletin: "Ship on Friday." });
+ const roomThread = store.createGroupTask(room.id, "Room follow-up", false)!;
+ store.patchGroupTask(room.id, roomThread.threadId, { pinned: true });
+ store.createGroup("Ada and Ben", [ada.id, ben.id], true);
+ return { store, ada: ada.id, ben: ben.id };
+}
+
+const fileText = (name: string) => readFileSync(join(DATA_DIR, name), "utf8");
+
+describe("the registry as persisted today (format 1)", () => {
+ beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ vi.useFakeTimers({ toFake: ["Date"], now: START });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("keeps bots with their threads in bots.json and rooms with theirs in groups.json, in this exact shape", async () => {
+ seedFolder();
+ const ids = new Map<string, string>();
+ const registry = readRegistry(DATA_DIR);
+ const bots = normalized(registry.bots, ids);
+ const rooms = normalized(registry.rooms, ids);
+ await expect(`${JSON.stringify(bots, null, 2)}\n`).toMatchFileSnapshot(`${GOLDEN}/bots.json`);
+ await expect(`${JSON.stringify(rooms, null, 2)}\n`).toMatchFileSnapshot(`${GOLDEN}/groups.json`);
+ });
+
+ it("writes each file as one line of JSON that the helper reads back unchanged", () => {
+ seedFolder();
+ for (const [part, name] of Object.entries(REGISTRY_FILES) as [keyof typeof REGISTRY_FILES, string][]) {
+ const text = fileText(name);
+ expect(text.includes("\n"), name).toBe(false);
+ expect(JSON.stringify(readRegistry(DATA_DIR)[part]), name).toBe(text);
+ }
+ });
+
+ it("loads a folder saved today without rewriting either file", () => {
+ const { ada } = seedFolder();
+ const before = Object.values(REGISTRY_FILES).map(fileText);
+ vi.advanceTimersByTime(60_000);
+ const reloaded = new Store(selection);
+ expect(reloaded.tasks(ada).map((task) => task.title)).toEqual(["Third thread", "Renamed thread", "New thread"]);
+ expect(Object.values(REGISTRY_FILES).map(fileText)).toEqual(before);
+ });
+});
diff --git a/server/routine-results.e2e.test.ts b/server/routine-results.e2e.test.ts
index c3fbdb847b..615c220d60 100644
--- a/server/routine-results.e2e.test.ts
+++ b/server/routine-results.e2e.test.ts
@@ -8,6 +8,7 @@ import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";
import { waitForExit } from "./testing/cleanup.ts";
import { splitLaunchNote } from "./testing/launch-note.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
it("reports every run into the bot's main thread while fresh executions, approvals, deletion and unread stay reachable", async () => {
const fixture = await launchVerificationServer();
@@ -301,9 +302,9 @@ it("after the upgrade, reports into and opens the conversation the person last w
delete file.frozenResultsCleared;
file.routines.find((candidate: any) => candidate.id === routine).resultsThreadId = oldest;
}, (dataDir) => {
- const bots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8")) as any[];
+ const bots = readRegistry(dataDir).bots as any[];
for (const saved of bots) for (const each of saved.tasks ?? []) delete each.askedAt;
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(bots));
+ writeRegistry(dataDir, { bots });
rmSync(join(dataDir, "asked-at-filled"), { force: true });
});
const saved = await f.savedBot(bot.id);
diff --git a/server/server-writes.e2e.test.ts b/server/server-writes.e2e.test.ts
index d5a9fb852d..c76326c2d8 100644
--- a/server/server-writes.e2e.test.ts
+++ b/server/server-writes.e2e.test.ts
@@ -6,6 +6,7 @@ import { afterEach, expect, it } from "vitest";
import { launchVerificationServer, runControlOmb, type VerificationServer } from "../scripts/control-omb.ts";
import { waitForExit } from "./testing/cleanup.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
+import { storedThread } from "./testing/registry.ts";
let fixture: VerificationServer | undefined;
afterEach(async () => {
@@ -31,7 +32,7 @@ it.each(["SIGKILL", "SIGTERM"] as const)("a turn and a routine run cut by %s kee
};
const { bot } = await cli("new-bot", "--name", "Talks");
const { bot: worker } = await cli("new-bot", "--name", "Works");
- const task = (id: string, threadId: string) => (json(join(dataDir, "bots.json")) as any[] | null)?.find((row) => row.id === id)?.tasks?.find((row: any) => row.threadId === threadId);
+ const task = (id: string, threadId: string) => storedThread(dataDir, id, threadId);
const { routine } = await api("POST", "/api/routines", { name: "Morning", prompt: "Summarise.", botId: worker.id, enabled: false, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });
const { run } = await api("POST", `/api/routines/${routine.id}/run`);
diff --git a/server/steer-e2e.test.ts b/server/steer-e2e.test.ts
index 30110a91ac..02131b5aab 100644
--- a/server/steer-e2e.test.ts
+++ b/server/steer-e2e.test.ts
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { splitLaunchNote } from "./testing/launch-note.ts";
import { withoutTurnClock } from "./testing/turn-clock-text.ts";
import { workerPort } from "./testing/worker-port.ts";
+import { readRegistry } from "./testing/registry.ts";
const SERVER_DIR = dirname(fileURLToPath(import.meta.url));
const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");
@@ -38,7 +39,7 @@ posixOnly("mid-turn steering e2e", () => {
return { status: res.status, body: await res.json() };
};
const getBot = async (id: string) => (await api("GET", "/api/bots")).body.bots.find((b: any) => b.id === id);
- const askedAt = (botId: string, threadId: string) => (JSON.parse(readFileSync(join(home, ".openmausbot", "bots.json"), "utf8")) as any[])
+ const askedAt = (botId: string, threadId: string) => (readRegistry(join(home, ".openmausbot")).bots as any[])
.find((bot) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId).askedAt;
const PAIRED = { name: "Safari on Mac", id: expect.stringMatching(/^p_[\w-]{22}$/) };
const asPairedPerson = async () => {
diff --git a/server/store.test.ts b/server/store.test.ts
index 4ee8a20a77..9932b19a94 100644
--- a/server/store.test.ts
+++ b/server/store.test.ts
@@ -25,6 +25,7 @@ import type { TeamSetupRequest } from "../shared/team-setup.ts";
import { SECTION_CONTEXTS_FILE, readSectionContext, writeSectionContext } from "./section-context.ts";
import { TeamComputers } from "./team-computers.ts";
import { allowsTool } from "../shared/tool-scope.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });
@@ -126,9 +127,9 @@ describe("Store", () => {
it("retains corrupt persisted tool selection as denied access instead of inheriting all tools", () => {
const store = new Store(selection);
const bot = store.createBot({ name: "Corrupt selection fixture" });
- const bots = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
+ const bots = readRegistry(DATA_DIR).bots;
bots[0].toolScope = { allow: "all" };
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(bots));
+ writeRegistry(DATA_DIR, { bots });
const restored = new Store(selection).bot(bot.id)!;
expect(restored).toHaveProperty("toolScope", { allow: "all" });
expect(allowsTool((restored as unknown as { toolScope: unknown }).toolScope, { kind: "native", name: "read" })).toBe(false);
@@ -162,7 +163,7 @@ describe("Store", () => {
expect(store.bot(ben.id)).toBeNull();
expect(store.messagesFor(ben.threadId)).toEqual([]);
expect(existsSync(soulFile(ben.id))).toBe(false);
- expect(JSON.parse(readFileSync(join(DATA_DIR, "groups.json"), "utf8"))[0].memberIds).toContain(ben.id);
+ expect(readRegistry(DATA_DIR).rooms[0].memberIds).toContain(ben.id);
expect(new Store(selection).group(room.id)?.memberIds).toEqual([ada.id]);
});
@@ -391,7 +392,7 @@ describe("Store", () => {
const reloaded = new Store(selection);
expect(reloaded.taskByThread(bot.id, bot.threadId)).toMatchObject({ surface: "local", surfaceSource: "user" });
expect(toWireTask(reloaded.taskByThread(bot.id, bot.threadId)!, selection())).not.toHaveProperty("surfaceSource");
- const saved = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8")) as any[];
+ const saved = readRegistry(DATA_DIR).bots as any[];
expect(saved[0].tasks[0]).toMatchObject({ surface: "local", surfaceSource: "user" });
});
@@ -416,7 +417,7 @@ describe("Store", () => {
expect(store.taskByThread(bot.id, legacyMismatch.threadId)).toMatchObject({ surface: "local" });
expect(store.taskByThread(bot.id, autoMatch.threadId)).toMatchObject({ surface: "vm" });
expect(changes).toHaveBeenCalledTimes(1);
- const saved = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8")) as any[];
+ const saved = readRegistry(DATA_DIR).bots as any[];
const savedCleared = saved[0].tasks.find((task: any) => task.threadId === autoMismatch.threadId);
expect(savedCleared).not.toHaveProperty("surface");
expect(savedCleared).not.toHaveProperty("surfaceSource");
@@ -640,12 +641,12 @@ describe("Store", () => {
original.appendMessage(group.threadId, { role: "user", kind: "text", text: "Keep the group conversation" });
const botMessages = original.messagesFor(bot.threadId);
const groupMessages = original.messagesFor(group.threadId);
- const bots = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
- const groups = JSON.parse(readFileSync(join(DATA_DIR, "groups.json"), "utf8"));
+ const bots = readRegistry(DATA_DIR).bots;
+ const groups = readRegistry(DATA_DIR).rooms;
delete bots[0].tasks; delete bots[0].soulHash;
delete groups[0].tasks; delete groups[0].defaultResponder;
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(bots));
- writeFileSync(join(DATA_DIR, "groups.json"), JSON.stringify(groups));
+ writeRegistry(DATA_DIR, { bots });
+ writeRegistry(DATA_DIR, { rooms: groups });
const malformed = '{"version":1,"contexts":';
writeFileSync(SECTION_CONTEXTS_FILE, malformed);
const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
@@ -656,8 +657,8 @@ describe("Store", () => {
expect(restored.group(group.id)?.defaultResponder).toEqual({ kind: "member", botId: bot.id });
expect(restored.messagesFor(bot.threadId)).toEqual(botMessages);
expect(restored.messagesFor(group.threadId)).toEqual(groupMessages);
- expect(JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"))[0].tasks).toHaveLength(1);
- expect(JSON.parse(readFileSync(join(DATA_DIR, "groups.json"), "utf8"))[0].tasks).toHaveLength(1);
+ expect(readRegistry(DATA_DIR).bots[0].tasks).toHaveLength(1);
+ expect(readRegistry(DATA_DIR).rooms[0].tasks).toHaveLength(1);
expect(warning.mock.calls.some(([message]) => String(message).includes("[teams] Startup could not register"))).toBe(true);
const beforeBots = structuredClone(restored.bots);
const beforeGroups = structuredClone(restored.groups);
@@ -1077,7 +1078,7 @@ describe("Store", () => {
});
expect(reloaded.bot(bot.id)).not.toHaveProperty("approvalGrant");
- const persisted: BotRecord[] = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
+ const persisted: BotRecord[] = readRegistry(DATA_DIR).bots;
expect(persisted.find((candidate) => candidate.id === bot.id)).toMatchObject({
approvalMode: "ask",
autoApprove: false,
@@ -1124,12 +1125,12 @@ describe("Store", () => {
const vps = store.createBot();
const invalid = store.createBot();
const absent = store.createBot();
- const raw: BotRecord[] = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
+ const raw: BotRecord[] = readRegistry(DATA_DIR).bots;
raw.find((bot) => bot.id === boat.id)!.cloudBackend = "box";
raw.find((bot) => bot.id === vps.id)!.cloudBackend = "vps";
(raw.find((bot) => bot.id === invalid.id) as unknown as { cloudBackend: string }).cloudBackend = "daytona";
delete raw.find((bot) => bot.id === absent.id)!.cloudBackend;
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(raw));
+ writeRegistry(DATA_DIR, { bots: raw });
const reloaded = new Store(selection);
expect(reloaded.bot(boat.id)?.cloudBackend).toBe("box");
@@ -1137,7 +1138,7 @@ describe("Store", () => {
expect(reloaded.bot(invalid.id)?.cloudBackend).toBeUndefined();
expect(reloaded.bot(absent.id)?.cloudBackend).toBeUndefined();
- const saved: BotRecord[] = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
+ const saved: BotRecord[] = readRegistry(DATA_DIR).bots;
expect(saved.find((bot) => bot.id === boat.id)?.cloudBackend).toBe("box");
expect(saved.find((bot) => bot.id === vps.id)?.cloudBackend).toBe("vps");
expect(saved.find((bot) => bot.id === invalid.id)).not.toHaveProperty("cloudBackend");
@@ -1239,7 +1240,7 @@ describe("Store", () => {
"provider-tool:claude:linear:list_issues:config-one",
]);
- const persisted: BotRecord[] = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
+ const persisted: BotRecord[] = readRegistry(DATA_DIR).bots;
expect(persisted.find((candidate) => candidate.id === bot.id)?.alwaysAllow).toEqual(
reloaded.bot(bot.id)?.alwaysAllow,
);
@@ -1795,9 +1796,9 @@ describe("Store", () => {
it("busy is wiped even when bots.json says otherwise", () => {
const store = new Store(selection);
const bot = store.createBot();
- const raw: BotRecord[] = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"));
+ const raw: BotRecord[] = readRegistry(DATA_DIR).bots;
raw.find((b) => b.id === bot.id)!.busy = true;
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(raw));
+ writeRegistry(DATA_DIR, { bots: raw });
const reloaded = new Store(selection);
expect(reloaded.bot(bot.id)?.busy).toBe(false);
@@ -2604,12 +2605,12 @@ describe("soul", () => {
it("backfills old bots' mirrors before the first non-soul history change", async () => {
const store = new Store(selection);
const bot = store.createBot();
- const raw = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8")) as Record<string, unknown>[];
+ const raw = readRegistry(DATA_DIR).bots as Record<string, unknown>[];
for (const record of raw) {
delete record.soul;
delete record.soulHash;
}
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify(raw));
+ writeRegistry(DATA_DIR, { bots: raw });
rmSync(join(DATA_DIR, "bots", bot.id), { recursive: true, force: true });
const reloaded = new Store(selection);
expect(reloaded.bot(bot.id)?.soul).toBe("");
@@ -2640,7 +2641,7 @@ describe("soul", () => {
expect(() => store.patchBotProfile(bot.id, { name: "Kiwi", soul: "new", lastProfileRequestId: "card" })).toThrow("disk full");
expect(bot).toEqual(before);
expect(readFileSync(soulFile(bot.id), "utf8")).toBe("");
- expect(JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"))[0].name).toBe(before.name);
+ expect(readRegistry(DATA_DIR).bots[0].name).toBe(before.name);
save.mockRestore();
const emit = vi.fn();
store.onChange(emit);
diff --git a/server/surface-pins.e2e.test.ts b/server/surface-pins.e2e.test.ts
index 7641688569..10dd6143b3 100644
--- a/server/surface-pins.e2e.test.ts
+++ b/server/surface-pins.e2e.test.ts
@@ -11,6 +11,7 @@ import { writeFileAtomic } from "./atomic.ts";
import { freePortBlock } from "./testing/ports.ts";
import { removeTempDir, waitForExit } from "./testing/cleanup.ts";
import { decodeCuaConnection } from "./local-computer.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const ROOT = fileURLToPath(new URL("..", import.meta.url));
@@ -68,12 +69,12 @@ describe("surface pin provenance against the real server", () => {
const busy = (botId: string, threadId: string) => until(() => threadState(botId, threadId), Boolean);
const idle = (botId: string, threadId: string) => until(() => threadState(botId, threadId), task => !task?.busy);
const savedTask = (botId: string, threadId: string) =>
- (JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as any[])
+ (readRegistry(data).bots as any[])
.find((bot: any) => bot.id === botId)?.tasks.find((task: any) => task.threadId === threadId);
const editSavedBot = (botId: string, edit: (bot: any) => void) => {
- const bots = JSON.parse(readFileSync(join(data, "bots.json"), "utf8")) as any[];
+ const bots = readRegistry(data).bots as any[];
edit(bots.find((bot: any) => bot.id === botId));
- writeFileSync(join(data, "bots.json"), JSON.stringify(bots, null, 2));
+ writeRegistry(data, { bots });
};
async function start(withBrowser = false) {
diff --git a/server/task-cwd-api.test.ts b/server/task-cwd-api.test.ts
index 4cf9f55de8..788a63c311 100644
--- a/server/task-cwd-api.test.ts
+++ b/server/task-cwd-api.test.ts
@@ -2,6 +2,7 @@ import { mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { readRegistry } from "./testing/registry.ts";
it("pins an explicitly chosen new-thread folder without moving existing sessions or the bot default", async () => {
const fixture = await launchVerificationServer();
@@ -38,7 +39,7 @@ it("pins an explicitly chosen new-thread folder without moving existing sessions
expect(explicit.body.task.cwd).toBe(chosen);
expect(explicit.body.bot.cwd).toBe(original);
const threadId = explicit.body.task.threadId;
- const persisted = () => JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8")).find((item: any) => item.id === bot.id);
+ const persisted = () => readRegistry(fixture.info.dataDir).bots.find((item: any) => item.id === bot.id);
expect(persisted().tasks.find((task: any) => task.threadId === threadId).cwd).toBe(chosen);
const beforeInvalid = persisted().tasks.length;
diff --git a/server/team-lifecycle.e2e.test.ts b/server/team-lifecycle.e2e.test.ts
index e6ce74d59b..81aa069734 100644
--- a/server/team-lifecycle.e2e.test.ts
+++ b/server/team-lifecycle.e2e.test.ts
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
import { waitForExit } from "./testing/cleanup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
it("retains empty teams, moves existing bots, and keeps legacy imports additive through restart", async () => {
const fixture = await launchVerificationServer();
@@ -116,14 +117,14 @@ it("retains empty teams, moves existing bots, and keeps legacy imports additive
expect(await control("wait", "--channel", room.id, "--timeout", "30")).toMatchObject({ status: "settled" });
const roomMessages = (await control("messages", "--channel", room.id, "--limit", "10") as any).messages;
await waitForExit(restarted, { signal: "SIGTERM" });
- const legacyBots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"));
- const legacyGroups = JSON.parse(readFileSync(join(dataDir, "groups.json"), "utf8"));
+ const legacyBots = readRegistry(dataDir).bots;
+ const legacyGroups = readRegistry(dataDir).rooms;
const legacyBot = legacyBots.find((bot: any) => bot.id === a.id);
const legacyGroup = legacyGroups.find((group: any) => group.id === room.id);
delete legacyBot.tasks; delete legacyBot.soulHash; legacyBot.section = "Recovered bot team";
delete legacyGroup.tasks; delete legacyGroup.defaultResponder; legacyGroup.section = "Recovered group team";
- writeFileSync(join(dataDir, "bots.json"), JSON.stringify(legacyBots));
- writeFileSync(join(dataDir, "groups.json"), JSON.stringify(legacyGroups));
+ writeRegistry(dataDir, { bots: legacyBots });
+ writeRegistry(dataDir, { rooms: legacyGroups });
const malformed = '{"version":1,"contexts":';
const registryFile = join(dataDir, "section-contexts.json");
writeFileSync(registryFile, malformed);
@@ -133,8 +134,8 @@ it("retains empty teams, moves existing bots, and keeps legacy imports additive
expect(recovered.groups.find((group: any) => group.id === room.id)).toMatchObject({ section: "Recovered group team", defaultResponder: { kind: "member", botId: a.id } });
expect(await messages()).toEqual(transcript);
expect((await control("messages", "--channel", room.id, "--limit", "10") as any).messages).toEqual(roomMessages);
- expect(JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8")).find((bot: any) => bot.id === a.id).tasks).toHaveLength(1);
- expect(JSON.parse(readFileSync(join(dataDir, "groups.json"), "utf8")).find((group: any) => group.id === room.id).tasks).toHaveLength(1);
+ expect(readRegistry(dataDir).bots.find((bot: any) => bot.id === a.id).tasks).toHaveLength(1);
+ expect(readRegistry(dataDir).rooms.find((group: any) => group.id === room.id).tasks).toHaveLength(1);
await api("/api/sidebar-sections", "POST", { name: "Must not overwrite recovery data" }, 500);
await api("/api/section-context?section=Recovered%20bot%20team", "PUT", { text: "Must not replace the damaged file" }, 500);
expect(readFileSync(registryFile, "utf8")).toBe(malformed);
diff --git a/server/testing/fixtures/registry-format1/bots.json b/server/testing/fixtures/registry-format1/bots.json
new file mode 100644
index 0000000000..01624ac0d5
--- /dev/null
+++ b/server/testing/fixtures/registry-format1/bots.json
@@ -0,0 +1,92 @@
+[
+ {
+ "id": "<id-1>",
+ "threadId": "<id-2>",
+ "name": "Ben",
+ "title": "",
+ "description": "",
+ "soul": "",
+ "soulHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "notifications": true,
+ "color": "blue",
+ "unread": false,
+ "modelSelection": {
+ "instanceId": "claude",
+ "model": "claude-sonnet-5"
+ },
+ "resumeCursors": {},
+ "createdAt": 1794819601000,
+ "section": "Engineering",
+ "tasks": [
+ {
+ "threadId": "<id-2>",
+ "title": "New thread",
+ "createdAt": 1794819601000,
+ "updatedAt": 1794819601000,
+ "resumeCursors": {},
+ "unread": false,
+ "lastThreadOrderAt": 1794819601000
+ }
+ ]
+ },
+ {
+ "id": "<id-3>",
+ "threadId": "<id-4>",
+ "name": "Ada",
+ "title": "Researcher",
+ "description": "Reads papers",
+ "soul": "Be brief.",
+ "soulHash": "213c22ed7234eb11116e1e88f314c73cb3a019b5c87fe224b6ce5665bd9ec50e",
+ "notifications": true,
+ "color": "green",
+ "unread": true,
+ "modelSelection": {
+ "instanceId": "claude",
+ "model": "claude-sonnet-5"
+ },
+ "resumeCursors": {
+ "claude": "session-a"
+ },
+ "createdAt": 1794819600000,
+ "tasks": [
+ {
+ "threadId": "<id-4>",
+ "title": "Third thread",
+ "createdAt": 1794819603000,
+ "updatedAt": 1794819603000,
+ "resumeCursors": {
+ "claude": "session-a"
+ },
+ "approvalMode": "full",
+ "autoApprove": false,
+ "alwaysAllow": [],
+ "unread": false,
+ "lastInstanceId": "claude",
+ "askedAt": 1794819600500,
+ "archivedAt": 1794819603000
+ },
+ {
+ "threadId": "<id-5>",
+ "title": "Renamed thread",
+ "createdAt": 1794819602000,
+ "updatedAt": 1794819602000,
+ "resumeCursors": {},
+ "approvalMode": "full",
+ "autoApprove": false,
+ "alwaysAllow": [],
+ "unread": true,
+ "pinned": true,
+ "snoozedUntil": 1794906000000
+ },
+ {
+ "threadId": "<id-6>",
+ "title": "New thread",
+ "createdAt": 1794819600000,
+ "updatedAt": 1794819600000,
+ "resumeCursors": {},
+ "unread": false,
+ "lastThreadOrderAt": 1794819600000
+ }
+ ]
+ }
+]
diff --git a/server/testing/fixtures/registry-format1/groups.json b/server/testing/fixtures/registry-format1/groups.json
new file mode 100644
index 0000000000..7a0f62b9cc
--- /dev/null
+++ b/server/testing/fixtures/registry-format1/groups.json
@@ -0,0 +1,52 @@
+[
+ {
+ "id": "<id-7>",
+ "threadId": "<id-8>",
+ "name": "Ada and Ben",
+ "memberIds": [
+ "<id-3>",
+ "<id-1>"
+ ],
+ "defaultResponder": {
+ "kind": "mentions"
+ },
+ "bulletin": "",
+ "unread": false,
+ "createdAt": 1794819604000,
+ "dm": true
+ },
+ {
+ "id": "<id-9>",
+ "threadId": "<id-10>",
+ "name": "Launch",
+ "memberIds": [
+ "<id-3>",
+ "<id-1>"
+ ],
+ "defaultResponder": {
+ "kind": "member",
+ "botId": "<id-3>"
+ },
+ "bulletin": "Ship on Friday.",
+ "unread": false,
+ "createdAt": 1794819604000,
+ "section": "Engineering",
+ "tasks": [
+ {
+ "threadId": "<id-11>",
+ "title": "Room follow-up",
+ "createdAt": 1794819604000,
+ "updatedAt": 1794819604000,
+ "pinned": true
+ },
+ {
+ "threadId": "<id-10>",
+ "title": "New task",
+ "createdAt": 1794819604000,
+ "updatedAt": 1794819604000
+ }
+ ],
+ "setupCompletedAt": null,
+ "setupSkippedAt": null
+ }
+]
diff --git a/server/testing/registry.ts b/server/testing/registry.ts
new file mode 100644
index 0000000000..20d8b180ed
--- /dev/null
+++ b/server/testing/registry.ts
@@ -0,0 +1,49 @@
+// The one place tests learn where a data folder keeps its bots, rooms and their threads.
+import { readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+/** A bot as persisted, with its threads under `tasks`. */
+export type StoredBot = any;
+/** A room as persisted, with its threads under `tasks`. */
+export type StoredRoom = any;
+
+export interface StoredRegistry {
+ bots: StoredBot[];
+ rooms: StoredRoom[];
+}
+
+export const REGISTRY_FILES = { bots: "bots.json", rooms: "groups.json" } as const;
+
+function readRecords(file: string): any[] {
+ let text: string;
+ try {
+ text = readFileSync(file, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
+ throw error;
+ }
+ return JSON.parse(text);
+}
+
+/** Every bot and room in `dataDir`, each with its threads, read when first looked at; a part never saved reads as
+ * empty, a damaged one throws. */
+export function readRegistry(dataDir: string): StoredRegistry {
+ let bots: StoredBot[] | undefined;
+ let rooms: StoredRoom[] | undefined;
+ return {
+ get bots() { return bots ??= readRecords(join(dataDir, REGISTRY_FILES.bots)); },
+ get rooms() { return rooms ??= readRecords(join(dataDir, REGISTRY_FILES.rooms)); },
+ };
+}
+
+export function storedThread(dataDir: string, ownerId: string, threadId: string): any {
+ const registry = readRegistry(dataDir);
+ const owner = registry.bots.find((bot) => bot.id === ownerId) ?? registry.rooms.find((room) => room.id === ownerId);
+ return owner?.tasks?.find((task: any) => task.threadId === threadId);
+}
+
+/** Replaces the parts given, for a server that is not running; a part left out stays as it is. */
+export function writeRegistry(dataDir: string, registry: Partial<StoredRegistry>): void {
+ if (registry.bots !== undefined) writeFileSync(join(dataDir, REGISTRY_FILES.bots), JSON.stringify(registry.bots), { mode: 0o600 });
+ if (registry.rooms !== undefined) writeFileSync(join(dataDir, REGISTRY_FILES.rooms), JSON.stringify(registry.rooms), { mode: 0o600 });
+}
diff --git a/server/thread-archive.test.ts b/server/thread-archive.test.ts
index 307b6ccce8..ae94911808 100644
--- a/server/thread-archive.test.ts
+++ b/server/thread-archive.test.ts
@@ -1,8 +1,7 @@
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { launchVerificationServer, type VerificationServer } from "../scripts/control-omb.ts";
+import { readRegistry } from "./testing/registry.ts";
describe("thread archive through an isolated HTTP fixture", () => {
let fixture: VerificationServer;
@@ -15,7 +14,7 @@ describe("thread archive through an isolated HTTP fixture", () => {
return { status: response.status, body: await response.json() as any };
};
const getBot = async (botId: string) => (await api("GET", "/api/bots?messages=1")).body.bots.find((bot: any) => bot.id === botId);
- const persistedTask = (botId: string, threadId: string) => JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8"))
+ const persistedTask = (botId: string, threadId: string) => readRegistry(fixture.info.dataDir).bots
.find((bot: any) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId);
beforeAll(async () => {
diff --git a/server/thread-link.test.ts b/server/thread-link.test.ts
index 94d81ef57d..866dafff2f 100644
--- a/server/thread-link.test.ts
+++ b/server/thread-link.test.ts
@@ -1,11 +1,11 @@
-import { readFileSync, rmSync } from "node:fs";
-import { join } from "node:path";
+import { rmSync } from "node:fs";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { launchVerificationServer, type VerificationServer } from "../scripts/control-omb.ts";
import { DATA_DIR } from "./config.ts";
import type { ModelSelection } from "./contracts.ts";
import { Store } from "./store.ts";
+import { readRegistry } from "./testing/registry.ts";
describe("thread link through an isolated HTTP fixture", () => {
let fixture: VerificationServer;
@@ -17,7 +17,7 @@ describe("thread link through an isolated HTTP fixture", () => {
});
return { status: response.status, body: await response.json() as any };
};
- const persistedTask = (botId: string, threadId: string) => JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8"))
+ const persistedTask = (botId: string, threadId: string) => readRegistry(fixture.info.dataDir).bots
.find((bot: any) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId);
beforeAll(async () => {
diff --git a/server/thread-model.test.ts b/server/thread-model.test.ts
index bff9cf1e16..d92a68a2bf 100644
--- a/server/thread-model.test.ts
+++ b/server/thread-model.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { beforeEach, describe, expect, it } from "vitest";
@@ -7,6 +7,7 @@ import type { ModelSelection, ProviderSnapshot } from "./contracts.ts";
import { Store, toWireTask, type BotRecord, type TaskRecord } from "./store.ts";
import { threadModelFallback, type ThreadEngine } from "./thread-model.ts";
import type { TeamSetupRequest } from "../shared/team-setup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
const opus: ModelSelection = { instanceId: "claude", model: "claude-opus-5" };
@@ -44,7 +45,7 @@ describe("threads follow their bot's model", () => {
expect(ownModel(reloaded, bot.id, second.threadId)).toBeUndefined();
reloaded.patchBot(bot.id, { modelSelection: opus });
expect(runsOn(reloaded, bot.id, second.threadId)).toEqual(opus);
- expect(JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"))[0].tasks
+ expect(readRegistry(DATA_DIR).bots[0].tasks
.every((task: TaskRecord) => !("modelSelection" in task))).toBe(true);
});
@@ -97,13 +98,13 @@ describe("threads follow their bot's model", () => {
unread: false, modelSelection: sonnet, resumeCursors: {}, createdAt: 1,
tasks: [task("copy", { ...sonnet }), task("different", codex), task("other-effort", { ...sonnet, effort: "high" })],
} as unknown as BotRecord;
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify([bot]));
+ writeRegistry(DATA_DIR, { bots: [bot] });
const store = open();
expect(ownModel(store, "legacy", "copy")).toBeUndefined();
expect(ownModel(store, "legacy", "different")).toEqual(codex);
expect(ownModel(store, "legacy", "other-effort")).toEqual({ ...sonnet, effort: "high" });
- const saved = JSON.parse(readFileSync(join(DATA_DIR, "bots.json"), "utf8"))[0].tasks as TaskRecord[];
+ const saved = readRegistry(DATA_DIR).bots[0].tasks as TaskRecord[];
expect(saved.map((entry) => entry.modelSelection)).toEqual([undefined, codex, { ...sonnet, effort: "high" }]);
store.patchBot("legacy", { modelSelection: codex });
@@ -123,7 +124,7 @@ describe("threads follow their bot's model", () => {
unread: false, modelSelection: sonnet, resumeCursors: {}, createdAt: 1,
tasks: [{ threadId: "copy", title: "copy", createdAt: 1, updatedAt: 1, resumeCursors: {}, modelSelection: { ...sonnet } }],
};
- writeFileSync(join(DATA_DIR, "bots.json"), JSON.stringify([bot]));
+ writeRegistry(DATA_DIR, { bots: [bot] });
expect(ownModel(open(), "legacy", "copy")).toBeUndefined();
});
diff --git a/server/thread-snooze.test.ts b/server/thread-snooze.test.ts
index 90630e421a..b8b1ec6b8a 100644
--- a/server/thread-snooze.test.ts
+++ b/server/thread-snooze.test.ts
@@ -1,11 +1,11 @@
-import { readFileSync, rmSync } from "node:fs";
-import { join } from "node:path";
+import { rmSync } from "node:fs";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { launchVerificationServer, type VerificationServer } from "../scripts/control-omb.ts";
import { DATA_DIR } from "./config.ts";
import type { ModelSelection } from "./contracts.ts";
import { Store } from "./store.ts";
+import { readRegistry } from "./testing/registry.ts";
describe("thread snooze through an isolated HTTP fixture", () => {
let fixture: VerificationServer;
@@ -19,7 +19,7 @@ describe("thread snooze through an isolated HTTP fixture", () => {
};
const taskOf = async (botId: string, threadId: string) => (await api("GET", "/api/bots?messages=1")).body.bots
.find((bot: any) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId);
- const persistedTask = (botId: string, threadId: string) => JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8"))
+ const persistedTask = (botId: string, threadId: string) => readRegistry(fixture.info.dataDir).bots
.find((bot: any) => bot.id === botId).tasks.find((task: any) => task.threadId === threadId);
beforeAll(async () => {
diff --git a/server/trust-controls.e2e.test.ts b/server/trust-controls.e2e.test.ts
index b162b98657..8e7707f825 100644
--- a/server/trust-controls.e2e.test.ts
+++ b/server/trust-controls.e2e.test.ts
@@ -7,6 +7,7 @@ import { afterAll, beforeAll, expect, it } from "vitest";
import { launchVerificationServer, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";
import { SessionRegistry } from "./sessions.ts";
import { waitForExit } from "./testing/cleanup.ts";
+import { readRegistry, writeRegistry } from "./testing/registry.ts";
const key = "isolated-trust-capability";
let fixture: VerificationServer;
@@ -117,8 +118,7 @@ beforeAll(async () => {
expect(sandboxCreated.status).toBe(201);
sandboxBot = (await sandboxCreated.json() as any).bot;
await waitForExit(fixture.child, { signal: "SIGTERM" });
- const botsFile = join(fixture.info.dataDir, "bots.json");
- const bots = JSON.parse(readFileSync(botsFile, "utf8"));
+ const bots = readRegistry(fixture.info.dataDir).bots;
const saved = bots.find((row: any) => row.id === fullBot.id);
for (const full of [saved, ...[draftBot, draftHelper, outboundPolicyBot, noRuleBot, sandboxBot].map(bot => bots.find((row: any) => row.id === bot.id))]) {
full.approvalMode = "full";
@@ -127,7 +127,7 @@ beforeAll(async () => {
}
// Full access asks only for a bot someone set a sending rule on. These rules carry the daily cap older apps stored.
for (const bot of [fullBot, draftBot, draftHelper, outboundPolicyBot]) bots.find((row: any) => row.id === bot.id).outbound = { policy: "ask", dailyCap: 100 };
- writeFileSync(botsFile, JSON.stringify(bots));
+ writeRegistry(fixture.info.dataDir, { bots });
const configFile = join(fixture.info.dataDir, "config.json");
const config = JSON.parse(readFileSync(configFile, "utf8"));
config.signIn = { admins: ["[email protected]"], members: ["[email protected]"] };
diff --git a/server/warm-summary.e2e.test.ts b/server/warm-summary.e2e.test.ts
index 085495f822..b75338458c 100644
--- a/server/warm-summary.e2e.test.ts
+++ b/server/warm-summary.e2e.test.ts
@@ -9,6 +9,7 @@ import { expect, it } from "vitest";
import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
import { request } from "../scripts/mcp-server.ts";
import { removeTempDir } from "./testing/cleanup.ts";
+import { readRegistry } from "./testing/registry.ts";
const COMPACT_MS = 6_000;
@@ -35,7 +36,7 @@ async function setup(extra: NodeJS.ProcessEnv) {
const thread = bot.activeTaskId as string;
// A 1M-window model, as on the trial: OpenMausBot's own fold would wait for 180k, so Claude Code's comes first.
await cli("set-model", "--bot", bot.id, "--instance", "claude", "--model", "claude-opus-5-5");
- const task = () => JSON.parse(readFileSync(join(session.info.dataDir, "bots.json"), "utf8"))
+ const task = () => readRegistry(session.info.dataDir).bots
.find((b: any) => b.id === bot.id).tasks.find((t: any) => t.threadId === thread);
/** The time from a send to the bot's reply being in the conversation. */
const send = async (text: string) => {