Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Orphan sweep: report, then remove, leftovers of conversations deleted before their cleanup (#7138)
Milind Sonif5b52d023010
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 49f49c6e78..02a1d7f78b 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -8,7 +8,7 @@ import { BOX_ENV_NAMES, BOX_ENV_NEVER, BOX_ENV_OMB_NAMES, BOX_ENV_OMB_PREFIXES,* ending in `_` is a family (`OMB_CLOUD_*`). */const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_ACP_LIMIT_QUIET_MS", "OMB_ACP_NO_SIGNS_STOP_MS", "OMB_ACP_PLAN_LINES", "OMB_ACP_QUIET_NOTICE_MS",- "OMB_ACP_QUIET_TICK_MS", "OMB_TASK_WORKSPACE_RETENTION", "OMB_CONVERSATION_FOLDER_CLEANUP", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP",+ "OMB_ACP_QUIET_TICK_MS", "OMB_TASK_WORKSPACE_RETENTION", "OMB_CONVERSATION_FOLDER_CLEANUP", "OMB_ORPHAN_SWEEP", "OMB_ORPHAN_SWEEP_MAX_SHARE", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP","OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY", "OMB_ANTIGRAVITY_NATIVE_CLI","OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT","OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.tsindex 3ba073cf78..aae0354454 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -50,6 +50,8 @@ const SERVER_ENV_NAMES = new Set(["OMB_TASK_WORKSPACE_RETENTION",// The delete-time cleanup's switch (server/host/conversation-folder-cleanup.ts): off unless the Admin sets it on."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",]);export function serverEnvironmentAllowed(name: string): boolean {return SERVER_ENV_NAMES.has(name) || name.startsWith("LC_");diff --git a/server/host/orphan-sweep.test.ts b/server/host/orphan-sweep.test.tsnew file mode 100644index 0000000000..3a8123f1a3--- /dev/null+++ b/server/host/orphan-sweep.test.ts@@ -0,0 +1,374 @@+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { createConversationFolderCleanup, type LiveRecords } from "./conversation-folder-cleanup.ts";+import { describeOrphanReport, orphanSweepMaxShare, orphanSweepMode, sweepOrphans, type OrphanSweepDeps, type OrphanSweepMode } from "./orphan-sweep.ts";++const DAY = 24 * 60 * 60 * 1000;+const made: string[] = [];+afterEach(() => {+ for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function put(path: string, text = "x"): string {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, text);+ return path;+}++/** Sets everything under `path` (itself included) to `days` ago, never through a link. */+function age(path: string, days: number): void {+ const at = new Date(Date.now() - days * DAY);+ const walk = (one: string) => {+ const stats = lstatSync(one);+ if (stats.isSymbolicLink()) return;+ if (stats.isDirectory()) for (const name of readdirSync(one)) walk(join(one, name));+ utimesSync(one, at, at);+ };+ walk(path);+}++function fixture(over: Partial<OrphanSweepDeps> = {}) {+ const sandbox = mkdtempSync(join(tmpdir(), "omb-orphan-sweep-"));+ made.push(sandbox);+ const dataDir = join(sandbox, "data");+ const outside = join(sandbox, "outside");+ mkdirSync(outside, { recursive: true });+ const bots: Array<LiveRecords["bots"][number]> = [{ id: "scout", tasks: [{ threadId: "live" }] }];+ const groups: Array<LiveRecords["groups"][number]> = [];+ const stored = new Set<string>(["live", "only-in-transcripts"]);+ const records = () => ({ bots, groups });+ // The same pause the server gives both (index.ts).+ const cleanup = createConversationFolderCleanup({ dataDir, records, paused: () => over.paused?.() ?? null, drainAfterMs: false, pause: async () => {}, log: () => {}, warn: () => {} });+ let now = Date.now();+ let mode: OrphanSweepMode = "report";+ const warnings: string[] = [];+ const deps: OrphanSweepDeps = {+ dataDir, mode: () => mode, records, storedThreadIds: async () => stored, cleanup, maxShare: () => 100, now: () => now, pause: async () => {}, log: () => {},+ warn: (line) => { warnings.push(line); },+ ...over,+ };+ const install = (at: string, size = "1234") => {+ put(join(at, "package.json"), "{}");+ put(join(at, "node_modules", ".package-lock.json"), "{}");+ return put(join(at, "node_modules", "x", "index.js"), size);+ };+ const files = {+ orphanResults: put(join(dataDir, "tool-results", "gone1", "r.txt"), "12345"),+ liveResults: put(join(dataDir, "tool-results", "live", "r.txt")),+ transcriptResults: put(join(dataDir, "tool-results", "only-in-transcripts", "r.txt")),+ gateFallback: put(join(dataDir, "tool-results", "thread", "r.txt")),+ orphanEvents: put(join(dataDir, "events", "gone1.ndjson"), "1234567890"),+ orphanNative: put(join(dataDir, "native", "gone2.ndjson"), "12345"),+ liveEvents: put(join(dataDir, "events", "live.ndjson")),+ transcriptEvents: put(join(dataDir, "events", "only-in-transcripts.ndjson")),+ orphanWork: put(join(dataDir, "task-workspaces", "scout", "gone1", "report.md"), "abc"),+ orphanDeps: install(join(dataDir, "task-workspaces", "scout", "gone1", "app")),+ deletedBotDeps: install(join(dataDir, "task-workspaces", "removed-bot", "gone5")),+ liveDeps: install(join(dataDir, "task-workspaces", "scout", "live")),+ transcriptDeps: install(join(dataDir, "task-workspaces", "scout", "only-in-transcripts")),+ };+ age(dataDir, 30);+ const sweep = () => sweepOrphans(deps);+ /** `count` passes, one a day; the report of the last. */+ const daily = async (count: number) => {+ let last;+ for (let i = 0; i < count; i++) { last = await sweep(); now += DAY; }+ now -= DAY;+ return last!;+ };+ const later = (days: number) => { now += days * DAY; };+ const state = () => JSON.parse(readFileSync(join(dataDir, "orphan-sweep.json"), "utf8")) as { seen: Record<string, { first: number; days: string[] }>; mode: string; cursor?: string; last: { at: number } };+ return { sandbox, dataDir, outside, bots, groups, stored, files, warnings, sweep, daily, later, state, install, setMode: (next: OrphanSweepMode) => { mode = next; }, nowIs: () => now };+}+type Fixture = ReturnType<typeof fixture>;++const present = (paths: Record<string, string>) => Object.fromEntries(Object.entries(paths).map(([key, path]) => [key, existsSync(path)]));+const allThere = (f: Fixture) => Object.values(present(f.files)).every(Boolean);++describe("the orphan sweep's switches", () => {+ it("is off unless set, and reads report (or dry-run) and remove", () => {+ expect(orphanSweepMode({})).toBe("off");+ expect(orphanSweepMode({ OMB_ORPHAN_SWEEP: "yes" })).toBe("off");+ expect(orphanSweepMode({ OMB_ORPHAN_SWEEP: " Report " })).toBe("report");+ expect(orphanSweepMode({ OMB_ORPHAN_SWEEP: "dry-run" })).toBe("report");+ expect(orphanSweepMode({ OMB_ORPHAN_SWEEP: "remove" })).toBe("remove");+ });++ it("removes at most 10% of the conversations on disk unless told otherwise", () => {+ expect(orphanSweepMaxShare({})).toBe(10);+ expect(orphanSweepMaxShare({ OMB_ORPHAN_SWEEP_MAX_SHARE: "60" })).toBe(60);+ expect(orphanSweepMaxShare({ OMB_ORPHAN_SWEEP_MAX_SHARE: "lots" })).toBe(10);+ expect(orphanSweepMaxShare({ OMB_ORPHAN_SWEEP_MAX_SHARE: "150" })).toBe(10);+ });++ it("off: reads and changes nothing", async () => {+ const f = fixture();+ f.setMode("off");+ expect((await f.sweep()).skipped).toBe("off");+ expect(allThere(f)).toBe(true);+ expect(existsSync(join(f.dataDir, "orphan-sweep.json"))).toBe(false);+ });+});++describe("report", () => {+ it("counts only orphans, with their bytes, and changes nothing", async () => {+ const f = fixture();+ const report = await f.sweep();+ expect(report.toolResults).toEqual({ count: 1, bytes: 5 });+ expect(report.eventLogs).toEqual({ count: 2, bytes: 15 });+ expect(report.workspaces.folders).toBe(2);+ expect(report.workspaces.rebuildableBytes).toBeGreaterThanOrEqual(8);+ expect(report.workspaces.keptFileBytes).toBeGreaterThanOrEqual(3);+ expect(report.conversations).toEqual({ onDisk: 5, orphaned: 3 });+ expect(report.removed).toBe(false);+ expect(allThere(f)).toBe(true);+ expect(describeOrphanReport(report)).toMatch(/^orphan sweep \(report\): conversations on disk 5, orphaned 3; tool results 1 folder/);+ expect(Object.keys(f.state().seen).sort()).toEqual(["events:gone1", "native:gone2", "results:gone1", "workspace:removed-bot/gone5", "workspace:scout/gone1"]);+ expect(f.state().mode).toBe("report");+ });+});++describe("remove", () => {+ it("waits a week and seven passes on different days, then removes orphans and keeps the person's files and everything live", async () => {+ const f = fixture();+ f.setMode("remove");+ expect((await f.daily(7)).waiting).toBe(5);+ expect(allThere(f)).toBe(true);+ f.later(1);+ const due = await f.sweep();+ expect(due.waiting).toBe(0);+ expect(due.removed).toBe(true);+ expect(present(f.files)).toEqual({+ orphanResults: false, liveResults: true, transcriptResults: true, gateFallback: true,+ orphanEvents: false, orphanNative: false, liveEvents: true, transcriptEvents: true,+ orphanWork: true, orphanDeps: false, deletedBotDeps: false, liveDeps: true, transcriptDeps: true,+ });+ });++ it("is not hurried by a clock that jumps ahead", async () => {+ const f = fixture();+ f.setMode("remove");+ await f.sweep();+ f.later(30);+ expect((await f.sweep()).waiting).toBe(5);+ expect(allThere(f)).toBe(true);+ });++ it("starts over on notes from the future, from another machine, or from report mode", async () => {+ // The next pass is dated before the notes' last one (a clock set back): they are dropped.+ const restored = fixture();+ restored.setMode("remove");+ await restored.sweep();+ const notes = restored.state();+ writeFileSync(join(restored.dataDir, "orphan-sweep.json"), JSON.stringify({ ...notes, last: { ...notes.last, at: restored.nowIs() + 30 * DAY },+ seen: Object.fromEntries(Object.keys(notes.seen).map((key) => [key, { first: restored.nowIs() - 30 * DAY, days: Array.from({ length: 7 }, (_, i) => new Date(restored.nowIs() - (i + 1) * DAY).toISOString().slice(0, 10)) }])) }));+ expect((await restored.sweep()).waiting).toBe(5);+ expect(allThere(restored)).toBe(true);++ const copied = fixture();+ copied.setMode("remove");+ put(join(copied.dataDir, "environment-id"), "machine-a");+ await copied.daily(8);+ expect(existsSync(copied.files.orphanEvents)).toBe(false);+ const other = fixture();+ other.setMode("remove");+ put(join(other.dataDir, "environment-id"), "machine-b");+ await other.daily(7);+ const aged = other.state();+ put(join(other.dataDir, "environment-id"), "machine-c");+ writeFileSync(join(other.dataDir, "orphan-sweep.json"), JSON.stringify(aged));+ other.later(1);+ expect((await other.sweep()).waiting).toBe(5);++ const reported = fixture();+ await reported.daily(8);+ reported.setMode("remove");+ reported.later(1);+ expect((await reported.sweep()).waiting).toBe(5);+ expect(allThere(reported)).toBe(true);+ });++ it("clamps a first sight noted in the future to now", async () => {+ const f = fixture();+ f.setMode("remove");+ await f.sweep();+ const notes = f.state();+ for (const key of Object.keys(notes.seen)) notes.seen[key] = { first: f.nowIs() + 365 * DAY, days: [] };+ writeFileSync(join(f.dataDir, "orphan-sweep.json"), JSON.stringify(notes));+ f.later(1);+ await f.daily(8);+ expect(existsSync(f.files.orphanEvents)).toBe(false);+ });++ it("keeps an orphan changed within the week, however long it has been known", async () => {+ const f = fixture();+ f.setMode("remove");+ await f.daily(7);+ f.later(1);+ const recent = new Date(f.nowIs() - DAY);+ utimesSync(put(f.files.orphanEvents, "written again"), recent, recent);+ utimesSync(put(join(dirname(f.files.orphanDeps), "fresh.js")), recent, recent);+ await f.sweep();+ expect(existsSync(f.files.orphanEvents)).toBe(true);+ expect(existsSync(f.files.orphanDeps)).toBe(true);+ expect(existsSync(f.files.orphanResults)).toBe(false);+ });++ it("keeps a folder a remaining conversation works in, and tool results a remaining thread's results share", async () => {+ const f = fixture();+ const long = `${"g".repeat(80)}x`;+ const shared = put(join(f.dataDir, "tool-results", "g".repeat(80), "r.txt"));+ age(dirname(shared), 30);+ f.bots.push({ id: "fork-bot", tasks: [{ threadId: long, cwd: join(f.dataDir, "task-workspaces", "scout", "gone1") }] });+ f.setMode("remove");+ const report = await f.daily(8);+ expect(report.workspaces.folders).toBe(1);+ expect(existsSync(f.files.orphanDeps)).toBe(true);+ expect(existsSync(shared)).toBe(true);+ expect(existsSync(f.files.deletedBotDeps)).toBe(false);+ });++ it("treats an archived bot's conversations as live", async () => {+ const f = fixture();+ f.bots.push({ id: "archived", hidden: true, tasks: [{ threadId: "kept-thread" }] } as LiveRecords["bots"][number]);+ const deps = f.install(join(f.dataDir, "task-workspaces", "archived", "kept-thread"));+ age(join(f.dataDir, "task-workspaces", "archived"), 30);+ f.setMode("remove");+ await f.daily(8);+ expect(existsSync(deps)).toBe(true);+ });+});++describe("failing closed", () => {+ it("does nothing while the transcripts cannot be read or no conversation is registered", async () => {+ const unreadable = fixture({ storedThreadIds: async () => { throw new Error("database is locked"); } });+ unreadable.setMode("remove");+ expect((await unreadable.sweep()).skipped).toMatch(/transcripts could not be read: database is locked/);+ expect(allThere(unreadable)).toBe(true);+ const empty = fixture();+ empty.bots.splice(0);+ empty.setMode("remove");+ expect((await empty.sweep()).skipped).toBe("no conversation is registered");+ expect(allThere(empty)).toBe(true);+ });++ it("reports only, loudly, when more than its share of the conversations on disk look orphaned", async () => {+ const f = fixture({ maxShare: () => 50 });+ f.setMode("remove");+ const report = await f.daily(8);+ expect(report.held).toMatch(/3 of 5 conversations on disk look orphaned \(60%, more than 50%\)/);+ expect(describeOrphanReport(report)).toMatch(/REMOVED NOTHING/);+ expect(f.warnings.join("\n")).toMatch(/records may be unreadable/);+ expect(allThere(f)).toBe(true);+ });++ it("does nothing while the workspace must not change, checked again before each removal", async () => {+ let paused: string | null = null;+ const f = fixture({ paused: () => paused });+ f.setMode("remove");+ await f.daily(7);+ f.later(1);+ paused = "frozen after a move";+ expect((await f.sweep()).skipped).toBe("frozen after a move");+ expect(allThere(f)).toBe(true);+ // Not paused when the pass starts, nor at the last look before removing, but at each removal itself.+ let asks = 0, counting = false;+ const g = fixture({ paused: () => (counting && ++asks > 2 ? "a backup is being made or restored" : null) });+ g.setMode("remove");+ await g.daily(7);+ g.later(1);+ counting = true;+ const report = await g.sweep();+ expect(report.removed).toBe(true);+ expect(allThere(g)).toBe(true);+ // And at the last look before removing: nothing is handed over.+ let looks = 0;+ const h = fixture({ paused: () => (counting && ++looks === 2 ? "frozen after a move" : null) });+ h.setMode("remove");+ counting = false;+ await h.daily(7);+ h.later(1);+ counting = true;+ expect((await h.sweep()).held).toBe("frozen after a move");+ expect(allThere(h)).toBe(true);+ });++ it("checks an event log again just before removing it: come back, or no longer a plain file", async () => {+ let step = 0, armed = false;+ const f = fixture({+ paused: () => {+ if (armed && ++step === 3) {+ f.bots.push({ id: "merged", tasks: [{ threadId: "gone1" }] });+ unlinkSync(f.files.orphanNative);+ symlinkSync(put(join(f.outside, "precious.ndjson")), f.files.orphanNative);+ }+ return null;+ },+ });+ f.setMode("remove");+ await f.daily(7);+ f.later(1);+ armed = true;+ await f.sweep();+ expect(step).toBeGreaterThanOrEqual(3);+ expect(existsSync(f.files.orphanEvents)).toBe(true);+ expect(lstatSync(f.files.orphanNative).isSymbolicLink()).toBe(true);+ expect(existsSync(join(f.outside, "precious.ndjson"))).toBe(true);+ });++ it("never follows a link out of the data folder, in its listings or its measures", async () => {+ const f = fixture();+ const victims = [put(join(f.outside, "results", "r.txt"), "x".repeat(10_000)), put(join(f.outside, "log.ndjson")), f.install(join(f.outside, "bot", "t9"))];+ symlinkSync(join(f.outside, "results"), join(f.dataDir, "tool-results", "linked"), "dir");+ symlinkSync(join(f.outside, "results"), join(f.dataDir, "tool-results", "gone1", "inner-link"), "dir");+ symlinkSync(join(f.outside, "log.ndjson"), join(f.dataDir, "events", "linked.ndjson"));+ symlinkSync(join(f.outside, "bot"), join(f.dataDir, "task-workspaces", "linked-bot"), "dir");+ f.setMode("remove");+ const first = await f.sweep();+ expect(first.toolResults.count).toBe(1);+ expect(first.toolResults.bytes).toBeLessThan(1_000);+ expect(first.eventLogs.count).toBe(2);+ expect(first.conversations.onDisk).toBe(6);+ // The links were made after the fixture's clock was read: one more day for their own week.+ await f.daily(9);+ expect(victims.filter((path) => !existsSync(path))).toEqual([]);+ expect(existsSync(f.files.orphanResults)).toBe(false);+ });++ it("keeps an item past its own budget, and carries on after a pass that ran out of budget", async () => {+ const small = fixture({ limits: { perItem: 3 } });+ small.setMode("remove");+ const report = await small.daily(8);+ expect(report.tooLarge).toBeGreaterThan(0);+ expect(existsSync(small.files.orphanDeps)).toBe(true);+ expect(existsSync(small.files.orphanEvents)).toBe(false);++ const short = fixture({ limits: { perPass: 12 } });+ const partial = await short.sweep();+ expect(partial.partial).toBe(true);+ const cursor = short.state().cursor;+ expect(cursor).toBeTruthy();+ short.later(1);+ const next = await short.sweep();+ expect(next.partial).toBe(true);+ expect(short.state().cursor).not.toBe(cursor);+ expect(describeOrphanReport(next)).toMatch(/stopped at its budget/);+ });++ it("leaves everything when a pass stops in the middle, and the next pass carries on", async () => {+ let crash = true;+ const f = fixture({ pause: async () => { if (crash) throw new Error("power cut"); } });+ for (let i = 0; i < 5_000; i++) put(join(f.dataDir, "task-workspaces", "scout", "gone1", "app", "node_modules", "big", `${i}.js`));+ age(join(f.dataDir, "task-workspaces"), 30);+ f.setMode("remove");+ await expect(f.sweep()).rejects.toThrow(/power cut/);+ expect(allThere(f)).toBe(true);+ crash = false;+ await f.daily(8);+ expect(existsSync(f.files.orphanDeps)).toBe(false);+ expect(existsSync(f.files.orphanWork)).toBe(true);+ });+});diff --git a/server/host/orphan-sweep.ts b/server/host/orphan-sweep.tsnew file mode 100644index 0000000000..d625911a53--- /dev/null+++ b/server/host/orphan-sweep.ts@@ -0,0 +1,318 @@+// Leftovers already on disk from conversations deleted before their cleanup existed: tool results+// (tool-results/<thread>), event logs (events/ and native/<thread>.ndjson) and the package installs of conversation+// folders (task-workspaces/<bot>/<thread>) whose conversation is gone. Behind OMB_ORPHAN_SWEEP, off unless set:+// "report" counts what it would remove and the bytes, and changes nothing; "remove" also removes it. A pass runs ten+// minutes after start and then once a day, and its numbers go to the log and to orphan-sweep.json.+//+// Conservative: anything not positively an orphan stays.+// - A conversation is gone only when neither the bots' and rooms' records nor the transcripts name it; if the+// transcripts cannot be read, or no conversation is registered at all, nothing is done.+// - An orphan goes only once it is a week old by its own newest change, the sweep has known it for a week and has seen+// it on seven different days, all in "remove" mode on this machine. What "report" saw does not count, and the notes+// are dropped when they come from another machine (a copied disk) or from the future (a clock set back).+// - When more than a small share of all conversations on disk look orphaned (OMB_ORPHAN_SWEEP_MAX_SHARE percent, 10 by+// default), the records are more likely unreadable than the conversations gone: the pass reports only, loudly.+// - No pass changes anything while the server is frozen after a move or a backup is being made or restored, checked+// before each removal.+// - Each item is measured within its own budget; one past it is kept. A pass past its total budget stops, saves what+// it saw, and the next pass carries on from there.+// The person's files in an orphaned conversation folder stay (the delete dialogs promise them; Files still shows them):+// only its package installs go, through the same checks as a delete (conversation-folder-cleanup.ts). Event logs go+// file by file after the same check again. Nothing follows a link.+import { lstat, readdir, readFile, unlink } from "node:fs/promises";+import { join, resolve } from "node:path";++import { writeFileAtomic } from "../atomic.ts";+import { gateResultsName, hookResultsName, liveThreadIds, type ConversationFolderCleanup, type LiveRecords } from "./conversation-folder-cleanup.ts";++export const ORPHAN_SWEEP_ENV = "OMB_ORPHAN_SWEEP";+export const ORPHAN_SWEEP_SHARE_ENV = "OMB_ORPHAN_SWEEP_MAX_SHARE";+export type OrphanSweepMode = "off" | "report" | "remove";+export const ORPHAN_GRACE_MS = 7 * 24 * 60 * 60 * 1000;+export const ORPHAN_PASS_DAYS = 7;+const DEFAULT_MAX_SHARE = 10;+const FIRST_PASS_MS = 10 * 60 * 1000;+const EVERY_MS = 24 * 60 * 60 * 1000;+const STATE_FILE = "orphan-sweep.json";+const ID = /^[\w-]{1,128}$/;+const PER_ITEM_ENTRIES = 250_000;+const PER_PASS_ENTRIES = 5_000_000;+const YIELD_EVERY = 256;+const PAUSE_EVERY = 4_096;+const PAUSE_MS = 20;++export function orphanSweepMode(env: NodeJS.ProcessEnv = process.env): OrphanSweepMode {+ const value = env[ORPHAN_SWEEP_ENV]?.trim().toLowerCase();+ if (value === "report" || value === "dry-run") return "report";+ if (value === "remove") return "remove";+ return "off";+}++/** The largest share of the conversations on disk, in percent, the sweep removes as orphans in one go. */+export function orphanSweepMaxShare(env: NodeJS.ProcessEnv = process.env): number {+ const value = Number(env[ORPHAN_SWEEP_SHARE_ENV]?.trim());+ return Number.isFinite(value) && value >= 0 && value <= 100 && env[ORPHAN_SWEEP_SHARE_ENV]?.trim() ? value : DEFAULT_MAX_SHARE;+}++export interface OrphanCount { count: number; bytes: number }+export interface OrphanReport {+ at: number;+ mode: OrphanSweepMode;+ /** Why nothing was looked at. */+ skipped?: string;+ /** Why nothing was removed although the mode is "remove". */+ held?: string;+ toolResults: OrphanCount;+ eventLogs: OrphanCount;+ /** Orphaned conversation folders: their installs (which go) and the person's files in them (which stay). */+ workspaces: { folders: number; rebuildableBytes: number; keptFileBytes: number };+ /** Conversations on disk, and how many of them look orphaned. */+ conversations: { onDisk: number; orphaned: number };+ /** Orphans not yet past their week and their seven days: counted above, removed by a later pass. */+ waiting: number;+ /** Items past their own budget, kept this pass. */+ tooLarge: number;+ /** The pass ran out of its budget; the next carries on. */+ partial: boolean;+ /** Whether a pass in "remove" mode handed the orphans over for removal. */+ removed: boolean;+}++export interface OrphanSweepDeps {+ dataDir: string;+ mode(): OrphanSweepMode;+ records(): LiveRecords;+ /** Why the workspace must not be changed now (frozen after a move, a backup being made or restored), else null. */+ paused?(): string | null;+ /** Every conversation the transcripts hold; rejects when they cannot be read. */+ storedThreadIds(): Promise<ReadonlySet<string>> | ReadonlySet<string>;+ cleanup: Pick<ConversationFolderCleanup, "orphans" | "whyKept" | "rebuildable" | "idle">;+ maxShare?(): number;+ limits?: { perItem?: number; perPass?: number };+ now?(): number;+ pause?(ms: number): Promise<void>;+ log?(line: string): void;+ warn?(line: string): void;+}++interface Seen { first: number; days: string[] }+interface State { environment: string; mode: OrphanSweepMode; seen: Record<string, Seen>; cursor?: string; last?: OrphanReport }++const empty = (at: number, mode: OrphanSweepMode, skipped?: string): OrphanReport => ({+ at, mode, ...(skipped ? { skipped } : {}), toolResults: { count: 0, bytes: 0 }, eventLogs: { count: 0, bytes: 0 },+ workspaces: { folders: 0, rebuildableBytes: 0, keptFileBytes: 0 }, conversations: { onDisk: 0, orphaned: 0 },+ waiting: 0, tooLarge: 0, partial: false, removed: false,+});+const mb = (bytes: number) => `${Math.round(bytes / 1024 / 1024)} MB`;+const message = (error: unknown) => (error instanceof Error ? error.message : String(error));+const day = (at: number) => new Date(at).toISOString().slice(0, 10);++export function describeOrphanReport(report: OrphanReport): string {+ if (report.skipped) return `orphan sweep (${report.mode}): skipped: ${report.skipped}`;+ return `orphan sweep (${report.mode}): conversations on disk ${report.conversations.onDisk}, orphaned ${report.conversations.orphaned}; ` ++ `tool results ${report.toolResults.count} folder(s) ${mb(report.toolResults.bytes)}; event logs ${report.eventLogs.count} file(s) ` ++ `${mb(report.eventLogs.bytes)}; conversation folders ${report.workspaces.folders}, installs ${mb(report.workspaces.rebuildableBytes)}, ` ++ `the person's files kept ${mb(report.workspaces.keptFileBytes)}; ${report.waiting} still waiting` ++ `${report.tooLarge ? `; ${report.tooLarge} too large to check` : ""}${report.partial ? "; stopped at its budget, the next pass carries on" : ""}` ++ `${report.held ? `; REMOVED NOTHING: ${report.held}` : report.removed ? "; the rest handed over for removal" : ""}`;+}++class OverBudget extends Error {}++export async function sweepOrphans(deps: OrphanSweepDeps): Promise<OrphanReport> {+ const dataDir = resolve(deps.dataDir);+ const now = (deps.now ?? Date.now)();+ const mode = deps.mode();+ const pause = deps.pause ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms)));+ const warn = deps.warn ?? ((line: string) => console.warn(line));+ const statePath = join(dataDir, STATE_FILE);+ const perItem = deps.limits?.perItem ?? PER_ITEM_ENTRIES, perPass = deps.limits?.perPass ?? PER_PASS_ENTRIES;+ let passSteps = 0;+ if (mode === "off") return empty(now, mode, "off");+ const paused = deps.paused?.() ?? null;+ if (paused) return empty(now, mode, paused);++ const records = deps.records();+ const registered = liveThreadIds(records);+ let stored: ReadonlySet<string>;+ try { stored = await deps.storedThreadIds(); } catch (error) {+ return empty(now, mode, `the transcripts could not be read: ${message(error)}`);+ }+ if (!registered.size) return empty(now, mode, "no conversation is registered");+ const live = new Set([...registered, ...stored]);+ const liveNames = new Set([...live].flatMap((id) => [hookResultsName(id), gateResultsName(id)]));+ const environment = (await readFile(join(dataDir, "environment-id"), "utf8").catch(() => "")).trim();++ // Notes from another machine, another mode or the future start over.+ let state: State = { environment, mode, seen: {} };+ try {+ const read = JSON.parse(await readFile(statePath, "utf8")) as Partial<State>;+ const fresh = read && read.environment === environment && read.mode === mode && !(typeof read.last?.at === "number" && read.last.at > now);+ if (fresh && read.seen && typeof read.seen === "object") state = { environment, mode, seen: { ...read.seen }, ...(typeof read.cursor === "string" ? { cursor: read.cursor } : {}) };+ } catch { /* none yet, or unreadable: every orphan starts its wait now */ }+ const report = empty(now, mode);+ const seen: Record<string, Seen> = {};+ const today = day(now);+ /** Whether an orphan is past its week, its seven days and its own week of quiet; notes this pass's sight of it. */+ const due = (key: string, newestMs: number) => {+ const before = state.seen[key];+ const first = before && Number.isFinite(before.first) ? Math.min(before.first, now) : now;+ const days = Array.isArray(before?.days) ? before.days.filter((one) => typeof one === "string" && one <= today) : [];+ if (days.at(-1) !== today) days.push(today);+ seen[key] = { first, days: days.slice(-ORPHAN_PASS_DAYS) };+ const ready = now - newestMs >= ORPHAN_GRACE_MS && now - first >= ORPHAN_GRACE_MS && seen[key]!.days.length >= ORPHAN_PASS_DAYS;+ if (!ready) report.waiting++;+ return ready;+ };+ const names = async (dir: string) => {+ try { return (await lstat(dir)).isDirectory() ? await readdir(dir) : []; } catch { return []; }+ };+ /** Bytes and newest change under `path`, never through a link, within one item's budget (null past it); `skip`+ * names subtrees counted elsewhere. */+ const measure = async (path: string, skip: ReadonlySet<string> = new Set()): Promise<{ bytes: number; newest: number } | null> => {+ const total = { bytes: 0, newest: 0 };+ let itemSteps = 0;+ const walk = async (at: string): Promise<boolean> => {+ if (++itemSteps > perItem) return false;+ if (++passSteps > perPass) throw new OverBudget();+ if (passSteps % PAUSE_EVERY === 0) await pause(PAUSE_MS);+ else if (passSteps % YIELD_EVERY === 0) await new Promise<void>((done) => setImmediate(done));+ const stats = await lstat(at).catch(() => null);+ if (!stats) return true;+ total.newest = Math.max(total.newest, stats.mtimeMs);+ if (!stats.isDirectory()) { total.bytes += stats.size; return true; }+ for (const name of await readdir(at).catch(() => [] as string[])) if (!skip.has(join(at, name)) && !await walk(join(at, name))) return false;+ return true;+ };+ return await walk(path) ? total : null;+ };++ // What is on disk, from listings alone: every conversation it holds something of, and which of those are orphans.+ type Item = { key: string; kind: "results" | "log" | "workspace"; path: string; id: string; name: string };+ const items: Item[] = [];+ const onDisk = new Set<string>(), orphaned = new Set<string>();+ for (const name of await names(join(dataDir, "tool-results"))) {+ if (!ID.test(name) || name === "thread") continue;+ onDisk.add(name);+ if (liveNames.has(name)) continue;+ orphaned.add(name);+ items.push({ key: `results:${name}`, kind: "results", path: join(dataDir, "tool-results", name), id: name, name });+ }+ for (const kind of ["events", "native"]) {+ for (const file of await names(join(dataDir, kind))) {+ const id = file.endsWith(".ndjson") ? file.slice(0, -".ndjson".length) : "";+ if (!ID.test(id)) continue;+ onDisk.add(id);+ if (live.has(id)) continue;+ orphaned.add(id);+ items.push({ key: `${kind}:${id}`, kind: "log", path: join(dataDir, kind, file), id, name: file });+ }+ }+ const tasksRoot = join(dataDir, "task-workspaces");+ for (const botId of await names(tasksRoot)) {+ if (!ID.test(botId)) continue;+ for (const threadId of await names(join(tasksRoot, botId))) {+ if (!ID.test(threadId)) continue;+ onDisk.add(threadId);+ if (live.has(threadId)) continue;+ orphaned.add(threadId);+ items.push({ key: `workspace:${botId}/${threadId}`, kind: "workspace", path: join(tasksRoot, botId, threadId), id: threadId, name: threadId });+ }+ }+ report.conversations = { onDisk: onDisk.size, orphaned: orphaned.size };+ // A pass that stopped at its budget left a cursor: this one starts there.+ const start = state.cursor ? Math.max(0, items.findIndex((item) => item.key === state.cursor)) : 0;+ const ordered = [...items.slice(start), ...items.slice(0, start)];++ const results: string[] = [], logs: Item[] = [], workspaces: string[] = [];+ let cursor: string | undefined;+ for (const item of ordered) {+ try {+ if (item.kind === "results") {+ if (!(await lstat(item.path).catch(() => null))?.isDirectory()) continue;+ const size = await measure(item.path);+ if (!size) { report.tooLarge++; continue; }+ report.toolResults.count++;+ report.toolResults.bytes += size.bytes;+ if (due(item.key, size.newest)) results.push(item.name);+ } else if (item.kind === "log") {+ const stats = await lstat(item.path).catch(() => null);+ if (!stats?.isFile()) continue;+ report.eventLogs.count++;+ report.eventLogs.bytes += stats.size;+ if (due(item.key, stats.mtimeMs)) logs.push(item);+ } else {+ if (deps.cleanup.whyKept(item.path)) continue;+ const trees = (await deps.cleanup.rebuildable(item.path)).map((tree) => tree.path);+ let treeBytes = 0, newest = 0, whole = true;+ for (const tree of trees) {+ const size = await measure(tree);+ if (!size) { whole = false; break; }+ treeBytes += size.bytes;+ newest = Math.max(newest, size.newest);+ }+ const rest = whole ? await measure(item.path, new Set(trees)) : null;+ if (!rest) { report.tooLarge++; continue; }+ report.workspaces.folders++;+ report.workspaces.rebuildableBytes += treeBytes;+ report.workspaces.keptFileBytes += rest.bytes;+ if (trees.length && due(item.key, Math.max(newest, rest.newest))) workspaces.push(item.path);+ }+ } catch (error) {+ if (!(error instanceof OverBudget)) throw error;+ report.partial = true;+ cursor = item.key;+ break;+ }+ }++ // Anything the pass did not reach keeps its notes; what is gone, or no longer an orphan, loses them.+ const listed = new Set(items.map((item) => item.key));+ for (const [key, value] of Object.entries(state.seen)) if (!(key in seen) && listed.has(key) && report.partial) seen[key] = value;++ const share = onDisk.size ? (orphaned.size / onDisk.size) * 100 : 0;+ const maxShare = (deps.maxShare ?? orphanSweepMaxShare)();+ if (mode === "remove") {+ const pausedNow = deps.paused?.() ?? null;+ if (pausedNow) report.held = pausedNow;+ else if (share > maxShare) {+ report.held = `${orphaned.size} of ${onDisk.size} conversations on disk look orphaned (${Math.round(share)}%, more than ${maxShare}%): the records may be unreadable; set ${ORPHAN_SWEEP_SHARE_ENV} after checking`;+ warn(`orphan sweep: ${report.held}`);+ } else {+ for (const item of logs) {+ // Checked again just before: a conversation may have come back meanwhile (a merge from another computer).+ if (deps.paused?.() || liveThreadIds(deps.records()).has(item.id)) continue;+ try {+ if ((await lstat(item.path)).isFile()) await unlink(item.path);+ } catch (error) {+ warn(`orphan sweep: kept ${item.path}: ${message(error)}`);+ }+ }+ deps.cleanup.orphans({ workspaces, results });+ await deps.cleanup.idle();+ report.removed = true;+ }+ }++ state = { environment, mode, seen, ...(cursor ? { cursor } : {}), last: report };+ try { writeFileAtomic(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); } catch (error) {+ warn(`orphan sweep: could not save its notes: ${message(error)}`);+ }+ return report;+}++/** The first pass ten minutes after start, then one a day; each reads the switch again, so it can be turned on or off+ * without a restart where the environment allows. */+export function startOrphanSweep(deps: OrphanSweepDeps & { firstPassMs?: number; everyMs?: number }): void {+ let running = false;+ const pass = () => {+ if (running || deps.mode() === "off") return;+ running = true;+ void sweepOrphans(deps)+ .then((report) => (deps.log ?? console.log)(describeOrphanReport(report)))+ .catch((error: unknown) => (deps.warn ?? console.warn)(`orphan sweep: stopped: ${message(error)}`))+ .finally(() => { running = false; });+ };+ setTimeout(pass, deps.firstPassMs ?? FIRST_PASS_MS).unref?.();+ setInterval(pass, deps.everyMs ?? EVERY_MS).unref?.();+}diff --git a/server/host/transcript-mentions.test.ts b/server/host/transcript-mentions.test.tsindex dd0caaf330..2309348daf 100644--- a/server/host/transcript-mentions.test.ts+++ b/server/host/transcript-mentions.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { afterEach, describe, expect, it } from "vitest";-import { threadsMentioning } from "./transcript-mentions.ts";+import { threadsMentioning, transcriptThreads } from "./transcript-mentions.ts";const made: string[] = [];afterEach(() => {@@ -47,4 +47,10 @@ describe("which conversations mention a word", () => {it("reads nothing for no words", async () => {expect((await threadsMentioning("/nowhere", [])).size).toBe(0);});++ it("lists every conversation the transcripts hold, and rejects when they cannot be read", async () => {+ const file = transcripts([["a", { text: "x" }], ["b", { text: "y" }], ["a", { text: "z" }]]);+ expect([...await transcriptThreads(file)].sort()).toEqual(["a", "b"]);+ await expect(transcriptThreads(join(tmpdir(), "no-such-folder-omb", "messages.db"))).rejects.toThrow(/missing/);+ });});diff --git a/server/host/transcript-mentions.ts b/server/host/transcript-mentions.tsindex 1e3b5474a3..81c9feaa11 100644--- a/server/host/transcript-mentions.ts+++ b/server/host/transcript-mentions.ts@@ -10,12 +10,16 @@ const { DatabaseSync } = require("node:sqlite");let db;try {db = new DatabaseSync(workerData.file, { readOnly: true });- const words = workerData.words;- const where = words.map(() => "instr(json, ?) > 0").join(" OR ");- const rows = db.prepare("SELECT thread_id, json FROM messages WHERE " + where).all(...words);- const found = {};- for (const row of rows) for (const word of words) if (row.json.includes(word)) (found[word] ??= new Set()).add(row.thread_id);- parentPort.postMessage({ found: Object.fromEntries(Object.entries(found).map(([word, ids]) => [word, [...ids]])) });+ if (workerData.threads) {+ parentPort.postMessage({ threads: db.prepare("SELECT DISTINCT thread_id FROM messages").all().map((row) => row.thread_id) });+ } else {+ const words = workerData.words;+ const where = words.map(() => "instr(json, ?) > 0").join(" OR ");+ const rows = db.prepare("SELECT thread_id, json FROM messages WHERE " + where).all(...words);+ const found = {};+ for (const row of rows) for (const word of words) if (row.json.includes(word)) (found[word] ??= new Set()).add(row.thread_id);+ parentPort.postMessage({ found: Object.fromEntries(Object.entries(found).map(([word, ids]) => [word, [...ids]])) });+ }} catch (error) {parentPort.postMessage({ error: String(error && error.message || error) });} finally {@@ -26,6 +30,29 @@ try {const MAX_WORDS = 200;const TIMEOUT_MS = 120_000;+/** Runs the worker once; rejects on any failure. */+function ask<T>(workerData: Record<string, unknown>, pick: (reply: Record<string, unknown>) => T | undefined): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const worker = new Worker(WORKER, { eval: true, workerData, execArgv: [] });+ const timer = setTimeout(() => { void worker.terminate(); reject(new Error("reading the transcripts took too long")); }, TIMEOUT_MS);+ worker.once("message", (reply: Record<string, unknown>) => {+ clearTimeout(timer);+ void worker.terminate();+ const value = reply.error === undefined ? pick(reply) : undefined;+ if (value === undefined) reject(new Error(typeof reply.error === "string" ? reply.error : "no answer"));+ else resolve(value);+ });+ worker.once("error", (error) => { clearTimeout(timer); reject(error); });+ worker.once("exit", (exitCode) => { clearTimeout(timer); if (exitCode !== 0) reject(new Error(`stopped (${exitCode})`)); });+ });+}++/** Every conversation the transcripts hold a message of; rejects when they cannot be read. */+export async function transcriptThreads(file: string): Promise<Set<string>> {+ if (!existsSync(file)) throw new Error("the transcripts are missing");+ return new Set(await ask({ file, threads: true }, (reply) => (Array.isArray(reply.threads) ? reply.threads as string[] : undefined)));+}+/** For each word, the conversations whose stored messages hold it. Rejects when the transcripts cannot be read, so a* caller that keeps on failure keeps. */export async function threadsMentioning(file: string, words: readonly string[]): Promise<Map<string, Set<string>>> {@@ -35,18 +62,7 @@ export async function threadsMentioning(file: string, words: readonly string[]):if (!existsSync(file)) throw new Error("the transcripts are missing");for (let at = 0; at < unique.length; at += MAX_WORDS) {const chunk = unique.slice(at, at + MAX_WORDS);- const found = await new Promise<Record<string, string[]>>((resolve, reject) => {- const worker = new Worker(WORKER, { eval: true, workerData: { file, words: chunk }, execArgv: [] });- const timer = setTimeout(() => { void worker.terminate(); reject(new Error("reading the transcripts took too long")); }, TIMEOUT_MS);- worker.once("message", (reply: { found?: Record<string, string[]>; error?: string }) => {- clearTimeout(timer);- void worker.terminate();- if (reply.error !== undefined || !reply.found) reject(new Error(reply.error ?? "no answer"));- else resolve(reply.found);- });- worker.once("error", (error) => { clearTimeout(timer); reject(error); });- worker.once("exit", (exitCode) => { clearTimeout(timer); if (exitCode !== 0) reject(new Error(`stopped (${exitCode})`)); });- });+ const found = await ask({ file, words: chunk }, (reply) => (reply.found && typeof reply.found === "object" ? reply.found as Record<string, string[]> : undefined));for (const word of chunk) result.set(word, new Set(found[word] ?? []));}return result;diff --git a/server/index.ts b/server/index.tsindex ac0a9c84f6..4df76a9b1e 100644--- a/server/index.ts+++ b/server/index.ts@@ -275,7 +275,7 @@ import { computerKindForResource, ManagedDesktopPolicy, type ComputerKind } fromimport { 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 } from "./host/transcript-mentions.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 { 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";@@ -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 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(CLOUD_HOME), () => 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 })) });+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!) });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) });+ 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 });if (enginesRead) {await enginesRead;if (companyShutdown) return;diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex c93520782b..adf5d3cd7d 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -48,8 +48,9 @@ const EXCLUDED = new Set(["box",// The processes this machine's servers started (engine-records.ts), stopped by its next start."engine-runs",- // Deleted conversations' dependency trees on their way out (host/conversation-folder-cleanup.ts).- ".removing",+ // Deleted conversations' dependency trees on their way out, and what the orphan sweep has seen on this disk+ // (host/conversation-folder-cleanup.ts, host/orphan-sweep.ts).+ ".removing", "orphan-sweep.json",// A Team Cloud's engine homes (engine-homes/layout.ts): CLI login homes, each audience's own transcripts and the held// folder, which no admin reads."engine-homes",