Skip to content

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

Cloud storage: caps for conversation logs, ended engine sessions and tool results (off by default) (#7274)

Milind Sonif61ff1d246a2
diff --git a/server/activity.ts b/server/activity.ts
index eb2d199b86..16f598c786 100644
--- a/server/activity.ts
+++ b/server/activity.ts
@@ -244,7 +244,7 @@ export function describedTool(name: string, input?: unknown): Described {
}
const DECISION_SCAN = 20_000;
-const EVENTS_PER_THREAD = 2_000;
+export const EVENTS_PER_THREAD = 2_000;
/** A verdict is written as the request opens and the run follows, occasionally a clock skew's worth earlier. */
const MATCH_BEFORE_MS = 5_000;
const MATCH_AFTER_MS = 30_000;
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 16b122bfd7..42245618a5 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -35,7 +35,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_CREDENTIAL_STORE", "OMB_CUSTOM_DECIDER_KEY", "OMB_CUSTOM_IMAGE_KEY", "OMB_CUSTOM_LIVE_ENDPOINT", "OMB_CUSTOM_LIVE_MODEL", "OMB_DATA_DIR", "OMB_DECISION_RETENTION_DAYS",
"OMB_DEEPSEEK_API_KEY", "OMB_DEEPSEEK_SPEECH_API", "OMB_DESKTOP_LAUNCH_ID", "OMB_DESKTOP_PARENT", "OMB_DEVS_STATUS_MS",
"OMB_DEV_TRUST_LOCAL_BROWSER", "OMB_DISABLE_ANNOUNCEMENTS", "OMB_DISABLE_MODEL_CATALOG_FETCH", "OMB_DISABLE_MODEL_MANIFEST_FETCH", "OMB_DUCKDB_DIR", "OMB_DUCKDB_MAX_TEMP_SIZE",
- "OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENGINE_TAG", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF",
+ "OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENGINE_SESSION_SWEEP", "OMB_ENGINE_TAG", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF",
"OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FISH_LIVE_AGENT_ID", "OMB_FISH_LIVE_URL", "OMB_FLEET_SOCKET", "OMB_GATE_",
"OMB_GEMINI_API_KEY", "OMB_GEMINI_IMAGE_KEY", "OMB_GEMINI_LIVE_MODEL", "OMB_GEMINI_LIVE_URL", "OMB_GEMINI_TTS_API", "OMB_GOAL_WAIT_MAX_MS",
"OMB_GREENFERENCE_API_KEY", "OMB_GROQ_API_KEY", "OMB_HANDOFF_MAX_FAILURES", "OMB_HANDOFF_MAX_TURNS", "OMB_HELPER_INSTANCE", "OMB_HELPER_MODEL", "OMB_HOOKS", "OMB_HOOK_",
@@ -50,9 +50,9 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_SESSION_IDLE_MIN_MS", "OMB_SESSION_IDLE_MS", "OMB_SESSION_MAX_DAYS", "OMB_SESSION_TTL_DAYS",
"OMB_SHARED_WORKSPACE_FULL_ACCESS", "OMB_SIGNIN_EMAILS", "OMB_SIGNIN_MEMBER_EMAILS", "OMB_SIGNIN_SMTP_FROM",
"OMB_SIGNIN_SMTP_URL", "OMB_SKILLS_DIR", "OMB_SMOKE_BUNDLED_CUA", "OMB_SMOKE_CUA", "OMB_SMOKE_KEEP_OPEN",
- "OMB_SMOKE_TEST", "OMB_SSE_HEARTBEAT_MS", "OMB_STATIC_DIR", "OMB_SYNC_ROOT", "OMB_TAILNET_ADDRESSES", "OMB_TAILNET_NAME", "OMB_TAILNET_SERVED", "OMB_TEAM_AWAY_WINDOW_MS",
+ "OMB_SMOKE_TEST", "OMB_SSE_HEARTBEAT_MS", "OMB_STATIC_DIR", "OMB_SYNC_ROOT", "OMB_TAILNET_ADDRESSES", "OMB_TAILNET_NAME", "OMB_TAILNET_SERVED", "OMB_TEAM_AWAY_WINDOW_MS", "OMB_TOOL_RESULTS_SWEEP",
"OMB_TEAM_PRESENCE_GRACE_MS", "OMB_TEST_COOKIE_KEY", "OMB_TEST_INTERNAL_CAPABILITY_KEY", "OMB_TEST_ORG_LIBRARY_KEY",
- "OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_THREAD_CACHE_MB", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE",
+ "OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_THREAD_CACHE_MB", "OMB_THREAD_LOG_CAP", "OMB_THREAD_LOG_CUT", "OMB_THREAD_LOG_SWEEP", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE",
"OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURNS_MAX_RUNNING", "OMB_TURN_STALL_MS", "OMB_UNATTENDED_TURN_MAX_DENIALS", "OMB_UNATTENDED_TURN_MAX_MS", "OMB_UNATTENDED_TURN_MAX_REQUESTS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL",
"OMB_USAGE_CAP_DAILY_TOKENS", "OMB_USAGE_CAP_DAILY_USD", "OMB_USAGE_CAP_MONTHLY_TOKENS", "OMB_USAGE_CAP_MONTHLY_USD",
"OMB_USAGE_CAP_STOPS", "OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET",
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index bee7e66cde..7ac534448f 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -38,6 +38,8 @@ const SERVER_ENV_NAMES = new Set([
"OMB_CLOUD_ROLE", "OMB_CLOUD_MACHINE_ID", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_IMAGE", "OMB_PUBLIC_URL", "OMB_WEBHOOK_PUBLIC_URL",
"OMB_CLOUD_TEAM_ID", "OMB_CLOUD_TEAM_NAME", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_VOICE_URL", "OMB_CLOUD_DECIDER_URL", "OMB_CLOUD_AI_URL", "OMB_CLOUD_X_URL", "OMB_CLOUD_HOSTING_URL", "OMB_TTS_DEFAULT_VOICE",
"OMB_COMPOSIO_BROKER_URL", "OMB_COMPOSIO_BROKER",
+ // Ended engine sessions' prune (server/host/engine-session-sweep.ts), off unless the Admin sets it.
+ "OMB_ENGINE_SESSION_SWEEP",
// The addresses a home answered at before it moved to another provider, which still forward to it.
"OMB_CLOUD_LEGACY_ORIGINS",
// The bot box switch (server/bot-box/detect.ts): the Admin may turn a home's box off for support.
@@ -46,6 +48,8 @@ const SERVER_ENV_NAMES = new Set([
"OMB_CACHE_ROOT",
// The image's own engine CLIs before older copies in the data folder (server/image-engines.ts), for one test Cloud first.
"OMB_IMAGE_ENGINES",
+ // The conversation logs' cap and age limit (server/host/thread-log-sweep.ts), off unless the Admin sets it.
+ "OMB_THREAD_LOG_SWEEP", "OMB_THREAD_LOG_CAP", "OMB_THREAD_LOG_CUT",
// An ended Cloud started only for its owner's export: the server runs frozen (server/move-freeze.ts).
"OMB_CLOUD_EXPORT_ONLY",
// The idle task workspaces' dependency sweep (server/host/start-upkeep.ts), off unless set: the Admin may turn it on.
@@ -54,6 +58,8 @@ const SERVER_ENV_NAMES = new Set([
"OMB_CONVERSATION_FOLDER_CLEANUP",
// The orphan sweep's switch (server/host/orphan-sweep.ts): off, report or remove, set per home by the Admin.
"OMB_ORPHAN_SWEEP", "OMB_ORPHAN_SWEEP_MAX_SHARE",
+ // The full tool results' day-old sweep (server/host/tool-results-sweep.ts), off unless the Admin sets it.
+ "OMB_TOOL_RESULTS_SWEEP",
]);
export function serverEnvironmentAllowed(name: string): boolean {
return SERVER_ENV_NAMES.has(name) || name.startsWith("LC_");
diff --git a/server/harness/bus.test.ts b/server/harness/bus.test.ts
index 420c7c9058..528ca816bf 100644
--- a/server/harness/bus.test.ts
+++ b/server/harness/bus.test.ts
@@ -62,6 +62,20 @@ describe("EventBus", () => {
expect(seen).toHaveLength(0);
});
+ it("says a conversation's log is quiet only when nothing of it is queued or being written", async () => {
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ const bus = new EventBus(async () => { await held; });
+ expect(bus.logQuiet("busy-log")).toBe(true);
+ bus.publish(testEvent({ threadId: "busy-log" }));
+ expect(bus.logQuiet("busy-log")).toBe(false);
+ await Promise.resolve();
+ expect(bus.logQuiet("busy-log")).toBe(false);
+ release();
+ await bus.flush();
+ expect(bus.logQuiet("busy-log")).toBe(true);
+ });
+
it("tees every published event to the per-thread NDJSON log", async () => {
const bus = new EventBus();
bus.publish(testEvent({ threadId: "log-me" }));
diff --git a/server/harness/bus.ts b/server/harness/bus.ts
index e7b6dac3fc..e97c4dbc53 100644
--- a/server/harness/bus.ts
+++ b/server/harness/bus.ts
@@ -212,6 +212,11 @@ export class EventBus {
});
}
+ /** Nothing of this conversation waits for its log, and no append is under way. */
+ logQuiet(threadId: string): boolean {
+ return !this.pumping && !this.kickScheduled && !this.queued.some((item) => item.event.threadId === threadId);
+ }
+
private flushDisk(): Promise<void> {
if (this.queued.length === 0 && !this.pumping && !this.kickScheduled) return Promise.resolve();
return new Promise((resolve) => {
diff --git a/server/host/engine-session-sweep.e2e.test.ts b/server/host/engine-session-sweep.e2e.test.ts
new file mode 100644
index 0000000000..ebac2b4fee
--- /dev/null
+++ b/server/host/engine-session-sweep.e2e.test.ts
@@ -0,0 +1,105 @@
+import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { launchVerificationServer, runControlOmb } from "../../scripts/control-omb.ts";
+import { rebuiltSessionNotice } from "../resume-recovery.ts";
+import { engineSessionFolders } from "./delete-leftovers.ts";
+import { createLoggedSessions, liveSessions, sweepEngineSessions } from "./engine-session-sweep.ts";
+
+const ENDED = "00000000-0000-4000-8000-00000000e7d0";
+
+// Cloud homes, where this runs, are Linux.
+it.skipIf(process.platform === "win32")("a conversation whose ended engine sessions were pruned still resumes the session it is on", async () => {
+ // The fake CLI keeps projects/<folder>/<session>.jsonl as Claude Code does and refuses --resume without it; each turn's
+ // engine exits once it answers, so the next turn relaunches with --resume.
+ const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_HOME_FILES: "1", FAKE_CLAUDE_EXIT_AFTER_TURN: "1" });
+ try {
+ const dataDir = fixture.info.dataDir;
+ const claude = join(dataDir, ".claude");
+ mkdirSync(claude, { recursive: true });
+ writeFileSync(join(claude, ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "fixture-token-not-a-credential" } }));
+ const control = (args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, { method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ expect(response.ok).toBe(true);
+ return response.json() as Promise<any>;
+ };
+ const { bot } = await api("POST", "/api/bots", { name: "Session keeper" });
+ const turn = async (text: string) => {
+ await control(["send", "--bot", bot.id, "--task", bot.threadId, "--text", text]);
+ expect((await control(["wait", "--bot", bot.id, "--task", bot.threadId, "--timeout", "30"])).status).toBe("settled");
+ };
+ await turn("First: remember the word HERON.");
+ const bots = JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8")) as any[];
+ const cursor = Object.values(bots.find((b) => b.id === bot.id)?.resumeCursors ?? {})[0] as string;
+ const project = readdirSync(join(claude, "projects")).find((folder) => existsSync(join(claude, "projects", folder, `${cursor}.jsonl`)))!;
+ expect(project).toBeTruthy();
+
+ // An earlier session of this conversation that it moved off, as a compaction or a model change leaves one.
+ const old = new Date(Date.now() - 10 * 24 * 60 * 60_000);
+ const ended = [join(claude, "projects", project, `${ENDED}.jsonl`), join(claude, "file-history", ENDED, "a@v1")];
+ for (const file of ended) {
+ mkdirSync(join(file, ".."), { recursive: true });
+ writeFileSync(file, "{}\n");
+ utimesSync(file, old, old);
+ }
+ utimesSync(join(claude, "file-history", ENDED), old, old);
+ appendFileSync(join(dataDir, "events", `${bot.threadId}.ndjson`), `${JSON.stringify({ eventId: "e", provider: "claudeAgent", threadId: bot.threadId, createdAt: old.toISOString(), type: "session.started", sessionId: ENDED, model: "m" })}\n`);
+ // The live session is as old: age alone never removes it.
+ utimesSync(join(claude, "projects", project, `${cursor}.jsonl`), old, old);
+
+ const result = await sweepEngineSessions({
+ dataDir, mode: "on", folders: engineSessionFolders(dataDir, [{ HOME: dataDir }]), cacheRoots: [],
+ live: () => liveSessions(JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8"))), logged: await createLoggedSessions(join(dataDir, "events"))(),
+ });
+ expect(result.refused).toBeUndefined();
+ expect(result.sessions).toBe(1);
+ for (const file of ended) expect(existsSync(file)).toBe(false);
+ expect(existsSync(join(claude, "projects", project, `${cursor}.jsonl`))).toBe(true);
+ expect(existsSync(join(claude, ".credentials.json"))).toBe(true);
+
+ await turn("Second: what was the word?");
+ const argv = JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")).argv as string[];
+ expect(argv.indexOf("--resume")).toBeGreaterThan(-1);
+ expect(argv[argv.indexOf("--resume") + 1]).toBe(cursor);
+ const said = JSON.stringify((await api("GET", "/api/bots")).bots.find((b: any) => b.id === bot.id).messages);
+ expect(said).toContain("remember the word HERON");
+ expect(said).not.toContain("No conversation found");
+ } finally {
+ await fixture.close();
+ }
+}, 120_000);
+
+it.skipIf(process.platform === "win32")("a conversation whose session Claude Code's own 30-day sweep removed goes on from its chat, and says so", async () => {
+ const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_HOME_FILES: "1", FAKE_CLAUDE_EXIT_AFTER_TURN: "1" });
+ try {
+ const dataDir = fixture.info.dataDir;
+ const claude = join(dataDir, ".claude");
+ mkdirSync(claude, { recursive: true });
+ writeFileSync(join(claude, ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "fixture-token-not-a-credential" } }));
+ const control = (args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
+ const bots = async () => (await (await fetch(`${fixture.info.url}/api/bots`)).json() as any).bots as any[];
+ const created = await (await fetch(`${fixture.info.url}/api/bots`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "Old friend" }) })).json() as any;
+ const bot = created.bot;
+ const turn = async (text: string) => {
+ await control(["send", "--bot", bot.id, "--task", bot.threadId, "--text", text]);
+ expect((await control(["wait", "--bot", bot.id, "--task", bot.threadId, "--timeout", "30"])).status).toBe("settled");
+ };
+ await turn("First: remember the word HERON.");
+ const saved = (JSON.parse(readFileSync(join(dataDir, "bots.json"), "utf8")) as any[]).find((b) => b.id === bot.id);
+ const cursor = Object.values(saved?.resumeCursors ?? {})[0] as string;
+ const project = readdirSync(join(claude, "projects")).find((folder) => existsSync(join(claude, "projects", folder, `${cursor}.jsonl`)))!;
+ // What Claude Code's cleanupPeriodDays sweep does to a session idle past it.
+ rmSync(join(claude, "projects", project, `${cursor}.jsonl`));
+
+ await turn("Back after a long while: what was the word?");
+ const messages = (await bots()).find((b) => b.id === bot.id).messages as any[];
+ const after = messages.slice(messages.findIndex((m) => m.role === "user" && m.text?.includes("Back after a long while")));
+ expect(after.some((m) => m.kind === "activity" && m.tool?.name === `notice: ${rebuiltSessionNotice("Claude Code")}`)).toBe(true);
+ expect(after.some((m) => m.role === "bot" && m.kind === "text" && m.text)).toBe(true);
+ expect(JSON.stringify(messages)).toContain("remember the word HERON");
+ } finally {
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/host/engine-session-sweep.test.ts b/server/host/engine-session-sweep.test.ts
new file mode 100644
index 0000000000..3daf647107
--- /dev/null
+++ b/server/host/engine-session-sweep.test.ts
@@ -0,0 +1,347 @@
+import { appendFileSync, chmodSync, existsSync, lstatSync, lutimesSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { engineSessionFolders } from "./delete-leftovers.ts";
+import {
+ CLAUDE_TRANSCRIPT_DAYS, IDLE_MS, TRASH_DIR, claudeCliCacheRoots, createLoggedSessions, emptyTrash, engineSessionSweepMode, liveSessions,
+ engineSessionPass, pinClaudeRetention, sweepEngineSessions, sweepLine, type EngineSessionPassDeps,
+ type EngineSessionSweepDeps,
+} from "./engine-session-sweep.ts";
+
+const NOW = Date.parse("2026-11-23T12:00:00Z");
+const DAY = 24 * 60 * 60_000;
+const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, "0")}`;
+const LIVE = id(1), ENDED = id(2), ENDED_RECENT = id(3), UNLOGGED = id(4), HANDED = id(5);
+
+let root: string, dataDir: string, home: string, claude: string, codex: string;
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "engine-session-sweep-"));
+ home = join(root, "home");
+ dataDir = join(home, ".openmausbot");
+ claude = join(home, ".claude");
+ codex = join(dataDir, "providers", "codex-own", "h1", "codex");
+ mkdirSync(join(dataDir, "events"), { recursive: true });
+});
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+function put(path: string, text = "x".repeat(100), ageMs = 10 * DAY): string {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, text);
+ utimesSync(path, new Date(NOW - ageMs), new Date(NOW - ageMs));
+ return path;
+}
+
+const started = (threadId: string, sessionId: string) => `${JSON.stringify({ eventId: sessionId, provider: "claudeAgent", threadId, createdAt: new Date(NOW).toISOString(), type: "session.started", sessionId, model: "m" })}\n`;
+
+/** A Claude session as Claude Code 2.1 keeps it, in a project folder, with its side folders. */
+function claudeSession(session: string, ageMs = 10 * DAY): string[] {
+ const project = join(claude, "projects", "-home-work");
+ const files = [
+ put(join(project, `${session}.jsonl`), "{}\n".repeat(50), ageMs),
+ put(join(project, session, "subagents", "agent-a.jsonl"), "{}\n", ageMs),
+ put(join(project, session, "tool-results", "r.txt"), "y".repeat(5_000), ageMs),
+ put(join(claude, "file-history", session, "a@v1"), "old", ageMs),
+ put(join(claude, "session-env", session, "env"), "", ageMs),
+ put(join(claude, "todos", `${session}-agent-${session}.json`), "[]", ageMs),
+ put(join(claude, "debug", `${session}.txt`), "debug", ageMs),
+ ];
+ // A session's folders last changed when it last wrote into them.
+ for (const dir of [join(project, session, "subagents"), join(project, session, "tool-results"), join(project, session), join(claude, "file-history", session), join(claude, "session-env", session)]) {
+ utimesSync(dir, new Date(NOW - ageMs), new Date(NOW - ageMs));
+ }
+ return files;
+}
+
+function seed() {
+ writeFileSync(join(dataDir, "events", "t1.ndjson"), [LIVE, ENDED, ENDED_RECENT, HANDED].map((s) => started("t1", s)).join(""));
+ const files = {
+ live: claudeSession(LIVE),
+ ended: claudeSession(ENDED),
+ recent: claudeSession(ENDED_RECENT, DAY),
+ unlogged: claudeSession(UNLOGGED),
+ handed: claudeSession(HANDED),
+ codexEnded: [put(join(codex, "sessions", "2026", "11", "01", `rollout-2026-11-01T00-00-00-${ENDED}.jsonl`))],
+ codexLive: [put(join(codex, "sessions", "2026", "11", "01", `rollout-2026-11-01T00-00-00-${LIVE}.jsonl`))],
+ kept: [
+ put(join(claude, ".credentials.json"), "{}"), put(join(claude, "settings.json"), "{}"),
+ put(join(claude, "projects", "-home-work", "memory", "MEMORY.md"), "notes"),
+ put(join(codex, "auth.json"), "{}"), put(join(codex, "config.toml"), ""), put(join(codex, "state_5.sqlite"), ""),
+ ],
+ cacheOld: put(join(home, ".cache", "claude-cli-nodejs", "-home-work", "mcp-logs-x", "2026-11-01.jsonl"), "z".repeat(1_000)),
+ cacheNew: put(join(home, ".cache", "claude-cli-nodejs", "-home-work", "mcp-logs-y", "2026-11-23.jsonl"), "z", 60_000),
+ };
+ // An old folder of only old logs goes once empty; its parent keeps the newer one.
+ utimesSync(dirname(files.cacheOld), new Date(NOW - 10 * DAY), new Date(NOW - 10 * DAY));
+ return files;
+}
+
+/** Every entry under `dir` with its size and change time, links as links. */
+function tree(dir: string): string[] {
+ const out: string[] = [];
+ const walk = (at: string) => {
+ const stats = lstatSync(at);
+ out.push(`${at} ${stats.size} ${stats.mtimeMs}`);
+ if (stats.isDirectory()) for (const name of readdirSync(at).sort()) walk(join(at, name));
+ };
+ walk(dir);
+ return out;
+}
+
+const bots = [{ id: "b1", resumeCursors: { claude: LIVE }, tasks: [{ threadId: "t1", resumeCursors: { claude: LIVE, codex: LIVE }, handedMessages: { claude: { session: HANDED } } }] }];
+
+async function deps(mode: "on" | "report", extra: Partial<EngineSessionSweepDeps> = {}): Promise<EngineSessionSweepDeps> {
+ return {
+ dataDir, mode, folders: engineSessionFolders(dataDir, [{ HOME: home }]), cacheRoots: claudeCliCacheRoots([{ HOME: home }]),
+ live: () => liveSessions(bots), logged: await createLoggedSessions(join(dataDir, "events"))(), now: () => NOW, ...extra,
+ };
+}
+
+describe("the engine sessions' switch and inputs", () => {
+ it("is off unless set", () => {
+ expect(engineSessionSweepMode({})).toBe("off");
+ expect(engineSessionSweepMode({ OMB_ENGINE_SESSION_SWEEP: "yes please" })).toBe("off");
+ expect(engineSessionSweepMode({ OMB_ENGINE_SESSION_SWEEP: "report" })).toBe("report");
+ expect(engineSessionSweepMode({ OMB_ENGINE_SESSION_SWEEP: "on" })).toBe("on");
+ });
+
+ it("counts every cursor and handed session as live", () => {
+ expect([...liveSessions(bots)].sort()).toEqual([LIVE, HANDED].sort());
+ expect(liveSessions([{ resumeCursors: { pi: "/abs/path.jsonl", x: 3 } }])).toEqual(new Set(["/abs/path.jsonl"]));
+ });
+
+ it("finds the CLI's log folder through XDG_CACHE_HOME or HOME, never a relative one", () => {
+ expect(claudeCliCacheRoots([{ HOME: "/data" }, { HOME: "/data", XDG_CACHE_HOME: "/data/x" }, { HOME: "rel" }, {}])).toEqual([join(resolve("/data"), ".cache", "claude-cli-nodejs"), join(resolve("/data/x"), "claude-cli-nodejs")]);
+ });
+
+ it("reads the logs' session lines on from where it stopped, and again from the start after a rewrite", async () => {
+ const log = join(dataDir, "events", "t2.ndjson");
+ const logged = createLoggedSessions(join(dataDir, "events"));
+ const whole = started("t2", id(7));
+ writeFileSync(log, started("t2", id(6)) + whole.slice(0, 40));
+ expect([...(await logged())]).toEqual([id(6)]);
+ appendFileSync(log, whole.slice(40));
+ expect([...(await logged())].sort()).toEqual([id(6), id(7)]);
+ writeFileSync(log, started("t2", id(8)));
+ expect([...(await logged())]).toEqual([id(8)]);
+ writeFileSync(join(dataDir, "events", "bad.ndjson"), `${JSON.stringify({ type: "session.started", sessionId: "../../etc" })}\nnot json "session.started"\n`);
+ expect([...(await logged())]).toEqual([id(8)]);
+ });
+});
+
+describe("sweepEngineSessions", () => {
+ it("removes MausBot's ended sessions a week idle and the CLI's old logs, and nothing else", async () => {
+ const files = seed();
+ const result = await sweepEngineSessions(await deps("on"));
+ expect(result.sessions).toBe(1);
+ expect(result.kept).toBe(1);
+ expect(result.cacheFiles).toBe(1);
+ for (const file of [...files.ended, ...files.codexEnded, files.cacheOld]) expect(existsSync(file), file).toBe(false);
+ expect(existsSync(join(claude, "projects", "-home-work", ENDED))).toBe(false);
+ expect(existsSync(dirname(files.cacheOld))).toBe(false);
+ for (const file of [...files.live, ...files.recent, ...files.unlogged, ...files.handed, ...files.codexLive, ...files.kept, files.cacheNew]) {
+ expect(existsSync(file), file).toBe(true);
+ }
+ expect(sweepLine(result)).toContain("freed");
+ // Removed by a rename into the app's trash, which the pass empties.
+ expect(readdirSync(join(dataDir, TRASH_DIR))).toEqual([]);
+ expect(JSON.parse(readFileSync(join(claude, "settings.json"), "utf8"))).toEqual({ cleanupPeriodDays: CLAUDE_TRANSCRIPT_DAYS });
+ expect(result.retentionSet).toBe(1);
+ });
+
+ it("removes nothing while a turn runs, and goes on once none does", async () => {
+ const files = seed();
+ const busy = await sweepEngineSessions(await deps("on", { turnsRunning: () => true, turnWaitMs: 0 }));
+ expect(busy.stopped).toBe(true);
+ for (const file of [...files.ended, files.cacheOld]) expect(existsSync(file)).toBe(true);
+ let checks = 0;
+ const later = await sweepEngineSessions(await deps("on", { turnsRunning: () => checks++ < 1, turnWaitMs: 60_000 }));
+ expect([later.sessions, later.cacheFiles]).toEqual([1, 1]);
+ }, 30_000);
+
+ it("empties a trash an interrupted pass left, and nothing outside it", async () => {
+ const left = put(join(dataDir, TRASH_DIR, "1700000000000", "0", "x.jsonl"));
+ const beside = put(join(dataDir, "cache", "trash", "other", "keep.txt"));
+ await emptyTrash(dataDir);
+ expect(existsSync(left)).toBe(false);
+ expect(existsSync(join(dataDir, TRASH_DIR))).toBe(true);
+ expect(existsSync(beside)).toBe(true);
+ });
+
+ it("a report frees nothing and counts what removing would", async () => {
+ seed();
+ const before = tree(home);
+ const report = await sweepEngineSessions(await deps("report"));
+ expect(tree(home)).toEqual(before);
+ const result = await sweepEngineSessions(await deps("on"));
+ expect([report.sessions, report.sessionBytes, report.cacheFiles, report.cacheBytes]).toEqual([result.sessions, result.sessionBytes, result.cacheFiles, result.cacheBytes]);
+ expect(report.sessionBytes).toBeGreaterThan(5_000);
+ expect(sweepLine(report)).toContain("would free");
+ });
+
+ it("keeps a session whose folder looks old but has a file written to lately", async () => {
+ const files = seed();
+ const deep = join(claude, "projects", "-home-work", ENDED, "tool-results", "r.txt");
+ writeFileSync(deep, "rewritten");
+ utimesSync(join(claude, "projects", "-home-work", ENDED, "tool-results"), new Date(NOW - 10 * DAY), new Date(NOW - 10 * DAY));
+ utimesSync(join(claude, "projects", "-home-work", ENDED), new Date(NOW - 10 * DAY), new Date(NOW - 10 * DAY));
+ const result = await sweepEngineSessions(await deps("on", { now: () => Date.now() + 60_000 }));
+ expect(result.sessions).toBe(0);
+ for (const file of files.ended) expect(existsSync(file)).toBe(true);
+ });
+
+ it("keeps a session that became a conversation's again while the pass ran", async () => {
+ const files = seed();
+ let reads = 0;
+ const result = await sweepEngineSessions(await deps("on", { live: () => (reads++ ? new Set([LIVE, HANDED, ENDED]) : liveSessions(bots)) }));
+ expect(result.sessions).toBe(0);
+ for (const file of files.ended) expect(existsSync(file)).toBe(true);
+ });
+
+ it("refuses when no conversation has a session, or none of theirs is where it looks", async () => {
+ const files = seed();
+ expect((await sweepEngineSessions(await deps("on", { live: () => new Set() }))).refused).toContain("may not have loaded");
+ expect((await sweepEngineSessions(await deps("on", { live: () => new Set([id(99)]) }))).refused).toContain("removed nothing");
+ for (const file of files.ended) expect(existsSync(file)).toBe(true);
+ });
+
+ it("stops for a move or backup", async () => {
+ const files = seed();
+ const result = await sweepEngineSessions(await deps("on", { paused: () => true }));
+ expect(result.stopped).toBe(true);
+ for (const file of files.ended) expect(existsSync(file)).toBe(true);
+ });
+});
+
+describe("Claude Code's own transcript age", () => {
+ it("is added where the person has not set it, kept where they have, and left alone where it cannot be read", async () => {
+ mkdirSync(claude, { recursive: true });
+ // No file: Claude Code's default is the same 30 days, so none is made.
+ expect(await pinClaudeRetention(claude, true)).toBe("absent");
+ expect(existsSync(join(claude, "settings.json"))).toBe(false);
+ writeFileSync(join(claude, "settings.json"), "{}");
+ expect(await pinClaudeRetention(claude, false)).toBe("set");
+ expect(readFileSync(join(claude, "settings.json"), "utf8")).toBe("{}");
+ expect(await pinClaudeRetention(claude, true)).toBe("set");
+ expect(JSON.parse(readFileSync(join(claude, "settings.json"), "utf8"))).toEqual({ cleanupPeriodDays: 30 });
+ writeFileSync(join(claude, "settings.json"), JSON.stringify({ cleanupPeriodDays: 365, model: "x" }));
+ expect(await pinClaudeRetention(claude, true)).toBe("kept");
+ expect(JSON.parse(readFileSync(join(claude, "settings.json"), "utf8"))).toEqual({ cleanupPeriodDays: 365, model: "x" });
+ writeFileSync(join(claude, "settings.json"), "{ not json");
+ expect(await pinClaudeRetention(claude, true)).toBe("skipped");
+ expect(readFileSync(join(claude, "settings.json"), "utf8")).toBe("{ not json");
+ if (process.platform === "win32") return;
+ rmSync(join(claude, "settings.json"));
+ const elsewhere = put(join(root, "theirs.json"), "{}");
+ symlinkSync(elsewhere, join(claude, "settings.json"));
+ expect(await pinClaudeRetention(claude, true)).toBe("skipped");
+ expect(readFileSync(elsewhere, "utf8")).toBe("{}");
+ });
+
+ it("keeps the file's mode, indentation and line endings", async () => {
+ mkdirSync(claude, { recursive: true });
+ const file = join(claude, "settings.json");
+ for (const [before, after] of [
+ ['{\n "theme": "dark"\n}\n', '{\n "theme": "dark",\n "cleanupPeriodDays": 30\n}\n'],
+ ['{\n\t"theme": "dark"\n}', '{\n\t"theme": "dark",\n\t"cleanupPeriodDays": 30\n}'],
+ ['{\r\n "theme": "dark"\r\n}\r\n', '{\r\n "theme": "dark",\r\n "cleanupPeriodDays": 30\r\n}\r\n'],
+ ['{"theme":"dark"}\n', '{"theme":"dark","cleanupPeriodDays":30}\n'],
+ ] as const) {
+ writeFileSync(file, before);
+ if (process.platform !== "win32") chmodSync(file, 0o644);
+ expect(await pinClaudeRetention(claude, true)).toBe("set");
+ expect(readFileSync(file, "utf8")).toBe(after);
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o644);
+ }
+ });
+});
+
+describe("a pass", () => {
+ const passDeps = async (mode: "on" | "report", extra: Partial<EngineSessionPassDeps> = {}): Promise<EngineSessionPassDeps> => {
+ const base = await deps(mode);
+ return {
+ dataDir, mode, folders: () => base.folders, cacheRoots: () => base.cacheRoots, live: base.live,
+ logged: () => createLoggedSessions(join(dataDir, "events"))(), now: () => NOW, ...extra,
+ };
+ };
+ const leftover = () => put(join(dataDir, TRASH_DIR, "1700000000000", "0", "x.jsonl"));
+
+ it("during a move or backup, or while a turn runs, reads and writes nothing: not the trash, not settings.json", async () => {
+ const files = seed();
+ const trash = leftover();
+ const settings = readFileSync(join(claude, "settings.json"), "utf8");
+ let logsRead = 0;
+ for (const extra of [{ paused: () => true }, { turnsRunning: () => true, turnWaitMs: 0 }]) {
+ const result = await engineSessionPass(await passDeps("on", { ...extra, logged: async () => (logsRead++, new Set()) }));
+ expect(result).toBeNull();
+ }
+ expect(logsRead).toBe(0);
+ expect(existsSync(trash)).toBe(true);
+ expect(readFileSync(join(claude, "settings.json"), "utf8")).toBe(settings);
+ for (const file of files.ended) expect(existsSync(file)).toBe(true);
+ });
+
+ it("a report changes nothing at all, an earlier pass's trash included", async () => {
+ seed();
+ leftover();
+ const before = tree(home);
+ const result = await engineSessionPass(await passDeps("report"));
+ expect(result?.sessions).toBe(1);
+ expect(result?.retentionSet).toBe(1);
+ expect(tree(home)).toEqual(before);
+ });
+
+ it("in on mode empties an interrupted pass's trash, then sweeps", async () => {
+ const files = seed();
+ const trash = leftover();
+ const result = await engineSessionPass(await passDeps("on"));
+ expect(existsSync(trash)).toBe(false);
+ expect(result?.sessions).toBe(1);
+ for (const file of files.ended) expect(existsSync(file)).toBe(false);
+ });
+});
+
+describe("what the engine sessions' sweep never reaches", () => {
+ // Windows makes a link only with a privilege CI's runners lack; Cloud homes, where this runs, are Linux.
+ it.skipIf(process.platform === "win32")("follows no link: a linked project folder, a linked session, a linked engine folder", async () => {
+ seed();
+ const outside = join(root, "outside");
+ const target = put(join(outside, "project", `${ENDED}.jsonl`));
+ const linkedFile = put(join(outside, "single.jsonl"));
+ symlinkSync(join(outside, "project"), join(claude, "projects", "-linked"));
+ rmSync(join(claude, "debug", `${ENDED}.txt`));
+ symlinkSync(linkedFile, join(claude, "debug", `${ENDED}.txt`));
+ lutimesSync(join(claude, "debug", `${ENDED}.txt`), new Date(NOW - 10 * DAY), new Date(NOW - 10 * DAY));
+ const otherHome = join(root, "other");
+ mkdirSync(otherHome);
+ symlinkSync(outside, join(otherHome, ".claude"));
+ const result = await sweepEngineSessions(await deps("on", { folders: engineSessionFolders(dataDir, [{ HOME: home }, { HOME: otherHome }]) }));
+ expect(result.sessions).toBe(1);
+ expect(existsSync(target)).toBe(true);
+ expect(existsSync(linkedFile)).toBe(true);
+ expect(lstatSync(join(claude, "projects", "-linked")).isSymbolicLink()).toBe(true);
+ expect(existsSync(join(claude, "debug", `${ENDED}.txt`))).toBe(false);
+ });
+
+ it("never names a file by anything but a whole session id from a log", async () => {
+ seed();
+ writeFileSync(join(dataDir, "events", "t9.ndjson"), started("t9", "projects") + started("t9", "../.credentials.json"));
+ const result = await sweepEngineSessions(await deps("on"));
+ expect(result.sessions).toBe(1);
+ expect(existsSync(join(claude, ".credentials.json"))).toBe(true);
+ expect(existsSync(join(claude, "projects"))).toBe(true);
+ });
+
+ it.skipIf(process.platform === "win32")("an engine folder inside the data folder reached through a link is skipped", async () => {
+ seed();
+ const real = join(root, "elsewhere");
+ mkdirSync(join(dataDir, "providers", "codex-own", "h2"), { recursive: true });
+ put(join(real, "sessions", "2026", "11", "01", `rollout-x-${ENDED}.jsonl`));
+ symlinkSync(real, join(dataDir, "providers", "codex-own", "h2", "codex"));
+ await sweepEngineSessions(await deps("on"));
+ expect(existsSync(join(real, "sessions", "2026", "11", "01", `rollout-x-${ENDED}.jsonl`))).toBe(true);
+ });
+
+ it("IDLE_MS is a week", () => expect(IDLE_MS).toBe(7 * DAY));
+});
diff --git a/server/host/engine-session-sweep.ts b/server/host/engine-session-sweep.ts
new file mode 100644
index 0000000000..1e695d8679
--- /dev/null
+++ b/server/host/engine-session-sweep.ts
@@ -0,0 +1,575 @@
+// A Cloud home's engine session history: the Claude Code and Codex sessions MausBot itself started that no conversation
+// can resume any more, and the Claude CLI's own MCP logs, go once they have been untouched for a week.
+//
+// The app resumes a conversation by its engine cursor alone (bots.json resumeCursors, through resume-plan.ts; a room
+// keeps its session in memory for minutes): a session that is no conversation's cursor and no conversation's handed
+// state is never resumed again. It is a session MausBot started when a session.started line in a remaining
+// conversation's events log names it. A session no log names (the person's own, a bot's own `claude` run in a shell,
+// one from before these logs) is never touched. A deleted conversation's sessions are delete-leftovers.ts's.
+//
+// Never removed: sign-in files, settings, `projects/<folder>/memory/` (only entries named by a whole session id are
+// considered), anything reached through a link, or anything outside each engine's folder. Nothing is removed while any
+// turn runs. An entry is first renamed, after a check that it is still the one listed (device and inode), into the
+// app's own trash on the same volume (cache/trash, left out of backups), which is emptied at the end of the pass and on
+// the next start after an interrupted one; an entry on another volume stays.
+//
+// Claude Code's own age sweep (cleanupPeriodDays) is made a deliberate 30 days in each of these Claude folders'
+// existing settings.json, only where the person has not set it. It removes by age alone, live sessions too: a conversation idle
+// longer goes on in a new session started from its chat, with a notice that earlier tool results did not carry over
+// (drivers/claude.ts classifyResumeFailure, resume-recovery.ts). 30 is Claude Code's default, so nothing changes today;
+// it stops a change of that default from changing what a Cloud keeps.
+import { lstat, mkdir, open, readFile, readdir, rename, rm, rmdir, type FileHandle } from "node:fs/promises";
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { dirname, isAbsolute, join, relative, resolve } from "node:path";
+import { setImmediate as yieldNow, setTimeout as sleep } from "node:timers/promises";
+
+import { writeFileAtomic } from "../atomic.ts";
+
+import { plainlyUnder, type EngineSessionFolders } from "./delete-leftovers.ts";
+
+export type EngineSessionSweepMode = "off" | "report" | "on";
+
+const DAY_MS = 24 * 60 * 60_000;
+/** A session file, or a CLI log, untouched this long. Far past a room's session idle and a warm fork moving a cursor. */
+export const IDLE_MS = 7 * DAY_MS;
+/** Soon after a start (a home that sleeps by stopping may be up only minutes), after the logs' sweep (3 minutes) and
+ * the tool results' (5), so the three do not start at once. */
+export const FIRST_PASS_MS = 7 * 60_000;
+/** A pass that stopped for a turn, a move or a backup is tried again this soon. */
+export const RETRY_MS = 30 * 60_000;
+/** When the last whole pass ended, under the data folder's cache/ (left out of backups): a restart, which reads the
+ * events logs again from their start, does not also bring the next pass forward. */
+export const STAMP_FILE = join("cache", "engine-session-sweep.json");
+/** Claude Code's transcript age limit for a Cloud's Claude folders (its default, made deliberate). */
+export const CLAUDE_TRANSCRIPT_DAYS = 30;
+/** While a turn runs nothing is removed: the pass waits this long for a quiet moment, then stops until the next. */
+export const TURN_WAIT_MS = 10 * 60_000;
+const TURN_POLL_MS = 15_000;
+/** The app's own trash, under the data folder's cache (left out of backups and exports). */
+export const TRASH_DIR = join("cache", "trash", "engine-sessions");
+export const PASS_EVERY_MS = DAY_MS;
+const SESSION_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
+const WHOLE_SESSION_ID = new RegExp(`^${SESSION_ID.source}$`, "i");
+/** Claude Code 2.1: `projects/<folder>/<session>.jsonl` and its `<session>/` folder, and one entry per session in these. */
+const CLAUDE_SESSION_FOLDERS = ["file-history", "session-env", "todos", "debug"] as const;
+/** Codex: `sessions/<year>/<month>/<day>/rollout-<time>-<session>.jsonl`. */
+const CODEX_SESSION_FOLDERS = ["sessions", "archived_sessions"] as const;
+const CODEX_DEPTH = 6;
+const CACHE_DEPTH = 4;
+const LOG_NAME = /^[\w-]{1,128}\.ndjson$/;
+const SESSION_MARK = Buffer.from('"session.started"');
+const CHUNK = 1024 * 1024;
+const MAX_LINE = 16 * 1024 * 1024;
+const MEASURE_ENTRIES = 50_000;
+
+/** OMB_ENGINE_SESSION_SWEEP: `report` (or `dry-run`) counts and changes nothing; `on` removes; anything else is off. */
+export function engineSessionSweepMode(env: NodeJS.ProcessEnv): EngineSessionSweepMode {
+ const raw = env.OMB_ENGINE_SESSION_SWEEP?.trim().toLowerCase();
+ if (raw === "report" || raw === "dry-run") return "report";
+ return raw === "on" ? "on" : "off";
+}
+
+type Cursors = Record<string, unknown> | undefined;
+type Handed = Record<string, { session?: unknown } | undefined> | undefined;
+export interface SessionHolder { resumeCursors?: Cursors; handedMessages?: Handed; tasks?: ReadonlyArray<{ resumeCursors?: Cursors; handedMessages?: Handed }> }
+
+/** Every session a remaining conversation can resume: its cursors, and the sessions its handed state describes. */
+export function liveSessions(bots: ReadonlyArray<SessionHolder>): Set<string> {
+ const live = new Set<string>();
+ const add = (value: unknown) => {
+ if (typeof value === "string" && value) live.add(value.toLowerCase());
+ };
+ for (const holder of [...bots, ...bots.flatMap((bot) => bot.tasks ?? [])]) {
+ for (const cursor of Object.values(holder.resumeCursors ?? {})) add(cursor);
+ for (const state of Object.values(holder.handedMessages ?? {})) add(state?.session);
+ }
+ return live;
+}
+
+/** The Claude CLI's own log folder for each environment an engine runs with (env-paths: XDG_CACHE_HOME, else ~/.cache). */
+export function claudeCliCacheRoots(environments: Iterable<Record<string, string | undefined>>): string[] {
+ const roots = new Set<string>();
+ for (const env of environments) {
+ const cache = env.XDG_CACHE_HOME && isAbsolute(env.XDG_CACHE_HOME) ? env.XDG_CACHE_HOME : env.HOME && isAbsolute(env.HOME) ? join(env.HOME, ".cache") : null;
+ if (cache) roots.add(join(resolve(cache), "claude-cli-nodejs"));
+ }
+ return [...roots];
+}
+
+async function entries(dir: string): Promise<string[]> {
+ try {
+ return await readdir(dir);
+ } catch {
+ return [];
+ }
+}
+
+async function stat(path: string) {
+ try {
+ return await lstat(path);
+ } catch {
+ return null;
+ }
+}
+
+async function realFolder(path: string): Promise<boolean> {
+ return (await stat(path))?.isDirectory() === true;
+}
+
+/** Bytes under `path` and the newest change of anything in it (a directory's mtime misses a write to a file in it),
+ * links counted as themselves and never followed; `whole` is false when the tree was past the budget or unreadable. */
+async function measure(path: string): Promise<{ bytes: number; newest: number; whole: boolean }> {
+ let bytes = 0;
+ let newest = 0;
+ let seen = 0;
+ let whole = true;
+ const walk = async (at: string) => {
+ if (++seen > MEASURE_ENTRIES) {
+ whole = false;
+ return;
+ }
+ const stats = await stat(at);
+ if (!stats) {
+ whole = false;
+ return;
+ }
+ bytes += stats.size;
+ newest = Math.max(newest, stats.mtimeMs);
+ if (stats.isDirectory()) for (const name of await entries(at)) await walk(join(at, name));
+ };
+ await walk(path);
+ return { bytes, newest, whole };
+}
+
+/**
+ * Session ids the conversations' events logs say MausBot started, read on from where the last pass stopped. A log
+ * rewritten (a new inode, or shorter) is read again from its start.
+ */
+export function createLoggedSessions(eventsDir: string) {
+ const read = new Map<string, { ino: number; size: number; ids: Set<string> }>();
+ /** Reads [from, size) and returns where the last whole line ended: a line still being written is read whole next time. */
+ async function scan(file: string, from: number, size: number, ids: Set<string>): Promise<number> {
+ let handle: FileHandle;
+ try {
+ handle = await open(file, "r");
+ } catch {
+ return from;
+ }
+ let consumed = from;
+ try {
+ let carry = Buffer.alloc(0);
+ const take = (line: Buffer) => {
+ if (!line.includes(SESSION_MARK)) return;
+ try {
+ const event = JSON.parse(line.toString("utf8")) as { type?: unknown; sessionId?: unknown };
+ if (event.type === "session.started" && typeof event.sessionId === "string" && WHOLE_SESSION_ID.test(event.sessionId)) ids.add(event.sessionId.toLowerCase());
+ } catch {}
+ };
+ for (let position = from; position < size; position += CHUNK) {
+ const buffer = Buffer.allocUnsafe(Math.min(CHUNK, size - position));
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
+ if (bytesRead === 0) break;
+ const chunk = buffer.subarray(0, bytesRead);
+ let start = 0;
+ for (let at = chunk.indexOf(0x0a); at !== -1; at = chunk.indexOf(0x0a, start)) {
+ take(carry.length ? Buffer.concat([carry, chunk.subarray(start, at)]) : chunk.subarray(start, at));
+ carry = Buffer.alloc(0);
+ start = at + 1;
+ consumed = position + start;
+ }
+ carry = Buffer.concat([carry, chunk.subarray(start)]);
+ // One line this long is no session line; skip past it.
+ if (carry.length > MAX_LINE) {
+ carry = Buffer.alloc(0);
+ consumed = position + chunk.length;
+ }
+ }
+ } finally {
+ await handle.close().catch(() => {});
+ }
+ return consumed;
+ }
+ return async function logged(): Promise<Set<string>> {
+ const all = new Set<string>();
+ if (!(await realFolder(eventsDir))) return all;
+ const names = (await entries(eventsDir)).filter((name) => LOG_NAME.test(name));
+ for (const name of read.keys()) if (!names.includes(name)) read.delete(name);
+ for (const name of names) {
+ const file = join(eventsDir, name);
+ const stats = await stat(file);
+ if (!stats?.isFile()) continue;
+ let known = read.get(name);
+ if (!known || known.ino !== stats.ino || stats.size < known.size) known = { ino: stats.ino, size: 0, ids: new Set() };
+ if (stats.size > known.size) known.size = await scan(file, known.size, stats.size, known.ids);
+ read.set(name, known);
+ for (const id of known.ids) all.add(id);
+ await yieldNow();
+ }
+ return all;
+ };
+}
+
+interface Found { path: string; mtimeMs: number; dev: number; ino: number }
+
+export interface EngineSessionSweepDeps {
+ dataDir: string;
+ mode: Exclude<EngineSessionSweepMode, "off">;
+ folders: EngineSessionFolders;
+ cacheRoots: readonly string[];
+ /** Read at the start and again just before anything is removed. */
+ live(): ReadonlySet<string>;
+ logged: ReadonlySet<string>;
+ paused?(): boolean;
+ /** Any turn running anywhere on this server. */
+ turnsRunning?(): boolean;
+ turnWaitMs?: number;
+ now?(): number;
+}
+
+/** True once nothing is paused and no turn runs; false when paused, or still busy after `waitMs`. */
+async function quietMoment(deps: { paused?(): boolean; turnsRunning?(): boolean }, waitMs: number): Promise<boolean> {
+ for (let waited = 0; ; waited += TURN_POLL_MS) {
+ if (deps.paused?.()) return false;
+ if (!deps.turnsRunning?.()) return true;
+ if (waited >= waitMs) return false;
+ await sleep(Math.min(TURN_POLL_MS, waitMs - waited), undefined, { ref: false });
+ }
+}
+
+/** Empties the trash a pass (or an interrupted one) left; the folder itself must be a real one under the data folder. */
+export async function emptyTrash(dataDir: string): Promise<void> {
+ const trash = join(resolve(dataDir), TRASH_DIR);
+ if (!(await realFolder(trash)) || !plainlyUnder(resolve(dataDir), trash)) return;
+ for (const name of await entries(trash)) await rm(join(trash, name), { recursive: true, force: true }).catch(() => {});
+}
+
+/**
+ * Claude Code's cleanupPeriodDays in a Claude folder's existing settings.json: added as CLAUDE_TRANSCRIPT_DAYS where the
+ * file does not set it, keeping the file's mode, indentation and line endings. A folder without the file is left
+ * without one ("absent"): Claude Code's default there is the same 30 days, so creating it would change nothing.
+ */
+export async function pinClaudeRetention(root: string, write: boolean, mayWrite: () => boolean = () => true): Promise<"set" | "kept" | "skipped" | "absent"> {
+ const file = join(root, "settings.json");
+ const stats = await stat(file);
+ if (!stats) return "absent";
+ if (!stats.isFile() || stats.size > 1024 * 1024) return "skipped";
+ let text: string;
+ let settings: Record<string, unknown>;
+ try {
+ text = await readFile(file, "utf8");
+ const parsed: unknown = JSON.parse(text);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "skipped";
+ settings = parsed as Record<string, unknown>;
+ } catch {
+ return "skipped";
+ }
+ if (Object.hasOwn(settings, "cleanupPeriodDays")) return "kept";
+ if (!write) return "set";
+ // The file's own layout: the indent of its first key (none when it is one line), its line ending, its last newline.
+ const multiline = /\n\s*\S/.test(text.trim());
+ const indent = multiline ? (/^\{\r?\n([ \t]+)"/.exec(text)?.[1] ?? 2) : undefined;
+ let next = JSON.stringify({ ...settings, cleanupPeriodDays: CLAUDE_TRANSCRIPT_DAYS }, null, indent);
+ if (text.includes("\r\n")) next = next.replace(/\n/g, "\r\n");
+ if (/\r?\n$/.test(text)) next += text.endsWith("\r\n") ? "\r\n" : "\n";
+ if (!mayWrite()) return "skipped";
+ writeFileAtomic(file, next, { mode: stats.mode & 0o777 });
+ return "set";
+}
+
+export interface EngineSessionSweepResult {
+ mode: Exclude<EngineSessionSweepMode, "off">;
+ /** Claude folders whose settings.json got cleanupPeriodDays, and those where the person's own value stays. */
+ retentionSet: number;
+ retentionKept: number;
+ sessions: number;
+ sessionBytes: number;
+ cacheFiles: number;
+ cacheBytes: number;
+ kept: number;
+ refused?: string;
+ stopped: boolean;
+}
+
+/** A root an engine of this server uses: a real folder, and inside the data folder only by real folders. */
+async function reachable(dataDir: string, root: string): Promise<boolean> {
+ const inData = !relative(dataDir, resolve(root)).startsWith("..") && !isAbsolute(relative(dataDir, resolve(root)));
+ return (await realFolder(root)) && (!inData || plainlyUnder(dataDir, root));
+}
+
+export async function sweepEngineSessions(deps: EngineSessionSweepDeps): Promise<EngineSessionSweepResult> {
+ const now = deps.now?.() ?? Date.now();
+ const write = deps.mode === "on";
+ const dataDir = resolve(deps.dataDir);
+ const result: EngineSessionSweepResult = { mode: deps.mode, retentionSet: 0, retentionKept: 0, sessions: 0, sessionBytes: 0, cacheFiles: 0, cacheBytes: 0, kept: 0, stopped: false };
+ const live = deps.live();
+ if (live.size === 0) return { ...result, refused: "no conversation has an engine session, so the records may not have loaded" };
+ const dead = new Set([...deps.logged].filter((id) => !live.has(id)));
+ for (const root of deps.folders.claude) {
+ if (!(await reachable(dataDir, root))) continue;
+ if (write && !(await quietMoment(deps, deps.turnWaitMs ?? TURN_WAIT_MS))) return { ...result, stopped: true };
+ // The write itself only in a quiet moment, checked with no await before it.
+ const pinned = await pinClaudeRetention(root, write, () => !deps.paused?.() && !deps.turnsRunning?.()).catch(() => "skipped" as const);
+ if (pinned === "set") result.retentionSet++;
+ else if (pinned === "kept") result.retentionKept++;
+ }
+
+ // Every entry named by a session id, under each root, with the session's newest change.
+ const bySession = new Map<string, { entries: Array<{ root: string; path: string; dev: number; ino: number }>; newest: number }>();
+ let liveFound = 0;
+ const note = (root: string, found: Found, id: string) => {
+ const session = bySession.get(id) ?? { entries: [], newest: 0 };
+ session.entries.push({ root, path: found.path, dev: found.dev, ino: found.ino });
+ session.newest = Math.max(session.newest, found.mtimeMs);
+ bySession.set(id, session);
+ };
+ const idOf = (name: string) => SESSION_ID.exec(name)?.[0]?.toLowerCase();
+ for (const root of deps.folders.claude) {
+ if (!(await reachable(dataDir, root))) continue;
+ const projects = join(root, "projects");
+ const folders = (await realFolder(projects)) ? (await entries(projects)).map((folder) => join(projects, folder)) : [];
+ for (const dir of [...folders, ...CLAUDE_SESSION_FOLDERS.map((folder) => join(root, folder))]) {
+ if (!(await realFolder(dir))) continue;
+ for (const name of await entries(dir)) {
+ const id = idOf(name);
+ if (!id) continue;
+ if (live.has(id)) liveFound++;
+ if (!dead.has(id)) continue;
+ const stats = await stat(join(dir, name));
+ if (stats) note(root, { path: join(dir, name), mtimeMs: stats.mtimeMs, dev: stats.dev, ino: stats.ino }, id);
+ }
+ await yieldNow();
+ }
+ }
+ for (const root of deps.folders.codex) {
+ if (!(await reachable(dataDir, root))) continue;
+ const walk = async (dir: string, depth: number): Promise<void> => {
+ if (depth > CODEX_DEPTH) return;
+ for (const name of await entries(dir)) {
+ const path = join(dir, name);
+ const stats = await stat(path);
+ if (!stats) continue;
+ if (stats.isDirectory()) {
+ await walk(path, depth + 1);
+ continue;
+ }
+ const id = idOf(name);
+ if (!id) continue;
+ if (live.has(id)) liveFound++;
+ if (dead.has(id)) note(root, { path, mtimeMs: stats.mtimeMs, dev: stats.dev, ino: stats.ino }, id);
+ }
+ await yieldNow();
+ };
+ for (const folder of CODEX_SESSION_FOLDERS) if (await realFolder(join(root, folder))) await walk(join(root, folder), 0);
+ }
+ if (bySession.size > 0 && liveFound === 0) {
+ return { ...result, refused: "none of the conversations' own sessions were found where this looks, so it removed nothing" };
+ }
+
+ const trash = join(dataDir, TRASH_DIR, String(now));
+ let trashReady = false;
+ let moved = 0;
+ /** Renames an entry into the trash: only the one listed, only on the trash's volume. */
+ const discard = async (root: string, path: string, listed: { dev: number; ino: number }): Promise<boolean> => {
+ if (!trashReady) {
+ await mkdir(trash, { recursive: true, mode: 0o700 });
+ if (!(await realFolder(trash)) || !plainlyUnder(dataDir, trash)) return false;
+ trashReady = true;
+ }
+ const current = await stat(path);
+ const trashStats = await stat(trash);
+ if (!current || current.dev !== listed.dev || current.ino !== listed.ino || !trashStats || trashStats.dev !== current.dev || !plainlyUnder(root, path)) return false;
+ // A turn, a move or a backup that began during the checks above: nothing more goes in this pass.
+ if (deps.paused?.() || deps.turnsRunning?.()) {
+ result.stopped = true;
+ return false;
+ }
+ return rename(path, join(trash, `${moved++}`)).then(() => true, () => false);
+ };
+ for (const [id, session] of bySession) {
+ if (now - session.newest < IDLE_MS || deps.live().has(id)) {
+ result.kept++;
+ continue;
+ }
+ if (!(await quietMoment(deps, deps.turnWaitMs ?? TURN_WAIT_MS))) {
+ result.stopped = true;
+ break;
+ }
+ // Every entry, all the way down, a week idle and readable, or the whole session stays.
+ const sizes: number[] = [];
+ let fresh = false;
+ for (const entry of session.entries) {
+ const measured = await measure(entry.path);
+ if (!measured.whole || now - measured.newest < IDLE_MS) fresh = true;
+ sizes.push(measured.bytes);
+ }
+ if (fresh) {
+ result.kept++;
+ continue;
+ }
+ let bytes = 0;
+ let gone = 0;
+ for (const [index, entry] of session.entries.entries()) {
+ if (!plainlyUnder(entry.root, entry.path)) continue;
+ if (write && !(await discard(entry.root, entry.path, entry))) {
+ if (result.stopped) break;
+ continue;
+ }
+ bytes += sizes[index]!;
+ gone++;
+ }
+ if (gone) {
+ result.sessions++;
+ result.sessionBytes += bytes;
+ }
+ if (result.stopped) break;
+ }
+ if (trashReady) await rm(trash, { recursive: true, force: true }).catch(() => {});
+ if (result.stopped) return result;
+
+ for (const root of deps.cacheRoots) {
+ if (!(await reachable(dataDir, root))) continue;
+ const walk = async (dir: string, depth: number): Promise<boolean> => {
+ let empty = true;
+ for (const name of await entries(dir)) {
+ if (deps.paused?.()) {
+ result.stopped = true;
+ return false;
+ }
+ const path = join(dir, name);
+ const stats = await stat(path);
+ if (!stats) continue;
+ if (stats.isDirectory() && depth < CACHE_DEPTH) {
+ const cleared = await walk(path, depth + 1);
+ // An empty folder only, by rmdir: one that got a file meanwhile stays.
+ if (!(cleared && now - stats.mtimeMs >= IDLE_MS && plainlyUnder(root, path) && (!write || (await rmdir(path).then(() => true, () => false))))) empty = false;
+ continue;
+ }
+ if (stats.isFile() && now - stats.mtimeMs >= IDLE_MS && plainlyUnder(root, path)) {
+ if (!(await quietMoment(deps, deps.turnWaitMs ?? TURN_WAIT_MS))) {
+ result.stopped = true;
+ return false;
+ }
+ // A log file in the CLI's own log folder: removed in place, the one listed only.
+ const current = await stat(path);
+ if (write && !(current?.isFile() && current.ino === stats.ino && (await rm(path, { force: true }).then(() => true, () => false)))) {
+ empty = false;
+ continue;
+ }
+ result.cacheFiles++;
+ result.cacheBytes += stats.size;
+ continue;
+ }
+ empty = false;
+ }
+ await yieldNow();
+ return empty;
+ };
+ await walk(root, 0);
+ if (result.stopped) return result;
+ }
+ return result;
+}
+
+const mb = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+
+export function sweepLine(result: EngineSessionSweepResult): string {
+ if (result.refused) return `[engine-sessions] ${result.mode}: ${result.refused}`;
+ const verb = result.mode === "report" ? "would free" : "freed";
+ return `[engine-sessions] ${result.mode}: Claude transcript age ${CLAUDE_TRANSCRIPT_DAYS} days ${result.mode === "report" ? "would be " : ""}set in ${result.retentionSet} folders (already set in ${result.retentionKept}); ${result.sessions} ended sessions (${mb(result.sessionBytes)}) and ${result.cacheFiles} CLI log files `
+ + `(${mb(result.cacheBytes)}); ${verb} ${mb(result.sessionBytes + result.cacheBytes)}; ${result.kept} ended sessions kept until a week idle`
+ + (result.stopped ? " (stopped for a move, a backup or a running turn; the next pass carries on)" : "");
+}
+
+export interface StartEngineSessionSweepDeps {
+ cloudHome: boolean;
+ env: NodeJS.ProcessEnv;
+ dataDir: string;
+ bots(): ReadonlyArray<SessionHolder>;
+ folders(): EngineSessionFolders;
+ environments(): Iterable<Record<string, string | undefined>>;
+ paused?(): boolean;
+ turnsRunning?(): boolean;
+ log?(line: string): void;
+}
+
+export interface EngineSessionPassDeps {
+ dataDir: string;
+ mode: Exclude<EngineSessionSweepMode, "off">;
+ folders(): EngineSessionFolders;
+ cacheRoots(): readonly string[];
+ live(): ReadonlySet<string>;
+ logged(): Promise<Set<string>>;
+ paused?(): boolean;
+ turnsRunning?(): boolean;
+ turnWaitMs?: number;
+ now?(): number;
+}
+
+/**
+ * One pass, or null when it did nothing: during a move freeze or a backup, or while turns kept running. Nothing is
+ * read or written before that check; then, in `on` mode only, an interrupted pass's trash is emptied (it is already
+ * out of every engine's reach) and the sweep runs.
+ */
+export async function engineSessionPass(deps: EngineSessionPassDeps): Promise<EngineSessionSweepResult | null> {
+ if (deps.paused?.()) return null;
+ if (!(await quietMoment(deps, deps.turnWaitMs ?? TURN_WAIT_MS))) return null;
+ if (deps.mode === "on") await emptyTrash(deps.dataDir);
+ return sweepEngineSessions({
+ dataDir: deps.dataDir, mode: deps.mode, folders: deps.folders(), cacheRoots: deps.cacheRoots(), live: deps.live,
+ logged: await deps.logged(), paused: deps.paused, turnsRunning: deps.turnsRunning, turnWaitMs: deps.turnWaitMs, now: deps.now,
+ });
+}
+
+/** Cloud homes only, and only with OMB_ENGINE_SESSION_SWEEP set: a pass when due, at the earliest FIRST_PASS_MS after start. */
+export function startEngineSessionSweep(deps: StartEngineSessionSweepDeps): boolean {
+ const mode = engineSessionSweepMode(deps.env);
+ if (!deps.cloudHome || mode === "off") return false;
+ const log = deps.log ?? ((line: string) => console.log(line));
+ const logged = createLoggedSessions(join(resolve(deps.dataDir), "events"));
+ const pass = async (): Promise<boolean> => {
+ try {
+ const result = await engineSessionPass({
+ dataDir: deps.dataDir, mode, folders: deps.folders, cacheRoots: () => claudeCliCacheRoots(deps.environments()),
+ live: () => liveSessions(deps.bots()), logged, paused: deps.paused, turnsRunning: deps.turnsRunning,
+ });
+ if (!result) return false;
+ if (result.refused || result.sessions || result.cacheFiles || result.retentionSet || result.stopped) log(sweepLine(result));
+ return !result.stopped;
+ } catch (error) {
+ log(`[engine-sessions] pass failed: ${error instanceof Error ? error.message : String(error)}`);
+ return false;
+ }
+ };
+ schedulePasses(join(deps.dataDir, STAMP_FILE), PASS_EVERY_MS, pass);
+ return true;
+}
+
+/**
+ * Runs `pass` FIRST_PASS_MS after start, or later when the last whole pass (saved in `stamp`) is not yet `every` old,
+ * then every `every`; a pass that stopped early is tried again after RETRY_MS. A stamp from the future (a clock set
+ * back) counts as none, and a home that slept past its time runs one pass on waking, never one per missed interval.
+ */
+export function schedulePasses(stamp: string, every: number, pass: () => Promise<boolean>, now: () => number = Date.now): void {
+ const run = async () => {
+ const whole = await pass();
+ if (whole) {
+ try {
+ mkdirSync(dirname(stamp), { recursive: true, mode: 0o700 });
+ writeFileSync(stamp, JSON.stringify({ at: now() }), { mode: 0o600 });
+ } catch {}
+ }
+ setTimeout(() => void run(), whole ? every : RETRY_MS).unref();
+ };
+ // The stamp is read in the first timer, never while the server is still starting.
+ const first = () => {
+ let last: number | null = null;
+ try {
+ const at = (JSON.parse(readFileSync(stamp, "utf8")) as { at?: unknown }).at;
+ if (typeof at === "number" && Number.isFinite(at) && at <= now()) last = at;
+ } catch {}
+ const wait = last === null ? 0 : last + every - now();
+ if (wait > 0) setTimeout(() => void run(), wait).unref();
+ else void run();
+ };
+ setTimeout(first, FIRST_PASS_MS).unref();
+}
diff --git a/server/host/thread-log-sweep.e2e.test.ts b/server/host/thread-log-sweep.e2e.test.ts
new file mode 100644
index 0000000000..ace5acec43
--- /dev/null
+++ b/server/host/thread-log-sweep.e2e.test.ts
@@ -0,0 +1,58 @@
+import { appendFileSync, existsSync, readFileSync, statSync, utimesSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { launchVerificationServer, runControlOmb } from "../../scripts/control-omb.ts";
+import { AGE_MS, sweepThreadLogs } from "./thread-log-sweep.ts";
+
+// Cloud homes, where this runs, are Linux; Windows refuses a rename over a log the server may hold open.
+it.skipIf(process.platform === "win32")("a conversation whose logs were trimmed and cut still resumes its engine session and keeps its transcript", async () => {
+ // Each turn's engine exits once it answers, so the next turn relaunches it with --resume.
+ const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_EXIT_AFTER_TURN: "1" });
+ try {
+ const control = (args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, { method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ expect(response.ok).toBe(true);
+ return response.json() as Promise<any>;
+ };
+ const argv = () => JSON.parse(readFileSync(fixture.fixtureDumpPath, "utf8")).argv as string[];
+ const { bot } = await api("POST", "/api/bots", { name: "Log keeper" });
+ const turn = async (text: string) => {
+ await control(["send", "--bot", bot.id, "--task", bot.threadId, "--text", text]);
+ expect((await control(["wait", "--bot", bot.id, "--task", bot.threadId, "--timeout", "30"])).status).toBe("settled");
+ };
+ await turn("First: remember the word HERON.");
+ const saved = (JSON.parse(readFileSync(join(fixture.info.dataDir, "bots.json"), "utf8")) as any[]).find((b) => b.id === bot.id);
+ const cursor = Object.values(saved?.resumeCursors ?? {})[0] as string;
+ expect(typeof cursor).toBe("string");
+
+ // A month of other activity after the session started, then a month of quiet.
+ const events = join(fixture.info.dataDir, "events", `${bot.threadId}.ndjson`);
+ const native = join(fixture.info.dataDir, "native", `${bot.threadId}.ndjson`);
+ const filler = `${JSON.stringify({ eventId: "f", provider: "claudeAgent", threadId: bot.threadId, createdAt: new Date().toISOString(), type: "turn.started", pad: "z".repeat(600) })}\n`;
+ appendFileSync(events, filler.repeat(6_000));
+ appendFileSync(native, `${JSON.stringify({ at: new Date().toISOString(), dir: "in", source: "claude", msg: { pad: "z".repeat(600) } })}\n`.repeat(6_000));
+ const then = new Date(Date.now() - AGE_MS - 24 * 60 * 60_000);
+ for (const file of [events, native]) utimesSync(file, then, then);
+ const before = statSync(events).size + statSync(native).size;
+
+ const result = await sweepThreadLogs({ dataDir: fixture.info.dataDir, mode: "on", cap: 1, cut: true, threads: () => new Map([[bot.threadId, { busy: false }]]) });
+ expect(result.trimmed).toBe(2);
+ expect(result.cut).toBe(2);
+ expect(existsSync(native)).toBe(false);
+ expect(statSync(events).size).toBeLessThan(before / 100);
+ expect(readFileSync(events, "utf8")).toContain(cursor);
+
+ await turn("Second: what was the word?");
+ const launched = argv();
+ expect(launched.indexOf("--resume")).toBeGreaterThan(-1);
+ expect(launched[launched.indexOf("--resume") + 1]).toBe(cursor);
+ const messages = (await api("GET", "/api/bots")).bots.find((b: any) => b.id === bot.id).messages;
+ const said = JSON.stringify(messages);
+ expect(said).toContain("remember the word HERON");
+ expect(said).toContain("what was the word?");
+ } finally {
+ await fixture.close();
+ }
+}, 120_000);
diff --git a/server/host/thread-log-sweep.test.ts b/server/host/thread-log-sweep.test.ts
new file mode 100644
index 0000000000..459c718500
--- /dev/null
+++ b/server/host/thread-log-sweep.test.ts
@@ -0,0 +1,312 @@
+import { appendFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { readBotActivity } from "../activity.ts";
+import { readThreadEvents } from "../thread-events.ts";
+import {
+ AGE_MS, CUT_AFTER_MS, FIRST_PASS_MS, QUIET_MS, READ_FLOOR, STAMP_FILE, knownThreads, listLogs, parseBytes, schedulePasses, startThreadLogSweep, sweepLine,
+ sweepThreadLogs, threadLogCap, threadLogCutEnabled, threadLogSweepMode, trimLog, type ThreadState,
+} from "./thread-log-sweep.ts";
+
+const NOW = Date.parse("2026-11-23T12:00:00Z");
+const DAY = 24 * 60 * 60_000;
+const PAD = "x".repeat(400);
+
+let dataDir: string;
+beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), "thread-log-sweep-"));
+ mkdirSync(join(dataDir, "events"));
+ mkdirSync(join(dataDir, "native"));
+});
+afterEach(() => rmSync(dataDir, { recursive: true, force: true }));
+
+const at = (i: number) => new Date(NOW - 60 * DAY + i * 1_000).toISOString();
+
+/** A conversation's events log: tool runs, with session.started lines at `sessionsAt`. */
+function writeEvents(threadId: string, count: number, sessionsAt: readonly number[] = []): string {
+ const lines: string[] = [];
+ for (let i = 0; i < count; i++) {
+ const base = { eventId: `e${i}`, provider: "claudeAgent", providerInstanceId: "claude", threadId, createdAt: at(i), turnId: `turn${Math.floor(i / 10)}` };
+ if (sessionsAt.includes(i)) lines.push(JSON.stringify({ ...base, type: "session.started", sessionId: `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`, model: "m" }));
+ else if (i % 2 === 0) lines.push(JSON.stringify({ ...base, type: "item.started", itemType: "tool", itemId: `i${i}`, title: "Bash", input: { command: `echo ${i} ${PAD}` } }));
+ else lines.push(JSON.stringify({ ...base, type: "item.completed", itemType: "tool", itemId: `i${i - 1}`, ok: true }));
+ }
+ const file = join(dataDir, "events", `${threadId}.ndjson`);
+ writeFileSync(file, lines.join("\n") + "\n");
+ return file;
+}
+
+function writeNative(threadId: string, count: number): string {
+ const lines = Array.from({ length: count }, (_, i) => JSON.stringify({ at: at(i), dir: i % 2 ? "in" : "out", source: "claude", msg: { n: i, pad: PAD } }));
+ const file = join(dataDir, "native", `${threadId}.ndjson`);
+ writeFileSync(file, lines.join("\n") + "\n");
+ return file;
+}
+
+const age = (file: string, ms: number) => utimesSync(file, new Date(NOW - ms), new Date(NOW - ms));
+const threads = (entries: Record<string, boolean>) => () => new Map<string, ThreadState>(Object.entries(entries).map(([id, busy]) => [id, { busy }]));
+const sessionIds = (file: string) => readFileSync(file, "utf8").split("\n").filter((line) => line.includes('"session.started"')).map((line) => JSON.parse(line).sessionId);
+const BIG_CAP = 1024 ** 4;
+
+describe("the conversation logs' switch and cap", () => {
+ it("never cuts unless OMB_THREAD_LOG_CUT is set", async () => {
+ expect(threadLogCutEnabled({})).toBe(false);
+ expect(threadLogCutEnabled({ OMB_THREAD_LOG_CUT: "1" })).toBe(true);
+ const small = writeEvents("small", 100);
+ age(small, AGE_MS + DAY);
+ const result = await sweepThreadLogs({ dataDir, mode: "on", cap: 1, threads: threads({ small: false }), now: () => NOW });
+ expect(result.cut).toBe(0);
+ expect(existsSync(small)).toBe(true);
+ });
+
+ it("schedules a pass soon after start, or when due by the last whole pass, and saves each whole one", async () => {
+ vi.useFakeTimers();
+ try {
+ const stamp = join(dataDir, "cache", "stamp.json");
+ let clock = NOW;
+ const passes: number[] = [];
+ schedulePasses(stamp, 6 * 60 * 60_000, async () => (passes.push(clock), true), () => clock);
+ clock += FIRST_PASS_MS;
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS);
+ expect(passes).toEqual([NOW + FIRST_PASS_MS]);
+ expect(JSON.parse(readFileSync(stamp, "utf8")).at).toBe(NOW + FIRST_PASS_MS);
+ vi.clearAllTimers();
+ // A restart an hour later reads the stamp at its first timer and waits for the rest of the six hours.
+ clock = NOW + FIRST_PASS_MS + 60 * 60_000;
+ schedulePasses(stamp, 6 * 60 * 60_000, async () => (passes.push(clock), true), () => clock);
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS + 4 * 60 * 60_000);
+ expect(passes).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ expect(passes).toHaveLength(2);
+ vi.clearAllTimers();
+ // A stamp from the future counts as none.
+ writeFileSync(stamp, JSON.stringify({ at: clock + 10 * DAY }));
+ schedulePasses(stamp, 6 * 60 * 60_000, async () => (passes.push(clock), true), () => clock);
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS);
+ expect(passes).toHaveLength(3);
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
+ it("a frozen home's pass reads nothing and writes no stamp", async () => {
+ vi.useFakeTimers();
+ try {
+ const events = writeEvents("t1", 6_000);
+ age(events, AGE_MS + DAY);
+ let asked = 0;
+ expect(startThreadLogSweep({ cloudHome: true, env: { OMB_THREAD_LOG_SWEEP: "on" }, dataDir, threads: () => (asked++, new Map()), paused: () => true, log: () => {} })).toBe(true);
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS);
+ expect(asked).toBe(0);
+ expect(existsSync(join(dataDir, STAMP_FILE))).toBe(false);
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
+ it("is off unless set, and counts only in report", () => {
+ expect(threadLogSweepMode({})).toBe("off");
+ expect(threadLogSweepMode({ OMB_THREAD_LOG_SWEEP: "maybe" })).toBe("off");
+ expect(threadLogSweepMode({ OMB_THREAD_LOG_SWEEP: "dry-run" })).toBe("report");
+ expect(threadLogSweepMode({ OMB_THREAD_LOG_SWEEP: " ON " })).toBe("on");
+ });
+
+ it("caps at the larger of 2 GiB and 3% of the volume, or what the Admin set", () => {
+ expect(threadLogCap({}, 10 * 1024 ** 3)).toBe(2 * 1024 ** 3);
+ expect(threadLogCap({}, 200 * 1024 ** 3)).toBe(Math.floor(0.03 * 200 * 1024 ** 3));
+ expect(threadLogCap({}, null)).toBe(2 * 1024 ** 3);
+ expect(threadLogCap({ OMB_THREAD_LOG_CAP: "512M" }, 200 * 1024 ** 3)).toBe(512 * 1024 ** 2);
+ expect(parseBytes("1.5G")).toBe(1.5 * 1024 ** 3);
+ expect(parseBytes("12345")).toBe(12345);
+ expect(parseBytes("-1")).toBeNull();
+ expect(parseBytes("lots")).toBeNull();
+ });
+
+ it("knows every bot's and room's conversation, and which have a turn running", () => {
+ const known = knownThreads(
+ [{ id: "b1", threadId: "main", tasks: [{ threadId: "main" }, { threadId: "side" }] }],
+ [{ threadId: "room", tasks: [{ threadId: "room-task" }] }],
+ (_bot, threadId) => threadId === "side",
+ );
+ expect(Object.fromEntries([...known].map(([id, state]) => [id, state.busy]))).toEqual({ main: false, side: true, room: false, "room-task": false });
+ });
+});
+
+describe("sweepThreadLogs", () => {
+ it("trims an idle month-old log to what the Inspector and Activity read, and keeps every session line", async () => {
+ const events = writeEvents("t1", 6_000, [3, 2_500, 5_990]);
+ const native = writeNative("t1", 6_000);
+ age(events, AGE_MS + DAY);
+ age(native, AGE_MS + DAY);
+ const inspector = () => readThreadEvents({ eventsDir: join(dataDir, "events"), nativeDir: join(dataDir, "native"), threadId: "t1", limit: READ_FLOOR.lines });
+ const activity = () => readBotActivity({ dataDir, eventsDir: join(dataDir, "events"), botId: "b1", threadIds: ["t1"], limit: 300 });
+ const seen = { inspector: inspector().entries, activity: activity() };
+ expect(seen.activity.length).toBeGreaterThan(0);
+ const sizes = { events: statSync(events).size, native: statSync(native).size };
+
+ const result = await sweepThreadLogs({ dataDir, mode: "on", cap: BIG_CAP, threads: threads({ t1: false }), now: () => NOW });
+
+ expect(result.trimmed).toBe(2);
+ expect(result.after).toBeLessThan(result.before);
+ expect(statSync(events).size).toBeLessThan(sizes.events);
+ expect(statSync(native).size).toBeLessThan(sizes.native);
+ expect(inspector().entries).toEqual(seen.inspector);
+ expect(activity()).toEqual(seen.activity);
+ expect(sessionIds(events)).toEqual(["00000000-0000-4000-8000-000000000003", "00000000-0000-4000-8000-000000002500", "00000000-0000-4000-8000-000000005990"]);
+ expect(statSync(events).mtimeMs).toBe(NOW - AGE_MS - DAY);
+ if (process.platform !== "win32") expect(statSync(events).mode & 0o777).toBe(0o600);
+ expect(existsSync(`${events}.sweep`)).toBe(false);
+ expect(sweepLine(result)).toContain("2 trimmed");
+ });
+
+ it("leaves a busy, a recently written, an unknown and a small log alone", async () => {
+ const busy = writeEvents("busy", 6_000);
+ const recent = writeEvents("recent", 6_000);
+ const unknown = writeEvents("orphan", 6_000);
+ const small = writeEvents("small", 100);
+ for (const file of [busy, unknown, small]) age(file, AGE_MS + DAY);
+ age(recent, QUIET_MS - 60_000);
+ const before = [busy, recent, unknown, small].map((file) => readFileSync(file, "utf8"));
+ const result = await sweepThreadLogs({ dataDir, mode: "on", cap: 1, cut: true, threads: threads({ busy: true, recent: false, small: false }), now: () => NOW });
+ expect([busy, recent, unknown].map((file) => readFileSync(file, "utf8"))).toEqual(before.slice(0, 3));
+ // Over the cap, the small idle log is cut to its session lines (it has none) only once idle a week; it is.
+ expect(existsSync(small)).toBe(false);
+ expect(result.cut).toBe(1);
+ });
+
+ it("over the cap trims least recently written first, then cuts week-idle logs to their session lines", async () => {
+ const old = writeEvents("old", 6_000, [10]);
+ const older = writeNative("older", 6_000);
+ const weekOld = writeEvents("week", 6_000, [20]);
+ const fresh = writeEvents("fresh", 6_000, [30]);
+ age(older, 20 * DAY);
+ age(old, 10 * DAY);
+ age(weekOld, CUT_AFTER_MS - DAY);
+ age(fresh, QUIET_MS + 60_000);
+ const listed = await listLogs(dataDir);
+ const total = listed.reduce((sum, file) => sum + file.size, 0);
+ const deps = { dataDir, cap: Math.floor(total * 0.1), cut: true, threads: threads({ old: false, older: false, week: false, fresh: false }), now: () => NOW };
+
+ const report = await sweepThreadLogs({ ...deps, mode: "report" });
+ expect(statSync(old).size).toBe(listed.find((file) => file.path === old)!.size);
+ const result = await sweepThreadLogs({ ...deps, mode: "on" });
+ expect(result.after).toBe(report.after);
+ expect([result.trimmed, result.cut]).toEqual([4, 2]);
+ expect(result.after).toBe((await listLogs(dataDir)).reduce((sum, file) => sum + file.size, 0));
+ // A week idle: the 20-day native log is gone (it has no session lines), the 10-day events log keeps its session.
+ expect(existsSync(older)).toBe(false);
+ expect(sessionIds(old)).toEqual(["00000000-0000-4000-8000-000000000010"]);
+ expect(readFileSync(old, "utf8").split("\n").filter(Boolean)).toHaveLength(1);
+ // Under a week idle: trimmed to the panels' lines plus its session line, never cut.
+ for (const [file, id] of [[weekOld, "20"], [fresh, "30"]] as const) {
+ expect(readFileSync(file, "utf8").split("\n").filter(Boolean)).toHaveLength(READ_FLOOR.lines + 1);
+ expect(sessionIds(file)).toEqual([`00000000-0000-4000-8000-0000000000${id}`]);
+ }
+ });
+
+ it("a report counts and changes nothing", async () => {
+ const events = writeEvents("t1", 6_000, [1]);
+ const native = writeNative("t1", 6_000);
+ age(events, AGE_MS + DAY);
+ age(native, AGE_MS + DAY);
+ const before = [events, native].map((file) => ({ text: readFileSync(file, "utf8"), mtime: statSync(file).mtimeMs, ino: statSync(file).ino }));
+ const sessionLine = readFileSync(events, "utf8").split("\n").find((line) => line.includes('"session.started"'))!;
+ const result = await sweepThreadLogs({ dataDir, mode: "report", cap: 1, cut: true, threads: threads({ t1: false }), now: () => NOW });
+ expect([result.trimmed, result.cut]).toEqual([2, 2]);
+ expect(result.after).toBe(sessionLine.length + 1);
+ expect([events, native].map((file) => ({ text: readFileSync(file, "utf8"), mtime: statSync(file).mtimeMs, ino: statSync(file).ino }))).toEqual(before);
+ expect(sweepLine(result)).toContain("would free");
+ });
+
+ it("changes nothing while a turn runs, and goes on once none does", async () => {
+ const events = writeEvents("t1", 6_000);
+ age(events, AGE_MS + DAY);
+ const text = readFileSync(events, "utf8");
+ const busy = await sweepThreadLogs({ dataDir, mode: "on", cap: BIG_CAP, threads: threads({ t1: false }), turnsRunning: () => true, turnWaitMs: 0, now: () => NOW });
+ expect(busy.stopped).toBe(true);
+ expect(readFileSync(events, "utf8")).toBe(text);
+ let checks = 0;
+ const later = await sweepThreadLogs({ dataDir, mode: "on", cap: BIG_CAP, threads: threads({ t1: false }), turnsRunning: () => checks++ < 1, turnWaitMs: 60_000, now: () => NOW });
+ expect(later.trimmed).toBe(1);
+ }, 30_000);
+
+ it("stops before its next file when a move or backup starts", async () => {
+ const events = writeEvents("t1", 6_000);
+ age(events, AGE_MS + DAY);
+ const text = readFileSync(events, "utf8");
+ const result = await sweepThreadLogs({ dataDir, mode: "on", cap: 1, threads: threads({ t1: false }), paused: () => true, now: () => NOW });
+ expect(result.stopped).toBe(true);
+ expect(readFileSync(events, "utf8")).toBe(text);
+ });
+});
+
+describe("what a sweep never reaches", () => {
+ // Windows makes a link only with a privilege CI's runners lack; Cloud homes, where this runs, are Linux.
+ it.skipIf(process.platform === "win32")("follows no link: a linked log, a linked folder, or a name that is not a conversation's", async () => {
+ const outside = mkdtempSync(join(tmpdir(), "thread-log-outside-"));
+ try {
+ const target = join(outside, "victim.ndjson");
+ writeFileSync(target, `${"y".repeat(2_000)}\n`.repeat(3_000));
+ age(target, AGE_MS + DAY);
+ symlinkSync(target, join(dataDir, "events", "linked.ndjson"));
+ rmSync(join(dataDir, "native"), { recursive: true });
+ symlinkSync(outside, join(dataDir, "native"));
+ writeFileSync(join(dataDir, "events", "..%2Fescape.ndjson"), "x\n");
+ expect((await listLogs(dataDir)).map((file) => file.path)).toEqual([]);
+ await sweepThreadLogs({ dataDir, mode: "on", cap: 1, threads: threads({ linked: false, victim: false }), now: () => NOW });
+ expect(statSync(target).size).toBe(2_001 * 3_000);
+ expect(lstatSync(join(dataDir, "events", "linked.ndjson")).isSymbolicLink()).toBe(true);
+ } finally {
+ rmSync(outside, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps a log that was written to while its trim was copied", async () => {
+ const events = writeEvents("t1", 6_000, [1]);
+ age(events, AGE_MS + DAY);
+ const [listed] = await listLogs(dataDir);
+ appendFileSync(events, `${JSON.stringify({ late: true })}\n`);
+ expect(await trimLog(listed!, READ_FLOOR, true)).toBe(0);
+ expect(readFileSync(events, "utf8")).toContain('"late":true');
+ expect(readFileSync(events, "utf8").split("\n").filter(Boolean)).toHaveLength(6_001);
+ });
+
+ it("keeps every session line from the part it cuts away", async () => {
+ const sessions = Array.from({ length: 1_500 }, (_, i) => i * 2 + 1);
+ const events = writeEvents("t1", 6_000, sessions);
+ age(events, AGE_MS + DAY);
+ await sweepThreadLogs({ dataDir, mode: "on", cap: BIG_CAP, threads: threads({ t1: false }), now: () => NOW });
+ expect(sessionIds(events)).toHaveLength(1_500);
+ });
+
+ it("keeps a log while the bus has its lines queued or an append under way", async () => {
+ const events = writeEvents("t1", 6_000);
+ age(events, AGE_MS + DAY);
+ const text = readFileSync(events, "utf8");
+ const result = await sweepThreadLogs({ dataDir, mode: "on", cap: BIG_CAP, threads: threads({ t1: false }), logQuiet: () => false, now: () => NOW });
+ expect(result.trimmed).toBe(0);
+ expect(readFileSync(events, "utf8")).toBe(text);
+ });
+
+ it("keeps a log when a turn starts while its trim was copied", async () => {
+ const events = writeEvents("t1", 6_000, [1]);
+ age(events, AGE_MS + DAY);
+ const text = readFileSync(events, "utf8");
+ const [listed] = await listLogs(dataDir);
+ expect(await trimLog(listed!, READ_FLOOR, true, () => false)).toBe(0);
+ expect(readFileSync(events, "utf8")).toBe(text);
+ expect(existsSync(`${events}.sweep`)).toBe(false);
+ });
+
+ it("never trims a log whose newest line alone is past the floor's bytes", async () => {
+ const file = join(dataDir, "events", "huge.ndjson");
+ writeFileSync(file, `${"a".repeat(100)}\n${"b".repeat(READ_FLOOR.bytes + 10)}\n`);
+ const [listed] = await listLogs(dataDir);
+ expect(await trimLog(listed!, READ_FLOOR, true)).toBe(0);
+ expect(statSync(file).size).toBe(101 + READ_FLOOR.bytes + 11);
+ });
+});
diff --git a/server/host/thread-log-sweep.ts b/server/host/thread-log-sweep.ts
new file mode 100644
index 0000000000..e42208f788
--- /dev/null
+++ b/server/host/thread-log-sweep.ts
@@ -0,0 +1,457 @@
+// A Cloud home's conversation logs (events/ and native/, one file per conversation) get a total cap and an age limit.
+//
+// What reads them: the Inspector (thread-events.ts readThreadEvents, the newest lines within MAX_TAIL_BYTES), a bot's
+// Activity panel (activity.ts, the newest EVENTS_PER_THREAD events of each conversation), the sentinel's turn records
+// (sentinel/sources.ts, read on from an offset and safe across a rename), and delete leftovers (delete-leftovers.ts
+// loggedSessions, every session.started line, to find a deleted conversation's engine sessions). What the person reads
+// as the conversation is messages.db, and a conversation resumes from its engine cursor in bots.json: neither is here.
+//
+// So a log is cut, never a conversation: an idle log keeps the newest lines those panels read (READ_FLOOR) and, for
+// events, every session.started line from the part cut away. Only when the folders are still over the cap after
+// that are the logs of conversations idle for a week cut to those session lines (events) or removed (native).
+// Never a log written to in the last day, a conversation with a turn running or handed off, or one this server does
+// not know (a deleted conversation's log is its delete's to remove). Nothing changes while any turn runs. Only plain
+// files inside events/ and native/ are rewritten or removed; nothing follows a link; every swap re-checks the file
+// just before the rename.
+import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, statfsSync, writeFileSync } from "node:fs";
+import { open, lstat, readdir, type FileHandle } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { setImmediate as yieldNow, setTimeout as sleep } from "node:timers/promises";
+
+import { EVENTS_PER_THREAD } from "../activity.ts";
+import { MAX_TAIL_BYTES } from "../thread-events.ts";
+
+export type ThreadLogSweepMode = "off" | "report" | "on";
+
+const GIB = 1024 ** 3;
+const DAY_MS = 24 * 60 * 60_000;
+/** The newest lines the Inspector and the Activity panel read; kept in every trimmed log. */
+export const READ_FLOOR = { lines: EVENTS_PER_THREAD, bytes: MAX_TAIL_BYTES } as const;
+/** A log written to within this long is left alone: its conversation may be mid-turn or about to be. */
+export const QUIET_MS = DAY_MS;
+/** An idle log older than this is trimmed to READ_FLOOR whether or not the folders are over the cap. */
+export const AGE_MS = 30 * DAY_MS;
+/** Over the cap after trimming, logs idle this long are cut to their session lines, least recently written first. */
+export const CUT_AFTER_MS = 7 * DAY_MS;
+/** A log smaller than this is never worth a trim. */
+export const MIN_TRIM_BYTES = 1024 * 1024;
+export const MIN_CAP_BYTES = 2 * GIB;
+export const CAP_SHARE = 0.03;
+const CHUNK = 1024 * 1024;
+const MAX_CARRY = 16 * 1024 * 1024;
+const SESSION_MARK = Buffer.from('"session.started"');
+const LOG_NAME = /^([\w-]{1,128})\.ndjson$/;
+/** Soon after a start (a home that sleeps by stopping may be up only minutes); the tool results' and the engine
+ * sessions' sweeps start at 5 and 7 minutes, so the three do not start at once. */
+export const FIRST_PASS_MS = 3 * 60_000;
+/** A pass that stopped for a turn, a move or a backup is tried again this soon. */
+export const RETRY_MS = 30 * 60_000;
+/** When the last whole pass ended, under cache/ (left out of backups): a restart does not reset the schedule. */
+export const STAMP_FILE = join("cache", "thread-log-sweep.json");
+/** While a turn runs nothing is changed: the pass waits this long for a quiet moment, then stops until the next. */
+export const TURN_WAIT_MS = 10 * 60_000;
+const TURN_POLL_MS = 15_000;
+export const PASS_EVERY_MS = 6 * 60 * 60_000;
+
+/** OMB_THREAD_LOG_SWEEP: `report` (or `dry-run`) counts and changes nothing; `on` trims; anything else is off. */
+export function threadLogSweepMode(env: NodeJS.ProcessEnv): ThreadLogSweepMode {
+ const raw = env.OMB_THREAD_LOG_SWEEP?.trim().toLowerCase();
+ if (raw === "report" || raw === "dry-run") return "report";
+ return raw === "on" ? "on" : "off";
+}
+
+/** OMB_THREAD_LOG_CUT: over the cap, also cut week-idle logs to their session lines (events) or remove them (native).
+ * Off by default: it is the one step that empties the Inspector and Activity rows of those conversations. */
+export function threadLogCutEnabled(env: NodeJS.ProcessEnv): boolean {
+ const raw = env.OMB_THREAD_LOG_CUT?.trim().toLowerCase();
+ return raw === "1" || raw === "on";
+}
+
+/** Bytes, or a number with K, M or G (powers of 1024); null for anything else. */
+export function parseBytes(raw: string | undefined): number | null {
+ const match = /^(\d+(?:\.\d+)?)\s*([KMG]?)i?B?$/i.exec(raw?.trim() ?? "");
+ if (!match) return null;
+ const bytes = Math.floor(Number(match[1]) * 1024 ** "_KMG".indexOf(match[2]!.toUpperCase() || "_"));
+ return Number.isSafeInteger(bytes) && bytes > 0 ? bytes : null;
+}
+
+/** OMB_THREAD_LOG_CAP when set, else the larger of 2 GiB and 3% of the volume. */
+export function threadLogCap(env: NodeJS.ProcessEnv, volumeBytes: number | null): number {
+ return parseBytes(env.OMB_THREAD_LOG_CAP) ?? Math.max(MIN_CAP_BYTES, Math.floor(CAP_SHARE * (volumeBytes ?? 0)));
+}
+
+function volumeBytes(path: string): number | null {
+ try {
+ const stats = statfsSync(path);
+ return stats.blocks * stats.bsize;
+ } catch {
+ return null;
+ }
+}
+
+export interface ThreadState { busy: boolean }
+
+/** Every conversation this server keeps, by thread id: each bot's and each room's. A room's busy is not tracked here;
+ * QUIET_MS keeps a room mid-turn out of reach. */
+export function knownThreads(
+ bots: ReadonlyArray<{ id: string; threadId?: string; tasks?: ReadonlyArray<{ threadId: string }> }>,
+ groups: ReadonlyArray<{ threadId?: string; tasks?: ReadonlyArray<{ threadId: string }> }>,
+ busy: (botId: string, threadId: string) => boolean,
+): Map<string, ThreadState> {
+ const threads = new Map<string, ThreadState>();
+ const add = (threadId: string | undefined, isBusy: boolean) => {
+ if (!threadId) return;
+ threads.set(threadId, { busy: isBusy || threads.get(threadId)?.busy === true });
+ };
+ for (const bot of bots) for (const threadId of [bot.threadId, ...(bot.tasks ?? []).map((task) => task.threadId)]) add(threadId, Boolean(threadId) && busy(bot.id, threadId!));
+ for (const group of groups) for (const threadId of [group.threadId, ...(group.tasks ?? []).map((task) => task.threadId)]) add(threadId, false);
+ return threads;
+}
+
+export interface LogFile {
+ kind: "events" | "native";
+ path: string;
+ threadId: string;
+ size: number;
+ mtimeMs: number;
+ ino: number;
+}
+
+export async function listLogs(dataDir: string): Promise<LogFile[]> {
+ const files: LogFile[] = [];
+ for (const kind of ["events", "native"] as const) {
+ const dir = join(dataDir, kind);
+ try {
+ if (!(await lstat(dir)).isDirectory()) continue;
+ } catch {
+ continue;
+ }
+ let names: string[];
+ try {
+ names = await readdir(dir);
+ } catch {
+ continue;
+ }
+ let seen = 0;
+ for (const name of names) {
+ const threadId = LOG_NAME.exec(name)?.[1];
+ if (!threadId) continue;
+ const path = join(dir, name);
+ try {
+ const stats = await lstat(path);
+ if (stats.isFile()) files.push({ kind, path, threadId, size: stats.size, mtimeMs: stats.mtimeMs, ino: stats.ino });
+ } catch {}
+ if (++seen % 200 === 0) await yieldNow();
+ }
+ }
+ return files;
+}
+
+async function readAt(handle: FileHandle, position: number, length: number): Promise<Buffer> {
+ const buffer = Buffer.allocUnsafe(length);
+ let filled = 0;
+ while (filled < length) {
+ const { bytesRead } = await handle.read(buffer, filled, length - filled, position + filled);
+ if (bytesRead === 0) break;
+ filled += bytesRead;
+ }
+ return buffer.subarray(0, filled);
+}
+
+/** Where the newest `floor` begins: 0 when the whole file fits, else just after a newline. */
+async function tailStart(handle: FileHandle, size: number, floor: { lines: number; bytes: number }): Promise<number> {
+ let best = size;
+ let lines = 0;
+ let end = size - 1;
+ while (end > 0) {
+ const start = Math.max(0, end - CHUNK);
+ const chunk = await readAt(handle, start, end - start);
+ for (let i = chunk.length - 1; i >= 0; i--) {
+ if (chunk[i] !== 0x0a) continue;
+ const candidate = start + i + 1;
+ if (size - candidate > floor.bytes) return best;
+ best = candidate;
+ if (++lines >= floor.lines) return best;
+ }
+ end = start;
+ }
+ return size <= floor.bytes ? 0 : best;
+}
+
+/** Every session.started line of [0, end): delete leftovers needs each one to find a deleted conversation's sessions. */
+async function sessionLines(handle: FileHandle, end: number): Promise<Buffer[]> {
+ const kept: Buffer[] = [];
+ let carry = Buffer.alloc(0);
+ const take = (line: Buffer) => {
+ if (!line.includes(SESSION_MARK)) return;
+ try {
+ const event = JSON.parse(line.toString("utf8")) as { type?: unknown; sessionId?: unknown };
+ if (event.type !== "session.started" || typeof event.sessionId !== "string") return;
+ } catch {
+ return;
+ }
+ kept.push(Buffer.concat([line, Buffer.from("\n")]));
+ };
+ for (let position = 0; position < end; position += CHUNK) {
+ const chunk = await readAt(handle, position, Math.min(CHUNK, end - position));
+ if (chunk.length === 0) break;
+ let from = 0;
+ for (let at = chunk.indexOf(0x0a); at !== -1; at = chunk.indexOf(0x0a, from)) {
+ take(carry.length ? Buffer.concat([carry, chunk.subarray(from, at)]) : chunk.subarray(from, at));
+ carry = Buffer.alloc(0);
+ from = at + 1;
+ }
+ carry = Buffer.concat([carry, chunk.subarray(from)]);
+ if (carry.length > MAX_CARRY) carry = Buffer.alloc(0);
+ }
+ if (carry.length) take(carry);
+ return kept;
+}
+
+const unchanged = (file: LogFile): boolean => {
+ try {
+ const now = lstatSync(file.path);
+ return now.isFile() && now.ino === file.ino && now.size === file.size && now.mtimeMs === file.mtimeMs;
+ } catch {
+ return false;
+ }
+};
+
+/**
+ * Keeps `floor` of the log's newest lines (none when null) and, for events, its session.started lines from the part
+ * cut away. Returns the bytes freed, or would free when `write` is false. A file that changed since it was listed, or
+ * whose kept part is empty and `floor` is not null, is left as it is, and so is one when `mayChange` says no at the swap.
+ */
+export async function trimLog(file: LogFile, floor: { lines: number; bytes: number } | null, write: boolean, mayChange: () => boolean = () => true): Promise<number> {
+ let handle: FileHandle;
+ try {
+ handle = await open(file.path, "r");
+ } catch {
+ return 0;
+ }
+ const staging = `${file.path}.sweep`;
+ let swapped = false;
+ let closed = false;
+ // Closed before the swap: Windows refuses to rename over, or remove, a file still open.
+ const closeSource = async () => {
+ if (closed) return;
+ closed = true;
+ await handle.close().catch(() => {});
+ };
+ try {
+ const stats = await handle.stat();
+ if (!stats.isFile() || stats.ino !== file.ino || stats.size !== file.size) return 0;
+ const start = floor ? await tailStart(handle, file.size, floor) : file.size;
+ // Nothing to cut, or a newest line past the floor's bytes: a trim would keep none of what the panels read.
+ if (start === 0 || (floor && start === file.size)) return 0;
+ const sessions = file.kind === "events" ? await sessionLines(handle, start) : [];
+ const keptBytes = sessions.reduce((sum, line) => sum + line.length, 0) + (file.size - start);
+ const freed = file.size - keptBytes;
+ if (freed <= 0) return 0;
+ if (!write) return freed;
+ if (keptBytes === 0) {
+ await closeSource();
+ if (!mayChange() || !unchanged(file)) return 0;
+ rmSync(file.path, { force: true });
+ return freed;
+ }
+ rmSync(staging, { force: true });
+ const target = await open(staging, "wx", 0o600);
+ try {
+ for (const line of sessions) await target.write(line);
+ for (let position = start; position < file.size; position += CHUNK) {
+ const chunk = await readAt(handle, position, Math.min(CHUNK, file.size - position));
+ if (chunk.length === 0) throw new Error("the log shrank while it was copied");
+ await target.write(chunk);
+ }
+ // The log keeps its last write time: it is how old the conversation's activity is, for this sweep's next pass too.
+ await target.utimes(stats.atime, stats.mtime);
+ } finally {
+ await target.close();
+ }
+ await closeSource();
+ // No await from here to the rename: an append, a turn or a pause that came while the copy ran keeps the log.
+ if (!mayChange() || !unchanged(file)) return 0;
+ renameSync(staging, file.path);
+ swapped = true;
+ return freed;
+ } catch {
+ return 0;
+ } finally {
+ await closeSource();
+ if (!swapped) rmSync(staging, { force: true });
+ }
+}
+
+export interface ThreadLogSweepDeps {
+ dataDir: string;
+ mode: Exclude<ThreadLogSweepMode, "off">;
+ cap: number;
+ /** Over the cap after trimming, cut week-idle logs too (OMB_THREAD_LOG_CUT). */
+ cut?: boolean;
+ threads(): ReadonlyMap<string, ThreadState>;
+ /** A move freeze or a backup under way: the pass stops before its next file. */
+ paused?(): boolean;
+ /** Any turn running anywhere on this server: the pass waits up to `turnWaitMs` before each change, then stops. */
+ turnsRunning?(): boolean;
+ turnWaitMs?: number;
+ /** The event bus has nothing queued or being written for this conversation's log (bus.ts logQuiet). */
+ logQuiet?(threadId: string): boolean;
+ now?(): number;
+}
+
+/** True once nothing is paused and no turn runs; false when paused, or still busy after `waitMs`. */
+export async function quietMoment(deps: { paused?(): boolean; turnsRunning?(): boolean }, waitMs: number): Promise<boolean> {
+ for (let waited = 0; ; waited += TURN_POLL_MS) {
+ if (deps.paused?.()) return false;
+ if (!deps.turnsRunning?.()) return true;
+ if (waited >= waitMs) return false;
+ await sleep(Math.min(TURN_POLL_MS, waitMs - waited), undefined, { ref: false });
+ }
+}
+
+export interface ThreadLogSweepResult {
+ mode: Exclude<ThreadLogSweepMode, "off">;
+ cap: number;
+ before: number;
+ after: number;
+ files: number;
+ trimmed: number;
+ cut: number;
+ stopped: boolean;
+}
+
+export async function sweepThreadLogs(deps: ThreadLogSweepDeps): Promise<ThreadLogSweepResult> {
+ const now = deps.now?.() ?? Date.now();
+ const write = deps.mode === "on";
+ const files = await listLogs(deps.dataDir);
+ const threads = deps.threads();
+ const before = files.reduce((sum, file) => sum + file.size, 0);
+ const result: ThreadLogSweepResult = { mode: deps.mode, cap: deps.cap, before, after: before, files: files.length, trimmed: 0, cut: 0, stopped: false };
+ const idle = (file: LogFile) => {
+ const thread = threads.get(file.threadId);
+ return thread !== undefined && !thread.busy && now - file.mtimeMs >= QUIET_MS;
+ };
+ /** What each trim freed (or would): a report counts a later cut of the same log net of it. */
+ const freedBy = new Map<LogFile, number>();
+ const apply = async (file: LogFile, floor: typeof READ_FLOOR | null): Promise<boolean> => {
+ if (!(await quietMoment(deps, deps.turnWaitMs ?? TURN_WAIT_MS))) {
+ result.stopped = true;
+ return false;
+ }
+ // A busy flag read now, not at the start of the pass.
+ if (deps.threads().get(file.threadId)?.busy) return true;
+ const earlier = freedBy.get(file) ?? 0;
+ // A log trimmed in this pass is listed again, so its cut sees what the trim left.
+ const target = earlier && write ? await relisted(file) : file;
+ if (!target) return true;
+ const freed = (await trimLog(target, floor, write, () => !deps.paused?.() && !deps.turnsRunning?.() && deps.logQuiet?.(file.threadId) !== false)) - (write ? 0 : earlier);
+ if (freed > 0) {
+ result.after -= freed;
+ freedBy.set(file, earlier + freed);
+ if (floor) result.trimmed++;
+ else result.cut++;
+ }
+ return true;
+ };
+ const oldestFirst = (a: LogFile, b: LogFile) => a.mtimeMs - b.mtimeMs;
+ const candidates = files.filter(idle).sort(oldestFirst);
+ for (const file of candidates) {
+ if (now - file.mtimeMs < AGE_MS || file.size < MIN_TRIM_BYTES) continue;
+ if (!(await apply(file, READ_FLOOR))) return result;
+ }
+ for (const file of candidates) {
+ if (result.after <= deps.cap) return result;
+ if (freedBy.has(file) || file.size < MIN_TRIM_BYTES) continue;
+ if (!(await apply(file, READ_FLOOR))) return result;
+ }
+ if (!deps.cut) return result;
+ for (const file of candidates) {
+ if (result.after <= deps.cap) return result;
+ if (now - file.mtimeMs < CUT_AFTER_MS) continue;
+ if (!(await apply(file, null))) return result;
+ }
+ return result;
+}
+
+async function relisted(file: LogFile): Promise<LogFile | null> {
+ try {
+ const stats = await lstat(file.path);
+ return stats.isFile() ? { ...file, size: stats.size, mtimeMs: stats.mtimeMs, ino: stats.ino } : null;
+ } catch {
+ return null;
+ }
+}
+
+const mb = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+
+export function sweepLine(result: ThreadLogSweepResult): string {
+ const freed = result.before - result.after;
+ const verb = result.mode === "report" ? "would free" : "freed";
+ return `[thread-logs] ${result.mode}: ${result.files} logs, ${mb(result.before)} against a cap of ${mb(result.cap)}; `
+ + `${result.trimmed} trimmed to their newest lines, ${result.cut} cut to their session lines; ${verb} ${mb(freed)}`
+ + (result.stopped ? " (stopped for a move, a backup or a running turn; the next pass carries on)" : "");
+}
+
+export interface StartThreadLogSweepDeps {
+ cloudHome: boolean;
+ env: NodeJS.ProcessEnv;
+ dataDir: string;
+ threads(): ReadonlyMap<string, ThreadState>;
+ paused?(): boolean;
+ turnsRunning?(): boolean;
+ logQuiet?(threadId: string): boolean;
+ log?(line: string): void;
+}
+
+/** Cloud homes only, and only with OMB_THREAD_LOG_SWEEP set: a pass when due, at the earliest FIRST_PASS_MS after start. */
+export function startThreadLogSweep(deps: StartThreadLogSweepDeps): boolean {
+ const mode = threadLogSweepMode(deps.env);
+ if (!deps.cloudHome || mode === "off") return false;
+ const log = deps.log ?? ((line: string) => console.log(line));
+ const pass = async (): Promise<boolean> => {
+ // A frozen or backing-up home: no read, no change, and no stamp, so the pass is tried again soon.
+ if (deps.paused?.()) return false;
+ try {
+ const cap = threadLogCap(deps.env, volumeBytes(deps.dataDir));
+ const result = await sweepThreadLogs({ dataDir: deps.dataDir, mode, cap, cut: threadLogCutEnabled(deps.env), threads: deps.threads, paused: deps.paused, turnsRunning: deps.turnsRunning, logQuiet: deps.logQuiet });
+ if (result.before !== result.after || result.before > cap || result.stopped) log(sweepLine(result));
+ return !result.stopped;
+ } catch (error) {
+ log(`[thread-logs] pass failed: ${error instanceof Error ? error.message : String(error)}`);
+ return false;
+ }
+ };
+ schedulePasses(join(deps.dataDir, STAMP_FILE), PASS_EVERY_MS, pass);
+ return true;
+}
+
+/**
+ * Runs `pass` FIRST_PASS_MS after start, or later when the last whole pass (saved in `stamp`) is not yet `every` old,
+ * then every `every`; a pass that stopped early is tried again after RETRY_MS. A stamp from the future (a clock set
+ * back) counts as none, and a home that slept past its time runs one pass on waking, never one per missed interval.
+ */
+export function schedulePasses(stamp: string, every: number, pass: () => Promise<boolean>, now: () => number = Date.now): void {
+ const run = async () => {
+ const whole = await pass();
+ if (whole) {
+ try {
+ mkdirSync(dirname(stamp), { recursive: true, mode: 0o700 });
+ writeFileSync(stamp, JSON.stringify({ at: now() }), { mode: 0o600 });
+ } catch {}
+ }
+ setTimeout(() => void run(), whole ? every : RETRY_MS).unref();
+ };
+ // The stamp is read in the first timer, never while the server is still starting.
+ const first = () => {
+ let last: number | null = null;
+ try {
+ const at = (JSON.parse(readFileSync(stamp, "utf8")) as { at?: unknown }).at;
+ if (typeof at === "number" && Number.isFinite(at) && at <= now()) last = at;
+ } catch {}
+ const wait = last === null ? 0 : last + every - now();
+ if (wait > 0) setTimeout(() => void run(), wait).unref();
+ else void run();
+ };
+ setTimeout(first, FIRST_PASS_MS).unref();
+}
diff --git a/server/host/tool-results-sweep.test.ts b/server/host/tool-results-sweep.test.ts
new file mode 100644
index 0000000000..cc2e406b8d
--- /dev/null
+++ b/server/host/tool-results-sweep.test.ts
@@ -0,0 +1,167 @@
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { spillToolResult } from "../tool-result-spill.ts";
+import { FIRST_PASS_MS, MAX_AGE_MS, STAMP_FILE, schedulePasses, startToolResultsSweep, sweepLine, sweepToolResults, toolResultsSweepMode } from "./tool-results-sweep.ts";
+
+const NOW = Date.parse("2026-11-23T12:00:00Z");
+let base: string, root: string;
+beforeEach(() => {
+ base = mkdtempSync(join(tmpdir(), "tool-results-sweep-"));
+ root = join(base, "tool-results");
+ mkdirSync(root);
+});
+afterEach(() => rmSync(base, { recursive: true, force: true }));
+
+function put(path: string, ageMs: number, bytes = 1_000): string {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "x".repeat(bytes));
+ utimesSync(path, new Date(NOW - ageMs), new Date(NOW - ageMs));
+ return path;
+}
+
+function seed() {
+ return {
+ oldHook: put(join(root, "thread-a", `${"a".repeat(64)}.txt`), MAX_AGE_MS + 60_000, 4_000),
+ oldGate: put(join(root, "thread-b", "1700000000000-42-0-search.json"), 3 * MAX_AGE_MS, 6_000),
+ newHook: put(join(root, "thread-a", `${"b".repeat(64)}.txt`), MAX_AGE_MS - 60_000),
+ newGate: put(join(root, "thread-b", "1700000000001-42-1-search.json"), 60_000),
+ topLevel: put(join(root, "stray.txt"), 10 * MAX_AGE_MS),
+ nested: put(join(root, "thread-a", "deeper", "old.txt"), 10 * MAX_AGE_MS),
+ };
+}
+
+describe("the tool results' sweep", () => {
+ it("is off unless set", () => {
+ expect(toolResultsSweepMode({})).toBe("off");
+ expect(toolResultsSweepMode({ OMB_TOOL_RESULTS_SWEEP: "please" })).toBe("off");
+ expect(toolResultsSweepMode({ OMB_TOOL_RESULTS_SWEEP: "dry-run" })).toBe("report");
+ expect(toolResultsSweepMode({ OMB_TOOL_RESULTS_SWEEP: "on" })).toBe("on");
+ });
+
+ it("removes every conversation's results older than a day, keeps newer ones and every folder", async () => {
+ const files = seed();
+ const result = await sweepToolResults({ root, mode: "on", now: () => NOW });
+ expect(result).toMatchObject({ folders: 2, files: 2, bytes: 10_000, stopped: false });
+ expect(existsSync(files.oldHook)).toBe(false);
+ expect(existsSync(files.oldGate)).toBe(false);
+ for (const file of [files.newHook, files.newGate, files.topLevel, files.nested]) expect(existsSync(file), file).toBe(true);
+ expect(readdirSync(root).sort()).toEqual(["stray.txt", "thread-a", "thread-b"]);
+ expect(sweepLine(result)).toContain("freed 0.0 MB");
+ });
+
+ it("leaves a folder the hook writes into again right after", async () => {
+ const files = seed();
+ rmSync(files.newHook);
+ await sweepToolResults({ root, mode: "on", now: () => NOW });
+ expect(readdirSync(join(root, "thread-a"))).toEqual(["deeper"]);
+ expect(spillToolResult(join(root, "thread-a"), "thread-a:turn:tool", "output", 100)).toBe(true);
+ expect(readdirSync(join(root, "thread-a"))).toHaveLength(2);
+ });
+
+ it("a report counts the same and changes nothing", async () => {
+ const files = seed();
+ const report = await sweepToolResults({ root, mode: "report", now: () => NOW });
+ for (const file of Object.values(files)) expect(existsSync(file)).toBe(true);
+ const result = await sweepToolResults({ root, mode: "on", now: () => NOW });
+ expect([report.files, report.bytes]).toEqual([result.files, result.bytes]);
+ expect(sweepLine(report)).toContain("would free");
+ });
+
+ // Windows makes a link only with a privilege CI's runners lack; Cloud homes, where this runs, are Linux.
+ it.skipIf(process.platform === "win32")("follows no link: a linked folder or a linked file stays, and so does what it points at", async () => {
+ seed();
+ const outside = join(base, "outside");
+ const target = put(join(outside, "precious.txt"), 10 * MAX_AGE_MS);
+ symlinkSync(outside, join(root, "thread-link"));
+ symlinkSync(target, join(root, "thread-a", "link.txt"));
+ await sweepToolResults({ root, mode: "on", now: () => NOW });
+ expect(existsSync(target)).toBe(true);
+ expect(lstatSync(join(root, "thread-a", "link.txt")).isSymbolicLink()).toBe(true);
+ expect(lstatSync(join(root, "thread-link")).isSymbolicLink()).toBe(true);
+ });
+
+ it.skipIf(process.platform === "win32")("a root that is a link, or missing, is left alone", async () => {
+ const outside = join(base, "outside");
+ const target = put(join(outside, "thread-x", "old.txt"), 10 * MAX_AGE_MS);
+ const linked = join(base, "linked-root");
+ symlinkSync(outside, linked);
+ expect((await sweepToolResults({ root: linked, mode: "on", now: () => NOW })).files).toBe(0);
+ expect(existsSync(target)).toBe(true);
+ expect((await sweepToolResults({ root: join(base, "missing"), mode: "on", now: () => NOW })).files).toBe(0);
+ });
+
+ it("over the cap removes the hook's outputs under a day old too, oldest first, never one under an hour, never a gate's result", async () => {
+ const files = seed();
+ const hook = (h: string) => join(root, "thread-c", `${h.repeat(64)}.txt`);
+ const hours = ([["c", 20], ["d", 10], ["e", 2]] as const).map(([name, h]) => put(hook(name), h * 60 * 60_000, 3_000));
+ const minutes = put(hook("f"), 30 * 60_000, 3_000);
+ const gate = put(join(root, "thread-c", "1700000000002-42-2-search.json"), 20 * 60 * 60_000, 3_000);
+ // Under a day: newHook and newGate 1 KB each, four hook outputs and one gate result at 3 KB, 17 KB against 8 KB.
+ const result = await sweepToolResults({ root, mode: "on", cap: 8_000, now: () => NOW });
+ expect(result.overCap).toBe(4);
+ for (const file of [files.newHook, ...hours]) expect(existsSync(file), file).toBe(false);
+ for (const file of [minutes, gate, files.newGate]) expect(existsSync(file), file).toBe(true);
+ const tight = await sweepToolResults({ root, mode: "on", cap: 0, now: () => NOW });
+ expect(tight.overCap).toBe(0);
+ for (const file of [minutes, gate, files.newGate]) expect(existsSync(file), file).toBe(true);
+ });
+
+ it("removes nothing while a turn runs, and goes on once none does", async () => {
+ const files = seed();
+ const busy = await sweepToolResults({ root, mode: "on", turnsRunning: () => true, turnWaitMs: 0, now: () => NOW });
+ expect(busy.stopped).toBe(true);
+ expect(existsSync(files.oldHook)).toBe(true);
+ let checks = 0;
+ const later = await sweepToolResults({ root, mode: "on", turnsRunning: () => checks++ < 1, turnWaitMs: 60_000, now: () => NOW });
+ expect(later.files).toBe(2);
+ }, 30_000);
+
+ it("schedules a pass soon after start, or when due by the last whole pass", async () => {
+ vi.useFakeTimers();
+ try {
+ const stamp = join(base, "cache", "stamp.json");
+ let clock = NOW;
+ const passes: number[] = [];
+ schedulePasses(stamp, 6 * 60 * 60_000, async () => (passes.push(clock), true), () => clock);
+ clock += FIRST_PASS_MS;
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS);
+ expect(passes).toHaveLength(1);
+ vi.clearAllTimers();
+ clock += 60 * 60_000;
+ // Read at the first timer, the stamp says five hours are left.
+ schedulePasses(stamp, 6 * 60 * 60_000, async () => (passes.push(clock), true), () => clock);
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS + 4 * 60 * 60_000);
+ expect(passes).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(60 * 60_000);
+ expect(passes).toHaveLength(2);
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
+ it("a frozen home's pass removes nothing and writes no stamp", async () => {
+ vi.useFakeTimers();
+ try {
+ const files = seed();
+ const dataDir = join(base, "data");
+ expect(startToolResultsSweep({ cloudHome: true, env: { OMB_TOOL_RESULTS_SWEEP: "on" }, dataDir, root, paused: () => true, log: () => {} })).toBe(true);
+ await vi.advanceTimersByTimeAsync(FIRST_PASS_MS);
+ expect(existsSync(files.oldHook)).toBe(true);
+ expect(existsSync(join(dataDir, STAMP_FILE))).toBe(false);
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
+ it("stops for a move or backup", async () => {
+ const files = seed();
+ const result = await sweepToolResults({ root, mode: "on", paused: () => true, now: () => NOW });
+ expect(result.stopped).toBe(true);
+ expect(existsSync(files.oldHook)).toBe(true);
+ });
+});
diff --git a/server/host/tool-results-sweep.ts b/server/host/tool-results-sweep.ts
new file mode 100644
index 0000000000..3909943af9
--- /dev/null
+++ b/server/host/tool-results-sweep.ts
@@ -0,0 +1,218 @@
+// A Cloud home's full tool results (tool-results/<thread>/) are swept on a timer: every file older than a day goes.
+//
+// Two writers share each conversation's folder. The MCP gate (mcp-gate.ts) saves a large result there and hands the
+// model the path; it already removes its folder's files older than SPILL_MAX_AGE_MS (a day), but only when a gate
+// starts in that conversation. The engine hook (index.ts, tool-result-spill.ts) saves each tool's full output as
+// <hash>.txt; nothing reads those back (a row keeps only `fullResult: true`). So the same one-day rule, run for every
+// conversation, removes nothing a turn or the person still reads.
+//
+// Size first, age as the tie-breaker: past CAP_BYTES the hook's outputs (nothing reads them back) go oldest first, down
+// to an hour old. The gate's saved results keep the day: a model may be told to read one later the same day.
+// Nothing is removed while any turn runs.
+//
+// Files only: both writers make their folder and then write into it, so a folder removed between the two would fail
+// the write. Folders of deleted conversations go with the conversation. A link is never followed or removed.
+import { lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
+import { lstat, opendir } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { setImmediate as yieldNow, setTimeout as sleep } from "node:timers/promises";
+
+export type ToolResultsSweepMode = "off" | "report" | "on";
+
+/** The MCP gate's own age for its saved results (mcp-gate.ts SPILL_MAX_AGE_MS). */
+export const MAX_AGE_MS = 24 * 60 * 60_000;
+/** Past this, the hook's outputs younger than a day go too, oldest first. */
+export const CAP_BYTES = 1024 ** 3;
+/** Never under the cap: a result this new may belong to a turn that has just paused. */
+export const MIN_AGE_MS = 60 * 60_000;
+/** The engine hook's full tool output (tool-result-spill.ts): a sha256 of its key, then .txt. */
+const HOOK_OUTPUT = /^[0-9a-f]{64}\.txt$/;
+/** Soon after a start (a home that sleeps by stopping may be up only minutes), after the logs' sweep (3 minutes) and
+ * before the engine sessions' (7), so the three do not start at once. */
+export const FIRST_PASS_MS = 5 * 60_000;
+/** A pass that stopped for a turn, a move or a backup is tried again this soon. */
+export const RETRY_MS = 30 * 60_000;
+/** When the last whole pass ended, under the data folder's cache/ (left out of backups). */
+export const STAMP_FILE = join("cache", "tool-results-sweep.json");
+/** While a turn runs nothing is removed: the pass waits this long for a quiet moment, then stops until the next. */
+export const TURN_WAIT_MS = 10 * 60_000;
+const TURN_POLL_MS = 15_000;
+export const PASS_EVERY_MS = 6 * 60 * 60_000;
+const YIELD_EVERY = 500;
+
+/** OMB_TOOL_RESULTS_SWEEP: `report` (or `dry-run`) counts and changes nothing; `on` removes; anything else is off. */
+export function toolResultsSweepMode(env: NodeJS.ProcessEnv): ToolResultsSweepMode {
+ const raw = env.OMB_TOOL_RESULTS_SWEEP?.trim().toLowerCase();
+ if (raw === "report" || raw === "dry-run") return "report";
+ return raw === "on" ? "on" : "off";
+}
+
+export interface ToolResultsSweepResult {
+ mode: Exclude<ToolResultsSweepMode, "off">;
+ folders: number;
+ files: number;
+ bytes: number;
+ /** Of `files`, those removed younger than a day because the folder was over CAP_BYTES. */
+ overCap: number;
+ stopped: boolean;
+}
+
+/** True once nothing is paused and no turn runs; false when paused, or still busy after `waitMs`. */
+async function quietMoment(deps: { paused?(): boolean; turnsRunning?(): boolean }, waitMs: number): Promise<boolean> {
+ for (let waited = 0; ; waited += TURN_POLL_MS) {
+ if (deps.paused?.()) return false;
+ if (!deps.turnsRunning?.()) return true;
+ if (waited >= waitMs) return false;
+ await sleep(Math.min(TURN_POLL_MS, waitMs - waited), undefined, { ref: false });
+ }
+}
+
+async function stat(path: string) {
+ try {
+ return await lstat(path);
+ } catch {
+ return null;
+ }
+}
+
+export async function sweepToolResults(deps: {
+ root: string;
+ mode: Exclude<ToolResultsSweepMode, "off">;
+ paused?(): boolean;
+ /** Any turn running anywhere on this server. */
+ turnsRunning?(): boolean;
+ turnWaitMs?: number;
+ cap?: number;
+ now?(): number;
+}): Promise<ToolResultsSweepResult> {
+ const now = deps.now?.() ?? Date.now();
+ const cap = deps.cap ?? CAP_BYTES;
+ const result: ToolResultsSweepResult = { mode: deps.mode, folders: 0, files: 0, bytes: 0, overCap: 0, stopped: false };
+ if (!(await stat(deps.root))?.isDirectory()) return result;
+ let seen = 0;
+ const pace = async (): Promise<boolean> => {
+ if (++seen % YIELD_EVERY === 0) await yieldNow();
+ if (deps.paused?.()) result.stopped = true;
+ return !result.stopped;
+ };
+ const remove = async (path: string, dev: number, ino: number): Promise<boolean> => {
+ if (!(await quietMoment(deps, deps.turnWaitMs ?? TURN_WAIT_MS))) {
+ result.stopped = true;
+ return false;
+ }
+ if (deps.mode !== "on") return true;
+ // The file listed and nothing else: the check is by device and inode, so a folder swapped for a link since the
+ // listing reaches a different file and nothing goes. No await between the check and the unlink.
+ try {
+ const current = lstatSync(path);
+ if (!current.isFile() || current.dev !== dev || current.ino !== ino) return false;
+ unlinkSync(path);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ const young: Array<{ path: string; dev: number; ino: number; size: number; mtimeMs: number }> = [];
+ let youngBytes = 0;
+ const top = await opendir(deps.root).catch(() => null);
+ if (!top) return result;
+ for await (const folder of top) {
+ if (!(await pace())) break;
+ if (!folder.isDirectory()) continue;
+ const dir = join(deps.root, folder.name);
+ // Dirent says what readdir saw; a folder swapped for a link since then is caught here.
+ if (!(await stat(dir))?.isDirectory()) continue;
+ result.folders++;
+ const inner = await opendir(dir).catch(() => null);
+ if (!inner) continue;
+ for await (const entry of inner) {
+ if (!(await pace())) break;
+ if (!entry.isFile()) continue;
+ const path = join(dir, entry.name);
+ const stats = await stat(path);
+ if (!stats?.isFile()) continue;
+ if (now - stats.mtimeMs < MAX_AGE_MS) {
+ if (HOOK_OUTPUT.test(entry.name)) young.push({ path, dev: stats.dev, ino: stats.ino, size: stats.size, mtimeMs: stats.mtimeMs });
+ youngBytes += stats.size;
+ continue;
+ }
+ if (!(await remove(path, stats.dev, stats.ino))) {
+ if (result.stopped) break;
+ continue;
+ }
+ result.files++;
+ result.bytes += stats.size;
+ }
+ if (result.stopped) return result;
+ }
+ young.sort((a, b) => a.mtimeMs - b.mtimeMs);
+ for (const file of young) {
+ if (youngBytes <= cap || now - file.mtimeMs < MIN_AGE_MS) break;
+ if (!(await remove(file.path, file.dev, file.ino))) {
+ if (result.stopped) break;
+ continue;
+ }
+ youngBytes -= file.size;
+ result.files++;
+ result.overCap++;
+ result.bytes += file.size;
+ }
+ return result;
+}
+
+export function sweepLine(result: ToolResultsSweepResult): string {
+ const verb = result.mode === "report" ? "would free" : "freed";
+ return `[tool-results] ${result.mode}: ${result.files} saved results in ${result.folders} conversations (${result.overCap} under a day old, over the cap); ${verb} ${(result.bytes / 1024 / 1024).toFixed(1)} MB`
+ + (result.stopped ? " (stopped for a move, a backup or a running turn; the next pass carries on)" : "");
+}
+
+/** Cloud homes only, and only with OMB_TOOL_RESULTS_SWEEP set: a pass when due, at the earliest FIRST_PASS_MS after start. */
+export function startToolResultsSweep(deps: { cloudHome: boolean; env: NodeJS.ProcessEnv; dataDir: string; root: string; paused?(): boolean; turnsRunning?(): boolean; log?(line: string): void }): boolean {
+ const mode = toolResultsSweepMode(deps.env);
+ if (!deps.cloudHome || mode === "off") return false;
+ const log = deps.log ?? ((line: string) => console.log(line));
+ const pass = async (): Promise<boolean> => {
+ // A frozen or backing-up home: no read, no change, and no stamp, so the pass is tried again soon.
+ if (deps.paused?.()) return false;
+ try {
+ const result = await sweepToolResults({ root: deps.root, mode, paused: deps.paused, turnsRunning: deps.turnsRunning });
+ if (result.files || result.stopped) log(sweepLine(result));
+ return !result.stopped;
+ } catch (error) {
+ log(`[tool-results] pass failed: ${error instanceof Error ? error.message : String(error)}`);
+ return false;
+ }
+ };
+ schedulePasses(join(deps.dataDir, STAMP_FILE), PASS_EVERY_MS, pass);
+ return true;
+}
+
+/**
+ * Runs `pass` FIRST_PASS_MS after start, or later when the last whole pass (saved in `stamp`) is not yet `every` old,
+ * then every `every`; a pass that stopped early is tried again after RETRY_MS. A stamp from the future (a clock set
+ * back) counts as none, and a home that slept past its time runs one pass on waking, never one per missed interval.
+ */
+export function schedulePasses(stamp: string, every: number, pass: () => Promise<boolean>, now: () => number = Date.now): void {
+ const run = async () => {
+ const whole = await pass();
+ if (whole) {
+ try {
+ mkdirSync(dirname(stamp), { recursive: true, mode: 0o700 });
+ writeFileSync(stamp, JSON.stringify({ at: now() }), { mode: 0o600 });
+ } catch {}
+ }
+ setTimeout(() => void run(), whole ? every : RETRY_MS).unref();
+ };
+ // The stamp is read in the first timer, never while the server is still starting.
+ const first = () => {
+ let last: number | null = null;
+ try {
+ const at = (JSON.parse(readFileSync(stamp, "utf8")) as { at?: unknown }).at;
+ if (typeof at === "number" && Number.isFinite(at) && at <= now()) last = at;
+ } catch {}
+ const wait = last === null ? 0 : last + every - now();
+ if (wait > 0) setTimeout(() => void run(), wait).unref();
+ else void run();
+ };
+ setTimeout(first, FIRST_PASS_MS).unref();
+}
diff --git a/server/index.ts b/server/index.ts
index 6f3baecd21..0066bf733c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -9,7 +9,7 @@ import { existsSync, realpathSync, rmSync } from "node:fs";
import { homedir } from "node:os";
import { rm as removeDirectory } from "node:fs/promises";
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
-import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts";
+import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts"; import { startToolResultsSweep } from "./host/tool-results-sweep.ts";
import { basename, join } from "node:path";
import { authorizeExternalRuntime, externalRuntimeIsActive, type ExternalRuntimeGrant } from "./external-runtime.ts";
import { z } from "zod";
@@ -275,7 +275,7 @@ import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } from
import { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.ts";
import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";
import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmentsForBox } from "./box-attachments.ts"; import { brokerPath } from "./bot-box/broker-probe.ts";
-import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment } from "./host/delete-leftovers.ts"; import { createConversationFolderCleanup, deleteTimeCleanup, linuxProcessPaths } from "./host/conversation-folder-cleanup.ts"; import { threadsMentioning, transcriptThreads } from "./host/transcript-mentions.ts"; import { orphanSweepMode, startOrphanSweep } from "./host/orphan-sweep.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft, memoryLayerRecords } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";
+import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { knownThreads, startThreadLogSweep } from "./host/thread-log-sweep.ts"; import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment } from "./host/delete-leftovers.ts"; import { createConversationFolderCleanup, deleteTimeCleanup, linuxProcessPaths } from "./host/conversation-folder-cleanup.ts"; import { threadsMentioning, transcriptThreads } from "./host/transcript-mentions.ts"; import { orphanSweepMode, startOrphanSweep } from "./host/orphan-sweep.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft, memoryLayerRecords } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";
import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";
import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts"; import { createSetupRecovery } from "./host/setup-recovered.ts";
import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { createTeamFilesHost } from "./host/team-files-host.ts"; import { createTeamFilesRoutes } from "./routes/team-files.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createPersonNames } from "./host/person-names.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";
@@ -643,7 +643,7 @@ import { createWebhookRoutes } from "./routes/webhooks.ts"; import { createRemot
import { withScopeHint } from "./connector-scope-hint.ts"; import { accountsByApp, withAccountHint } from "./connector-account-hint.ts";
import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";
import { createConnectorCards } from "./host/connector-cards.ts";
-import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { createLateToolResults } from "./host/late-tool-results.ts"; import { internalBodyRefusal } from "./host/internal-body-ids.ts";
+import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { startEngineSessionSweep } from "./host/engine-session-sweep.ts"; import { createLateToolResults } from "./host/late-tool-results.ts"; import { internalBodyRefusal } from "./host/internal-body-ids.ts";
import { onThreadMade, onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { bearerForGrants, createEnginePrestart } from "./engine-prestart.ts"; import { prestartAllowed } from "./drivers/session-idle.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";
const PORT = Number(process.env.OMB_PORT || process.env.OGB_PORT || 8799);
@@ -5390,7 +5390,7 @@ function clearTurnDigestState(threadId: string): void {
memoryRowsByThread.delete(threadId);
}
-const TOOL_RESULTS_DIR = join(DATA_DIR, "tool-results");
+const TOOL_RESULTS_DIR = join(DATA_DIR, "tool-results"); startToolResultsSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, root: TOOL_RESULTS_DIR, paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()) });
const TOOL_RESULT_SPILL_MAX = 512 * 1024;
const DIGESTS_AFTER_COMPACTION = 2;
@@ -11973,7 +11973,7 @@ const { react } = createReactions({
});
const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, createBotLibraryRoutes({ bot: (id) => store.bot(id), visibleFor: (auth) => visibleTo(viewerFor(auth)), pages: () => publishedPages.store.list() }), savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));
// `let` slots are read per request.
-const folderCleanup = CLOUD_HOME && (deleteTimeCleanup(process.env, true, () => true) || orphanSweepMode() !== "off") ? createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, heldText: () => routines ? JSON.stringify([cfg, routines.listRoutines()]) : null, mentions: (words) => threadsMentioning(join(DATA_DIR, "messages.db"), words), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), processFolders: linuxProcessPaths, processPaths: linuxProcessPaths }) : undefined; const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, checkpointsQuiet: checkpoints.quiet, threadsReferencing, keptAttachments, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), engineFolders: () => engineSessionFolders(DATA_DIR, [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env))), layers: memoryLayerRecords, folders: deleteTimeCleanup(process.env, Boolean(folderCleanup), () => folderCleanup!) });
+const engineEnvironments = () => [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env)); const folderCleanup = CLOUD_HOME && (deleteTimeCleanup(process.env, true, () => true) || orphanSweepMode() !== "off") ? createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, heldText: () => routines ? JSON.stringify([cfg, routines.listRoutines()]) : null, mentions: (words) => threadsMentioning(join(DATA_DIR, "messages.db"), words), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), processFolders: linuxProcessPaths, processPaths: linuxProcessPaths }) : undefined; const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, checkpointsQuiet: checkpoints.quiet, threadsReferencing, keptAttachments, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), engineFolders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), layers: memoryLayerRecords, folders: deleteTimeCleanup(process.env, Boolean(folderCleanup), () => folderCleanup!) }); startEngineSessionSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, bots: () => store.bots, folders: () => engineSessionFolders(DATA_DIR, engineEnvironments()), environments: engineEnvironments, paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()) });
ROUTES.push(createThreadRoutes({
groupFor: personRooms.groupForAuth, ...(botOrders ? { botOrderFor: (auth: RequestAuth, bots: readonly BotRecord[]) => { const person = botOrders.personOf(auth); return person ? botOrders.ordered(person, bots) : bots; } } : {}),
store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,
@@ -15148,7 +15148,7 @@ server.listen(PORT, listenHost(server), async () => {
drainQueuedSends();
drainQueuedChannelSends();
void cloudComputerPower.armRunning();
- startUpkeep({ bots: () => store.bots, retentionDays: () => threadEventLogRetentionDays(cfg), busy: threadBusy, openDirectHandoff: (threadId) => coordinator.activeDirect(threadId) }); if (folderCleanup) startOrphanSweep({ dataDir: DATA_DIR, mode: () => orphanSweepMode(), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), records: () => store, storedThreadIds: () => transcriptThreads(join(DATA_DIR, "messages.db")), cleanup: folderCleanup });
+ startUpkeep({ bots: () => store.bots, retentionDays: () => threadEventLogRetentionDays(cfg), busy: threadBusy, openDirectHandoff: (threadId) => coordinator.activeDirect(threadId) }); startThreadLogSweep({ cloudHome: CLOUD_HOME !== null, env: process.env, dataDir: DATA_DIR, threads: () => knownThreads(store.bots, store.groups, (botId, threadId) => threadBusy(botId, threadId) || coordinator.activeDirect(threadId)), paused: () => moveFreeze.frozen() || workspaceMaintenance.active, turnsRunning: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking) || Boolean(routines?.hasActiveRuns()), logQuiet: (threadId) => bus.logQuiet(threadId) }); if (folderCleanup) startOrphanSweep({ dataDir: DATA_DIR, mode: () => orphanSweepMode(), paused: () => (moveFreeze.frozen() ? "frozen after a move" : workspaceMaintenance.active ? "a backup is being made or restored" : null), records: () => store, storedThreadIds: () => transcriptThreads(join(DATA_DIR, "messages.db")), cleanup: folderCleanup });
if (enginesRead) {
await enginesRead;
if (companyShutdown) return;
diff --git a/server/thread-events.ts b/server/thread-events.ts
index 42fd198aa2..5808a7a17c 100644
--- a/server/thread-events.ts
+++ b/server/thread-events.ts
@@ -8,7 +8,7 @@ export type { InspectorEntry, InspectorPage, NativeRecord } from "../shared/insp
const DEFAULT_LIMIT = 300;
const MAX_LIMIT = 2000;
const READ_CHUNK = 64 * 1024;
-const MAX_TAIL_BYTES = 8 * 1024 * 1024;
+export const MAX_TAIL_BYTES = 8 * 1024 * 1024;
interface LineCount {
dev: number;