Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bots: a save serializes only the bot it names; safety changes always land in the same save (#6788)
Milind Soni6cec8c6ef9eb
diff --git a/scripts/bench-bots-serialize.ts b/scripts/bench-bots-serialize.tsnew file mode 100644index 0000000000..746d122aaf--- /dev/null+++ b/scripts/bench-bots-serialize.ts@@ -0,0 +1,56 @@+// Synthetic bots and threads only, in OMB_DATA_DIR, which must be set to an empty temporary folder before this starts.+// Counts how many bots each save of bots.json serializes, and what one setting save and a round of turns write, for the+// checkout at <repo>, so two checkouts can be compared with the same script:+// OMB_DATA_DIR=$(mktemp -d) node --experimental-strip-types scripts/bench-bots-serialize.ts <repo> 200x200+import { randomUUID } from "node:crypto";+import { statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+if (!process.env.OMB_DATA_DIR) throw new Error("Set OMB_DATA_DIR to an empty temporary folder first: the store saves there.");+const [repo, shape] = process.argv.slice(2) as [string, string];+const [nBots, nThreads] = shape.split("x").map(Number) as [number, number];+const { Store } = await import(join(repo, "server/store.ts"));+const batch = await import(join(repo, "server/save-batch.ts"));+const selection = () => ({ instanceId: "claude", model: "synthetic" });+const seed = new Store(selection);+const first = seed.createBot({ name: "Bench 0" }, { seedMessages: false });+const file = join(process.env.OMB_DATA_DIR!, "bots.json");+const template = JSON.parse(JSON.stringify(seed.bot(first.id)));+const rows = Array.from({ length: nBots }, (_, b) => ({ ...template, id: randomUUID(), threadId: `thread-${b}-0`, name: `Bench ${b}`,+ tasks: Array.from({ length: nThreads }, (_, t) => ({ ...template.tasks[0], id: randomUUID(), threadId: `thread-${b}-${t}`,+ title: `Synthetic thread ${t} with a title of ordinary length`, resumeCursors: { claude: { sessionId: randomUUID() } },+ usage: { input: 120_000 + t, output: 4_000 + t, cachedInput: 90_000, costUsd: null, turns: 12, lastTurn: { input: 900, output: 80, costUsd: null } } })) }));+writeFileSync(file, JSON.stringify(rows));+const store = new Store(selection);+const ids = new Set(rows.map((r) => r.id));+let serialized = 0;+const real = JSON.stringify;+JSON.stringify = function (value: unknown, ...rest: unknown[]) {+ if (Array.isArray(value)) { for (const v of value) if (v && typeof v === "object" && ids.has((v as { id: string }).id)) serialized++; }+ else if (value && typeof value === "object" && ids.has((value as { id: string }).id) && "soul" in (value as object)) serialized++;+ return (real as (...a: unknown[]) => string)(value, ...rest);+} as typeof JSON.stringify;+let writes = 0, bytes = 0, inode = statSync(file).ino;+const counted = () => { const s = statSync(file); if (s.ino !== inode) { writes++; bytes += s.size; inode = s.ino; } };+store.patchBot(rows[0]!.id, { title: "warm" }); counted();+const ms: number[] = []; let ser = 0; writes = 0; bytes = 0;+for (let i = 0; i < 9; i++) { serialized = 0; const a = performance.now(); store.patchBot(rows[i % nBots]!.id, { title: `Durable change ${i}` }); ms.push(performance.now() - a); ser += serialized; counted(); }+const oneSetting = { medianMs: Number(ms.sort((a, b) => a - b)[4]!.toFixed(1)), botsSerializedPerSave: ser / 9, bytesWrittenPerSave: Math.round(bytes / writes) };+const TURNS = 34;+const oneTurn = (turn: number) => {+ const botId = rows[turn % nBots]!.id, threadId = `thread-${turn % nBots}-1`;+ batch.batchSaves(() => { store.setTaskAskedAt(botId, threadId, Date.now()); store.patchTask(botId, threadId, { unread: false }); }); counted();+ store.markTaskDispatched(botId, threadId, "claude"); counted();+ store.setHandedMessages(botId, threadId, "claude", { session: { sessionId: `session-${turn % nBots}` }, lastMessageId: `m-${turn}-${Date.now()}` }); counted();+ batch.batchSaves(() => store.setResumeCursor(botId, "claude", { sessionId: `session-${turn % nBots}` }, threadId)); counted();+ batch.batchSaves(() => { store.addTaskUsage(botId, threadId, { input: 900, output: 80, costUsd: null }); store.patchTask(botId, threadId, { lastContextModel: "claude:synthetic" }); store.patchTask(botId, threadId, { unread: true }, { turnEnd: true }); }); counted();+};+for (let t = 0; t < TURNS; t++) oneTurn(t);+batch.flushLaterSaves(); counted();+writes = 0; bytes = 0; serialized = 0;+let busy = 0;+const start = performance.now();+for (let t = 0; t < TURNS; t++) { const a = performance.now(); oneTurn(t); busy += performance.now() - a; await new Promise((r) => setImmediate(r)); counted(); }+await new Promise((r) => setTimeout(r, 1200)); counted();+const b0 = performance.now(); batch.flushLaterSaves(); busy += performance.now() - b0; counted();+console.log(real({ shape, botsJsonMb: Number((statSync(file).size / 1e6).toFixed(1)), oneSetting,+ round: { turns: TURNS, wholeFileWrites: writes, writesPerTurn: Number((writes / TURNS).toFixed(2)), botsSerialized: serialized, botsSerializedPerTurn: Number((serialized / TURNS).toFixed(1)), mbWritten: Number((bytes / 1e6).toFixed(1)), blockedMs: Math.round(busy), wallMs: Math.round(performance.now() - start) } }));diff --git a/scripts/control-omb.test.ts b/scripts/control-omb.test.tsindex dc36d7ce55..ad04509af8 100644--- a/scripts/control-omb.test.ts+++ b/scripts/control-omb.test.ts@@ -19,6 +19,10 @@ describe("a fixture driven from a real browser", () => {expect(childEnv({}).OMB_DISABLE_MODEL_MANIFEST_FETCH).toBe("1");expect(childEnv({ OMB_DISABLE_MODEL_MANIFEST_FETCH: "0" }).OMB_DISABLE_MODEL_MANIFEST_FETCH).toBe("1");});++ it("checks every narrowed save of bots.json against the whole serialization", () => {+ expect(childEnv({}).OMB_BOTS_SAVE_CHECK).toBe("1");+ });});describe("the fixture's fake engine knobs", () => {diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex 4246510b89..12dee9ef87 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -167,6 +167,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data// The bundled model list, as in-process tests use: a downloaded one that differs makes the engines read their status// again mid-boot, so what a fixture probes would depend on what is published on main.OMB_DISABLE_MODEL_MANIFEST_FETCH: "1",+ // A save of bots.json that serializes only the bots it names is checked against the whole serialization.+ OMB_BOTS_SAVE_CHECK: "1",});// The fake engines' knobs are the one thing a caller may script into the child.for (const [key, value] of Object.entries(parentEnv)) {diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex aa14c4399e..993c3efc6a 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -11,7 +11,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_ACP_QUIET_TICK_MS", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP","OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY","OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT",- "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",+ "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE","OMB_BROWSER_CONNECTION", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL","OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING","OMB_BUG_REPORT_URL", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",diff --git a/server/bot-safety-digest.ts b/server/bot-safety-digest.tsnew file mode 100644index 0000000000..a5ada56744--- /dev/null+++ b/server/bot-safety-digest.ts@@ -0,0 +1,30 @@+// Security invariant: what a bot may do (its approval level, grants, tools, apps, folders, who may reach it) is on disk+// after the next save of bots.json, whichever bot that save names. A save that serializes only the bots it names+// compares this digest of every other bot with the one from the last write and serializes again any bot whose digest+// moved, so a permission changed in place without naming its bot (a revocation above all) is never left out.+import type { BotRecord, TaskRecord } from "./store.ts";++export const BOT_SAFETY_FIELDS = [+ "approvalMode", "autoApprove", "alwaysAllow", "approvalGrant", "toolScope", "toolsOff", "connectorTools", "connectorScopes",+ "outbound", "composio", "computer", "cloudBackend", "browser", "browserProfile", "mcpServers", "phoneApps", "cwd",+ "chiefOfStaff", "managedSections", "reportsTo", "visibility", "access", "onlyPeopleAdded", "createdBy", "hidden",+] as const satisfies readonly (keyof BotRecord)[];++export const THREAD_SAFETY_FIELDS = [+ "approvalMode", "autoApprove", "alwaysAllow", "cwd", "private", "shared", "sharedChat",+] as const satisfies readonly (keyof TaskRecord)[];++export function botSafetyDigest(bot: BotRecord): string {+ const parts: string[] = [];+ for (const key of BOT_SAFETY_FIELDS) if (bot[key] !== undefined) parts.push(key, JSON.stringify(bot[key]) ?? "");+ for (const task of bot.tasks ?? []) {+ let named = false;+ for (const key of THREAD_SAFETY_FIELDS) {+ if (task[key] === undefined) continue;+ if (!named) parts.push(`#${task.threadId}`);+ named = true;+ parts.push(key, JSON.stringify(task[key]) ?? "");+ }+ }+ return parts.join("\u0000");+}diff --git a/server/bots-save-crash.e2e.test.ts b/server/bots-save-crash.e2e.test.tsnew file mode 100644index 0000000000..ce07b2b5c9--- /dev/null+++ b/server/bots-save-crash.e2e.test.ts@@ -0,0 +1,34 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { expect, it } from "vitest";+import { launchVerificationServer } from "../scripts/control-omb.ts";+import { waitForExit } from "./testing/cleanup.ts";++type SavedBot = { id: string; approvalMode?: string; alwaysAllow?: string[]; toolScope?: { allow: string[] | null; deny: string[] } };++it("has a permission taken back through the settings route on disk when the route answers, with the server killed at once", async () => {+ const fixture = await launchVerificationServer();+ const api = async (method: string, path: string, body?: unknown, status = 200) => {+ const response = await fetch(`${fixture.info.url}${path}`, {+ method, headers: { "content-type": "application/json", origin: fixture.info.url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const data = await response.json() as { bot: { id: string } };+ expect(response.status, JSON.stringify(data)).toBe(status);+ return data;+ };+ try {+ const others = [];+ for (const name of ["Crash one", "Crash two", "Crash three"]) others.push((await api("POST", "/api/bots", { name, useDefaults: false }, 201)).bot);+ const target = others[1]!;+ await api("PATCH", `/api/bots/${others[0]!.id}`, { title: "Warm" });+ await api("PATCH", `/api/bots/${target.id}`, { approvalMode: "ask", toolScope: { allow: [], deny: ["native:bash"] } });+ fixture.child.kill("SIGKILL");+ await waitForExit(fixture.child);+ const saved = (JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8")) as SavedBot[]).find((bot) => bot.id === target.id)!;+ expect(saved.approvalMode).toBe("ask");+ expect(saved.toolScope).toEqual({ allow: [], deny: ["native:bash"] });+ } finally {+ await fixture.close();+ }+}, 60_000);diff --git a/server/bots-text.ts b/server/bots-text.tsnew file mode 100644index 0000000000..aaf969c73a--- /dev/null+++ b/server/bots-text.ts@@ -0,0 +1,58 @@+// The text of bots.json, kept as one serialized string per bot so a save that names its owners serializes only those.+// Bots change in place all over the store and nothing here is told of it, so a narrowed text is only built while the+// list holds the same bot objects in the same places as at the last write; anything else serializes every bot.+// Known open risk: a change made in place to a bot no save named is missing from a narrowed text, and is written by the+// next whole serialization (at most a moment later), so a crash in between loses it. A change to what a bot may do is+// the exception: every bot's safety digest is compared on each narrowed text.+import { botSafetyDigest } from "./bot-safety-digest.ts";+import type { BotRecord } from "./store.ts";++export class BotsText {+ private readonly persisted: (bot: BotRecord) => unknown;+ private bots: readonly BotRecord[] = [];+ private texts: string[] = [];+ private digests: string[] = [];+ private known = false;+ private readonly named = new Set<string>();++ constructor(persisted: (bot: BotRecord) => unknown) {+ this.persisted = persisted;+ }++ /** `id`'s record or one of its threads changed: the next narrowed text serializes it again. */+ name(id: string): void {+ this.named.add(id);+ }++ forget(): void {+ this.known = false;+ }++ canNarrow(bots: readonly BotRecord[]): boolean {+ if (!this.known || bots.length !== this.bots.length) return false;+ for (let i = 0; i < bots.length; i++) if (bots[i] !== this.bots[i]) return false;+ return true;+ }++ /** JSON.stringify of the persisted list, byte for byte. `narrow` (after canNarrow) serializes only the named bots;+ * `commit` once the text is on disk makes it the last write. */+ build(bots: readonly BotRecord[], narrow: boolean): { text: string; commit: () => void } {+ const texts: string[] = narrow ? this.texts.slice() : [];+ const digests: string[] = [];+ for (let i = 0; i < bots.length; i++) {+ digests[i] = botSafetyDigest(bots[i]!);+ if (!narrow || this.named.has(bots[i]!.id) || digests[i] !== this.digests[i]) texts[i] = JSON.stringify(this.persisted(bots[i]!));+ }+ const named = [...this.named];+ return {+ text: `[${texts.join(",")}]`,+ commit: () => {+ this.bots = bots.slice();+ this.texts = texts;+ this.digests = digests;+ this.known = true;+ for (const id of named) this.named.delete(id);+ },+ };+ }+}diff --git a/server/registry-store-narrow.test.ts b/server/registry-store-narrow.test.tsnew file mode 100644index 0000000000..012db255ba--- /dev/null+++ b/server/registry-store-narrow.test.ts@@ -0,0 +1,200 @@+import { mkdirSync, readFileSync, rmSync } from "node:fs";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { OwnedFile } from "./atomic.ts";+import { DATA_DIR } from "./config.ts";+import type { ModelSelection } from "./contracts.ts";+import { BOTS_FILE, BOTS_FULL_SAVE_ENV, JsonRegistry, persistedBots } from "./registry-store.ts";+import { flushLaterSaves } from "./save-batch.ts";+import { Store, type BotRecord } from "./store.ts";++const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });+const bot = (id: string, threads = 2) => ({ id, name: id, threadId: `${id}-0`, soul: `${id} soul`, busy: true, activity: "working",+ tasks: Array.from({ length: threads }, (_, t) => ({ threadId: `${id}-${t}`, title: `Thread ${t}`, busy: false, turnStartedAt: 1, pinned: t === 0 })) }) as unknown as BotRecord;+const owner = (id: string) => ({ kind: "bot", id }) as const;+const onDisk = () => readFileSync(BOTS_FILE, "utf8");++/** Which bots were serialized while `run` ran, by id, one entry per serialization. */+function serialized(bots: readonly BotRecord[], run: () => void): string[] {+ const ids = new Set(bots.map((b) => b.id));+ const stringify = vi.spyOn(JSON, "stringify");+ try {+ run();+ return stringify.mock.calls.flatMap(([value]) => {+ const record = value as { id?: unknown; soul?: unknown } | null;+ return record && !Array.isArray(record) && typeof record.id === "string" && ids.has(record.id) && "soul" in record ? [record.id] : [];+ });+ } finally {+ stringify.mockRestore();+ }+}++describe("bots.json saves that name their bot serialize only that bot", () => {+ beforeEach(() => {+ rmSync(DATA_DIR, { recursive: true, force: true });+ mkdirSync(DATA_DIR, { recursive: true });+ });+ afterEach(() => {+ flushLaterSaves();+ delete process.env[BOTS_FULL_SAVE_ENV];+ });++ it("serializes the named bot and writes the same bytes a whole serialization would", () => {+ const registry = new JsonRegistry();+ const bots = [bot("a"), bot("b"), bot("c")];+ const save = () => registry.writeBots(bots, true);+ expect(serialized(bots, save).sort(), "the first save knows nothing yet").toEqual(["a", "b", "c"]);+ bots[1]!.tasks![0]!.title = "Renamed in place";+ expect(serialized(bots, () => registry.upsertThread(owner("b"), "b-0", "now", save))).toEqual(["b"]);+ expect(onDisk()).toBe(JSON.stringify(persistedBots(bots)));+ });++ it("writes a change made in place to a bot no save named with the whole pass that follows a narrowed save", () => {+ const registry = new JsonRegistry();+ const bots = [bot("a"), bot("b")];+ const save = () => registry.writeBots(bots, true);+ save();+ bots[1]!.name = "Changed elsewhere";+ // The self-check is what a test sees of this: it refuses a narrowed text that misses a change.+ expect(() => registry.upsertThread(owner("a"), undefined, "now", save)).toThrow(/left out a change to b/);+ expect(JSON.parse(onDisk())[1].name).toBe("b");++ const vitest = process.env.VITEST;+ delete process.env.VITEST;+ const quiet = new JsonRegistry(); // as outside tests: no self-check+ process.env.VITEST = vitest;+ const write = () => quiet.writeBots(bots, true);+ write();+ bots[1]!.name = "Changed again";+ quiet.upsertThread(owner("a"), undefined, "now", write);+ expect(JSON.parse(onDisk())[1].name, "not in the narrowed save").toBe("Changed elsewhere");+ flushLaterSaves();+ expect(onDisk()).toBe(JSON.stringify(persistedBots(bots)));+ });++ it("writes a permission changed in place on a bot no save named in the very next save, whichever bot that names", () => {+ const vitest = process.env.VITEST;+ delete process.env.VITEST;+ const registry = new JsonRegistry(); // as outside tests: no self-check, so only the safety digest can catch it+ process.env.VITEST = vitest;+ const bots = [bot("a"), bot("b"), bot("c")];+ Object.assign(bots[1]!, { approvalMode: "full", alwaysAllow: ["Bash(git push)"] });+ Object.assign(bots[2]!.tasks![1]!, { alwaysAllow: ["Bash(rm -rf build)"] });+ const save = () => registry.writeBots(bots, true);+ save();+ for (const revoke of [+ () => { bots[1]!.approvalMode = "ask"; },+ () => { bots[1]!.alwaysAllow = []; },+ () => { delete bots[2]!.tasks![1]!.alwaysAllow; },+ () => { bots[2]!.toolScope = { allow: [], deny: ["native:bash"] } as never; },+ ]) {+ revoke();+ bots[0]!.name = `${bots[0]!.name}.`;+ registry.upsertThread(owner("a"), undefined, "now", save);+ expect(onDisk(), "on disk when the save returns, with no whole pass yet").toBe(JSON.stringify(persistedBots(bots)));+ }+ });++ it("serializes every owner a batch named, however many saves it held", () => {+ const registry = new JsonRegistry();+ const bots = [bot("a"), bot("b"), bot("c")];+ const save = () => registry.writeBots(bots, true);+ save();+ const ids = serialized(bots, () => registry.batch(() => {+ bots[0]!.tasks![1]!.title = "One";+ registry.upsertThread(owner("a"), "a-1", "pass", save);+ bots[2]!.tasks![1]!.title = "Two";+ registry.upsertThread(owner("c"), "c-1", "pass", save);+ }));+ expect(ids.sort()).toEqual(["a", "c"]);+ expect(onDisk()).toBe(JSON.stringify(persistedBots(bots)));+ });++ it("serializes every bot again when the list gained, lost or moved a bot, or a bot was replaced", () => {+ const registry = new JsonRegistry();+ const bots = [bot("a"), bot("b"), bot("c")];+ const save = () => registry.writeBots(bots, true);+ save();+ for (const change of [+ () => bots.unshift(bot("d")),+ () => bots.splice(1, 1),+ () => bots.reverse(),+ () => { bots[0] = { ...bots[0]!, name: "Replaced" }; },+ ]) {+ change();+ expect(serialized(bots, () => registry.upsertThread(owner(bots[0]!.id), undefined, "pass", save))).toHaveLength(bots.length);+ expect(onDisk()).toBe(JSON.stringify(persistedBots(bots)));+ }+ });++ it("serializes every bot after a save of a list that is not live yet, and after a write that failed", () => {+ const registry = new JsonRegistry();+ const bots = [bot("a"), bot("b")];+ const save = () => registry.writeBots(bots, true);+ save();+ registry.writeBots([...bots, bot("pending")], false);+ expect(serialized(bots, () => registry.upsertThread(owner("a"), undefined, "now", save))).toHaveLength(2);++ bots[0]!.name = "Will fail";+ const write = vi.spyOn(OwnedFile.prototype, "write").mockImplementationOnce(() => { throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); });+ expect(() => registry.upsertThread(owner("a"), undefined, "now", save)).toThrow(/disk full/);+ write.mockRestore();+ bots[1]!.name = "Changed meanwhile";+ expect(serialized(bots, () => registry.upsertThread(owner("a"), undefined, "now", save)), "the retry is whole").toHaveLength(2);+ expect(onDisk()).toBe(JSON.stringify(persistedBots(bots)));+ });++ it("serializes every bot on every save with the switch set", () => {+ process.env[BOTS_FULL_SAVE_ENV] = "1";+ const registry = new JsonRegistry();+ const bots = [bot("a"), bot("b"), bot("c")];+ const save = () => registry.writeBots(bots, true);+ save();+ bots[1]!.name = "Changed";+ expect(serialized(bots, () => registry.upsertThread(owner("b"), undefined, "now", save))).toHaveLength(3);+ expect(onDisk()).toBe(JSON.stringify(persistedBots(bots)));+ });++ it("keeps a store of 100 bots byte for byte what a whole serialization writes, through a day of mixed saves and a reload", () => {+ const store = new Store(selection);+ for (let i = 0; i < 100; i++) store.createBot({ name: `Bot ${i}`, section: i % 3 ? "Ops" : undefined }, { seedMessages: false });+ for (let i = 0; i < 100; i += 7) store.createTask(store.bots[i]!.id, `Extra ${i}`);+ const live = () => JSON.stringify(persistedBots(store.bots));+ for (let round = 0; round < 5; round++) {+ for (let i = round; i < 100; i += 11) {+ const target = store.bots[i]!, threadId = target.tasks![0]!.threadId;+ store.patchBot(target.id, { title: `Title ${round}` });+ store.patchTask(target.id, threadId, { title: `Round ${round}` });+ store.markTaskDispatched(target.id, threadId, "claude");+ store.setTaskAskedAt(target.id, threadId, 1_000 + round);+ store.addTaskUsage(target.id, threadId, { input: 10, output: 2, costUsd: null });+ }+ store.reorderBots([store.bots[99]!.id, store.bots[0]!.id]);+ expect(onDisk()).toBe(live());+ }+ flushLaterSaves();+ expect(onDisk()).toBe(live());+ const reloaded = new Store(selection);+ expect(JSON.stringify(persistedBots(reloaded.bots))).toBe(live());+ });++ it("carries a thread's new activity time, which no save of its own writes, in the next narrowed save of any bot", () => {+ const store = new Store(selection);+ const [a, b] = [store.createBot({ name: "A" }, { seedMessages: false }), store.createBot({ name: "B" }, { seedMessages: false })];+ store.patchBot(b.id, { title: "Warm" });+ store.appendMessage(a.threadId, { role: "user", kind: "text", text: "Hello" });+ expect(serialized(store.bots, () => store.patchBot(b.id, { title: "Next" })).sort()).toEqual([a.id, b.id].sort());+ expect(onDisk()).toBe(JSON.stringify(persistedBots(store.bots)));+ });++ it("serializes one bot of a hundred for a setting saved by a person and for a turn's bookkeeping", () => {+ const store = new Store(selection);+ for (let i = 0; i < 100; i++) store.createBot({ name: `Bot ${i}` }, { seedMessages: false });+ const target = store.bots[42]!, threadId = target.tasks![0]!.threadId;+ store.patchBot(target.id, { title: "Warm" });+ expect(serialized(store.bots, () => store.patchBot(target.id, { title: "Head of research" }))).toEqual([target.id]);+ expect(serialized(store.bots, () => store.markTaskDispatched(target.id, threadId, "claude"))).toEqual([target.id]);+ expect(serialized(store.bots, () => store.patchTask(target.id, threadId, { title: "Renamed" }))).toEqual([target.id]);+ expect(onDisk()).toBe(JSON.stringify(persistedBots(store.bots)));+ });+});diff --git a/server/registry-store.ts b/server/registry-store.tsindex a845d25bff..0a96f094ca 100644--- a/server/registry-store.ts+++ b/server/registry-store.ts@@ -8,6 +8,7 @@ import { join } from "node:path";import { OwnedFile } from "./atomic.ts";import { DATA_DIR } from "./config.ts";+import { BotsText } from "./bots-text.ts";import { batchSaves, saveLater, saveSoon, supersedeLaterSave } from "./save-batch.ts";import type { BotRecord, GroupRecord } from "./store.ts";@@ -45,6 +46,8 @@ export interface RegistryStore {*/upsertThread(owner: RegistryOwner & { kind: "bot" }, threadId: string | undefined, durability: RegistryDurability, write: () => void): void;upsertThread(owner: RegistryOwner & { kind: "group" }, threadId: string | undefined, durability: Exclude<RegistryDurability, "later">, write: () => void): void;+ /** An owner's record or one of its threads changed in place with no save of its own: it goes with the next save. */+ changedInPlace(owner: RegistryOwner): void;/** An owner and all its threads leave the registry; `write` saves the list without it, synced, before it returns. */deleteOwner(owner: RegistryOwner, write: () => void): void;/** Saves asked for with "pass" while `run` runs are written once when it returns: one transaction in a row layout. */@@ -67,10 +70,20 @@ export function persistedPin<T extends { pinned?: boolean }>(task: T): T {return rest as T;}-/** What bots.json holds: live state (busy, activity, a turn's start) is never saved. */-export const persistedBots = (bots: readonly BotRecord[]) => bots.map(({ busy: _busy, activity: _activity, ...bot }) => ({ ...bot,+/** What bots.json holds of one bot: live state (busy, activity, a turn's start) is never saved. */+export const persistedBot = ({ busy: _busy, activity: _activity, ...bot }: BotRecord) => ({ ...bot,tasks: bot.tasks?.map(({ busy: _taskBusy, activity: _taskActivity, turnStartedAt: _taskTurnStarted, ...task }) => persistedPin(task)),-}));+});++export const persistedBots = (bots: readonly BotRecord[]) => bots.map(persistedBot);++/** Set to 1, every save of bots.json serializes every bot. */+export const BOTS_FULL_SAVE_ENV = "OMB_BOTS_FULL_SAVE";+/** Set to 1 (fixture servers), a narrowed save that differs from the whole serialization throws. */+export const BOTS_SAVE_CHECK_ENV = "OMB_BOTS_SAVE_CHECK";+/** The waiting whole pass after a narrowed save has its own key: a whole write of the live list supersedes the waiting+ * writes of BOTS_FILE, and is that pass's job too. */+const WHOLE_PASS = `${BOTS_FILE}:whole`;/** What groups.json holds: a room's running turn is never saved. */export const persistedGroups = (groups: readonly GroupRecord[]) => groups.map(({ busyBotId: _busyBotId, turnStartedAt: _turnStartedAt, ...g }) => ({@@ -82,10 +95,19 @@ export const persistedGroups = (groups: readonly GroupRecord[]) => groups.map(({export class JsonRegistry implements RegistryStore {private readonly botsFile = new OwnedFile(BOTS_FILE, { mode: 0o600 });private readonly groupsFile = new OwnedFile(GROUPS_FILE, { mode: 0o600 });+ private readonly botsText = new BotsText(persistedBot);+ private readonly narrows = process.env[BOTS_FULL_SAVE_ENV] !== "1";+ /** In tests and fixture servers, every narrowed text is compared with the whole serialization, so a path that changes+ * a bot its save does not name fails there instead of waiting for the next whole pass. */+ private readonly checksNarrowing = process.env.VITEST !== undefined || process.env[BOTS_SAVE_CHECK_ENV] === "1";+ private narrowing = false;+ /** A narrowed text was written since the last whole one. */+ private narrowedSinceWhole = false;loadBots(): BotRecord[] {tightenRegistryFile(BOTS_FILE);supersedeLaterSave(BOTS_FILE); // the file is read afresh, so a write still waiting has nothing left to add+ supersedeLaterSave(WHOLE_PASS);const text = readFileSync(BOTS_FILE, "utf8"), bots = JSON.parse(text) as BotRecord[];this.botsFile.loaded(text);return bots;@@ -99,8 +121,22 @@ export class JsonRegistry implements RegistryStore {}writeBots(bots: readonly BotRecord[], current: boolean): void {- this.botsFile.write(JSON.stringify(persistedBots(bots)));- if (current) supersedeLaterSave(BOTS_FILE);+ const narrow = this.narrowing && current && this.botsText.canNarrow(bots);+ this.narrowing = false; // one narrowed write per request; any other save made during it (by a listener) is whole+ const { text, commit } = this.botsText.build(bots, narrow);+ if (narrow && this.checksNarrowing) assertNarrowed(text, bots);+ try {+ this.botsFile.write(text);+ } catch (error) {+ this.botsText.forget();+ throw error;+ }+ if (current) {+ commit();+ supersedeLaterSave(BOTS_FILE);+ this.narrowedSinceWhole = narrow;+ if (!narrow) supersedeLaterSave(WHOLE_PASS);+ } else this.botsText.forget();}writeGroups(groups: readonly GroupRecord[]): void {@@ -108,11 +144,36 @@ export class JsonRegistry implements RegistryStore {}upsertThread(owner: RegistryOwner, _threadId: string | undefined, durability: RegistryDurability, write: () => void): void {+ if (owner.kind === "bot" && this.narrows) {+ this.botsText.name(owner.id); // a waiting "later" write is superseded by the next narrowed one, so it must hold this owner+ // A "later" write is already one per moment however many changes wait; it stays whole, so nothing it queues can+ // miss the flush at exit.+ if (durability !== "later") {+ const whole = write;+ write = () => this.narrowed(whole);+ }+ }if (durability === "pass") saveSoon(owner.kind === "bot" ? this.botsFile : this.groupsFile, write);else if (durability === "later") saveLater(BOTS_FILE, write); // bots only (see RegistryDurability)else write();}+ /** Runs the Store's save of the whole list serializing only the bots named since the last write, then queues a whole+ * pass for what was changed in place on a bot no save named. */+ private narrowed(write: () => void): void {+ this.narrowing = true;+ try {+ write();+ } finally {+ this.narrowing = false;+ }+ if (this.narrowedSinceWhole) saveLater(WHOLE_PASS, write);+ }++ changedInPlace(owner: RegistryOwner): void {+ if (owner.kind === "bot") this.botsText.name(owner.id);+ }+deleteOwner(_owner: RegistryOwner, write: () => void): void {write();}@@ -121,3 +182,9 @@ export class JsonRegistry implements RegistryStore {return batchSaves(run);}}++function assertNarrowed(text: string, bots: readonly BotRecord[]): void {+ if (text === JSON.stringify(persistedBots(bots))) return;+ const stale = bots.filter((bot) => !text.includes(JSON.stringify(persistedBot(bot)))).map((bot) => bot.id);+ throw new Error(`a narrowed save of bots.json left out a change to ${stale.join(", ")}: name its owner, or save it whole`);+}diff --git a/server/store-deferred-saves.test.ts b/server/store-deferred-saves.test.tsindex 72110cf45e..2c3676b741 100644--- a/server/store-deferred-saves.test.ts+++ b/server/store-deferred-saves.test.ts@@ -82,7 +82,9 @@ describe("what bots.json holds, and when", () => {const saved = onDisk(bot.id);check(saved);expect(task(saved).usage, `${what}: the waiting changes ride along`).toMatchObject({ turns: n + 1 });- expect(waitingSaves(), `${what}: nothing is left waiting`).toBe(0);+ const now = written();+ flushLaterSaves();+ expect(written(), `${what}: nothing is left waiting`).toBe(now);});});@@ -91,7 +93,9 @@ describe("what bots.json holds, and when", () => {const bot = store.createBot({ name: "Maus" }, { seedMessages: false });store.patchTask(bot.id, bot.threadId, { snoozedUntil: 0 });store.patchTask(bot.id, bot.threadId, { unread: true });- expect(waitingSaves()).toBe(0);+ const now = written();+ flushLaterSaves();+ expect(written(), "nothing of it was left waiting").toBe(now);const task = onDisk(bot.id).tasks!.find((candidate) => candidate.threadId === bot.threadId)!;expect(task.unread).toBe(true);expect(task.snoozedUntil).toBeUndefined();diff --git a/server/store.ts b/server/store.tsindex b363a40226..3604c07b3e 100644--- a/server/store.ts+++ b/server/store.ts@@ -557,8 +557,8 @@ export class Store {/** In memory only: message writes must not rewrite bots.json. */private noteThreadActivity(threadId: string, at: number, forOrder = false, orderAt = at): void {if (!Number.isFinite(at)) return;- for (const task of [...this.bots, ...this.groups].map((owner) => owner.tasks?.find((candidate) => candidate.threadId === threadId))) {- if (!task) continue;+ for (const [kind, owner] of [...this.bots.map((bot) => ["bot", bot] as const), ...this.groups.map((group) => ["group", group] as const)]) {+ const task = owner.tasks?.find((candidate) => candidate.threadId === threadId); if (!task) continue; this.registry.changedInPlace({ kind, id: owner.id });task.updatedAt = Math.max(task.updatedAt ?? 0, at);if (forOrder) task.lastThreadOrderAt = Math.max(task.lastThreadOrderAt ?? 0, orderAt);}@@ -1506,7 +1506,7 @@ export class Store {// New authority goes live only after its durable save succeeds.this.saveBots(this.bots.map((candidate) => candidate === bot ? { ...bot, toolScope: nextToolScope } : candidate));bot.toolScope = nextToolScope;- } else this.saveBots();+ } else this.saveBotThread(id, undefined, "now");this.emit({ type: "bot", botId: id });return bot;}