Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Bound each bot's memory journal and drop rows past the read window
erywim5671f2734af3
diff --git a/server/memory-journal.test.ts b/server/memory-journal.test.tsindex b5c8186c92..b436e4a088 100644--- a/server/memory-journal.test.ts+++ b/server/memory-journal.test.ts@@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {BEFORE_CAP,+ DEFAULT_JOURNAL_MAX_BYTES,DIFF_CAP,JOURNAL_DIR,beginMemoryTurn,@@ -13,6 +14,7 @@ import {forgetBotMemoryJournal,flushMemoryJournal,journalFile,+ journalMaxBytes,journalMemoryDelete,journalMemoryWrite,journalTurnWrite,@@ -20,6 +22,7 @@ import {recordMemoryChange,resetMemoryJournalState,revertMemoryChange,+ trimMemoryJournal,unifiedDiff,} from "./memory-journal.ts";import { MEMORY_INDEX, hashMemoryText, readMemoryDoc } from "./memory-store.ts";@@ -194,6 +197,44 @@ describe("journalMemoryWrite / readMemoryJournal", () => {expect(revertMemoryChange(bot, secret!.id)).toMatchObject({ ok: false, status: 400 });});+ it("keeps the journal bounded: the oldest rows go once the file passes its cap", async () => {+ const bot = freshBot();+ for (let i = 0; i < 60; i++) journalMemoryWrite(bot, `memory/${i}.md`, `entry ${i}\n`, { actor: "person", via: "ui" });+ await flushMemoryJournal(bot);+ const before = statSync(journalFile(bot)).size;+ expect(before).toBeGreaterThan(2048);+ expect(trimMemoryJournal(bot, 2048)).toBe(true);+ expect(statSync(journalFile(bot)).size).toBeLessThan(before);+ const rows = readMemoryJournal(bot, 500);+ expect(rows.length).toBeGreaterThan(0);+ expect(rows[0].path).toBe("memory/59.md");+ expect(rows.some((row) => row.path === "memory/0.md")).toBe(false);+ for (const line of readFileSync(journalFile(bot), "utf8").trimEnd().split("\n")) expect(() => JSON.parse(line)).not.toThrow();+ if (process.platform !== "win32") expect(statSync(journalFile(bot)).mode & 0o777).toBe(0o600);+ });++ it("honours OMB_MEMORY_JOURNAL_MAX_BYTES after each write", async () => {+ const bot = freshBot();+ const previous = process.env.OMB_MEMORY_JOURNAL_MAX_BYTES;+ process.env.OMB_MEMORY_JOURNAL_MAX_BYTES = "1024";+ try {+ for (let i = 0; i < 40; i++) journalMemoryWrite(bot, `memory/cap-${i}.md`, `row ${i}\n`, { actor: "bot", via: "turn" });+ await flushMemoryJournal(bot);+ expect(statSync(journalFile(bot)).size).toBeLessThan(4096);+ expect(readMemoryJournal(bot, 1)[0].path).toBe("memory/cap-39.md");+ expect(journalMaxBytes()).toBe(1024);+ } finally {+ if (previous === undefined) delete process.env.OMB_MEMORY_JOURNAL_MAX_BYTES;+ else process.env.OMB_MEMORY_JOURNAL_MAX_BYTES = previous;+ }+ });++ it("reads the cap from the environment only when it is a sane byte count", () => {+ expect(journalMaxBytes({})).toBe(DEFAULT_JOURNAL_MAX_BYTES);+ expect(journalMaxBytes({ OMB_MEMORY_JOURNAL_MAX_BYTES: "0" })).toBe(DEFAULT_JOURNAL_MAX_BYTES);+ expect(journalMaxBytes({ OMB_MEMORY_JOURNAL_MAX_BYTES: "2048" })).toBe(2048);+ });+it("skips a torn last line rather than failing the read", async () => {const bot = freshBot();journalMemoryWrite(bot, "memory/a.md", "one", { actor: "person", via: "ui" });diff --git a/server/memory-journal.ts b/server/memory-journal.tsindex baacee6c11..268c13ee63 100644--- a/server/memory-journal.ts+++ b/server/memory-journal.ts@@ -1,7 +1,7 @@// Kept outside the workspace on purpose: an audit trail the audited bot can rewrite is not an audit trail.// A journal write must never fail the change it records.import { randomUUID } from "node:crypto";-import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync } from "node:fs";+import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, statSync } from "node:fs";import { appendFile } from "node:fs/promises";import { join } from "node:path";@@ -45,6 +45,9 @@ export const JOURNAL_DIR = join(DATA_DIR, "memory-journal");export const DIFF_CAP = 8_000;export const BEFORE_CAP = 512 * 1024;const MAX_JOURNAL_READ_BYTES = 8 * 1024 * 1024;+/** Past this size the oldest rows go: they sit outside the read window already, so nothing reachable is lost. */+export const DEFAULT_JOURNAL_MAX_BYTES = 32 * 1024 * 1024;+const MIN_JOURNAL_MAX_BYTES = 1024;const MAX_ROWS = 500;const LCS_CELL_CAP = 4_000_000;const CONTEXT = 2;@@ -159,6 +162,44 @@ export function unifiedDiff(before: string, after: string, path: string, cap = D}+/** The journal's byte cap: `OMB_MEMORY_JOURNAL_MAX_BYTES` (at least 1 KB), else 32 MiB. */+export function journalMaxBytes(env: NodeJS.ProcessEnv = process.env): number {+ const raw = env.OMB_MEMORY_JOURNAL_MAX_BYTES;+ if (!raw || !/^\d+$/.test(raw)) return DEFAULT_JOURNAL_MAX_BYTES;+ const value = Number(raw);+ return Number.isSafeInteger(value) && value >= MIN_JOURNAL_MAX_BYTES ? value : DEFAULT_JOURNAL_MAX_BYTES;+}++/** Drops the oldest rows once the file passes `maxBytes`, keeping the newest rows the read window can still reach. */+export function trimMemoryJournal(botId: string, maxBytes = journalMaxBytes()): boolean {+ const file = journalFile(botId);+ let size: number;+ try { size = statSync(file).size; } catch { return false; }+ if (size <= maxBytes) return false;+ const keep = Math.min(MAX_JOURNAL_READ_BYTES, maxBytes);+ let text: string;+ try {+ const fd = openSync(file, "r");+ try {+ const offset = Math.max(0, size - keep);+ const buffer = Buffer.alloc(size - offset);+ let length = 0;+ while (length < buffer.length) {+ const count = readSync(fd, buffer, length, buffer.length - length, offset + length);+ if (!count) break;+ length += count;+ }+ text = buffer.subarray(0, length).toString("utf8");+ } finally { closeSync(fd); }+ } catch { return false; }+ // The first line of a tail read is usually cut mid-row; everything after it is a whole record.+ const firstBreak = text.indexOf("\n");+ const kept = firstBreak >= 0 ? text.slice(firstBreak + 1) : "";+ if (!kept.trim()) return false;+ writeFileAtomic(file, kept, { mode: 0o600 });+ return true;+}+const writeQueues = new Map<string, Promise<void>>();function enqueue(botId: string, entry: MemoryJournalEntry): void {@@ -167,6 +208,7 @@ function enqueue(botId: string, entry: MemoryJournalEntry): void {.then(async () => {mkdirSync(JOURNAL_DIR, { recursive: true, mode: 0o700 });await appendFile(journalFile(botId), `${JSON.stringify(entry)}\n`, { mode: 0o600 });+ trimMemoryJournal(botId);}).catch((error: unknown) => {console.error(`memory-journal: could not append for ${botId}:`, error instanceof Error ? error.message : error);