Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Delete leftovers: a deleted conversation's or bot's dependency trees and tool results go (#7136)
Milind Sonie01cccd395b2
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex b0337ac786..49f49c6e78 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_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_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 457648c99d..3ba073cf78 100644--- a/server/cloud-home-start.ts+++ b/server/cloud-home-start.ts@@ -48,6 +48,8 @@ const SERVER_ENV_NAMES = new Set(["OMB_CLOUD_EXPORT_ONLY",// The idle task workspaces' dependency sweep (server/host/start-upkeep.ts), off unless set: the Admin may turn it on."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",]);export function serverEnvironmentAllowed(name: string): boolean {return SERVER_ENV_NAMES.has(name) || name.startsWith("LC_");diff --git a/server/host/conversation-folder-cleanup.linux.test.ts b/server/host/conversation-folder-cleanup.linux.test.tsnew file mode 100644index 0000000000..0f4547a4aa--- /dev/null+++ b/server/host/conversation-folder-cleanup.linux.test.ts@@ -0,0 +1,99 @@+// The drain on Linux, as on a Cloud home: the system's GNU rm removes what was moved to .removing, and a process still+// in an entry keeps it. Races a link swapped in for a folder while rm walks the tree. Elsewhere the suite skips.+import { spawn } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { createConversationFolderCleanup, gnuRm, linuxProcessPaths, REMOVING_DIR } from "./conversation-folder-cleanup.ts";++const made: string[] = [];+afterEach(() => {+ for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function sandbox() {+ const root = mkdtempSync(join(tmpdir(), "omb-drain-linux-"));+ made.push(root);+ const dataDir = join(root, "data");+ const outside = join(root, "outside");+ mkdirSync(join(dataDir, REMOVING_DIR), { recursive: true });+ mkdirSync(outside, { recursive: true });+ const logs: string[] = [];+ const cleanup = createConversationFolderCleanup({ dataDir, records: () => ({ bots: [], groups: [] }), drainAfterMs: false, log: (line) => { logs.push(line); }, warn: (line) => { logs.push(line); } });+ return { root, dataDir, outside, cleanup, logs, entry: (name: string) => join(dataDir, REMOVING_DIR, name) };+}++describe.runIf(process.platform === "linux")("the drain on Linux", () => {+ it("uses the system's GNU rm", async () => {+ expect(await gnuRm()).toBe("rm");+ });++ it("never reaches an outside folder through links swapped in while rm walks the tree", async () => {+ const s = sandbox();+ const precious = join(s.outside, "work", "thesis.docx");+ mkdirSync(join(s.outside, "work"), { recursive: true });+ writeFileSync(precious, "work");+ const entry = s.entry("1700000000000-0123456789ab");+ const folders: string[] = [];+ for (let d = 0; d < 300; d++) {+ const folder = join(entry, `pkg${d}`, "lib");+ mkdirSync(folder, { recursive: true });+ for (let i = 0; i < 40; i++) writeFileSync(join(folder, `${i}.js`), "x");+ folders.push(folder);+ }+ // While the drain runs, each folder in turn becomes a link to the outside folder.+ let racing = true, swapped = 0;+ const race = (async () => {+ while (racing) {+ for (const folder of folders) {+ if (!racing) break;+ try { renameSync(folder, `${folder}-x`); symlinkSync(join(s.outside, "work"), folder, "dir"); swapped++; } catch { /* rm took it first */ }+ await new Promise<void>((done) => setImmediate(done));+ }+ }+ })();+ await s.cleanup.drain();+ racing = false;+ await race;+ for (let pass = 0; pass < 3 && existsSync(entry); pass++) await s.cleanup.drain();+ expect(swapped).toBeGreaterThan(0);+ expect(existsSync(precious)).toBe(true);+ expect(readdirSync(join(s.outside, "work"))).toEqual(["thesis.docx"]);+ expect(existsSync(entry)).toBe(false);+ });++ it("leaves an entry a process works in, and finishes it once the process is gone", async () => {+ const s = sandbox();+ const entry = s.entry("1700000000001-0123456789ab");+ mkdirSync(join(entry, "app"), { recursive: true });+ writeFileSync(join(entry, "app", "server.js"), "x");+ const child = spawn("sleep", ["60"], { cwd: join(entry, "app"), stdio: "ignore" });+ try {+ await new Promise<void>((done) => child.once("spawn", () => done()));+ expect((await linuxProcessPaths())?.some((path) => path.startsWith(entry))).toBe(true);+ await s.cleanup.drain();+ expect(existsSync(entry)).toBe(true);+ expect(s.logs.join("\n")).toMatch(/a process still holds something in it/);+ } finally {+ child.kill("SIGKILL");+ await new Promise<void>((done) => (child.exitCode !== null || child.signalCode !== null ? done() : child.once("exit", () => done())));+ }+ await s.cleanup.drain();+ expect(existsSync(entry)).toBe(false);+ });++ it("moves nothing it cannot confirm and renames nothing outside .removing", async () => {+ const s = sandbox();+ const outsideEntry = join(s.outside, "1700000000002-0123456789ab");+ mkdirSync(outsideEntry, { recursive: true });+ writeFileSync(join(outsideEntry, "keep.txt"), "x");+ // A link in .removing under a drain name goes as a link; what it leads to stays.+ symlinkSync(outsideEntry, s.entry("1700000000002-0123456789ab"), "dir");+ renameSync(s.entry("1700000000002-0123456789ab"), s.entry("1700000000003-0123456789ab"));+ await s.cleanup.drain();+ expect(existsSync(join(outsideEntry, "keep.txt"))).toBe(true);+ expect(readdirSync(join(s.dataDir, REMOVING_DIR))).toEqual([]);+ });+});diff --git a/server/host/conversation-folder-cleanup.test.ts b/server/host/conversation-folder-cleanup.test.tsnew file mode 100644index 0000000000..d737f4f364--- /dev/null+++ b/server/host/conversation-folder-cleanup.test.ts@@ -0,0 +1,631 @@+import { execFileSync } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { basename, dirname, join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { spillDir } from "../mcp-gate-config.ts";+import { createConversationFolderCleanup, deleteTimeCleanup, folderMentions, gateResultsName, hookResultsName, indexNames, plainFolderUnder, REMOVING_DIR, type FolderCleanupDeps, type LiveRecords } from "./conversation-folder-cleanup.ts";++/** Hooks into the file calls the cleanup makes, to swap a folder for a link at the worst moment. */+const fsHooks = vi.hoisted(() => ({ renames: 0 } as { renames: number; afterRename?: (n: number, from: string, to: string) => void; beforeReaddir?: (path: string) => void }));+vi.mock("node:fs/promises", async (importOriginal) => {+ const real = await importOriginal<typeof import("node:fs/promises")>();+ return {+ ...real,+ rename: async (from: string, to: string) => { await real.rename(from, to); fsHooks.renames++; fsHooks.afterRename?.(fsHooks.renames, from, to); },+ readdir: (async (path: string, options?: unknown) => { fsHooks.beforeReaddir?.(String(path)); return (real.readdir as (path: string, options?: unknown) => Promise<unknown>)(path, options); }) as typeof real.readdir,+ };+});++const made: string[] = [];+afterEach(() => {+ delete fsHooks.afterRename;+ delete fsHooks.beforeReaddir;+ fsHooks.renames = 0;+ for (const dir of made.splice(0)) {+ try { chmodSync(dir, 0o700); } catch {}+ rmSync(dir, { recursive: true, force: true });+ }+});++function put(path: string, text = "x"): string {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, text);+ return path;+}++type Bots = Array<LiveRecords["bots"][number]>;+type Groups = Array<LiveRecords["groups"][number]>;+const posixOnly = process.platform !== "win32";+const gitAvailable = (() => { try { execFileSync("git", ["--version"], { stdio: "ignore" }); return true; } catch { return false; } })();++function fixture(over: Partial<FolderCleanupDeps> = {}) {+ const sandbox = mkdtempSync(join(tmpdir(), "omb-folder-cleanup-"));+ made.push(sandbox);+ const dataDir = join(sandbox, "data");+ const outside = join(sandbox, "outside");+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(outside, { recursive: true });+ const bots: Bots = [];+ const groups: Groups = [];+ const logs: string[] = [];+ const warnings: string[] = [];+ const deps: FolderCleanupDeps = {+ dataDir,+ records: () => ({ bots, groups }),+ drainAfterMs: false,+ pause: async () => {},+ log: (line) => { logs.push(line); },+ warn: (line) => { warnings.push(line); },+ ...over,+ };+ const cleanup = createConversationFolderCleanup(deps);+ const folder = (bot: string, thread: string) => join(dataDir, "task-workspaces", bot, thread);+ /** A node_modules a package manager made, with its package.json beside it. */+ const install = (at: string) => {+ put(join(at, "package.json"), "{}");+ put(join(at, "node_modules", ".package-lock.json"), "{}");+ put(join(at, "node_modules", "left-pad", "index.js"));+ return join(at, "node_modules");+ };+ /** A conversation folder with the person's files, two installs and look-alikes that are not installs. */+ const work = (bot: string, thread: string) => {+ const at = folder(bot, thread);+ return {+ kept: [+ put(join(at, "report.md"), "the person's report"),+ put(join(at, "app", "src", "index.js")),+ put(join(at, "tool", "Cargo.toml")),+ put(join(at, "tool", "target", "release", "tool")), // a build's output can be the deliverable+ put(join(at, "venv-lookalike", "venv", "notes.txt")), // no pyvenv.cfg: not a venv+ put(join(at, "repo", ".git", "node_modules", "HEAD")), // never walked into .git+ put(join(at, "unmarked", "package.json"), "{}"),+ put(join(at, "unmarked", "node_modules", "hand-written.js")), // no package manager's record+ put(join(at, "alone", "node_modules", ".package-lock.json")), // no package.json beside it+ put(join(at, "analysis", ".venv", "pyvenv.cfg")),+ put(join(at, "analysis", ".venv", "my_analysis.py")), // the person's script at a venv's top: kept+ ],+ gone: [join(at, "app", "node_modules"), join(at, "py", ".venv")],+ fill() {+ install(join(at, "app"));+ put(join(at, "py", ".venv", "pyvenv.cfg"));+ put(join(at, "py", ".venv", "lib", "python3.12", "site-packages", "x.py"));+ put(join(at, "py", ".venv", "bin", "python"));+ return this;+ },+ };+ };+ const removingEmpty = () => !existsSync(join(dataDir, REMOVING_DIR)) || readdirSync(join(dataDir, REMOVING_DIR)).length === 0;+ return { sandbox, dataDir, outside, bots, groups, logs, warnings, cleanup, folder, work, install, removingEmpty };+}+type Fixture = ReturnType<typeof fixture>;++async function deleteAndWait(f: Fixture, ...threads: string[]) {+ f.cleanup.conversationsGone(threads);+ await f.cleanup.idle();+}++describe("the switch", () => {+ it("is off unless a Cloud home sets OMB_CONVERSATION_FOLDER_CLEANUP=on", () => {+ const make = () => "cleanup";+ expect(deleteTimeCleanup({}, true, make)).toBeUndefined();+ expect(deleteTimeCleanup({ OMB_CONVERSATION_FOLDER_CLEANUP: "off" }, true, make)).toBeUndefined();+ expect(deleteTimeCleanup({ OMB_CONVERSATION_FOLDER_CLEANUP: "yes" }, true, make)).toBeUndefined();+ expect(deleteTimeCleanup({ OMB_CONVERSATION_FOLDER_CLEANUP: "on" }, false, make)).toBeUndefined();+ expect(deleteTimeCleanup({ OMB_CONVERSATION_FOLDER_CLEANUP: " On " }, true, make)).toBe("cleanup");+ });+});++describe("a deleted conversation's folder", () => {+ it("loses its package installs and keeps the person's files, build output and every look-alike", async () => {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path), path).toBe(false);+ for (const path of tree.kept) expect(existsSync(path), path).toBe(true);+ expect(f.removingEmpty()).toBe(true);+ expect(f.logs.join("\n")).toMatch(/removed 2 install or tool-result folder/);+ expect(f.logs.join("\n")).toMatch(/kept .*unmarked.node_modules: no package manager's record/);+ expect(f.logs.join("\n")).toMatch(/kept .*alone.node_modules: no package.json beside it/);+ expect(f.logs.join("\n")).toMatch(/kept .*analysis.\.venv: holds my_analysis\.py/);+ });++ it("takes a venv whole when only its top level is a venv's own, the person's files deeper inside included", async () => {+ // An owner decision, stated in the PR: only top-level foreign entries keep a venv.+ const f = fixture();+ const venv = join(f.folder("scout", "t1"), "py", ".venv");+ put(join(venv, "pyvenv.cfg"));+ put(join(venv, "bin", "my_job.sh"), "the person's script");+ put(join(venv, "share", "notes", "plan.md"), "the person's notes");+ await deleteAndWait(f, "t1");+ expect(existsSync(venv)).toBe(false);+ });++ it("loses its full tool results, and keeps a live thread's and the gate's shared fallback folder", async () => {+ const f = fixture();+ put(join(f.dataDir, "tool-results", "t1", "abc.txt"));+ put(join(f.dataDir, "tool-results", "t2", "def.txt"));+ put(join(f.dataDir, "tool-results", "thread", "ghi.txt"));+ f.bots.push({ id: "scout", tasks: [{ threadId: "t2" }] });+ await deleteAndWait(f, "t1", "thread");+ expect(existsSync(join(f.dataDir, "tool-results", "t1"))).toBe(false);+ expect(existsSync(join(f.dataDir, "tool-results", "t2", "def.txt"))).toBe(true);+ expect(existsSync(join(f.dataDir, "tool-results", "thread", "ghi.txt"))).toBe(true);+ });++ it("takes each member's folder of a deleted room conversation", async () => {+ const f = fixture();+ const a = f.work("ann", "room1").fill(), b = f.work("ben", "room1").fill();+ await deleteAndWait(f, "room1");+ for (const path of [...a.gone, ...b.gone]) expect(existsSync(path)).toBe(false);+ for (const path of [...a.kept, ...b.kept]) expect(existsSync(path)).toBe(true);+ });++ it.runIf(gitAvailable)("keeps a node_modules git tracks, and takes one git ignores", async () => {+ const f = fixture();+ const repo = join(f.folder("scout", "t1"), "repo2");+ const vendored = f.install(join(repo, "vendored"));+ const ignored = f.install(join(repo, "ignored"));+ put(join(repo, ".gitignore"), "ignored/node_modules/\n");+ const git = (...args: string[]) => execFileSync("git", ["-c", "core.fsmonitor=false", ...args], { cwd: repo, stdio: "ignore", env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: join(f.sandbox, "no-gitconfig") } });+ git("init", "-q");+ git("add", "-f", "vendored", "ignored/package.json", ".gitignore");+ await deleteAndWait(f, "t1");+ expect(existsSync(join(vendored, "left-pad", "index.js"))).toBe(true);+ expect(existsSync(ignored)).toBe(false);+ expect(f.logs.join("\n")).toMatch(/kept .*vendored.node_modules: git tracks it/);+ });+});++describe("a folder something remaining still uses", () => {+ it("stays whole while its conversation remains anywhere, as a bot's or a room's", async () => {+ const f = fixture();+ const own = f.work("scout", "t1").fill(), room = f.work("scout", "room1").fill();+ f.bots.push({ id: "other", tasks: [{ threadId: "t1" }] });+ f.groups.push({ id: "g1", threadId: "room1" });+ await deleteAndWait(f, "t1", "room1");+ for (const path of [...own.gone, ...room.gone]) expect(existsSync(path)).toBe(true);+ });++ it("stays whole while a fork, a bot or a room works in it, inside it or above it in the data folder", async () => {+ for (const used of [+ (f: Fixture) => f.bots.push({ id: "scout", tasks: [{ threadId: "fork", cwd: f.folder("scout", "t1") }] }),+ (f: Fixture) => f.bots.push({ id: "scout", cwd: join(f.folder("scout", "t1"), "app") }),+ (f: Fixture) => f.bots.push({ id: "scout", cwd: join(f.dataDir, "task-workspaces", "scout") }),+ (f: Fixture) => f.groups.push({ id: "g1", threadId: "room9", pinnedCwd: f.folder("scout", "t1") }),+ (f: Fixture) => f.groups.push({ id: "g1", threadId: "room9", tasks: [{ threadId: "room9", pinnedCwd: f.folder("scout", "t1") }] }),+ ]) {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ used(f);+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(true);+ expect(f.logs.join("\n")).toMatch(/kept .*a remaining conversation works in/);+ }+ });++ it("stays whole while a live folder leads into it through a link, or names it by its real path", async () => {+ const viaLink = fixture();+ const linked = viaLink.work("scout", "t1").fill();+ symlinkSync(viaLink.folder("scout", "t1"), join(viaLink.outside, "alias"), "dir");+ viaLink.bots.push({ id: "other", cwd: join(viaLink.outside, "alias") });+ await deleteAndWait(viaLink, "t1");+ for (const path of linked.gone) expect(existsSync(path)).toBe(true);++ const byRealPath = fixture();+ const named = byRealPath.work("scout", "t1").fill();+ // The data folder reached through a link (on macOS the temporary folder is one): the live cwd names its real path.+ symlinkSync(byRealPath.dataDir, join(byRealPath.sandbox, "data-link"), "dir");+ const aliased = createConversationFolderCleanup({ dataDir: join(byRealPath.sandbox, "data-link"), records: () => ({ bots: [{ id: "other", cwd: realpathSync(byRealPath.folder("scout", "t1")) }], groups: [] }), drainAfterMs: false, pause: async () => {}, log: () => {}, warn: () => {} });+ aliased.conversationsGone(["t1"]);+ await aliased.idle();+ for (const path of named.gone) expect(existsSync(path)).toBe(true);+ });++ it.runIf(process.platform === "darwin" || process.platform === "win32")("stays whole while a live folder or the settings name it in another case", async () => {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ f.bots.push({ id: "other", cwd: join(f.dataDir, "Task-Workspaces", "Scout", "T1") });+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(true);+ const named = fixture({ heldText: () => "C:\\DATA\\TASK-WORKSPACES\\SCOUT\\T1" });+ const other = named.work("scout", "t1").fill();+ await deleteAndWait(named, "t1");+ for (const path of other.gone) expect(existsSync(path)).toBe(true);+ });++ it("stays whole while the settings in memory name it, in any of the ways a path is written, or cannot be read", async () => {+ for (const held of [+ JSON.stringify({ instances: { x: { config: { cli: "/data/task-workspaces/scout/t1/app/node_modules/.bin/agent acp" } } } }),+ "C:\\data\\task-workspaces\\scout\\t1\\app",+ JSON.stringify({ cwd: "C:\\data\\task-workspaces\\scout\\t1" }),+ null,+ ]) {+ const f = fixture({ heldText: () => held });+ const tree = f.work("scout", "t1").fill();+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path), String(held)).toBe(true);+ expect(f.logs.join("\n")).toMatch(held === null ? /the settings cannot be read yet/ : /the settings or a routine name a path in it/);+ }+ });++ it("stays whole while the saved definitions or instructions name it", async () => {+ for (const [file, text] of [+ ["routines.json", JSON.stringify({ routines: [{ prompt: "run node /data/task-workspaces/scout/t1/app/server.js" }] })],+ ["published-pages.json", JSON.stringify([{ path: "C:\\data\\task-workspaces\\scout\\t1\\site" }])],+ [join("bots", "scout", "SOUL.md"), "My project lives in task-workspaces/scout/t1."],+ [join("workspaces", "scout", "memory", "projects.md"), "- app: task-workspaces/scout/t1/app"],+ ] as const) {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ put(join(f.dataDir, file), text);+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path), file).toBe(true);+ expect(f.logs.join("\n")).toMatch(/saved definitions or instructions name a path in it/);+ }+ });++ it("stays whole while a remaining conversation's messages name it, or the transcripts cannot be read", async () => {+ const said = new Map<string, Set<string>>([["t1", new Set(["t2", "t1"])], ["t4", new Set(["gone"])]]);+ const asked: string[][] = [];+ const f = fixture({ mentions: async (words) => { asked.push([...words]); return new Map([...said].filter(([word]) => words.includes(word))); } });+ f.bots.push({ id: "scout", tasks: [{ threadId: "t2" }] });+ const named = f.work("scout", "t1").fill(), unnamed = f.work("scout", "t4").fill();+ await deleteAndWait(f, "t1", "t4");+ for (const path of named.gone) expect(existsSync(path)).toBe(true);+ for (const path of unnamed.gone) expect(existsSync(path)).toBe(false);+ expect(asked).toEqual([["t1", "t4"]]);+ const failing = fixture({ mentions: async () => { throw new Error("database is locked"); } });+ const tree = failing.work("scout", "t1").fill();+ await deleteAndWait(failing, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(true);+ expect(failing.logs.join("\n")).toMatch(/the transcripts cannot be read/);+ });++ it("stays whole while a link in the bot's other folders leads into it, relative or absolute", async () => {+ for (const target of ["relative", "absolute"]) {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ mkdirSync(f.folder("scout", "t2"), { recursive: true });+ symlinkSync(target === "relative" ? join("..", "t1", "app") : join(f.folder("scout", "t1"), "app"), join(f.folder("scout", "t2"), "app-link"), "dir");+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path), target).toBe(true);+ expect(f.logs.join("\n")).toMatch(/a link in the bot's other folders leads into it/);+ }+ });++ it("is not held by a link of its own", async () => {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ symlinkSync(join("..", "app"), join(f.folder("scout", "t1"), "py", "app-link"), "dir");+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(false);+ });++ it("stays whole while a process works inside it", async () => {+ const f = fixture({ processFolders: async () => [join(f.folder("scout", "t1"), "app")] });+ const tree = f.work("scout", "t1").fill();+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(true);+ expect(f.logs.join("\n")).toMatch(/a process works in it/);+ });++ it("stays whole while the server is frozen or a backup is under way, and goes once that ends", async () => {+ let paused: string | null = "frozen after a move";+ const f = fixture({ paused: () => paused });+ const tree = f.work("scout", "t1").fill();+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(true);+ expect(f.logs.join("\n")).toMatch(/kept .* for now: frozen after a move/);+ paused = null;+ await deleteAndWait(f, "t1");+ for (const path of tree.gone) expect(existsSync(path)).toBe(false);+ });++ it("checks again before each move: a conversation that starts working there keeps the rest", async () => {+ let moves = 0;+ const f = fixture({ paused: () => { if (++moves === 1) f.bots.push({ id: "scout", tasks: [{ threadId: "new", cwd: f.folder("scout", "t1") }] }); return null; } });+ const tree = f.work("scout", "t1").fill();+ await deleteAndWait(f, "t1");+ expect(tree.gone.filter(existsSync)).toHaveLength(1);+ expect(f.logs.join("\n")).toMatch(/kept .*a remaining conversation works in/);+ });+});++describe("a deleted bot", () => {+ it("loses the installs of every conversation folder it leaves, and keeps one a remaining conversation uses", async () => {+ const f = fixture();+ const now = f.work("scout", "t1").fill(), before = f.work("scout", "old").fill(), room = f.work("scout", "room1").fill();+ f.groups.push({ id: "g1", threadId: "room1" });+ f.cleanup.botGone("scout");+ await f.cleanup.idle();+ for (const path of [...now.gone, ...before.gone]) expect(existsSync(path)).toBe(false);+ for (const path of [...now.kept, ...before.kept, ...room.gone, ...room.kept]) expect(existsSync(path)).toBe(true);+ });+});++describe("paths", () => {+ it("never follows a link out of the data folder", async () => {+ const f = fixture();+ const victim = put(join(f.outside, "node_modules", "precious.js"));+ f.install(join(f.outside, "work"));+ mkdirSync(join(f.dataDir, "task-workspaces", "scout"), { recursive: true });+ symlinkSync(join(f.outside, "work"), f.folder("scout", "t1"), "dir");+ symlinkSync(join(f.outside, "work"), join(f.dataDir, "task-workspaces", "linked"), "dir");+ mkdirSync(f.folder("scout", "t2"), { recursive: true });+ put(join(f.folder("scout", "t2"), "package.json"));+ symlinkSync(join(f.outside, "node_modules"), join(f.folder("scout", "t2"), "node_modules"), "dir");+ // A link inside a real node_modules goes as a link, never what it points at.+ f.install(f.folder("scout", "t5"));+ symlinkSync(join(f.outside, "node_modules"), join(f.folder("scout", "t5"), "node_modules", "escape"), "dir");+ f.cleanup.conversationsGone(["t1", "t2", "t5"]);+ f.cleanup.botGone("linked");+ await f.cleanup.idle();+ expect(existsSync(victim)).toBe(true);+ expect(existsSync(join(f.outside, "work", "node_modules", "left-pad", "index.js"))).toBe(true);+ expect(existsSync(join(f.folder("scout", "t2"), "node_modules"))).toBe(true);+ expect(existsSync(join(f.folder("scout", "t5"), "node_modules"))).toBe(false);+ expect(f.removingEmpty()).toBe(true);+ });++ it("never reaches a folder a fork worked in through a linked bot folder", async () => {+ const f = fixture();+ const outsideTree = f.install(join(f.outside, "bot", "t1", "app"));+ mkdirSync(join(f.dataDir, "task-workspaces"), { recursive: true });+ symlinkSync(join(f.outside, "bot"), join(f.dataDir, "task-workspaces", "scout"), "dir");+ f.cleanup.conversationsGone(["fork"], [f.folder("scout", "t1")]);+ await f.cleanup.idle();+ expect(existsSync(join(outsideTree, "left-pad", "index.js"))).toBe(true);+ expect(f.removingEmpty()).toBe(true);+ });++ it("puts back what a link swapped in just before the move led to", async () => {+ const f = fixture({+ beforeMove: (path) => {+ // The tree's folder is swapped for a link to a folder outside holding an install of its own.+ const parent = dirname(path);+ renameSync(parent, join(f.sandbox, "moved-away"));+ symlinkSync(join(f.outside, "app"), parent, "dir");+ },+ });+ const outsideTree = f.install(join(f.outside, "app"));+ f.install(join(f.folder("scout", "t1"), "app"));+ await deleteAndWait(f, "t1");+ expect(existsSync(join(outsideTree, "left-pad", "index.js"))).toBe(true);+ expect(f.removingEmpty()).toBe(true);+ expect(f.warnings.join("\n")).toMatch(/it changed since it was checked/);+ });++ it("keeps a tree replaced after it was found", async () => {+ let swapped = false;+ const f = fixture({+ paused: () => {+ if (swapped) return null;+ swapped = true;+ const tree = join(f.folder("scout", "t1"), "app", "node_modules");+ renameSync(tree, join(f.sandbox, "old-tree"));+ put(join(tree, "new.js"));+ return null;+ },+ });+ f.install(join(f.folder("scout", "t1"), "app"));+ await deleteAndWait(f, "t1");+ expect(existsSync(join(f.folder("scout", "t1"), "app", "node_modules", "new.js"))).toBe(true);+ expect(f.warnings.join("\n")).toMatch(/it changed since it was checked/);+ });++ it("never moves a folder whose parent became a link to an outside folder, even when the link goes again", async () => {+ const f = fixture({+ beforeMove: (path) => {+ const parent = dirname(path);+ renameSync(parent, join(f.sandbox, "moved-away"));+ symlinkSync(join(f.outside, "app"), parent, "dir");+ },+ });+ f.install(join(f.outside, "app"));+ const precious = put(join(f.outside, "app", "node_modules", "precious.txt"), "work");+ f.install(join(f.folder("scout", "t1"), "app"));+ fsHooks.afterRename = (n) => { if (n === 1) rmSync(join(f.folder("scout", "t1"), "app")); };+ await deleteAndWait(f, "t1");+ await f.cleanup.drain();+ expect(existsSync(precious)).toBe(true);+ });++ it("keeps what a failed put-back left under a name the drain never takes", async () => {+ const f = fixture();+ const tree = f.install(join(f.folder("scout", "t1"), "app"));+ // Something other than the checked folder arrives (the moved entry replaced), and the way back is gone.+ fsHooks.afterRename = (n, _from, to) => {+ if (n !== 1) return;+ renameSync(to, `${to}-elsewhere`);+ put(join(to, "precious.txt"), "work");+ rmSync(dirname(tree), { recursive: true, force: true });+ };+ await deleteAndWait(f, "t1");+ await f.cleanup.drain();+ const kept = readdirSync(join(f.dataDir, REMOVING_DIR)).filter((name) => !name.endsWith("-elsewhere"));+ expect(kept).toHaveLength(1);+ expect(kept[0]).toMatch(/^check-\d+-[0-9a-f]{12}$/);+ expect(existsSync(join(f.dataDir, REMOVING_DIR, kept[0]!, "precious.txt"))).toBe(true);+ expect(f.warnings.join("\n")).toMatch(/COULD NOT PUT IT BACK/);+ });++ it("never walks into a folder swapped for a link while the drain lists it (the Node walk, where GNU rm is not there)", async () => {+ const f = fixture({ systemRm: async () => null });+ const precious = put(join(f.outside, "work", "thesis.docx"), "work");+ f.install(join(f.folder("scout", "t1"), "app"));+ put(join(f.folder("scout", "t1"), "app", "node_modules", "left-pad", "lib", "a.js"));+ let swapped = false;+ fsHooks.beforeReaddir = (path) => {+ if (!swapped && path.includes(REMOVING_DIR) && path.endsWith(join("left-pad", "lib"))) {+ swapped = true;+ renameSync(path, `${path}-x`);+ symlinkSync(join(f.outside, "work"), path, "dir");+ }+ };+ await deleteAndWait(f, "t1");+ expect(swapped).toBe(true);+ expect(existsSync(precious)).toBe(true);+ });++ it("leaves an entry a process still holds something in, and finishes it once none does", async () => {+ let held: string[] = [];+ const f = fixture({ processPaths: async () => held });+ f.install(join(f.folder("scout", "t1"), "app"));+ fsHooks.afterRename = (_n, _from, to) => { if (!to.includes("check-")) held = [join(to, "left-pad", "index.js")]; };+ await deleteAndWait(f, "t1");+ expect(f.removingEmpty()).toBe(false);+ expect(f.logs.join("\n")).toMatch(/left .* for now: a process still holds something in it/);+ held = [];+ await f.cleanup.drain();+ expect(f.removingEmpty()).toBe(true);+ });++ it("refuses a .removing that is a link, for moves and for finishing an earlier pass", async () => {+ const f = fixture();+ const tree = f.work("scout", "t1").fill();+ const kept = put(join(f.outside, "1700000000000-0123456789ab", "precious.txt"));+ symlinkSync(f.outside, join(f.dataDir, REMOVING_DIR), "dir");+ await deleteAndWait(f, "t1");+ await f.cleanup.drain();+ for (const path of tree.gone) expect(existsSync(path)).toBe(true);+ expect(existsSync(kept)).toBe(true);+ expect(f.warnings.join("\n")).toMatch(/not a plain folder/);+ });++ it("finishes only its own entries in .removing", async () => {+ const f = fixture();+ const mine = put(join(f.dataDir, REMOVING_DIR, "1700000000000-0123456789ab", "x.js"));+ const other = put(join(f.dataDir, REMOVING_DIR, "notes", "keep.txt"));+ await f.cleanup.drain();+ expect(existsSync(dirname(mine))).toBe(false);+ expect(existsSync(other)).toBe(true);+ });++ it("ignores an id that is not a plain name, wherever it comes in", async () => {+ const f = fixture();+ const victim = f.install(f.dataDir);+ f.install(join(f.dataDir, "task-workspaces", "scout"));+ put(join(f.dataDir, "tool-results-x", "keep.txt"));+ mkdirSync(join(f.dataDir, "x", "y"), { recursive: true });+ const deeper = f.install(join(f.folder("scout", "t1"), "app"));+ f.cleanup.conversationsGone(["..", "../..", "a/b", "", "t1/../..", "a\\b"]);+ f.cleanup.conversationsGone(["t9"], [join(f.dataDir, "task-workspaces", "..", "x", "y"), join(f.dataDir, "task-workspaces", "scout"), "relative/path", join(f.dataDir, "task-workspaces", "scout", "t1", "app")]);+ f.cleanup.botGone("..");+ f.cleanup.botGone("a/b");+ f.cleanup.orphans({ workspaces: [f.dataDir, join(f.dataDir, "task-workspaces", "scout")], results: ["..", "a/b"] });+ await f.cleanup.idle();+ expect(existsSync(join(victim, "left-pad", "index.js"))).toBe(true);+ expect(existsSync(join(f.dataDir, "task-workspaces", "scout", "node_modules", "left-pad", "index.js"))).toBe(true);+ // A fork that worked deeper inside a conversation folder hands over no folder: only a whole one is taken.+ expect(existsSync(join(deeper, "left-pad", "index.js"))).toBe(true);+ expect(existsSync(join(f.dataDir, "tool-results-x", "keep.txt"))).toBe(true);+ // Turned away where they come in: nothing was even looked at.+ expect(f.logs.filter((line) => line.includes("kept"))).toEqual([]);+ expect(f.warnings).toEqual([]);+ expect(f.cleanup.whyKept(join(f.dataDir, "task-workspaces", "scout"))).toBe("not a conversation folder");+ expect(f.cleanup.whyKept(join(f.dataDir, "task-workspaces", "sc out", "t1"))).toBe("not a conversation folder");+ expect(f.cleanup.whyKept(join(f.dataDir, "task-workspaces", "scout", "t1", "x"))).toBe("not a conversation folder");+ });++ it("knows a plain folder: inside its root, the root inside the data folder, no link on the way, really inside", () => {+ const f = fixture();+ const root = join(f.dataDir, "task-workspaces");+ mkdirSync(join(root, "scout", "t1"), { recursive: true });+ mkdirSync(join(f.outside, "t9"), { recursive: true });+ symlinkSync(join(f.outside, "t9"), join(root, "scout", "t9"), "dir");+ expect(plainFolderUnder(f.dataDir, root, join(root, "scout", "t1"))).toBe(true);+ expect(plainFolderUnder(f.dataDir, f.outside, join(f.outside, "t9"))).toBe(false); // root outside the data folder+ expect(plainFolderUnder(f.dataDir, root, join(f.dataDir, "other"))).toBe(false); // outside the root+ expect(plainFolderUnder(f.dataDir, root, root)).toBe(false); // the root itself+ expect(plainFolderUnder(f.dataDir, root, join(root, "scout", "t9"))).toBe(false); // a link+ expect(plainFolderUnder(f.dataDir, root, join(root, "scout", "missing"))).toBe(false);+ expect(plainFolderUnder(f.dataDir, root, join(root, "scout", "t9", "inner"))).toBe(false); // through a link+ // Each check on its own: a root around the data folder, a folder outside the root that exists, a link that leads+ // back into the data folder.+ mkdirSync(join(f.dataDir, "other"), { recursive: true });+ expect(plainFolderUnder(f.dataDir, f.sandbox, join(f.dataDir, "other"))).toBe(false);+ expect(plainFolderUnder(f.dataDir, root, join(f.dataDir, "other"))).toBe(false);+ symlinkSync(join(f.dataDir, "other"), join(root, "scout", "t8"), "dir");+ expect(plainFolderUnder(f.dataDir, root, join(root, "scout", "t8"))).toBe(false);+ });++ it("names a folder's mentions with both separators and as JSON writes a backslash", () => {+ expect(folderMentions("scout", "t1")).toEqual(["task-workspaces/scout/t1", "task-workspaces\\scout\\t1", "task-workspaces\\\\scout\\\\t1"]);+ });++ it("names tool results' folders as the MCP gate does", () => {+ for (const id of ["t1", "a".repeat(81), "x.y", "bad/../id", ""]) expect(gateResultsName(id)).toBe(basename(spillDir(id)));+ });++ it("keeps tool results kept under a name a remaining thread's results share", async () => {+ const f = fixture();+ const short = "a".repeat(80), long = `${short}b`;+ expect(gateResultsName(long)).toBe(short);+ expect(hookResultsName("t1")).toBe("t1");+ put(join(f.dataDir, "tool-results", short, "r.txt"));+ f.bots.push({ id: "scout", tasks: [{ threadId: long }] });+ await deleteAndWait(f, short);+ expect(existsSync(join(f.dataDir, "tool-results", short, "r.txt"))).toBe(true);+ });+});++describe("a git index", () => {+ it("reads v2 entries and refuses what it cannot tell", () => {+ const entry = (name: string) => {+ const length = Math.ceil((62 + name.length + 1) / 8) * 8;+ const out = Buffer.alloc(length);+ out.writeUInt16BE(Math.min(name.length, 0xfff), 60);+ out.write(name, 62, "utf8");+ return out;+ };+ const index = (version: number, names: string[], extension?: string) => {+ const header = Buffer.alloc(12);+ header.write("DIRC", 0, "latin1");+ header.writeUInt32BE(version, 4);+ header.writeUInt32BE(names.length, 8);+ const ext = extension ? Buffer.concat([Buffer.from(extension, "latin1"), Buffer.from([0, 0, 0, 0])]) : Buffer.alloc(0);+ return Buffer.concat([header, ...names.map(entry), ext, Buffer.alloc(20)]);+ };+ expect(indexNames(index(2, ["a.txt", "app/node_modules/x/index.js"]), "app/node_modules")).toBe(true);+ expect(indexNames(index(2, ["a.txt", "app/node_modules_old/x.js", "other/app/node_modules/x.js"]), "app/node_modules")).toBe(false);+ expect(indexNames(index(4, ["a.txt"]), "app/node_modules")).toBeNull();+ expect(indexNames(index(2, ["a.txt"], "link"), "app/node_modules")).toBeNull();+ expect(indexNames(index(2, ["a.txt"], "sdir"), "app/node_modules")).toBeNull();+ expect(indexNames(Buffer.from("not an index"), "x")).toBeNull();+ });+});++describe("a crash in the middle", () => {+ it("leaves the person's files and a part of the tree in .removing, which the next start finishes", async () => {+ let crash = true;+ // The Node walk, paced (a Cloud home's GNU rm runs in its own process).+ const f = fixture({ systemRm: async () => null, pause: async () => { if (crash) throw new Error("power cut"); } });+ const tree = f.work("scout", "t1");+ f.install(join(f.folder("scout", "t1"), "app"));+ for (let i = 0; i < 5_000; i++) put(join(f.folder("scout", "t1"), "app", "node_modules", `p${i % 50}`, `${i}.js`));+ await deleteAndWait(f, "t1");+ expect(existsSync(tree.gone[0]!)).toBe(false);+ for (const path of tree.kept) expect(existsSync(path)).toBe(true);+ expect(f.removingEmpty()).toBe(false);+ expect(f.warnings.join("\n")).toMatch(/power cut/);+ crash = false;+ const restarted = createConversationFolderCleanup({ dataDir: f.dataDir, records: () => ({ bots: [], groups: [] }), drainAfterMs: 0, pause: async () => {}, log: () => {}, systemRm: async () => null });+ await new Promise((done) => setTimeout(done, 0));+ await restarted.idle();+ expect(f.removingEmpty()).toBe(true);+ for (const path of tree.kept) expect(existsSync(path)).toBe(true);+ });++ it.runIf(posixOnly && process.getuid?.() !== 0)("removes a tree holding folders without write permission", async () => {+ const f = fixture();+ const tree = f.install(join(f.folder("scout", "t1"), "app"));+ put(join(tree, "locked", "inner", "file.js"));+ chmodSync(join(tree, "locked", "inner"), 0o500);+ chmodSync(join(tree, "locked"), 0o500);+ await deleteAndWait(f, "t1");+ expect(existsSync(tree)).toBe(false);+ expect(f.removingEmpty()).toBe(true);+ });+});diff --git a/server/host/conversation-folder-cleanup.ts b/server/host/conversation-folder-cleanup.tsnew file mode 100644index 0000000000..2a371df9f4--- /dev/null+++ b/server/host/conversation-folder-cleanup.ts@@ -0,0 +1,702 @@+// What a deleted conversation or bot leaves in its folders that is nobody's work: the package installs in its+// conversation folders (task-workspaces/<bot>/<thread>: a node_modules a package manager made, a Python venv holding+// only a venv's own folders), which Files never carries and an install makes again, and the full tool results kept for+// it (tool-results/<thread>). A build's output (a Rust target folder) is not among them: it can be the program the+// person asked for, and Files brings it to them. The files the bot made for the person stay: the delete dialogs+// promise them ("Generated project files are kept"), Files lists every conversation folder that holds a file and+// brings it to the person's computer, and the bot's other conversations are told where these folders are. Event logs+// and engine sessions go with the conversation elsewhere (store.ts, delete-leftovers.ts).+//+// What counts as an install, and nothing else: a node_modules with a package manager's own marker in it and a+// package.json beside it, that git does not track; a venv (.venv or venv) with a pyvenv.cfg whose top level holds+// only a venv's own entries. Anything else, or anything that cannot be read, stays, with a line in the log.+//+// Safety: a folder is touched only when nothing that remains can use it. Its conversation is no remaining bot's or+// room's (a room's turns use a member bot's conversation folder under the room's own id); no remaining bot,+// conversation or room works in it, inside it or in a folder between it and the data folder (a fork keeps working in+// its source's folder), compared as the file system names it (case-insensitively on macOS and Windows); no link in+// the bot's other folders leads into it; no process (Linux) works in it, holds a file open or has one mapped there;+// and neither the saved definitions and instructions nor a remaining conversation's messages name it. While any of+// those cannot be read, it stays. That is checked again just before each move, and nothing moves while the server is+// frozen or a backup is under way.+// Nothing is reached through a link: every folder from the data folder down must be a real folder, and what is moved+// must be the very folder that was checked. It lands first under .removing/check-…, a name the drain never takes, is+// compared there by device and inode, and only then gets the drain's name; a mismatch is moved back, or kept under+// check-… when that fails. The drain leaves an entry a process is still in, and on Linux removes it with the system's+// GNU rm (one file system, no link followed), elsewhere with a Node walk that re-checks each folder after listing it.+// A crash leaves either the whole tree in place or a part of it in .removing, which the next start finishes. Nothing+// runs on the delete's own call: the work is queued and paced, rm runs at low priority in its own process, and the+// transcripts are read in a worker, so a tree of hundreds of thousands of files never holds a turn or the event loop.+// Wired on a Cloud home only, and only with OMB_CONVERSATION_FOLDER_CLEANUP=on (off by default).+import { execFile } from "node:child_process";+import { randomBytes } from "node:crypto";+import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rmdir, unlink } from "node:fs/promises";+import { lstatSync, readdirSync, realpathSync } from "node:fs";+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";++export const REMOVING_DIR = ".removing";+export const FOLDER_CLEANUP_ENV = "OMB_CONVERSATION_FOLDER_CLEANUP";++/** The delete-time cleanup, on a Cloud home with OMB_CONVERSATION_FOLDER_CLEANUP=on only (off by default, so a delete+ * behaves as before until it has been proven on a test Cloud); undefined otherwise. */+export function deleteTimeCleanup<T>(env: NodeJS.ProcessEnv, cloudHome: boolean, make: () => T): T | undefined {+ return cloudHome && env[FOLDER_CLEANUP_ENV]?.trim().toLowerCase() === "on" ? make() : undefined;+}+const ID = /^[\w-]{1,128}$/;+const RETIRED = /^\d{1,16}-[0-9a-f]{12}$/;+const MAX_DEPTH = 8;+const MAX_SCANNED = 200_000;+const MAX_LINK_SCAN = 50_000;+const MAX_HELD_FILE_BYTES = 16 * 1024 ** 2;+const MAX_GIT_INDEX_BYTES = 64 * 1024 ** 2;+const YIELD_EVERY = 256;+const PAUSE_EVERY = 4_096;+const PAUSE_MS = 20;+const DRAIN_AFTER_START_MS = 60_000;+/** A package manager's own record inside a node_modules it made (npm, pnpm, Yarn 1, Yarn 2+). */+const NODE_MARKERS = [".package-lock.json", ".modules.yaml", ".yarn-integrity", ".yarn-state.yml"];+/** What a venv made by venv, virtualenv or uv holds at its top level. */+const VENV_ENTRIES = new Set(["bin", "Scripts", "lib", "lib64", "Lib", "include", "Include", "share", "pyvenv.cfg", ".gitignore", "CACHEDIR.TAG"]);+/** Folders a link scan of the bot's other folders does not walk into: installs and history. */+const LINK_SCAN_SKIP = new Set(["node_modules", ".git", ".venv", "venv"]);++type Folder = string | null | undefined;+type TaskLike = { threadId: string; cwd?: Folder; pinnedCwd?: Folder };+/** The parts of the store's records this needs: every remaining conversation and every folder one works in. */+export interface LiveRecords {+ readonly bots: ReadonlyArray<{ id: string; threadId?: string; cwd?: Folder; tasks?: ReadonlyArray<TaskLike> }>;+ readonly groups: ReadonlyArray<{ id: string; threadId?: string; cwd?: Folder; pinnedCwd?: Folder; tasks?: ReadonlyArray<TaskLike> }>;+}++export function liveThreadIds(records: LiveRecords): Set<string> {+ const ids = new Set<string>();+ for (const owner of [...records.bots, ...records.groups]) {+ if (owner.threadId) ids.add(owner.threadId);+ for (const task of owner.tasks ?? []) ids.add(task.threadId);+ }+ return ids;+}++export function liveFolders(records: LiveRecords): string[] {+ const folders: Folder[] = [];+ for (const bot of records.bots) folders.push(bot.cwd, ...(bot.tasks ?? []).flatMap((task) => [task.cwd, task.pinnedCwd]));+ for (const group of records.groups) folders.push(group.cwd, group.pinnedCwd, ...(group.tasks ?? []).flatMap((task) => [task.cwd, task.pinnedCwd]));+ return folders.filter((folder): folder is string => typeof folder === "string" && isAbsolute(folder));+}++/** The folder names a thread's full tool results are kept under: the hook's (index.ts) and the MCP gate's+ * (mcp-gate-config.ts spillDir). */+export const hookResultsName = (threadId: string) => threadId.replace(/[^\w.-]/g, "_");+export const gateResultsName = (threadId: string) => threadId.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 80) || "thread";++/** Paths compared as the file system compares them: macOS's and Windows' default volumes ignore case. */+const FOLDS = process.platform === "darwin" || process.platform === "win32";+const fold = (path: string) => (FOLDS ? path.toLowerCase() : path);+export const inside = (root: string, path: string) => {+ const rel = relative(fold(root), fold(path));+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));+};+/** `inside` for paths already absolute and normalized (resolve, realpath): a string compare, for the checks that run+ * over every live folder. */+const within = (root: string, path: string) => {+ const a = fold(root), b = fold(path);+ return a === b || b.startsWith(a.endsWith(sep) ? a : a + sep);+};+function real(path: string): string | null {+ try { return realpathSync.native(path); } catch { return null; }+}+function realFolder(path: string): boolean {+ try { return lstatSync(path).isDirectory(); } catch { return false; }+}++/** Whether `path` is strictly inside `root`, `root` is inside `dataDir`, every folder from `dataDir` down to `path`+ * (itself included) is a real folder, not a link, and where `path` really is stays inside where `dataDir` really is. */+export function plainFolderUnder(dataDir: string, root: string, path: string): boolean {+ if (!inside(dataDir, root) || !inside(root, path) || fold(resolve(path)) === fold(resolve(root))) return false;+ let at = resolve(dataDir);+ for (const part of relative(resolve(dataDir), resolve(path)).split(sep)) {+ if (!part || part === "..") return false;+ at = join(at, part);+ if (!realFolder(at)) return false;+ }+ const realData = real(dataDir), realPath = real(path);+ return Boolean(realData && realPath && inside(realData, realPath));+}++/** The ways a text may name a conversation folder: its path with either separator, as JSON writes it, and its id. */+export function folderMentions(botId: string, threadId: string): string[] {+ return [`task-workspaces/${botId}/${threadId}`, `task-workspaces\\${botId}\\${threadId}`, `task-workspaces\\\\${botId}\\\\${threadId}`];+}++export interface FolderCleanupDeps {+ dataDir: string;+ records(): LiveRecords;+ /** What the server holds in memory that may name a path (its settings, routines, …); null while not readable yet,+ * and then every folder stays. The saved definitions and instructions on disk are read as well. */+ heldText?(): string | null;+ /** For each word, the remaining conversations whose messages hold it (transcript-mentions.ts); a rejection keeps. */+ mentions?(words: readonly string[]): Promise<Map<string, ReadonlySet<string>>>;+ /** Why nothing may move now (frozen after a move, a backup being made or restored), else null. Asked before each move+ * and before the start's leftovers are finished. */+ paused?(): string | null;+ /** Every path the processes work in, hold open or have mapped (linuxProcessPaths), or null where that cannot be read. */+ processFolders?(): Promise<readonly string[] | null>;+ /** When the start's leftover .removing is finished; false: only on request. Default: a minute after start. */+ drainAfterMs?: number | false;+ pause?(ms: number): Promise<void>;+ /** Every path this machine's processes work in, hold open or have mapped (linuxProcessPaths), or null where that+ * cannot be read; the drain leaves an entry one of them is in. */+ processPaths?(): Promise<readonly string[] | null>;+ /** The system's GNU rm, or null to walk in Node (gnuRm by default). */+ systemRm?(): Promise<string | null>;+ /** For tests: runs between the last check of a tree and its move. */+ beforeMove?(path: string): void;+ log?(line: string): void;+ warn?(line: string): void;+}++/** `name`: a folder name under tool-results, which is a thread id for a deleted conversation. */+type Job = { kind: "workspace"; folder: string } | { kind: "results"; name: string };+export interface CleanupTotals { folders: number; entries: number; bytes: number; failed: number }+/** An install found in a conversation folder, with the identity it had when found. */+export interface FoundTree { path: string; dev: number; ino: number }++const message = (error: unknown) => (error instanceof Error ? error.message : String(error));+const code = (error: unknown) => (error as NodeJS.ErrnoException | undefined)?.code;++/** Every path this machine's processes work in, hold open or have mapped, from /proc; null where that cannot be read. */+export async function linuxProcessPaths(): Promise<string[] | null> {+ if (process.platform !== "linux") return null;+ let pids: string[];+ try { pids = (await readdir("/proc")).filter((name) => /^\d+$/.test(name)); } catch { return null; }+ const paths = new Set<string>();+ for (const pid of pids) {+ try { paths.add(await readlink(`/proc/${pid}/cwd`)); } catch { /* gone, or another user's */ }+ for (const fd of await readdir(`/proc/${pid}/fd`).catch(() => [] as string[])) {+ const target = await readlink(`/proc/${pid}/fd/${fd}`).catch(() => "");+ if (target.startsWith("/")) paths.add(target.replace(/ \(deleted\)$/, ""));+ }+ const maps = await readFile(`/proc/${pid}/maps`, "utf8").catch(() => "");+ for (const line of maps.split("\n")) {+ const at = line.indexOf(" /");+ if (at > 0) paths.add(line.slice(at + 1).replace(/ \(deleted\)$/, ""));+ }+ }+ return [...paths];+}++/** The system's GNU rm (coreutils, as in the Cloud image's Debian base), found once; null elsewhere (macOS, Windows,+ * busybox), where the cleanup walks in Node instead. */+let gnuRmFound: Promise<string | null> | undefined;+export function gnuRm(): Promise<string | null> {+ return gnuRmFound ??= process.platform !== "linux" ? Promise.resolve(null) : new Promise((done) => {+ execFile("rm", ["--version"], { timeout: 10_000, env: { PATH: process.env.PATH ?? "/usr/bin:/bin", LANG: "C" } }, (error, stdout) => {+ done(!error && /GNU coreutils/.test(String(stdout)) ? "rm" : null);+ });+ });+}++/** `nice rm -rf --one-file-system -- entry`: true once the entry is gone. */+function runRm(rm: string, entry: string): Promise<boolean> {+ return new Promise((done) => {+ execFile("nice", ["-n", "19", rm, "-rf", "--one-file-system", "--", entry], { timeout: 30 * 60_000, env: { PATH: process.env.PATH ?? "/usr/bin:/bin", LANG: "C" } }, () => {+ lstat(entry).then(() => done(false), () => done(true));+ });+ });+}++/** Makes a moved tree's folders writable for its owner (GNU chmod never follows a link it meets), for rm's second go. */+function chmodTree(entry: string): Promise<void> {+ return new Promise((done) => {+ execFile("chmod", ["-R", "u+rwx", "--", entry], { timeout: 10 * 60_000, env: { PATH: process.env.PATH ?? "/usr/bin:/bin", LANG: "C" } }, () => done());+ });+}++/** Whether a git index (v2 or v3) names a file under `rel` (a path from the repository's top, `/`-separated); null when+ * that cannot be told (v4's compressed names, a split or sparse index, a large or unreadable index). */+async function gitTracks(indexFile: string, rel: string): Promise<boolean | null> {+ let data: Buffer;+ try {+ const stats = await lstat(indexFile);+ if (!stats.isFile()) return null;+ if (stats.size > MAX_GIT_INDEX_BYTES) return null;+ data = await readFile(indexFile);+ } catch (error) {+ return code(error) === "ENOENT" ? false : null;+ }+ return indexNames(data, rel);+}++/** Reads a git index's entries (v2, v3) and its extensions; see gitTracks. */+export function indexNames(data: Buffer, rel: string): boolean | null {+ if (data.length < 12 || data.toString("latin1", 0, 4) !== "DIRC") return null;+ const version = data.readUInt32BE(4);+ if (version !== 2 && version !== 3) return null;+ const count = data.readUInt32BE(8);+ const end = data.length - 20; // the trailing checksum+ let at = 12, tracked = false;+ for (let n = 0; n < count; n++) {+ if (at + 62 > end) return null;+ const flags = data.readUInt16BE(at + 60);+ const extended = version === 3 && (flags & 0x4000) !== 0;+ const nameAt = at + 62 + (extended ? 2 : 0);+ const nul = data.indexOf(0, nameAt);+ if (nul < 0 || nul > end) return null;+ const name = data.toString("utf8", nameAt, nul);+ if (name === rel || name.startsWith(`${rel}/`)) tracked = true;+ // An entry is padded with 1 to 8 NULs so its length from its start is a multiple of 8.+ at += Math.ceil((nameAt - at + (nul - nameAt) + 1) / 8) * 8;+ }+ while (at + 8 <= end) {+ const signature = data.toString("latin1", at, at + 4);+ if (signature === "link" || signature === "sdir") return null;+ at += 8 + data.readUInt32BE(at + 4);+ }+ return tracked;+}++export function createConversationFolderCleanup(deps: FolderCleanupDeps) {+ const dataDir = resolve(deps.dataDir);+ const tasksRoot = join(dataDir, "task-workspaces");+ const resultsRoot = join(dataDir, "tool-results");+ const removing = join(dataDir, REMOVING_DIR);+ const log = deps.log ?? ((line: string) => console.log(line));+ const warn = deps.warn ?? ((line: string) => console.warn(line));+ const pause = deps.pause ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms)));+ const queued = new Map<string, Job>();+ let running: Promise<void> = Promise.resolve();+ let active = false;+ let steps = 0;++ async function step(): Promise<void> {+ steps++;+ if (steps % PAUSE_EVERY === 0) await pause(PAUSE_MS);+ else if (steps % YIELD_EVERY === 0) await new Promise<void>((done) => setImmediate(done));+ }++ /** One pass's view of what remains, resolved once: the live conversations and where they work, as written and as the+ * file system names them. Records are read again before each move; a folder's real path only once per pass. */+ function batchView() {+ const realOf = new Map<string, string | null>();+ const resolved = (path: string) => {+ if (!realOf.has(path)) realOf.set(path, real(path));+ return realOf.get(path) ?? null;+ };+ const now = () => {+ const records = deps.records();+ const folders: string[] = [];+ for (const used of new Set(liveFolders(records))) {+ folders.push(resolve(used));+ const found = resolved(used);+ if (found) folders.push(found);+ }+ return { live: liveThreadIds(records), folders };+ };+ /** Resolves every live folder off the event loop first, a few at a time, so the checks before each move only read. */+ const warm = async () => {+ const pending = [...new Set(liveFolders(deps.records()))].filter((path) => !realOf.has(path));+ for (let at = 0; at < pending.length; at += 64) {+ await Promise.all(pending.slice(at, at + 64).map(async (path) => {+ realOf.set(path, await realpath(path).catch(() => null));+ }));+ }+ if (!realOf.has(dataDir)) realOf.set(dataDir, await realpath(dataDir).catch(() => null));+ };+ return { now, resolved, warm, links: new Map<string, Promise<Array<{ from: string; leads: string[] }> | null>>() };+ }+ type View = ReturnType<typeof batchView>;++ /** The saved definitions and instructions, which name paths in settings and prose: every JSON file at the top of the+ * data folder, each bot's SOUL.md and its memory files. Null when one cannot be read. */+ async function savedText(): Promise<string | null> {+ const parts: string[] = [];+ const take = async (path: string) => {+ const stats = await lstat(path).catch(() => null);+ if (!stats || !stats.isFile()) return true;+ if (stats.size > MAX_HELD_FILE_BYTES) return false;+ try { parts.push(await readFile(path, "utf8")); return true; } catch { return false; }+ };+ const names = async (dir: string) => (realFolder(dir) ? readdir(dir).catch(() => [] as string[]) : []);+ for (const name of await names(dataDir)) if (name.endsWith(".json") && !await take(join(dataDir, name))) return null;+ for (const bot of await names(join(dataDir, "bots"))) if (!await take(join(dataDir, "bots", bot, "SOUL.md"))) return null;+ const walk = async (dir: string, depth: number): Promise<boolean> => {+ for (const name of await names(dir)) {+ const path = join(dir, name);+ if (realFolder(path)) { if (depth < 4 && !await walk(path, depth + 1)) return false; }+ else if (name.endsWith(".md") && !await take(path)) return false;+ }+ return true;+ };+ for (const workspace of await names(join(dataDir, "workspaces"))) {+ if (!await take(join(dataDir, "workspaces", workspace, "MEMORY.md"))) return null;+ if (!await walk(join(dataDir, "workspaces", workspace, "memory"), 0)) return null;+ }+ return parts.join("\n");+ }++ /** The links in a bot's own folder and its conversation folders, each with where it leads (a relative one resolved+ * from its folder): read once per pass for each bot; null when they were too many to look through. */+ async function botLinks(botId: string, view: View): Promise<Array<{ from: string; leads: string[] }> | null> {+ let scanned = 0;+ const links: Array<{ from: string; leads: string[] }> = [];+ const walk = async (dir: string, depth: number): Promise<boolean> => {+ let entries;+ try { entries = await readdir(dir, { withFileTypes: true }); } catch { return true; }+ for (const entry of entries) {+ if (++scanned > MAX_LINK_SCAN) return false;+ await step();+ const path = join(dir, entry.name);+ if (entry.isSymbolicLink()) {+ let target: string | null = null;+ try { target = resolve(dir, await readlink(path)); } catch { /* unreadable: its real path below, if any */ }+ links.push({ from: path, leads: [target, view.resolved(path)].filter((one): one is string => Boolean(one)) });+ } else if (entry.isDirectory() && depth < MAX_DEPTH && !LINK_SCAN_SKIP.has(entry.name)) {+ if (!await walk(path, depth + 1)) return false;+ }+ }+ return true;+ };+ const places = [join(dataDir, "workspaces", botId), ...readdirNames(join(tasksRoot, botId)).filter((name) => ID.test(name)).map((name) => join(tasksRoot, botId, name))];+ for (const place of places) if (realFolder(place) && !await walk(place, 0)) return null;+ return links;+ }++ /** Whether a link outside `folder`, in the bot's own folder or its other conversation folders, leads into it; null+ * when they were too many to look through. */+ async function linkedInto(botId: string, folder: string, view: View): Promise<boolean | null> {+ let found = view.links.get(botId);+ if (!found) view.links.set(botId, found = botLinks(botId, view));+ const links = await found;+ if (!links) return null;+ const own = [folder, view.resolved(folder)].filter((path): path is string => Boolean(path));+ return links.some((link) => !inside(folder, link.from) && link.leads.some((lead) => own.some((mine) => inside(mine, lead))));+ }++ /** What in the records still uses this conversation folder, or null: the quick check, made again before each move. */+ function heldByRecords(folder: string, view: View): string | null {+ const [botId, threadId, ...rest] = relative(tasksRoot, folder).split(sep);+ if (!botId || !threadId || rest.length || !ID.test(botId) || !ID.test(threadId)) return "not a conversation folder";+ if (!plainFolderUnder(dataDir, tasksRoot, folder)) return "not a plain folder in task-workspaces";+ const { live, folders } = view.now();+ if (live.has(threadId)) return "its conversation remains";+ const own = [folder, view.resolved(folder)].filter((path): path is string => Boolean(path));+ const tops = [dataDir, view.resolved(dataDir)].filter((path): path is string => Boolean(path));+ for (const path of folders) {+ // In the folder or inside it, or between it and the data folder (which sees it whole).+ if (own.some((mine) => within(mine, path) || (within(path, mine) && tops.some((top) => within(top, path))))) return `a remaining conversation works in ${path}`;+ }+ const held = deps.heldText ? deps.heldText() : "";+ if (held === null) return "the settings cannot be read yet";+ if (folderMentions(botId, threadId).some((fragment) => fold(held).includes(fold(fragment)))) return "the settings or a routine name a path in it";+ return null;+ }++ /** Everything that may still use this conversation folder, or null: the records, the saved definitions and+ * instructions, links from the bot's other folders, processes and the remaining conversations' messages. */+ async function heldBy(folder: string, view: View, mentioned: ReadonlyMap<string, ReadonlySet<string>> | null): Promise<string | null> {+ const quick = heldByRecords(folder, view);+ if (quick) return quick;+ const [botId, threadId] = relative(tasksRoot, folder).split(sep) as [string, string];+ const saved = await savedText();+ if (saved === null) return "the saved definitions cannot be read";+ if (folderMentions(botId, threadId).some((fragment) => fold(saved).includes(fold(fragment)))) return "the saved definitions or instructions name a path in it";+ const linked = await linkedInto(botId, folder, view);+ if (linked === null) return "the bot's other folders hold too many entries to check for links into it";+ if (linked) return "a link in the bot's other folders leads into it";+ if (deps.processFolders) {+ const cwds = await deps.processFolders();+ const own = [folder, view.resolved(folder)].filter((path): path is string => Boolean(path));+ if (cwds && cwds.some((cwd) => own.some((mine) => inside(mine, cwd)))) return "a process works in it";+ }+ if (deps.mentions) {+ if (!mentioned) return "the transcripts cannot be read";+ const live = view.now().live;+ if ([...(mentioned.get(threadId) ?? [])].some((id) => id !== threadId && live.has(id))) return "a remaining conversation names it";+ }+ return null;+ }++ /** Why an install candidate must stay, or null when it is plainly an install a package manager makes again. */+ async function notAnInstall(path: string, folder: string): Promise<string | null> {+ const isFile = async (file: string) => (await lstat(file).catch(() => null))?.isFile() === true;+ const name = path.slice(path.lastIndexOf(sep) + 1);+ if (name === "node_modules") {+ let marked = false;+ for (const marker of NODE_MARKERS) if (await isFile(join(path, marker))) marked = true;+ if (!marked) return "no package manager's record in it";+ if (!await isFile(join(dirname(path), "package.json"))) return "no package.json beside it";+ // A repository that commits its node_modules keeps it.+ for (let at = dirname(path); inside(folder, at); at = dirname(at)) {+ const dotGit = await lstat(join(at, ".git")).catch(() => null);+ if (!dotGit) { if (at === folder) break; continue; }+ if (!dotGit.isDirectory()) return "inside a git checkout whose index cannot be read";+ const tracked = await gitTracks(join(at, ".git", "index"), relative(at, path).split(sep).join("/"));+ if (tracked === null) return "inside a git checkout whose index cannot be read";+ if (tracked) return "git tracks it";+ break;+ }+ return null;+ }+ let entries: string[];+ try { entries = await readdir(path); } catch { return "cannot be read"; }+ const other = entries.filter((entry) => !VENV_ENTRIES.has(entry));+ return other.length ? `holds ${other.slice(0, 3).join(", ")}${other.length > 3 ? ", …" : ""}` : null;+ }++ /** The installs in a conversation folder, never through a link nor into .git, each with its identity. */+ async function rebuildable(folder: string, report = (_path: string, _why: string) => {}): Promise<FoundTree[]> {+ const found: FoundTree[] = [];+ let scanned = 0;+ const walk = async (dir: string, depth: number): Promise<void> => {+ let entries;+ try { entries = await readdir(dir, { withFileTypes: true }); } catch { return; }+ for (const entry of entries) {+ if (++scanned > MAX_SCANNED) return;+ await step();+ if (!entry.isDirectory() || entry.isSymbolicLink() || entry.name === ".git") continue;+ const path = join(dir, entry.name);+ const candidate = entry.name === "node_modules" || ((entry.name === ".venv" || entry.name === "venv") && (await lstat(join(path, "pyvenv.cfg")).catch(() => null))?.isFile() === true);+ if (candidate) {+ const why = await notAnInstall(path, folder);+ const stats = why ? null : await lstat(path).catch(() => null);+ if (why) report(path, why);+ else if (stats?.isDirectory()) found.push({ path, dev: stats.dev, ino: stats.ino });+ } else if (depth < MAX_DEPTH) await walk(path, depth + 1);+ }+ };+ await walk(folder, 0);+ return found;+ }++ const sameNode = (a: { dev: number; ino: number }, b: { dev: number; ino: number }) => a.dev === b.dev && a.ino === b.ino;++ /** Moves `tree` into .removing; false (and the tree untouched) when that cannot be done safely. The move lands first+ * under a name the drain never takes (check-…), is compared there by device and inode, and only then gets the drain's+ * name; something else moved there (a link swapped in on the way) is put back, and if that fails it stays under check-…+ * for a person to look at, never drained. */+ async function retire(root: string, tree: FoundTree): Promise<boolean> {+ const paused = deps.paused?.() ?? null;+ if (paused) { log(`cleanup: kept ${tree.path} for now: ${paused}`); return false; }+ try {+ await mkdir(removing, { recursive: true, mode: 0o700 });+ if (!plainFolderUnder(dataDir, dataDir, removing)) throw new Error(`${REMOVING_DIR} is not a plain folder`);+ if (!plainFolderUnder(dataDir, root, tree.path)) throw new Error("not a plain folder in the data folder");+ const before = lstatSync(tree.path);+ if (!before.isDirectory() || !sameNode(before, tree)) throw new Error("it changed since it was checked");+ const parent = realpathSync.native(dirname(tree.path));+ deps.beforeMove?.(tree.path);+ // The last look, with no wait before the move: the folder it is in is still where it was (no link swapped in).+ if (real(dirname(tree.path)) !== parent || !sameNode(lstatSync(tree.path), tree)) throw new Error("it changed since it was checked");+ const name = `${Date.now()}-${randomBytes(6).toString("hex")}`;+ const checking = join(removing, `check-${name}`);+ await rename(tree.path, checking);+ const moved = await lstat(checking);+ if (!sameNode(moved, tree)) {+ // Something else was moved: put it back where it was and keep it.+ try {+ await rename(checking, tree.path);+ } catch (error) {+ warn(`cleanup: MOVED SOMETHING ELSE AND COULD NOT PUT IT BACK: it is kept at ${checking} (it came from ${tree.path}, ${message(error)}); the cleanup never removes it`);+ }+ throw new Error("what was moved is not what was checked; put back");+ }+ await rename(checking, join(removing, name));+ return true;+ } catch (error) {+ warn(`cleanup: kept ${tree.path}: ${message(error)}`);+ return false;+ }+ }++ /** Removes one entry of .removing with Node, deepest first, a link as a link, never across a mount (`dev`); a folder+ * that is no longer the folder it was when listed (a link swapped in) is left for the next pass. Used where GNU rm is+ * not there (macOS, Windows); what fails stays for the next pass. */+ async function remove(path: string, dev: number, totals: CleanupTotals): Promise<void> {+ await step();+ let stats;+ try { stats = await lstat(path); } catch (error) { if (code(error) !== "ENOENT") totals.failed++; return; }+ if (stats.dev !== dev) { totals.failed++; return; }+ if (stats.isDirectory()) {+ let names: string[] = [];+ try { names = await readdir(path); } catch (error) {+ if (code(error) === "EACCES" || code(error) === "EPERM") { await chmod(path, 0o700).catch(() => {}); names = await readdir(path).catch(() => []); }+ }+ // The listing must be of the folder that was checked: a link swapped in before it is never walked.+ const again = await lstat(path).catch(() => null);+ if (!again || !again.isDirectory() || !sameNode(again, stats)) { totals.failed++; return; }+ for (const name of names) await remove(join(path, name), dev, totals);+ }+ const drop = () => (stats.isDirectory() ? rmdir(path) : unlink(path));+ try {+ await drop();+ } catch (error) {+ if (code(error) === "ENOENT") return;+ // A read-only file (Windows) or a folder without write permission: it and its folder made writable, then again;+ // only ever a real folder, never through a link.+ try {+ const parent = await lstat(dirname(path)).catch(() => null);+ if (parent?.isDirectory() && parent.dev === dev) await chmod(dirname(path), 0o700).catch(() => {});+ const self = await lstat(path).catch(() => null);+ if (self && !self.isSymbolicLink() && sameNode(self, stats)) await chmod(path, stats.isDirectory() ? 0o700 : 0o600).catch(() => {});+ await drop();+ } catch {+ totals.failed++;+ return;+ }+ }+ totals.entries++;+ totals.bytes += stats.isDirectory() ? 0 : stats.size;+ }++ /** Finishes what an earlier pass moved to .removing: only its own entries, only in a plain .removing, never one a+ * process still works in, holds open or has mapped (it is tried again on a later pass). On Linux the system's GNU rm+ * removes it (one file system, no link followed, a race-safe walk), at low priority. */+ async function drainPending(totals: CleanupTotals): Promise<void> {+ if (!realFolder(removing) || !plainFolderUnder(dataDir, dataDir, removing)) return;+ if (deps.paused?.()) return;+ const names = (await readdir(removing).catch(() => [] as string[])).filter((name) => RETIRED.test(name));+ if (!names.length) return;+ const held = await (deps.processPaths ?? linuxProcessPaths)();+ if (held === null && process.platform === "linux") return warn("cleanup: left .removing for now: which files processes hold cannot be read");+ const removingDev = lstatSync(removing).dev;+ const rm = await (deps.systemRm ?? gnuRm)();+ for (const name of names) {+ if (deps.paused?.()) return;+ const entry = join(removing, name);+ const stats = await lstat(entry).catch(() => null);+ if (!stats) continue;+ if (stats.dev !== removingDev) { totals.failed++; continue; }+ const realEntry = await realpath(entry).catch(() => entry);+ if (held && held.some((path) => within(entry, path) || within(realEntry, path))) { log(`cleanup: left ${entry} for now: a process still holds something in it`); continue; }+ if (!rm || !stats.isDirectory()) { await remove(entry, stats.dev, totals); continue; }+ const again = await lstat(entry).catch(() => null);+ if (!again || !sameNode(again, stats)) { totals.failed++; continue; }+ if (await runRm(rm, entry) || (await chmodTree(entry), await runRm(rm, entry))) totals.entries++;+ else totals.failed++;+ }+ }++ async function runJob(job: Job, totals: CleanupTotals, view: View, mentioned: () => Promise<ReadonlyMap<string, ReadonlySet<string>> | null>): Promise<void> {+ if (job.kind === "results") {+ const name = job.name;+ // A name another thread's results may also be kept under (the gate cuts names at 80 characters) stays.+ const shared = [...view.now().live].some((id) => hookResultsName(id) === name || gateResultsName(id) === name);+ if (shared || !ID.test(name) || name === "thread") return;+ const path = join(resultsRoot, name);+ const stats = await lstat(path).catch(() => null);+ if (stats?.isDirectory() && await retire(resultsRoot, { path, dev: stats.dev, ino: stats.ino })) totals.folders++;+ return;+ }+ if (!realFolder(job.folder)) return;+ const why = heldByRecords(job.folder, view);+ if (why) return log(`cleanup: kept ${job.folder}: ${why}`);+ const trees = await rebuildable(job.folder, (path, reason) => log(`cleanup: kept ${path}: ${reason}`));+ if (!trees.length) return;+ const late = await heldBy(job.folder, view, await mentioned());+ if (late) return log(`cleanup: kept ${job.folder}: ${late}`);+ for (const tree of trees) {+ // Checked again just before each move: a conversation may have started working there meanwhile.+ const again = heldByRecords(job.folder, view);+ if (again) return log(`cleanup: kept ${job.folder}: ${again}`);+ if (await retire(tasksRoot, tree)) totals.folders++;+ }+ }++ function kick(): void {+ if (active) return;+ active = true;+ running = running.then(async () => {+ const totals: CleanupTotals = { folders: 0, entries: 0, bytes: 0, failed: 0 };+ try {+ while (queued.size) {+ const batch = [...queued.entries()];+ queued.clear();+ const view = batchView();+ await view.warm();+ // The transcripts are read once per batch, for every conversation in it, and only when one has an install.+ let mentioned: Promise<ReadonlyMap<string, ReadonlySet<string>> | null> | undefined;+ const ids = batch.flatMap(([, job]) => (job.kind === "workspace" ? [relative(tasksRoot, job.folder).split(sep)[1] ?? ""] : [])).filter((id) => ID.test(id));+ const read = () => (mentioned ??= deps.mentions+ ? deps.mentions(ids).then((found) => found, (error: unknown) => { warn(`cleanup: the transcripts could not be read: ${message(error)}`); return null; })+ : Promise.resolve(new Map()));+ for (const [key, job] of batch) {+ try { await runJob(job, totals, view, read); } catch (error) { warn(`cleanup: kept ${key}: ${message(error)}`); }+ }+ }+ await drainPending(totals);+ } catch (error) {+ warn(`cleanup: stopped: ${message(error)}`);+ } finally {+ active = false;+ }+ if (totals.folders || totals.entries) {+ log(`cleanup: removed ${totals.folders} install or tool-result folder(s) of deleted conversations, ${totals.entries} entries, ${Math.round(totals.bytes / 1024 / 1024)} MB${totals.failed ? `; ${totals.failed} left for the next pass` : ""}`);+ }+ if (queued.size) kick();+ });+ }++ function enqueue(job: Job): void {+ queued.set(job.kind === "workspace" ? `workspace:${job.folder}` : `results:${job.name}`, job);+ }++ const children = (dir: string) => (realFolder(dir) ? readdirNames(dir) : []);++ /** Deleted conversations: their folders under every bot (a room's under each member's), the conversation folders+ * they worked in (a fork's source's, which may now belong to nothing), and their tool results. */+ function conversationsGone(threadIds: Iterable<string>, workedIn: Iterable<string> = []): void {+ const ids = [...new Set(threadIds)].filter((id) => ID.test(id));+ if (!ids.length) return;+ for (const used of workedIn) {+ if (!isAbsolute(used)) continue;+ const [botId, threadId, ...rest] = relative(tasksRoot, resolve(used)).split(sep);+ if (botId && threadId && !rest.length && ID.test(botId) && ID.test(threadId)) enqueue({ kind: "workspace", folder: join(tasksRoot, botId, threadId) });+ }+ const bots = children(tasksRoot).filter((id) => ID.test(id));+ for (const threadId of ids) {+ for (const botId of bots) if (realFolder(join(tasksRoot, botId, threadId))) enqueue({ kind: "workspace", folder: join(tasksRoot, botId, threadId) });+ enqueue({ kind: "results", name: threadId });+ }+ kick();+ }++ /** A deleted bot: each of its conversation folders, including those of conversations deleted before it. */+ function botGone(botId: string): void {+ if (!ID.test(botId)) return;+ for (const threadId of children(join(tasksRoot, botId))) if (ID.test(threadId)) enqueue({ kind: "workspace", folder: join(tasksRoot, botId, threadId) });+ kick();+ }++ /** Folders the orphan sweep found: conversation folders (their installs go) and tool-results folder names. */+ function orphans(found: { workspaces?: Iterable<string>; results?: Iterable<string> }): void {+ for (const folder of found.workspaces ?? []) {+ const [botId, threadId, ...rest] = relative(tasksRoot, resolve(folder)).split(sep);+ if (botId && threadId && !rest.length && ID.test(botId) && ID.test(threadId)) enqueue({ kind: "workspace", folder: join(tasksRoot, botId, threadId) });+ }+ for (const name of found.results ?? []) if (ID.test(name)) enqueue({ kind: "results", name });+ kick();+ }++ if (deps.drainAfterMs !== false) setTimeout(kick, deps.drainAfterMs ?? DRAIN_AFTER_START_MS).unref?.();++ return {+ conversationsGone,+ botGone,+ orphans,+ /** What in the records still uses a conversation folder, or null when nothing there does. */+ whyKept: (folder: string) => heldByRecords(folder, batchView()),+ /** Its installs, and through `report` the look-alikes that stay. */+ rebuildable,+ /** Finishes what an earlier run left in .removing. */+ drain: () => { kick(); return running; },+ /** Resolves once everything queued so far is done. */+ idle: async () => { while (active || queued.size) { kick(); await running; } },+ };+}++/** Synchronous on purpose and shallow: one listing of bot or conversation names, never a tree. */+function readdirNames(dir: string): string[] {+ try { return readdirSync(dir); } catch { return []; }+}++export type ConversationFolderCleanup = ReturnType<typeof createConversationFolderCleanup>;diff --git a/server/host/delete-leftovers.store.test.ts b/server/host/delete-leftovers.store.test.tsindex d3b079a5b0..d9facdda73 100644--- a/server/host/delete-leftovers.store.test.ts+++ b/server/host/delete-leftovers.store.test.ts@@ -7,6 +7,7 @@ import type { ModelSelection } from "../contracts.ts";import { journalFile } from "../memory-journal.ts";import * as mdb from "../message-db.ts";import { Store } from "../store.ts";+import { createConversationFolderCleanup, deleteTimeCleanup } from "./conversation-folder-cleanup.ts";import { createDeleteLeftovers, engineSessionFolders, type DeleteLeftoversDeps } from "./delete-leftovers.ts";import { memoryLayerRecords } from "./team-member-left.ts";@@ -21,12 +22,11 @@ function put(path: string): string {return path;}-function fixture(over: Partial<DeleteLeftoversDeps> = {}) {- const store = new Store(selection);+function fixture(over: Partial<Omit<DeleteLeftoversDeps, "store">> & { store?: Store } = {}) {+ const store = over.store ?? new Store(selection);const warnings: string[] = [];const leftovers = createDeleteLeftovers({dataDir: DATA_DIR,- store,threadsReferencing: mdb.threadsReferencing,keptAttachments: () => new Set(),deleteAttachment: (name) => rmSync(join(DATA_DIR, "attachments", name)),@@ -35,6 +35,7 @@ function fixture(over: Partial<DeleteLeftoversDeps> = {}) {defer: () => {},warn: (line) => { warnings.push(line); },...over,+ store,});const bot = store.createBot({ name: "Scout" });const task = store.createTask(bot.id, "Launch post", false)!;@@ -122,4 +123,61 @@ describe("deleting through the store", () => {leftovers.flush();expect(existsSync(upload)).toBe(false);});++ it("with the cleanup switched off (the default, and on every desktop), a delete leaves installs and tool results as before", async () => {+ const store = new Store(selection);+ const folders = deleteTimeCleanup({}, true, () => createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, drainAfterMs: false, pause: async () => {}, log: () => {} }));+ expect(folders).toBeUndefined();+ const { bot, task, leftovers } = fixture({ store, ...(folders ? { folders } : {}) });+ const own = join(DATA_DIR, "task-workspaces", bot.id, task.threadId);+ const deps = put(join(own, "site", "node_modules", "react", "index.js"));+ put(join(own, "site", "node_modules", ".package-lock.json"));+ put(join(own, "site", "package.json"));+ const results = put(join(DATA_DIR, "tool-results", task.threadId, "r.txt"));+ expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();+ leftovers.flush();+ await new Promise((done) => setTimeout(done, 0));+ expect([existsSync(deps), existsSync(results)]).toEqual([true, true]);+ expect(existsSync(join(DATA_DIR, ".removing"))).toBe(false);+ });++ it("takes a deleted conversation's installs and tool results, never while a fork still works in its folder", async () => {+ const store = new Store(selection);+ const folders = createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, drainAfterMs: false, pause: async () => {}, log: () => {} });+ const { bot, task, leftovers } = fixture({ store, folders });+ const own = join(DATA_DIR, "task-workspaces", bot.id, task.threadId);+ store.pinTaskCwd(bot.id, task.threadId, own, { privateOnly: true });+ const said = store.appendMessage(task.threadId, { role: "user", kind: "text", text: "build it" });+ const fork = store.forkTask(bot.id, task.threadId, said.id)!;+ const made = put(join(own, "site", "index.html"));+ const deps = put(join(own, "site", "node_modules", "react", "index.js"));+ put(join(own, "site", "node_modules", ".package-lock.json"));+ put(join(own, "site", "package.json"));+ const results = put(join(DATA_DIR, "tool-results", task.threadId, "r.txt"));+ expect(store.deleteTask(bot.id, task.threadId)).not.toBeNull();+ leftovers.flush();+ await folders.idle();+ expect(existsSync(results)).toBe(false);+ expect(existsSync(deps)).toBe(true);+ expect(store.deleteTask(bot.id, fork.threadId)).not.toBeNull();+ leftovers.flush();+ await folders.idle();+ expect(existsSync(deps)).toBe(false);+ expect(existsSync(made)).toBe(true);+ });++ it("takes a deleted bot's conversation folders' installs and keeps their files", async () => {+ const store = new Store(selection);+ const folders = createConversationFolderCleanup({ dataDir: DATA_DIR, records: () => store, drainAfterMs: false, pause: async () => {}, log: () => {} });+ const { bot, task, leftovers } = fixture({ store, folders });+ const made = put(join(DATA_DIR, "task-workspaces", bot.id, task.threadId, "result.txt"));+ const deps = put(join(DATA_DIR, "task-workspaces", bot.id, "deleted-earlier", "node_modules", "x.js"));+ put(join(DATA_DIR, "task-workspaces", bot.id, "deleted-earlier", "node_modules", ".modules.yaml"));+ put(join(DATA_DIR, "task-workspaces", bot.id, "deleted-earlier", "package.json"));+ expect(store.deleteBot(bot.id)).toBe(true);+ leftovers.flush();+ await folders.idle();+ expect(existsSync(deps)).toBe(false);+ expect(existsSync(made)).toBe(true);+ });});diff --git a/server/host/delete-leftovers.test.ts b/server/host/delete-leftovers.test.tsindex d91318df3f..778c3f5373 100644--- a/server/host/delete-leftovers.test.ts+++ b/server/host/delete-leftovers.test.ts@@ -22,7 +22,7 @@ function put(path: string, text = "x"): string {return path;}-type Task = { threadId: string; resumeCursors?: Record<string, unknown> };+type Task = { threadId: string; resumeCursors?: Record<string, unknown>; cwd?: string };type Bot = { id: string; threadId?: string; resumeCursors?: Record<string, unknown>; tasks?: Task[] };function fixture(over: Partial<DeleteLeftoversDeps> = {}) {@@ -303,6 +303,22 @@ describe("a deleted bot", () => {});});+describe("the conversation folders' cleanup", () => {+ it("is handed the deleted conversations, the folders they worked in and the deleted bots, and a failure there stays inside it", () => {+ const calls: unknown[] = [];+ const { bots, deleteThreads, deleteBot, warnings, say } = fixture({ folders: {+ conversationsGone: (ids, workedIn) => { calls.push(["threads", [...ids], [...(workedIn ?? [])]]); throw new Error("busy disk"); },+ botGone: (botId) => { calls.push(["bot", botId]); },+ } });+ bots.push({ id: "scout", tasks: [{ threadId: "t1", cwd: "/data/task-workspaces/scout/t0" }, { threadId: "t2" }] });+ say("t1", upload(1));+ deleteThreads("t1");+ deleteBot("scout");+ expect(calls).toEqual([["threads", ["t1"], ["/data/task-workspaces/scout/t0"]], ["threads", ["t2"], []], ["bot", "scout"]]);+ expect(warnings.filter((line) => line.includes("busy disk"))).toHaveLength(2);+ });+});+describe("a cleanup that fails", () => {it("is logged, never thrown into the delete, and the rest still goes", () => {const { dataDir, home, bots, say, deleteThreads, warnings } = fixture({ deleteAttachment: () => { throw new Error("disk is read-only"); } });diff --git a/server/host/delete-leftovers.ts b/server/host/delete-leftovers.tsindex 5a23311bc2..54ff281162 100644--- a/server/host/delete-leftovers.ts+++ b/server/host/delete-leftovers.ts@@ -1,7 +1,8 @@// Deleting a conversation or a bot removes what it kept on disk outside its transcript: the files uploaded to the// conversation, its box uploads folder, its own notes, the session files the engines wrote for it, and for a bot its checkpoints and// the memory layers kept beside its own folder. A conversation's own folder (task-workspaces/<bot>/<thread>) holds-// files the bot made for the person, and stays when the conversation or the bot is deleted.+// files the bot made for the person, and stays when the conversation or the bot is deleted: on a Cloud home only its+// package installs, and the conversation's full tool results, go (conversation-folder-cleanup.ts).//// Security: a file goes only when it is provably the deleted conversation's or bot's. An upload another conversation,// a picture or a routine still names stays; an engine session a remaining conversation still resumes stays. Nothing is@@ -35,12 +36,14 @@ export interface EngineSessionFolders {}type Cursors = Record<string, unknown> | undefined;+type Folder = string | null | undefined;type Change = { type: string; threadId?: string; botId?: string };export interface DeleteLeftoversDeps {dataDir: string;store: {- readonly bots: ReadonlyArray<{ id: string; threadId?: string; resumeCursors?: Cursors; tasks?: ReadonlyArray<{ threadId: string; resumeCursors?: Cursors }> }>;+ readonly bots: ReadonlyArray<{ id: string; threadId?: string; resumeCursors?: Cursors; tasks?: ReadonlyArray<{ threadId: string; resumeCursors?: Cursors; cwd?: Folder }> }>;+ readonly groups?: ReadonlyArray<{ threadId?: string; pinnedCwd?: Folder; tasks?: ReadonlyArray<{ threadId: string; pinnedCwd?: Folder }> }>;messagesFor(threadId: string): readonly unknown[];onChange(listener: (change: Change) => void): unknown;/** Set here: the store calls it before it tries to delete these conversations. */@@ -58,6 +61,8 @@ export interface DeleteLeftoversDeps {checkpointsQuiet?(botId: string): Promise<void>;/** Runs `flush` once the delete under way has finished, so one pass covers every conversation it removed. */defer?(flush: () => void): void;+ /** What clears the deleted conversations' and bots' rebuildable trees and tool results, off the delete's own call. */+ folders?: { conversationsGone(threadIds: Iterable<string>, workedIn?: Iterable<string>): void; botGone(botId: string): void };warn?(line: string): void;}@@ -203,7 +208,10 @@ export function instanceEnvironment(base: Record<string, string | undefined>, ininterface Noted {attachments: Set<string>;sessions: Set<string>;+ /** The folders it worked in: a fork works in its source's folder, which may be left with no conversation. */+ folders: Set<string>;}+const nothingNoted = (): Noted => ({ attachments: new Set(), sessions: new Set(), folders: new Set() });export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {const dataDir = resolve(deps.dataDir);@@ -225,11 +233,16 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {function note(threadId: string): void {if (!ID.test(threadId)) return;- const found: Noted = { attachments: new Set(), sessions: new Set() };+ const found = nothingNoted();for (const match of JSON.stringify(deps.store.messagesFor(threadId)).matchAll(ATTACHMENT)) found.attachments.add(match[1]!);for (const bot of deps.store.bots) {if (bot.threadId === threadId) for (const cursor of cursorsOf(bot.resumeCursors)) found.sessions.add(cursor);for (const task of bot.tasks ?? []) if (task.threadId === threadId) for (const cursor of cursorsOf(task.resumeCursors)) found.sessions.add(cursor);+ for (const task of bot.tasks ?? []) if (task.threadId === threadId && task.cwd) found.folders.add(task.cwd);+ }+ for (const group of deps.store.groups ?? []) {+ if (group.threadId === threadId && group.pinnedCwd) found.folders.add(group.pinnedCwd);+ for (const task of group.tasks ?? []) if (task.threadId === threadId && task.pinnedCwd) found.folders.add(task.pinnedCwd);}for (const session of loggedSessions(dataDir, threadId)) found.sessions.add(session);noted.delete(threadId);@@ -311,6 +324,11 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {for (const threadId of threads.keys()) attempt(`box uploads of ${threadId}`, () => removeBoxUploads(threadId));for (const threadId of threads.keys()) attempt(`notes of ${threadId}`, () => removeThreadNotes(threadId));for (const botId of bots) removeBot(botId);+ if (deps.folders) {+ const folders = deps.folders;+ attempt("conversation folders", () => folders.conversationsGone(threads.keys(), [...threads.values()].flatMap((found) => [...found.folders])));+ for (const botId of bots) if (!isLayerId(botId)) attempt(`conversation folders of ${botId}`, () => folders.botGone(botId));+ }}function schedule(): void {@@ -324,7 +342,7 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {};deps.store.onChange((change) => {if (change.type === "thread.deleted" && change.threadId && ID.test(change.threadId)) {- gone.set(change.threadId, noted.get(change.threadId) ?? { attachments: new Set(), sessions: new Set() });+ gone.set(change.threadId, noted.get(change.threadId) ?? nothingNoted());noted.delete(change.threadId);schedule();} else if (change.type === "bot.deleted" && change.botId) {diff --git a/server/host/transcript-mentions.test.ts b/server/host/transcript-mentions.test.tsnew file mode 100644index 0000000000..dd0caaf330--- /dev/null+++ b/server/host/transcript-mentions.test.ts@@ -0,0 +1,50 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { afterEach, describe, expect, it } from "vitest";++import { threadsMentioning } from "./transcript-mentions.ts";++const made: string[] = [];+afterEach(() => {+ for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function transcripts(rows: Array<[string, unknown]>): string {+ const dir = mkdtempSync(join(tmpdir(), "omb-mentions-"));+ made.push(dir);+ const file = join(dir, "messages.db");+ const db = new DatabaseSync(file);+ db.exec("CREATE TABLE messages(thread_id TEXT NOT NULL, json TEXT NOT NULL)");+ const insert = db.prepare("INSERT INTO messages(thread_id, json) VALUES (?, ?)");+ for (const [thread, message] of rows) insert.run(thread, JSON.stringify(message));+ db.close();+ return file;+}++describe("which conversations mention a word", () => {+ it("answers for every word in one read, off the event loop", async () => {+ const file = transcripts([+ ["live", { text: "see task-workspaces/scout/gone1/app" }],+ ["other", { text: "nothing here" }],+ ["gone1", { text: "my own folder gone1" }],+ ]);+ const found = await threadsMentioning(file, ["gone1", "gone2", "gone1"]);+ expect([...found.get("gone1")!].sort()).toEqual(["gone1", "live"]);+ expect([...found.get("gone2")!]).toEqual([]);+ });++ it("rejects when the transcripts are missing or cannot be read, so a caller keeps", async () => {+ await expect(threadsMentioning(join(tmpdir(), "no-such-folder-omb", "messages.db"), ["x"])).rejects.toThrow(/missing/);+ const file = transcripts([]);+ const db = new DatabaseSync(file);+ db.exec("DROP TABLE messages");+ db.close();+ await expect(threadsMentioning(file, ["x"])).rejects.toThrow(/no such table/);+ });++ it("reads nothing for no words", async () => {+ expect((await threadsMentioning("/nowhere", [])).size).toBe(0);+ });+});diff --git a/server/host/transcript-mentions.ts b/server/host/transcript-mentions.tsnew file mode 100644index 0000000000..1e3b5474a3--- /dev/null+++ b/server/host/transcript-mentions.ts@@ -0,0 +1,53 @@+// Which conversations' messages mention any of some words, read off the event loop: one read-only query of messages.db+// in a short-lived worker, so a large transcript store never stalls a turn. Used before a deleted conversation's+// folders are cleaned, to keep what a remaining conversation still names.+import { existsSync } from "node:fs";+import { Worker } from "node:worker_threads";++const WORKER = `+const { parentPort, workerData } = require("node:worker_threads");+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]])) });+} catch (error) {+ parentPort.postMessage({ error: String(error && error.message || error) });+} finally {+ try { db && db.close(); } catch {}+}+`;++const MAX_WORDS = 200;+const TIMEOUT_MS = 120_000;++/** 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>>> {+ const unique = [...new Set(words.filter(Boolean))];+ const result = new Map<string, Set<string>>();+ if (!unique.length) return result;+ 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})`)); });+ });+ for (const word of chunk) result.set(word, new Set(found[word] ?? []));+ }+ return result;+}diff --git a/server/index.ts b/server/index.tsindex 10b3657c26..ac0a9c84f6 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 { 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 } 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 { 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 });+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 })) });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,diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex ba2d05a83b..c93520782b 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -48,6 +48,8 @@ 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",// 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",