Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(backup): take bursts.db whole, carry bots' Data tables; moves say Data stays behind (#6848)
Milind Sonie76762171440
diff --git a/electron/team-move-bring.node-test.mjs b/electron/team-move-bring.node-test.mjsindex 94171f0fab..a5bc2b5720 100644--- a/electron/team-move-bring.node-test.mjs+++ b/electron/team-move-bring.node-test.mjs@@ -124,7 +124,7 @@ test("its confirm says what the page's confirm says, word for word", () => {const words = teamMoveConfirmWords({ bot: "Atlas", team: "Acme" });assert.equal(words.message, fill("teamMove.title"));assert.equal(words.buttons[0], fill("teamMove.confirm"));- for (const key of ["teamMove.yours", "teamMove.goes", "teamMove.private", "teamMove.staysOnMyCloud", "teamMove.noWayBack"]) assert.ok(words.detail.includes(fill(key)), key);+ for (const key of ["teamMove.yours", "teamMove.goes", "teamMove.private", "teamMove.staysOnMyCloud", "teamMove.dataStays", "teamMove.noWayBack"]) assert.ok(words.detail.includes(fill(key)), key);});test("the native confirm and IPC refusals follow the app's current language", async () => {@@ -144,6 +144,7 @@ test("the native confirm and IPC refusals follow the app's current language", as"Vão com Atlas: instruções, habilidades, arquivos, rotinas e suas conversas com Atlas","Suas conversas continuam privadas lá: só você pode vê-las.","Ficam no My Cloud: o que Atlas lembra, suas conexões e o MausBot",+ "As tabelas que Atlas carregou em Dados não são transferidas: ficam no My Cloud, onde Atlas não consegue abri-las depois que entra em Acme.","Não é possível desfazer: você não pode mover o bot de volta para o My Cloud.",].join("\n\n"),buttons: ["Mover para Acme", "Cancelar"],diff --git a/electron/team-move-main.mjs b/electron/team-move-main.mjsindex 94b2e11a79..81bcbc21e8 100644--- a/electron/team-move-main.mjs+++ b/electron/team-move-main.mjs@@ -48,6 +48,7 @@ export function teamMoveConfirmWords(names, t = nativeText.englishText.t) {t("teamMove.goes", names),t("teamMove.private"),t("teamMove.staysOnMyCloud", names),+ t("teamMove.dataStays", names),t("teamMove.noWayBack"),].join("\n\n"),buttons: [t("teamMove.confirm", names), t("native.common.cancel")],diff --git a/server/data/engine.ts b/server/data/engine.tsindex 9cd7850a06..0c4d596b24 100644--- a/server/data/engine.ts+++ b/server/data/engine.ts@@ -20,6 +20,7 @@ import {type DataConnection,type DataEngine,type DataExtension,+ type DataHeld,type DataHistogram,type DataPage,type DescribeResult,@@ -29,6 +30,8 @@ import {} from "./types.ts";type Binding = typeof DuckDB;+type DataShut = { closed: true } | { closed: false; why: DataHeld["why"]; detail?: string };+const CLOSED: DataShut = { closed: true };type Cell = string | number | boolean | null;export const DATA_DB_FILE = "data.duckdb";@@ -295,7 +298,9 @@ function formatEpoch(seconds: number, dateOnly: boolean): string {class BotDb implements BotDatabase {private state: Promise<Open> | null = null;- private closing: Promise<void> | null = null;+ private closing: Promise<DataShut> | null = null;+ /** The instance a close could not let go of: still open on the file, so the next statement uses it, never a second one. */+ private kept: Promise<Open> | null = null;private idleTimer: NodeJS.Timeout | null = null;private inFlight = 0;private readonly statsCache = new Map<string, DataColumnStats>();@@ -307,9 +312,10 @@ class BotDb implements BotDatabase {private open(): Promise<Open> {if (!this.state) {- // The file admits one instance per process: a reopen waits for a close that may still be draining.- const previous = this.closing ?? Promise.resolve();- const opening = previous.then(() => this.openNow());+ // The file admits one instance per process: a reopen waits for a close that may still be draining, and after a close+ // that could not let go of the instance it goes on with that one.+ const previous = this.closing ?? Promise.resolve(CLOSED);+ const opening = previous.then((shut) => (shut.closed || !this.kept ? this.openNow() : this.kept));this.state = opening;opening.catch(() => {if (this.state === opening) this.state = null;@@ -700,28 +706,51 @@ FROM ${from} AS omb_source, omb_range WHERE ${finite} GROUP BY bin ORDER BY bin`}async close(): Promise<void> {+ await this.shut();+ }++ /** Closed, or why the instance is still open: a statement that did not stop, or a close that failed. */+ async shut(): Promise<DataShut> {if (this.idleTimer) {clearTimeout(this.idleTimer);this.idleTimer = null;}const pending = this.state;- if (!pending) return this.closing ?? undefined;+ if (!pending) return this.closing ?? CLOSED;this.state = null;this.statsCache.clear();- const closing = (async () => {+ const closing = (async (): Promise<DataShut> => {let open: Open;- try { open = await pending; } catch { return; }- // Closing a connection with a statement in flight is undefined: interrupt first, then let the lanes drain.- for (const lane of Object.values(open.lanes)) lane.interrupt();- if (!await drainLanes(Object.values(open.lanes), CLOSE_DRAIN_MS)) {- console.warn(`data: ${this.botId}'s database still had a statement running after ${CLOSE_DRAIN_MS} ms; its handles are left to the process`);- return;+ try { open = await pending; } catch { return CLOSED; }+ const shut = await this.closeOpen(open);+ if (shut.closed) this.kept = null;+ else {+ this.kept = pending;+ if (!this.state) this.state = pending;}- for (const lane of Object.values(open.lanes)) lane.connection.closeSync();- open.instance.closeSync();+ return shut;})();this.closing = closing;- try { await closing; } finally { if (this.closing === closing) this.closing = null; }+ try { return await closing; } finally { if (this.closing === closing) this.closing = null; }+ }++ private async closeOpen(open: Open): Promise<DataShut> {+ // Closing a connection with a statement in flight is undefined: interrupt first, then let the lanes drain.+ for (const lane of Object.values(open.lanes)) { try { lane.interrupt(); } catch { /* the drain below decides */ } }+ if (!await drainLanes(Object.values(open.lanes), CLOSE_DRAIN_MS)) {+ console.warn(`data: ${this.botId}'s database still had a statement running after ${CLOSE_DRAIN_MS} ms; its handles are left to the process`);+ return { closed: false, why: "running" };+ }+ try {+ for (const lane of Object.values(open.lanes)) lane.connection.closeSync();+ // The last close writes the WAL into the file and removes it: the file then holds every table on its own.+ open.instance.closeSync();+ } catch (error) {+ const detail = (error instanceof Error ? error.message : String(error)).split("\n")[0]!.slice(0, 200);+ console.warn(`data: ${this.botId}'s database did not close: ${detail}`);+ return { closed: false, why: "failed", detail };+ }+ return CLOSED;}get isOpen(): boolean {@@ -814,6 +843,13 @@ class Engine implements DataEngine {}}+ /** Every bot's database closed and kept, to open again on its next statement; the ones still open, and why. */+ async release(): Promise<DataHeld[]> {+ const open = [...this.databases.values()];+ const shut = await Promise.all(open.map((db) => db.shut()));+ return open.flatMap((db, i) => { const one = shut[i]!; return one.closed ? [] : [{ botId: db.botId, why: one.why, ...(one.detail ? { detail: one.detail } : {}) }]; });+ }+async closeAll(): Promise<void> {const open = [...this.databases.values()];this.databases.clear();diff --git a/server/data/types.ts b/server/data/types.tsindex 61128bb474..459b0c7f3b 100644--- a/server/data/types.ts+++ b/server/data/types.ts@@ -70,6 +70,9 @@ export interface BotDatabase {close(): Promise<void>;}+/** A bot's database a release could not close, kept open (never a second instance on its file) until it can be. */+export interface DataHeld { botId: string; why: "running" | "failed"; detail?: string }+export interface DataEngine {unavailable(): string | null;/** What a status read shows: the loaded binding's state, or, before anything has loaded it, whether its files are in@@ -79,6 +82,9 @@ export interface DataEngine {onInstalledChange(listener: () => void): void;forBot(botId: string): Promise<BotDatabase>;deleteBot(botId: string): Promise<void>;+ /** Closes every bot's database, its WAL written into the file, so its files are at rest until its next statement (a+ * full backup copies them then). Returns the databases still open: a statement that did not stop, or a failed close. */+ release(): Promise<DataHeld[]>;closeAll(): Promise<void>;}diff --git a/server/index.ts b/server/index.tsindex 83ddcaef94..e99b0936f8 100644--- a/server/index.ts+++ b/server/index.ts@@ -516,7 +516,7 @@ import { acquireDataDirLeaseForProcess, releaseOnceAtExit } from "./data-dir-leaimport { createWorkspaceAccess, describeEdition, editionForSettings, editionStatus, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer, workspaceMembership, type WorkspaceAccess } from "./enterprise.ts";import { environmentDescriptor, loadEnvironmentId, OWNER_LENDING, serverVersion } from "./environment.ts"; import { dataFormatAtStart } from "./data-format.ts"; import { doctorAtStart } from "./doctor/start.ts";import { WorkspaceBackupMaintenance } from "./workspace-backup-maintenance.ts";-import { createWorkspaceBackupRoutes, isWorkspaceBackupSessionControl } from "./workspace-backup-http.ts";+import { createWorkspaceBackupRoutes, isWorkspaceBackupSessionControl, releaseDataForBackup } from "./workspace-backup-http.ts";import { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRestoreResult } from "./workspace-backup.ts";import { repairMovedWorkspacePaths } from "./moved-paths-repair.ts";import { createCustomDomainVerifier, customDomainIpv4, normalizeCustomDomain } from "./custom-domain.ts";@@ -11960,7 +11960,7 @@ const workspaceBackupAccess = {pause: () => { routines?.stop(); calendarCalls?.stop(); botWaits.stop(); checkBacks.stop(); watchdog.stop(); memoryUpkeep.pause(); },resume: () => { if (!moveFreeze.frozen()) { routines?.start(); calendarCalls?.start(); botWaits.start(); checkBacks.start(); } watchdog.start(); memoryUpkeep.resume(); },flush: async () => {- await Promise.all([chatApps.settleLive(), flushAllProfileHistory(), flushAllMemoryJournals(), flushUsageLedger(DATA_DIR), flushDecisionLog(DATA_DIR), flushAdminActivity(DATA_DIR)]);+ await Promise.all([chatApps.settleLive(), flushAllProfileHistory(), flushAllMemoryJournals(), flushUsageLedger(DATA_DIR), flushDecisionLog(DATA_DIR), flushAdminActivity(DATA_DIR), releaseDataForBackup(dataEngine, (id) => store.bot(id)?.name)]);// Writers gated and work idle: release the WAL connection for a consistent snapshot; Store reopens it lazily.await closeMessageSearch();closeMessageDb();diff --git a/server/user-errors.ts b/server/user-errors.tsindex 9a137275ef..09cec13367 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -100,6 +100,10 @@ export const USER_ERROR = {"serverError.department.deleteBusy": "Stop this department's active work before deleting it","serverError.department.generalChief": "General already has a Chief of Staff. Move or change this department's Chief before deleting it","serverError.backup.recursiveLink": "Cannot back up a symbolic link to the folder that contains it: {path}",+ "serverError.backup.dataQueryRunning": "{bot}'s Data query is still running and did not stop when asked. Fully quit and reopen OpenMausBot (or restart the hosted server) to stop it, then try again.",+ "serverError.backup.dataCloseFailed": "{bot}'s Data tables could not be closed for the backup ({detail}). Fully quit and reopen OpenMausBot (or restart the hosted server), then try again.",+ "serverError.backup.tooLargeData": "This installation exceeds the 10 GB backup limit; {size} of it is bots' Data tables.",+ "serverError.backup.legacyBursts": "This backup's burst records (bursts.db) are damaged, so nothing was restored and nothing here changed. Make a new backup where it came from.","serverError.setup.noTools": "This bot's AI can't set it up by itself. Tell the bot what you'd like it to do instead.","serverError.setup.missingConversation": "There is no such conversation.","serverError.setup.stopOwner": "Only the person who pressed Set me up, or an owner or admin, can stop it.",diff --git a/server/workspace-backup-databases.test.ts b/server/workspace-backup-databases.test.tsnew file mode 100644index 0000000000..7f244f62fc--- /dev/null+++ b/server/workspace-backup-databases.test.ts@@ -0,0 +1,333 @@+// The databases a full backup carries are taken whole, as the server would read them: every SQLite database by the+// snapshot SQLite makes while a writer goes on, and each bot's Data tables once the engine has let go of them.+import { createCipheriv, createHash, randomBytes, randomUUID, scryptSync } from "node:crypto";+import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import type * as DuckDB from "@duckdb/node-api";+import { afterEach, describe, expect, it } from "vitest";++import { DATA_RESULTS_SCHEMA } from "../shared/data-surface.ts";+import { createDataEngine } from "./data/engine.ts";+import { openRuntimeStore } from "./runtime/store.ts";+import { applyPendingWorkspaceRestore, commitPendingWorkspaceRestore, createWorkspaceBackup, stageWorkspaceBackup } from "./workspace-backup.ts";+import { ONE_STEP, releaseDataForBackup, snapshotDatabases, tooLargeError } from "./workspace-backup-databases.ts";++const PASSWORD = "correct horse battery staple";+// Real encrypted backups: a few seconds here, much longer on the Windows runners.+const TIMEOUT_MS = 120_000;+const scratch: string[] = [];+// Windows keeps a just-closed file busy for a moment; rm retries EBUSY/EPERM.+afterEach(() => { for (const path of scratch.splice(0)) rmSync(path, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }); });+const directory = () => { const path = mkdtempSync(join(tmpdir(), "omb-backup-databases-")); scratch.push(path); return path; };++async function restored(backup: string): Promise<string> {+ const target = directory();+ const staged = await stageWorkspaceBackup(target, backup, { password: PASSWORD });+ commitPendingWorkspaceRestore(target, staged.id);+ expect(applyPendingWorkspaceRestore(target)).toMatchObject({ restored: true });+ return target;+}++const PAD = "x".repeat(2_000);+/** A database as the server keeps it: WAL mode, its rows still in the WAL, and a connection that goes on writing. */+function liveDatabase(path: string, schema: string, insert: string, rows: number) {+ const db = new DatabaseSync(path);+ db.exec("PRAGMA journal_mode = WAL");+ db.exec("PRAGMA wal_autocheckpoint = 0");+ db.exec(schema);+ const statement = db.prepare(insert);+ let next = 0;+ const write = () => { statement.run(next, PAD); next++; };+ db.exec("BEGIN");+ for (let i = 0; i < rows; i++) write();+ db.exec("COMMIT");+ return { db, write, written: () => next };+}++/** The rows a restored database holds: whole (integrity), and every one from the first, none skipped. */+function rowsOf(path: string, sql: string): number {+ const db = new DatabaseSync(path, { readOnly: true });+ try {+ expect(db.prepare("PRAGMA integrity_check").get()).toEqual({ integrity_check: "ok" });+ const ids = db.prepare(sql).all().map((row) => Number(Object.values(row)[0]));+ expect(ids).toEqual(ids.map((_, i) => i));+ return ids.length;+ } finally { db.close(); }+}++describe("SQLite databases in a full backup", () => {+ it("snapshots in one step at a rate every Node takes: a positive Int32", async () => {+ expect(Number.isInteger(ONE_STEP) && ONE_STEP >= 1 && ONE_STEP <= 2 ** 31 - 1).toBe(true);+ const root = directory(), snapshot = directory();+ liveDatabase(join(root, "bursts.db"), "CREATE TABLE probe(i INTEGER PRIMARY KEY, pad TEXT)", "INSERT INTO probe VALUES (?, ?)", 20).db.close();+ await snapshotDatabases(root, snapshot);+ expect(rowsOf(join(snapshot, "bursts-snapshot.db"), "SELECT i FROM probe ORDER BY i")).toBe(20);+ });++ it("restores each database whole and complete while a writer goes on inserting into it", async () => {+ const source = directory();+ // A big file before the databases keeps the copy going while the writers write.+ mkdirSync(join(source, "attachments"));+ writeFileSync(join(source, "attachments", "big.bin"), Buffer.alloc(32 * 1024 * 1024, 0x5a));+ openRuntimeStore(join(source, "runtime.db")).close();+ const live = [+ liveDatabase(join(source, "messages.db"),+ "CREATE TABLE messages(thread_id TEXT, id INTEGER, text TEXT, json TEXT, PRIMARY KEY(thread_id, id)); CREATE TABLE thread_state(thread_id TEXT PRIMARY KEY, active_leaf_id TEXT)",+ "INSERT INTO messages VALUES ('thread', ?, ?, '{}')", 400),+ liveDatabase(join(source, "runtime.db"), "CREATE TABLE probe(i INTEGER PRIMARY KEY, pad TEXT)", "INSERT INTO probe VALUES (?, ?)", 400),+ liveDatabase(join(source, "bursts.db"), "CREATE TABLE probe(i INTEGER PRIMARY KEY, pad TEXT)", "INSERT INTO probe VALUES (?, ?)", 400),+ ];+ const before = live.map((database) => database.written());+ const writer = setInterval(() => { for (const database of live) database.write(); }, 1);+ let backup: string;+ try {+ backup = (await createWorkspaceBackup(source, { password: PASSWORD })).path;+ } finally {+ clearInterval(writer);+ for (const database of live) database.db.close();+ }+ expect(live.every((database, i) => database.written() > before[i]!)).toBe(true);+ const target = await restored(backup);+ const counts = [+ rowsOf(join(target, "messages.db"), "SELECT id FROM messages ORDER BY id"),+ rowsOf(join(target, "runtime.db"), "SELECT i FROM probe ORDER BY i"),+ rowsOf(join(target, "bursts.db"), "SELECT i FROM probe ORDER BY i"),+ ];+ counts.forEach((count, i) => expect(count).toBeGreaterThanOrEqual(before[i]!));+ // Each arrives as one file: no log of the source's beside it for SQLite to apply or drop.+ expect(readdirSync(target).filter((name) => /\.db-(?:wal|shm)$/.test(name))).toEqual([]);+ }, TIMEOUT_MS);+});++const duck = createRequire(import.meta.url)("@duckdb/node-api") as typeof DuckDB;++/** Everything a bot's Data tables hold, read straight from the file: columns and their types, views, and every row. */+async function dataTables(file: string) {+ const instance = await duck.DuckDBInstance.create(file, { access_mode: "READ_ONLY" });+ const connection = await instance.connect();+ const read = async (sql: string) => (await connection.runAndReadAll(sql)).getRowsJson();+ try {+ return {+ columns: await read("SELECT table_schema, table_name, column_name, data_type FROM information_schema.columns ORDER BY ALL"),+ views: await read("SELECT schema_name, view_name, sql FROM duckdb_views() WHERE NOT internal ORDER BY ALL"),+ rows: await read("SELECT * FROM main.measures ORDER BY id"),+ bytes: await read("SELECT id, hex(raw) FROM main.measures ORDER BY id"),+ view: await read("SELECT * FROM main.large ORDER BY id"),+ result: await read(`SELECT * FROM ${DATA_RESULTS_SCHEMA}.top ORDER BY id`),+ };+ } finally { connection.closeSync(); instance.closeSync(); }+}++const MEASURES = `CREATE TABLE measures(id INTEGER, amount DECIMAL(18,3), seen TIMESTAMPTZ, big HUGEINT, tags VARCHAR[], point STRUCT(x DOUBLE, y DOUBLE), raw BLOB, note VARCHAR);+INSERT INTO measures VALUES+ (1, 12.345, TIMESTAMPTZ '2026-11-20 09:30:00+05:30', 170141183460469231731687303715884105727, ['a', 'b'], {'x': 1.5, 'y': -2.25}, '\\x00\\xFF\\x10'::BLOB, 'first'),+ (2, NULL, NULL, NULL, NULL, NULL, NULL, NULL),+ (3, -0.001, TIMESTAMPTZ '1999-12-31 23:59:59.999999+00', -170141183460469231731687303715884105728, [], {'x': NULL, 'y': 0}, ''::BLOB, 'naïve ☃');+CREATE VIEW large AS SELECT id, big FROM measures WHERE big > 0;`;++describe("a bot's Data tables in a full backup", () => {+ it("round-trips them exactly: columns, types, views, rows, and what the engine had not yet written into the file", async () => {+ const source = directory();+ const env = { ...process.env, OMB_DUCKDB_DIR: undefined, OMB_RESOURCES_PATH: undefined };+ const engine = createDataEngine({ botFolder: (id) => join(source, "bots", id), dataDir: source, env });+ try {+ const database = await engine.forBot("b1");+ for (const statement of MEASURES.split(";").map((sql) => sql.trim()).filter(Boolean)) await database.run(statement, { connection: "bot" });+ await database.materialise("SELECT id, amount FROM measures WHERE amount IS NOT NULL", "top", { connection: "bot" });+ writeFileSync(join(source, "bots", "b1", "SOUL.md"), "Keeps the numbers.");+ // The engine holds its newest work in the WAL beside the file: a copy of the file alone would lose it.+ expect(existsSync(join(source, "bots", "b1", "data.duckdb.wal"))).toBe(true);+ // What the maintenance gate does before the backup starts.+ await releaseDataForBackup(engine);+ expect(existsSync(join(source, "bots", "b1", "data.duckdb.wal"))).toBe(false);+ const exported = await createWorkspaceBackup(source, { password: PASSWORD });+ const target = await restored(exported.path);+ const want = await dataTables(join(source, "bots", "b1", "data.duckdb"));+ expect(want.rows).toHaveLength(3);+ expect(want.rows[0]).toContain("170141183460469231731687303715884105727");+ expect(want.bytes).toEqual([[1, "00FF10"], [2, null], [3, ""]]);+ expect(want.views).toHaveLength(1);+ expect(want.result).toHaveLength(2);+ expect(await dataTables(join(target, "bots", "b1", "data.duckdb"))).toEqual(want);+ expect(readFileSync(join(target, "bots", "b1", "SOUL.md"), "utf8")).toBe("Keeps the numbers.");+ // The bot's database opens again on its next statement, here as before.+ expect((await database.run("SELECT count(*) AS n FROM measures", { connection: "panel" })).rows).toEqual([["3"]]);+ } finally { await engine.closeAll(); }+ }, TIMEOUT_MS);++ // Copies the files from under an open instance, which Windows' file sharing may refuse.+ it.skipIf(process.platform === "win32")("carries a database and its WAL as they lie when no engine holds them, as after a crash, and DuckDB applies the WAL", async () => {+ const source = directory();+ const folder = join(source, "bots", "b2");+ mkdirSync(folder, { recursive: true });+ const instance = await duck.DuckDBInstance.create(join(folder, "data.duckdb"));+ const connection = await instance.connect();+ try {+ for (const statement of MEASURES.split(";").map((sql) => sql.trim()).filter(Boolean)) await connection.run(statement);+ await connection.run(`CREATE SCHEMA ${DATA_RESULTS_SCHEMA}; CREATE TABLE ${DATA_RESULTS_SCHEMA}.top AS SELECT id, amount FROM measures WHERE amount IS NOT NULL`);+ // A process that stopped here leaves both files: the pair is the database.+ const crashed = join(source, "bots", "b3");+ mkdirSync(crashed);+ for (const name of ["data.duckdb", "data.duckdb.wal"]) copyFileSync(join(folder, name), join(crashed, name));+ } finally { connection.closeSync(); instance.closeSync(); }+ rmSync(folder, { recursive: true, maxRetries: 20, retryDelay: 100 });+ const exported = await createWorkspaceBackup(source, { password: PASSWORD });+ const target = await restored(exported.path);+ expect(readdirSync(join(target, "bots", "b3")).sort()).toEqual(["data.duckdb", "data.duckdb.wal"]);+ const tables = await dataTables(join(target, "bots", "b3", "data.duckdb"));+ expect(tables.rows).toHaveLength(3);+ expect(tables.result).toHaveLength(2);+ }, TIMEOUT_MS);++ it("says which bot's Data query holds its database, and that a restart ends it", async () => {+ const running = await releaseDataForBackup({ release: async () => [{ botId: "b1", why: "running" }] }, () => "Ledger").catch((error: unknown) => error);+ expect(running).toMatchObject({ status: 409, errorKey: "serverError.backup.dataQueryRunning", errorParams: { bot: "Ledger" } });+ expect((running as Error).message).toBe("Ledger's Data query is still running and did not stop when asked. Fully quit and reopen OpenMausBot (or restart the hosted server) to stop it, then try again.");+ const failed = await releaseDataForBackup({ release: async () => [{ botId: "b1", why: "failed", detail: "IO Error: disk full" }] }).catch((error: unknown) => error);+ expect(failed).toMatchObject({ status: 409, errorKey: "serverError.backup.dataCloseFailed" });+ expect((failed as Error).message).toContain("b1's Data tables could not be closed for the backup (IO Error: disk full).");+ await expect(releaseDataForBackup({ release: async () => [] })).resolves.toBeUndefined();+ });++ it("never opens a second instance on a file a statement that did not stop still holds, and reports it until it closes", async () => {+ // A statement DuckDB does not stop (seen on Windows): the engine keeps its instance, and every statement meanwhile,+ // even one that asked while the release was draining, goes to that same instance.+ let finish = () => {};+ let created = 0, closed = 0, closeFails = 0;+ const result = { statementType: 1, chunkCount: 0, columnCount: 0, rowCount: 0 };+ const connection = () => ({+ run: async (sql: string) => sql === "SELECT stuck" ? new Promise((resolve) => { finish = () => resolve(result); }) : result,+ runAndReadAll: async () => ({ getRowsJson: () => [] }),+ interrupt() {},+ closeSync() { if (closeFails > 0) { closeFails--; throw new Error("IO Error: could not write the checkpoint"); } },+ });+ const binding = {+ version: () => "fake",+ DuckDBInstance: { create: async () => { created++; return { connect: async () => connection(), closeSync() { closed++; } }; } },+ StatementType: { SELECT: 1, EXPLAIN: 2 },+ } as unknown as NonNullable<Parameters<typeof createDataEngine>[0]>["binding"];+ const engine = createDataEngine({ botFolder: (id) => join(directory(), id), dataDir: directory(), binding });+ const database = await engine.forBot("b1");+ const running = database.run("SELECT stuck", { connection: "bot", timeoutMs: 120_000 });+ await new Promise((resolve) => setTimeout(resolve, 50));+ const releasing = engine.release();+ await new Promise((resolve) => setTimeout(resolve, 50));+ const during = database.run("SELECT 1", { connection: "panel" });+ expect(await releasing).toEqual([{ botId: "b1", why: "running" }]);+ await during;+ await database.run("SELECT 2", { connection: "panel" });+ expect(created).toBe(1);+ expect(await engine.release()).toEqual([{ botId: "b1", why: "running" }]);+ expect(closed).toBe(0);+ finish();+ await running;+ // A close that throws leaves the instance tracked, said with DuckDB's words, and tried again next time.+ closeFails = 1;+ expect(await engine.release()).toEqual([{ botId: "b1", why: "failed", detail: "IO Error: could not write the checkpoint" }]);+ await database.run("SELECT 3", { connection: "panel" });+ expect(created).toBe(1);+ expect(await engine.release()).toEqual([]);+ expect(closed).toBe(1);+ await database.run("SELECT 4", { connection: "panel" });+ expect(created).toBe(2);+ await engine.closeAll();+ }, TIMEOUT_MS);+});++/** A backup as releases before this one made it (the same format): its SQLite databases copied raw, a WAL beside its+ * bursts database, and no Data tables. */+function legacyBackup(source: string, out: string): string {+ const stage = directory();+ const entries: Array<{ path: string; type: "file" | "directory"; size: number; mode: number; sha256?: string }> = [];+ const walk = (from: string, prefix = "") => {+ for (const name of readdirSync(from).sort()) {+ const path = prefix ? `${prefix}/${name}` : name;+ const full = join(from, name);+ if (lstatSync(full).isDirectory()) {+ entries.push({ path, type: "directory", size: 0, mode: 0o700 });+ mkdirSync(join(stage, "data", path), { recursive: true });+ walk(full, path);+ } else {+ const bytes = readFileSync(full);+ entries.push({ path, type: "file", size: bytes.length, mode: 0o600, sha256: createHash("sha256").update(bytes).digest("hex") });+ writeFileSync(join(stage, "data", path), bytes);+ }+ }+ };+ mkdirSync(join(stage, "data"));+ walk(source);+ const files = entries.filter((entry) => entry.type === "file");+ writeFileSync(join(stage, "manifest.json"), JSON.stringify({+ summary: { format: "openmaus.workspace-backup", version: 1, id: randomUUID(), createdAt: new Date().toISOString(), appVersion: "0.1.174",+ files: files.length, directories: entries.length - files.length, bytes: files.reduce((sum, entry) => sum + entry.size, 0),+ bots: 0, groups: 0, threads: 0, messages: 0, exclusions: [], warnings: [] },+ sourceDataDir: source, clientState: {}, entries,+ }));+ const tar = createRequire(import.meta.url)("tar") as typeof import("tar");+ const plain = join(out, "legacy.tar");+ tar.c({ cwd: stage, portable: true, strict: true, sync: true, file: plain }, ["manifest.json", "data"]);+ const salt = randomBytes(16), iv = randomBytes(12);+ const header = Buffer.concat([Buffer.from("OMB-WORKSPACE-1\n"), salt, iv]);+ const cipher = createCipheriv("aes-256-gcm", scryptSync(PASSWORD, salt, 32, { N: 131_072, r: 8, p: 1, maxmem: 256 * 1024 ** 2 }), iv);+ cipher.setAAD(header);+ const path = join(out, "legacy.ombbackup");+ writeFileSync(path, Buffer.concat([header, cipher.update(readFileSync(plain)), cipher.final(), cipher.getAuthTag()]));+ return path;+}++describe("the 10 GB limit", () => {+ it("says how much of it is Data tables when they are most of it", () => {+ expect(tooLargeError(11 * 1024 ** 3, 3 * 1024 ** 3).message).toBe("The workspace exceeds the 10 GB backup limit.");+ const data = tooLargeError(11 * 1024 ** 3, 7.4 * 1024 ** 3);+ expect(data).toMatchObject({ errorKey: "serverError.backup.tooLargeData", errorParams: { size: "7.4 GB" } });+ expect(data.message).toBe("This installation exceeds the 10 GB backup limit; 7.4 GB of it is bots' Data tables.");+ });+});++describe("backups older releases made", () => {+ it("still restore: a raw bursts database and its WAL arrive as one database, and a backup without Data tables restores without them", async () => {+ const live = directory();+ const { db } = liveDatabase(join(live, "bursts.db"), "CREATE TABLE probe(i INTEGER PRIMARY KEY, pad TEXT)", "INSERT INTO probe VALUES (?, ?)", 50);+ const source = directory();+ try {+ // Taken as older releases took it: each file copied as it lay, the rows still in the WAL.+ for (const name of ["bursts.db", "bursts.db-wal", "bursts.db-shm"]) copyFileSync(join(live, name), join(source, name));+ } finally { db.close(); }+ mkdirSync(join(source, "bots", "b1"), { recursive: true });+ writeFileSync(join(source, "bots", "b1", "SOUL.md"), "Older soul.");+ writeFileSync(join(source, "notes.md"), "kept");+ const backup = legacyBackup(source, directory());+ const target = directory();+ // The destination's own Data tables and live burst log: the restore replaces them, and keeps them in its safety copy.+ mkdirSync(join(target, "bots", "b1"), { recursive: true });+ writeFileSync(join(target, "bots", "b1", "data.duckdb"), "destination tables");+ writeFileSync(join(target, "bursts.db-wal"), "destination log");+ const staged = await stageWorkspaceBackup(target, backup, { password: PASSWORD });+ commitPendingWorkspaceRestore(target, staged.id);+ const result = applyPendingWorkspaceRestore(target);+ expect(result).toMatchObject({ restored: true });+ expect(rowsOf(join(target, "bursts.db"), "SELECT i FROM probe ORDER BY i")).toBe(50);+ expect(readdirSync(target).filter((name) => name.startsWith("bursts.db")).sort()).toEqual(["bursts.db"]);+ expect(readFileSync(join(target, "notes.md"), "utf8")).toBe("kept");+ expect(readdirSync(join(target, "bots", "b1"))).toEqual(["SOUL.md"]);+ expect(readFileSync(join(result.safetyCopyPath!, "data", "bots", "b1", "data.duckdb"), "utf8")).toBe("destination tables");+ }, TIMEOUT_MS);++ it("refuses one whose bursts database is damaged with words a person can act on, changing nothing", async () => {+ const source = directory();+ writeFileSync(join(source, "bursts.db"), "not a database at all, but long enough to be read as a header by SQLite........");+ writeFileSync(join(source, "bursts.db-wal"), "nor a log");+ writeFileSync(join(source, "notes.md"), "kept");+ const backup = legacyBackup(source, directory());+ const target = directory();+ writeFileSync(join(target, "notes.md"), "here");+ const staged = await stageWorkspaceBackup(target, backup, { password: PASSWORD });+ expect(() => commitPendingWorkspaceRestore(target, staged.id)).toThrow(expect.objectContaining({ errorKey: "serverError.backup.legacyBursts",+ message: "This backup's burst records (bursts.db) are damaged, so nothing was restored and nothing here changed. Make a new backup where it came from." }));+ expect(applyPendingWorkspaceRestore(target)).toEqual({ restored: false });+ expect(readFileSync(join(target, "notes.md"), "utf8")).toBe("here");+ }, TIMEOUT_MS);+});diff --git a/server/workspace-backup-databases.ts b/server/workspace-backup-databases.tsnew file mode 100644index 0000000000..03e5211c4e--- /dev/null+++ b/server/workspace-backup-databases.ts@@ -0,0 +1,88 @@+// The databases in the data folder a full backup carries, and how each is taken whole. A database the server keeps in+// WAL mode holds its newest rows in the -wal file beside it, and a copy of the two taken one after the other while a+// writer goes on is not one database: each is taken instead by SQLite's own snapshot, which reads one moment of it.+// Each bot's Data tables (bots/<id>/data.duckdb) are copied as files once the Data engine has let go of them, which+// writes its WAL into the file: the maintenance gate does that (releaseDataForBackup) and keeps them shut until the+// backup ends.+// Not carried: sync/index.db (Sync with My Cloud's own records, the whole sync folder is this machine's), the engines'+// own databases (in their login homes, which never go), and DuckDB's spill folder (data-tmp), emptied when it closes.+import { existsSync, lstatSync, rmSync } from "node:fs";+import { join } from "node:path";+import { backup, DatabaseSync } from "node:sqlite";++import type { DataEngine } from "./data/types.ts";+import { userErrorThrown } from "./user-errors.ts";++/** Each database the server keeps in WAL mode at the data folder's top, and the name of its snapshot. */+export const SNAPSHOT_DATABASES: Record<string, string> = { "messages.db": "messages-snapshot.db", "runtime.db": "runtime-snapshot.db", "bursts.db": "bursts-snapshot.db" };+/** The pages a snapshot copies in one step: every page, as a positive Int32, which is all Node accepts. */+export const ONE_STEP = 2_147_483_647;+const LABELS: Record<string, string> = { "messages.db": "message", "runtime.db": "runtime", "bursts.db": "burst" };++/** The live WAL and shared-memory files of the snapshotted databases. */+export const LIVE_DATABASE_SIDECARS = new Set(Object.keys(SNAPSHOT_DATABASES).flatMap((name) => [`${name}-wal`, `${name}-shm`]));++/** Sidecars a backup leaves out, which older backups carried raw beside their database: they still restore, folded into it. */+export const LEGACY_SIDECARS = new Set(["bursts.db-wal", "bursts.db-shm"]);++/** One moment of each database, as `snapshot/<snapshot name>` in DELETE mode: never the live file and its log. */+export async function snapshotDatabases(root: string, snapshot: string): Promise<void> {+ for (const [name, snapshotName] of Object.entries(SNAPSHOT_DATABASES)) {+ const sourceDb = join(root, name);+ if (!existsSync(sourceDb)) continue;+ if (lstatSync(sourceDb).isSymbolicLink()) throw new Error(`The ${LABELS[name]} database must not be a symbolic link.`);+ // Another connection may open this database meanwhile; without a busy timeout the backup fails at once ("database is locked").+ const db = new DatabaseSync(sourceDb, { readOnly: true, timeout: 5_000 });+ // Node 26's native backup completion can wait on unrelated event-loop activity after an async scrypt; this pulse keeps it moving.+ const completionPulse = setInterval(() => {}, 25);+ // In one step: a backup in steps starts again whenever another connection writes between them, and a writer that keeps+ // writing would keep it from ever finishing. SQLite reads -1 as every page, but Node 24.22 refuses a rate under 1, so+ // the step is the largest rate Node takes, more pages than any database here holds.+ try { await backup(db, join(snapshot, snapshotName), { rate: ONE_STEP }); }+ finally { clearInterval(completionPulse); db.close(); }+ const snapshotDb = new DatabaseSync(join(snapshot, snapshotName));+ try { snapshotDb.exec("PRAGMA journal_mode = DELETE"); } finally { snapshotDb.close(); }+ }+}++/** An older backup's raw WAL goes into its database before the restore installs it, so the restored folder holds one+ * file per database as a new backup does. SQLite applies what of the log matches the database, as it would have on open. */+export function foldLegacySidecars(prepared: string): void {+ for (const name of Object.keys(SNAPSHOT_DATABASES)) {+ const wal = join(prepared, `${name}-wal`);+ const shm = join(prepared, `${name}-shm`);+ if (!LEGACY_SIDECARS.has(`${name}-wal`) || (!existsSync(wal) && !existsSync(shm))) continue;+ // The shared-memory index is the source server's; SQLite rebuilds it from the log.+ rmSync(shm, { force: true });+ if (existsSync(join(prepared, name)) && existsSync(wal)) {+ try {+ const db = new DatabaseSync(join(prepared, name));+ try { db.exec("PRAGMA journal_mode = DELETE"); } finally { db.close(); }+ } catch (error) {+ throw Object.assign(userErrorThrown("serverError.backup.legacyBursts"), { cause: error });+ }+ }+ rmSync(wal, { force: true });+ }+}++/** Part of the gate's flush before a backup or restore: every bot's Data tables written into their files and let go. One+ * still open (a statement that did not stop, or a close that failed) could be missing what it wrote, so the backup stops+ * and says which bot, and that a restart ends it: until then every attempt finds it the same. */+export async function releaseDataForBackup(engine: Pick<DataEngine, "release">, name: (botId: string) => string | undefined = () => undefined): Promise<void> {+ const [held] = await engine.release();+ if (!held) return;+ const bot = name(held.botId) ?? held.botId;+ throw Object.assign(held.why === "running"+ ? userErrorThrown("serverError.backup.dataQueryRunning", { bot })+ : userErrorThrown("serverError.backup.dataCloseFailed", { bot, detail: held.detail ?? "" }), { status: 409 });+}++/** The 10 GB limit's words: how much of it is Data tables when they are most of it, the part a person would look at. */+export function tooLargeError(bytes: number, dataBytes: number): Error {+ if (dataBytes * 2 <= bytes) return new Error("The workspace exceeds the 10 GB backup limit.");+ return userErrorThrown("serverError.backup.tooLargeData", { size: `${(dataBytes / 1024 ** 3).toFixed(1)} GB` });+}++/** A bot's Data tables: its database and a WAL left beside it. */+export const DATA_TABLES = /^bots\/[^/]+\/data\.duckdb(?:\.wal)?$/;diff --git a/server/workspace-backup-http.ts b/server/workspace-backup-http.tsindex 08e902e252..e63167e062 100644--- a/server/workspace-backup-http.ts+++ b/server/workspace-backup-http.ts@@ -15,6 +15,9 @@ import {import type { RequestAuth } from "./request-auth.ts";import { userErrorFields } from "./user-errors.ts";+/** For the gate's flush (server/index.ts): each bot's Data tables written into their files and let go. */+export { releaseDataForBackup } from "./workspace-backup-databases.ts";+const PREFIX = "/api/workspace-backup";const MAX_UPLOAD_BYTES = MAX_WORKSPACE_BACKUP_UPLOAD_BYTES;const MAX_CLIENT_STATE_BYTES = 2 * 1024 ** 2;diff --git a/server/workspace-backup-policy.test.ts b/server/workspace-backup-policy.test.tsindex 1ce33ba30f..5730c27976 100644--- a/server/workspace-backup-policy.test.ts+++ b/server/workspace-backup-policy.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, liveDataEnginePath, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";+import { dataEngineSpillPath, ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";describe("workspace backup data boundary", () => {it("exports ordinary settings only and retains destination connection sections unchanged", () => {@@ -89,13 +89,13 @@ describe("workspace backup data boundary", () => {}});- it("leaves out a bot's live DuckDB database, WAL and spill directory, and nothing else in its folder", () => {- for (const path of ["bots/b1/data.duckdb", "bots/b1/data.duckdb.wal", "bots/b1/data-tmp", "bots/b1/data-tmp/duckdb_temp_storage-0.tmp"]) {- expect(liveDataEnginePath(path)).toBe(true);+ it("leaves out a bot's DuckDB spill directory, and nothing else in its folder: its Data tables go", () => {+ for (const path of ["bots/b1/data-tmp", "bots/b1/data-tmp/duckdb_temp_storage-0.tmp"]) {+ expect(dataEngineSpillPath(path)).toBe(true);}- for (const path of ["bots/b1/SOUL.md", "bots/b1/sheet.json", "bots/b1/data.duckdb.bak", "bots/b1/data-tmp.zip", "bots/data.duckdb", "data.duckdb",+ for (const path of ["bots/b1/data.duckdb", "bots/b1/data.duckdb.wal", "bots/b1/SOUL.md", "bots/b1/sheet.json", "bots/b1/data.duckdb.bak", "bots/b1/data-tmp.zip", "bots/data.duckdb", "data.duckdb","workspaces/bot/data.duckdb", "bots/b1/exports/data.duckdb", "attachments/data-tmp/x"]) {- expect(liveDataEnginePath(path)).toBe(false);+ expect(dataEngineSpillPath(path)).toBe(false);}});diff --git a/server/workspace-backup-policy.ts b/server/workspace-backup-policy.tsindex f2baec5e97..63ac5ae8c7 100644--- a/server/workspace-backup-policy.ts+++ b/server/workspace-backup-policy.ts@@ -62,9 +62,10 @@ export function ephemeralWorkspaceTokenPath(path: string): boolean {return /^(?:hook-tokens(?:\/|$)|sessions\.json\.open$)/.test(path);}-/** Not a consistent snapshot while the engine holds it open (unflushed WAL), and reloadable from its sources. */-export function liveDataEnginePath(path: string): boolean {- return /^bots\/[^/]+\/(?:data\.duckdb(?:\.wal)?$|data-tmp(?:\/|$))/.test(path);+/** DuckDB's spill folder for a bot's Data tables: scratch space for one query, emptied when the database closes. The+ * database itself (data.duckdb) goes, taken at rest (workspace-backup-databases.ts). */+export function dataEngineSpillPath(path: string): boolean {+ return /^bots\/[^/]+\/data-tmp(?:\/|$)/.test(path);}/** Read the link text, never follow it. A link points at the bot's own skill, or at the same-named skill brought indiff --git a/server/workspace-backup-team-private.test.ts b/server/workspace-backup-team-private.test.tsindex d858a550db..a19b1a0847 100644--- a/server/workspace-backup-team-private.test.ts+++ b/server/workspace-backup-team-private.test.ts@@ -46,6 +46,8 @@ function teamData(root: string): void {file(join(root, "task-workspaces", "bot", "main", "plan.md"), "shared plan");file(join(root, "task-workspaces", "bot", "bob-chat", "draft.md"), "Bob's draft");file(join(root, "people", BOB, "about.json"), "{\"aboutMe\":\"interviewing elsewhere\"}");+ file(join(root, "bots", "bot", "data.duckdb"), "team tables");+ file(join(root, "bots", "bobs-own", "data.duckdb"), "Bob's own tables");const db = new DatabaseSync(join(root, "messages.db"));db.exec("CREATE TABLE messages(thread_id TEXT, id TEXT, at INTEGER, role TEXT, kind TEXT, text TEXT, json TEXT, PRIMARY KEY(thread_id,id)); CREATE TABLE thread_state(thread_id TEXT PRIMARY KEY, active_leaf_id TEXT);"+ " CREATE TABLE chat_followups(id TEXT PRIMARY KEY, kind TEXT, owner_id TEXT, thread_id TEXT, send_id TEXT, status TEXT, payload TEXT);"@@ -102,6 +104,9 @@ describe("what a Team Cloud's export leaves out (the private sentence: not the Oexpect(omittedAsTeamPrivate("task-workspaces/bot/bob-chat/draft.md", privacy)).toBe(true);expect(omittedAsTeamPrivate("task-workspaces/bot/main/plan.md", privacy)).toBe(false);expect(omittedAsTeamPrivate(`people/${BOB}/about.json`, privacy)).toBe(true);+ // Every bot's Data tables: a team bot's hold tables members loaded in their private chats, unmarked.+ for (const path of ["bots/bobs-own/data.duckdb", "bots/bot/data.duckdb", "bots/bot/data.duckdb.wal"]) expect(omittedAsTeamPrivate(path, privacy), path).toBe(true);+ expect(omittedAsTeamPrivate("bots/bot/SOUL.md", privacy)).toBe(false);expect(omittedAsTeamPrivate("peoplesoft/x", privacy)).toBe(false);for (const kept of ["events/bob-chat.ndjson", "native/bob-chat.ndjson", `memory-journal/bot--member-${BOB}.ndjson`]) expect(omittedAsTeamPrivate(kept, privacy), kept).toBe(true);for (const shared of ["events/main.ndjson", "native/main.ndjson", "memory-journal/bot.ndjson", "memory-journal/bot--room-room.ndjson"]) expect(omittedAsTeamPrivate(shared, privacy), shared).toBe(false);@@ -160,6 +165,11 @@ describe("what a Team Cloud's export leaves out (the private sentence: not the Oexpect(existsSync(join(team.data, "attachments", "both.png"))).toBe(true);expect(existsSync(join(team.data, "attachments", "avatar.png"))).toBe(true);expect(existsSync(join(team.data, "workspaces", "bobs-own"))).toBe(false);+ // No bot's Data tables leave a Team Cloud, the team's bots' included; its notes still do.+ expect(existsSync(join(team.data, "bots", "bot", "data.duckdb"))).toBe(false);+ expect(team.warnings).toContain(TEAM_PRIVATE_NOTE);+ expect(TEAM_PRIVATE_NOTE).toContain("the bots' Data tables");+ expect(existsSync(join(team.data, "bots", "bobs-own"))).toBe(false);expect(table(join(team.data, "messages.db"), "SELECT thread_id AS id FROM messages").map((row) => row.id).sort()).toEqual(["main", "outside-thread", "room-thread"]);expect(table(join(team.data, "runtime.db"), "SELECT id FROM assignments").map((row) => row.id)).toEqual(["as-team"]);expect(textOf(join(team.data, "messages.db")).toLowerCase()).not.toContain("secret");@@ -170,6 +180,9 @@ describe("what a Team Cloud's export leaves out (the private sentence: not the Oconst home = await exported(own);expect(home.warnings).not.toContain(TEAM_PRIVATE_NOTE);expect(existsSync(join(home.data, "workspaces", `bot--member-${BOB}`, "MEMORY.md"))).toBe(true);+ // A personal export carries every bot's Data tables.+ expect(textOf(join(home.data, "bots", "bot", "data.duckdb"))).toBe("team tables");+ expect(textOf(join(home.data, "bots", "bobs-own", "data.duckdb"))).toBe("Bob's own tables");expect(table(join(home.data, "messages.db"), "SELECT thread_id AS id FROM messages").map((row) => row.id).sort()).toEqual(["bob-chat", "bobs-inbox", "main", "outside-thread", "room-thread"]);}, 60_000);});diff --git a/server/workspace-backup-team-private.ts b/server/workspace-backup-team-private.tsindex 36b6bf2326..91d74d7b0b 100644--- a/server/workspace-backup-team-private.ts+++ b/server/workspace-backup-team-private.ts@@ -55,9 +55,11 @@ export function teamPrivateThreads(files: { starters: string; groups: string; boconst memberLayer = (id: string): boolean => isLayerId(id) && layerAudience(id).startsWith("member:");/** A path in the data folder that is one member's: their folder under people/, their inbox, a file only their chats use,- * or anything named for one of their conversations, their layers or their own bot, wherever it is kept. */+ * or anything named for one of their conversations, their layers or their own bot, wherever it is kept. Every bot's Data+ * tables too: a bot has one database whatever chat a table was loaded in, and it does not record which. */export function omittedAsTeamPrivate(path: string, privacy: TeamPrivacy): boolean {if (/^(?:people(?:\/|$)|person-inbox\.json)/.test(path)) return true;+ if (/^bots\/[^/]+\/data\.duckdb(?:\.wal)?$/.test(path)) return true;const attachment = /^attachments\/([^/]+)$/.exec(path)?.[1];if (attachment && privacy.attachments.has(attachment)) return true;return path.split("/").some((part) => {@@ -184,4 +186,4 @@ export function stripTeamPrivate(snapshot: { messages: string; runtime: string }});}-export const TEAM_PRIVATE_NOTE = "Members' private chats are theirs alone and are not in this export: their conversations, what bots remember from them, their own MausBot and their About you stay out.";+export const TEAM_PRIVATE_NOTE = "Members' private chats are theirs alone and are not in this export: their conversations, what bots remember from them, their own MausBot and their About you stay out, and so do the bots' Data tables, which don't record whose chat loaded them.";diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex 9447510195..3ef8853130 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -7,7 +7,7 @@ import {} from "node:fs";import { isAbsolute, join, parse, posix, relative, resolve, sep, win32 } from "node:path";import { homedir } from "node:os";-import { backup, DatabaseSync } from "node:sqlite";+import { DatabaseSync } from "node:sqlite";import { pipeline } from "node:stream/promises";import { Worker } from "node:worker_threads";import { writeFileAtomic } from "./atomic.ts";@@ -15,9 +15,10 @@ import { userErrorFields, userErrorThrown } from "./user-errors.ts";import { WORKSPACE_BACKUP_CLIENT_KEYS } from "../shared/workspace-backup-client.ts";import { INSTRUCTION_FILE, restorePaths, validRelative } from "./workspace-backup-paths.ts";import { cjkSearchText } from "./cjk-search.ts";-import { ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, liveDataEnginePath, managedTaskSkillLink, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";+import { dataEngineSpillPath, ephemeralWorkspaceTokenPath, excludedWorkspaceAuthPath, managedTaskSkillLink, portableWorkspaceConfig, redownloadedOrgLibraryPath, restoredWorkspaceConfig } from "./workspace-backup-policy.ts";import { omittedAsTeamPrivate, routinesWithoutTeamPrivate, stripTeamPrivate, TEAM_PRIVATE_NOTE, teamPrivateAttachments, teamPrivateThreads, withoutTeamPrivate } from "./workspace-backup-team-private.ts";import { flushLaterSaves } from "./save-batch.ts";+import { DATA_TABLES, foldLegacySidecars, LEGACY_SIDECARS, LIVE_DATABASE_SIDECARS, SNAPSHOT_DATABASES, snapshotDatabases, tooLargeError } from "./workspace-backup-databases.ts";import type { WorkspaceBackupClientState, WorkspaceBackupPrivateMetadata, WorkspaceBackupSummary, WorkspaceLeftBehind } from "../shared/workspace-backup.ts";export type { WorkspaceBackupSummary, WorkspaceBackupPrivateMetadata } from "../shared/workspace-backup.ts";@@ -111,8 +112,6 @@ function preserved(name: string): boolean {const folded = name.toLowerCase();return excluded(folded) && !LIVE_DATABASE_SIDECARS.has(folded) && folded !== WAITS_FILE;}-const SNAPSHOT_DATABASES: Record<string, string> = { "messages.db": "messages-snapshot.db", "runtime.db": "runtime-snapshot.db" };-const LIVE_DATABASE_SIDECARS = new Set(Object.keys(SNAPSHOT_DATABASES).flatMap((name) => [`${name}-wal`, `${name}-shm`]));function keptInPlace(name: string): boolean {return preserved(name) || name.toLowerCase() === "sessions.json.open";}@@ -322,25 +321,14 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Crconst foldedPaths = new Map<string, string>();const warnings = ["Stop external editors and managed desktops before exporting; files written outside this server cannot be frozen by the backup gate.", "Conversation text and user files are not redacted and may contain secrets you pasted. Keep the encrypted backup private.", RESTORE_WARNING];let bytes = 0;+ let dataBytes = 0;let skippedLinks = 0;let skippedDependencies = 0;let skippedWorkLinks = 0;let copiedLinks = 0;try {const root = realpathSync(dataDir);- for (const [name, snapshotName] of Object.entries(SNAPSHOT_DATABASES)) {- const sourceDb = join(root, name);- if (!existsSync(sourceDb)) continue;- if (lstatSync(sourceDb).isSymbolicLink()) throw new Error(`The ${name === "messages.db" ? "message" : "runtime"} database must not be a symbolic link.`);- // Another connection may open this database meanwhile; without a busy timeout the backup fails at once ("database is locked").- const db = new DatabaseSync(sourceDb, { readOnly: true, timeout: 5_000 });- // Node 26's native backup completion can wait on unrelated event-loop activity after an async scrypt; this pulse keeps it moving.- const completionPulse = setInterval(() => {}, 25);- try { await backup(db, join(snapshot, snapshotName)); }- finally { clearInterval(completionPulse); db.close(); }- const snapshotDb = new DatabaseSync(join(snapshot, snapshotName));- try { snapshotDb.exec("PRAGMA journal_mode = DELETE"); } finally { snapshotDb.close(); }- }+ await snapshotDatabases(root, snapshot);const teamPrivate = teamPrivateThreads({ starters: join(root, "thread-starters.json"), groups: join(root, "groups.json"), bots: join(root, "bots.json") });const privacy = teamPrivate && { ...teamPrivate, attachments: teamPrivateAttachments(root, join(snapshot, SNAPSHOT_DATABASES["messages.db"]!), teamPrivate) };if (privacy) {@@ -349,9 +337,9 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Cr}const walk = (directory: string, prefix = "", chain: string[] = [root]) => {for (const name of readdirSync(directory).sort()) {- if (!prefix && excluded(name)) continue;+ if (!prefix && (excluded(name) || LEGACY_SIDECARS.has(name))) continue;const path = prefix ? `${prefix}/${name}` : name;- if (excludedWorkspaceAuthPath(path) || ephemeralWorkspaceTokenPath(path) || redownloadedOrgLibraryPath(path) || liveDataEnginePath(path)) continue;+ if (excludedWorkspaceAuthPath(path) || ephemeralWorkspaceTokenPath(path) || redownloadedOrgLibraryPath(path) || dataEngineSpillPath(path)) continue;if (privacy && omittedAsTeamPrivate(path, privacy)) continue;// Reject noncanonical spellings: a case-sensitive host must not export auth paths active on Windows/Mac.if (forbiddenArchivePath(path)) throw new Error("A workspace filename conflicts with a protected authentication or runtime path.");@@ -407,6 +395,8 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Crentries.push({ path, type: "directory", size: 0, mode: 0o700 });walk(source, path, [...chain, source]);} else if (stat.isFile()) {+ // Said before a copy that could take minutes: Data tables are the files a workspace grows past the limit with.+ if (DATA_TABLES.test(path) && bytes + stat.size > MAX_WORKSPACE_BACKUP_BYTES) throw tooLargeError(bytes + stat.size, dataBytes + stat.size);let copied: { size: number; mode: number; sha256: string };if (path === "config.json" || path === "webhooks.json" || (privacy && (path === "bots.json" || path === "routines.json"))) {const value = privateJson(source);@@ -422,7 +412,8 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Crcopied = { size: lstatSync(destination).size, mode: 0o600, sha256: hashFile(destination) };} else copied = copyRegular(SNAPSHOT_DATABASES[path] ? join(snapshot, SNAPSHOT_DATABASES[path]) : source, destination);bytes += copied.size;- if (bytes > MAX_WORKSPACE_BACKUP_BYTES) throw new Error("The workspace exceeds the 10 GB backup limit.");+ if (DATA_TABLES.test(path)) dataBytes += copied.size;+ if (bytes > MAX_WORKSPACE_BACKUP_BYTES) throw tooLargeError(bytes, dataBytes);entries.push({ path, type: "file", ...copied });} else throw new Error(`Cannot back up special or live runtime file: ${path}`);}@@ -724,6 +715,7 @@ function prepareRestore(dataDir: string, id: string, manifest: Manifest): stringconst destination = join(prepared, entry.path);if (entry.type === "file") copyRegular(join(job, "staged", "data", entry.path), destination);}+ foldLegacySidecars(prepared);const changeJson = (name: string, change: (value: unknown) => void) => {const path = join(prepared, name);if (!existsSync(path)) return;@@ -987,5 +979,5 @@ export function removeWorkspaceBackupJob(dataDir: string, id: string): void {}export function omittedFromWorkspaceBackup(path: string): boolean {- return excluded(path.split("/")[0]) || excludedWorkspaceAuthPath(path) || ephemeralWorkspaceTokenPath(path) || redownloadedOrgLibraryPath(path) || liveDataEnginePath(path);+ return excluded(path.split("/")[0]) || excludedWorkspaceAuthPath(path) || ephemeralWorkspaceTokenPath(path) || redownloadedOrgLibraryPath(path) || dataEngineSpillPath(path);}diff --git a/src/components/AlwaysOnHomeSection.tsx b/src/components/AlwaysOnHomeSection.tsxindex eff1b1b78a..5a45a912fc 100644--- a/src/components/AlwaysOnHomeSection.tsx+++ b/src/components/AlwaysOnHomeSection.tsx@@ -184,7 +184,7 @@ function AddedComputer({ server, status, offered }: { server: SavedServer; statu{said && <p role="alert" className="text-[12px] leading-4 text-danger">{said}</p>}<ul className="flex list-disc flex-col gap-1 pl-4 text-[12px] leading-4 text-ink-secondary"><li>{t("alwaysOn.added.sidebar", { name: server.name })}</li>- {offered && <li>{t("alwaysOn.added.keepRunning", { name: server.name })}</li>}+ {offered && <li>{t("alwaysOn.added.keepRunning", { name: server.name })} {t("rail.makeHomeDataStays", { name: server.name })}</li>}<li>{t("alwaysOn.added.screen", { app: productName() })}</li></ul></div>diff --git a/src/components/MoveToMyCloud.dom.test.ts b/src/components/MoveToMyCloud.dom.test.tsindex 9bde6d3d43..6c84f217cb 100644--- a/src/components/MoveToMyCloud.dom.test.ts+++ b/src/components/MoveToMyCloud.dom.test.ts@@ -92,6 +92,7 @@ it("a bot's menu offers Move to My Cloud, and it goes after one confirm", asyncawait menu({ id: "ada", name: "Ada" });await click(q("[data-item]"));expect(q("[data-bot-move-confirm]")!.textContent).toContain("Ada's chats, skills, memory and routines go with it");+ expect(q("[data-bot-move-confirm]")!.textContent).toContain("Tables Ada loaded in Data don't move: they stay on this computer, where Ada can't open them once it lives on My Cloud.");await click(all("button").find((button) => button.textContent === "Move") ?? null);expect(page.moveBots).toHaveBeenCalledWith(["ada"]);});diff --git a/src/components/MoveToMyCloud.tsx b/src/components/MoveToMyCloud.tsxindex 81b9aba7d7..5b676afcff 100644--- a/src/components/MoveToMyCloud.tsx+++ b/src/components/MoveToMyCloud.tsx@@ -58,7 +58,7 @@ export function MoveChooser({ onClose }: { onClose: () => void }) {<div ref={root} role="dialog" aria-modal="true" aria-labelledby="move-chooser-title" data-move-chooser=""className="ui-modal relative flex max-h-[min(640px,calc(100dvh-32px))] w-[min(440px,calc(100vw-32px))] flex-col border-0 p-5 text-ink"><h2 id="move-chooser-title" className="pe-8 text-[17px] font-semibold">{t("cloudSend.choose.title")}</h2>- <p className="mt-1 text-[14px] leading-5 text-ink-secondary">{t("cloudSend.choose.line")}</p>+ <p className="mt-1 text-[14px] leading-5 text-ink-secondary">{t("cloudSend.choose.line")} {t("cloudSend.dataStays")}</p><button type="button" disabled={busy} data-move-everything="" className={`${PRIMARY_BUTTON} mt-4 w-full justify-center`}onClick={() => go(page?.moveEverything)}>{t("cloudSend.choose.everything")}</button><div className="mt-4 flex items-center gap-2">@@ -131,7 +131,7 @@ export function useMoveToMyCloud() {},dialog: <ConfirmDialog open={asked !== null} tone="neutral" icon={<Cloud size={18} />} title={t("cloudSend.botMove.confirmTitle", names)}body={<span className="flex flex-col gap-2" data-bot-move-confirm="">- <span>{t("cloudSend.botMove.confirmBody", names)}</span>+ <span>{t("cloudSend.botMove.confirmBody", names)} {t("cloudSend.botMove.dataStays", names)}</span>{error && <span role="alert" className="text-danger">{error}</span>}</span>}confirmLabel={t("cloudSend.botMove.confirm")} pending={busy} onCancel={() => setAsked(null)} onConfirm={confirm} />,diff --git a/src/components/MoveToTeam.test.ts b/src/components/MoveToTeam.test.tsindex e093fe3c84..1cf608b533 100644--- a/src/components/MoveToTeam.test.ts+++ b/src/components/MoveToTeam.test.ts@@ -109,7 +109,7 @@ it("the bot menu has one Move to item per team, none without a team or for a botconst confirm = html(menu);for (const said of ["Move Scout to Acme?", "Only you and Acme's admins can use Scout until you share it.","Goes with Scout: instructions, skills, files, routines, and your chats with Scout", "Your chats stay private there: only you can see them.",- "Stays on My Cloud: what Scout remembers, your connections, and MausBot", "There's no way back: you can't move it back to My Cloud.", "Move to Acme"]) expect(confirm).toContain(said);+ "Stays on My Cloud: what Scout remembers, your connections, and MausBot", "Tables Scout loaded in Data don't move: they stay on My Cloud, where Scout can't open them once it's in Acme.", "There's no way back: you can't move it back to My Cloud.", "Move to Acme"]) expect(confirm).toContain(said);expect(page.moveToTeam, "nothing moves until the confirm").not.toHaveBeenCalled();});diff --git a/src/components/MoveToTeam.tsx b/src/components/MoveToTeam.tsxindex 8386211a08..90b2ae89b8 100644--- a/src/components/MoveToTeam.tsx+++ b/src/components/MoveToTeam.tsx@@ -68,6 +68,7 @@ export function useMoveToTeam({ blocked }: { blocked: (bot: Bot) => string | und<span>{t("teamMove.goes", names)}</span><span>{t("teamMove.private", names)}</span><span>{t("teamMove.staysOnMyCloud", names)}</span>+ <span>{t("teamMove.dataStays", names)}</span><span data-team-move-final className="font-medium text-ink">{t("teamMove.noWayBack", names)}</span>{error && <span role="alert" className="text-danger">{error}</span>}</span>}diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.tsindex 8419a170c2..1104edc4fb 100644--- a/src/components/PlacesRail.test.ts+++ b/src/components/PlacesRail.test.ts@@ -611,7 +611,7 @@ it("a server of the person's own that main offers as home: its menu's one tap stawait act(async () => { host.querySelector("[data-rail-menu]")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });const menu = await menuOf("garage");const row = menu!.querySelector("[data-rail-make-home-start]");- expect(row?.textContent).toBe("Make Garage server my homeMoves this computer's bots, chats, memory and routines to Garage server, and this computer then works for it.");+ expect(row?.textContent).toBe("Make Garage server my homeMoves this computer's bots, chats, memory and routines to Garage server, and this computer then works for it. Tables your bots loaded in Data don't move: they stay on this computer, where your bots can't open them once they live on Garage server.");await click(row);await settle();expect(makeHome).toHaveBeenCalledWith("garage");diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsxindex f5bc92c8a7..bc05ca9793 100644--- a/src/components/PlacesRail.tsx+++ b/src/components/PlacesRail.tsx@@ -211,7 +211,7 @@ function MakeHomeRow({ place, onStarted }: { place: RailPlace; onStarted: () =>{busy ? <Loader2 size={15} aria-hidden="true" className="mt-0.5 shrink-0 animate-spin motion-reduce:animate-none" /> : <House size={15} aria-hidden="true" className="mt-0.5 shrink-0" />}<span className="flex min-w-0 flex-col text-start"><span className="text-[13px] text-ink">{t("rail.makeHome", { name: place.name })}</span>- <span className="text-[12px] leading-snug text-ink-secondary">{t("rail.makeHomeSub", { name: place.name })}</span>+ <span className="text-[12px] leading-snug text-ink-secondary">{t("rail.makeHomeSub", { name: place.name })} {t("rail.makeHomeDataStays", { name: place.name })}</span></span></button>{said && <p role="alert" className="px-1.5 pb-1 text-[12px] text-danger">{said}</p>}diff --git a/src/locales/en.json b/src/locales/en.jsonindex a172bf1117..b4181005db 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -834,6 +834,7 @@"rail.remove": "Remove from list","rail.makeHome": "Make {name} my home","rail.makeHomeSub": "Moves this computer's bots, chats, memory and routines to {name}, and this computer then works for it.",+ "rail.makeHomeDataStays": "Tables your bots loaded in Data don't move: they stay on this computer, where your bots can't open them once they live on {name}.","rail.makeHomeFailed": "Your bots didn't start moving. Try again in a moment.","twoPlaces.title": "Bring your bots together","twoPlaces.body": "Your bots live in two places, so they can't work together. Bring them together on {place}?",@@ -1481,6 +1482,7 @@"cloudSend.move.queuedAny": "Waiting for your other computer to finish moving to My Cloud. Your bots move right after.","cloudSend.choose.title": "Move your bots to My Cloud","cloudSend.choose.line": "Choose which bots move. The others stay on this computer and keep working here.",+ "cloudSend.dataStays": "Tables your bots loaded in Data don't move: they stay on this computer, where moved bots can't open them, and Move everything deletes them with this computer's copy 30 days after the move, once My Cloud is paid for.","cloudSend.choose.everything": "Move everything","cloudSend.choose.moveSome": "Move {count} bots","cloudSend.choose.moveOne": "Move 1 bot",@@ -1495,6 +1497,7 @@"cloudSend.botMove.menu": "Move to My Cloud","cloudSend.botMove.confirmTitle": "Move {bot} to My Cloud?","cloudSend.botMove.confirmBody": "{bot}'s chats, skills, memory and routines go with it, and it works on My Cloud from then on. Your other bots stay on this computer.",+ "cloudSend.botMove.dataStays": "Tables {bot} loaded in Data don't move: they stay on this computer, where {bot} can't open them once it lives on My Cloud.","cloudSend.botMove.confirm": "Move","cloudSend.botMove.moving": "Moving {bot} to My Cloud…","cloudSend.botMove.movingMany": "Moving {count} bots to My Cloud…",@@ -7886,6 +7889,7 @@"teamMove.goes": "Goes with {bot}: instructions, skills, files, routines, and your chats with {bot}","teamMove.private": "Your chats stay private there: only you can see them.","teamMove.staysOnMyCloud": "Stays on My Cloud: what {bot} remembers, your connections, and MausBot",+ "teamMove.dataStays": "Tables {bot} loaded in Data don't move: they stay on My Cloud, where {bot} can't open them once it's in {team}.","teamMove.noWayBack": "There's no way back: you can't move it back to My Cloud.","teamMove.confirm": "Move to {team}","teamMove.moving": "Moving {bot} to {team}…",@@ -9927,6 +9931,10 @@"native.decider.routerRejected": "OpenRouter rejected this key. Check it at openrouter.ai/keys and paste it again.","serverError.decider.accountFormat": "decider.workersAiAccountId a Cloudflare account ID is 32 letters and digits","serverError.backup.recursiveLink": "Cannot back up a symbolic link to the folder that contains it: {path}",+ "serverError.backup.dataQueryRunning": "{bot}'s Data query is still running and did not stop when asked. Fully quit and reopen OpenMausBot (or restart the hosted server) to stop it, then try again.",+ "serverError.backup.dataCloseFailed": "{bot}'s Data tables could not be closed for the backup ({detail}). Fully quit and reopen OpenMausBot (or restart the hosted server), then try again.",+ "serverError.backup.tooLargeData": "This installation exceeds the 10 GB backup limit; {size} of it is bots' Data tables.",+ "serverError.backup.legacyBursts": "This backup's burst records (bursts.db) are damaged, so nothing was restored and nothing here changed. Make a new backup where it came from.","chat.notice.exportedGoal.working": "{before}[Goal: working]{content}","chat.notice.exportedGoal.completed": "{before}[Goal: completed]{content}","chat.notice.exportedGoal.needs-input": "{before}[Goal: needs-input]{content}",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 20958d5738..3c67c63c77 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -810,6 +810,7 @@"rail.remove": "Remover da lista","rail.makeHome": "Definir {name} como base dos meus bots","rail.makeHomeSub": "Transfere os bots, conversas, memória e rotinas deste computador para {name}. Depois, este computador passa a trabalhar para ele.",+ "rail.makeHomeDataStays": "As tabelas que seus bots carregaram em Dados não são transferidas: ficam neste computador, onde seus bots não conseguem abri-las depois que passam a viver em {name}.","rail.makeHomeFailed": "A transferência dos seus bots não começou. Tente novamente em instantes.","twoPlaces.title": "Reúna seus bots","twoPlaces.body": "Seus bots estão em dois lugares e, por isso, não conseguem trabalhar juntos. Quer reuni-los em {place}?",@@ -7615,6 +7616,7 @@"cloudSend.move.queuedAny": "Esperando seu outro computador terminar de ir para o Cloud. Seus bots vão logo depois.","cloudSend.choose.title": "Levar seus bots para o Cloud","cloudSend.choose.line": "Escolha quais bots vão. Os outros ficam neste computador e continuam funcionando aqui.",+ "cloudSend.dataStays": "As tabelas que seus bots carregaram em Dados não são transferidas: ficam neste computador, onde os bots transferidos não conseguem abri-las, e Levar tudo as apaga junto com a cópia deste computador 30 dias após a transferência, depois que o My Cloud for pago.","cloudSend.choose.everything": "Levar tudo","cloudSend.choose.moveSome": "Levar {count} bots","cloudSend.choose.moveOne": "Levar 1 bot",@@ -7629,6 +7631,7 @@"cloudSend.botMove.menu": "Levar para o Cloud","cloudSend.botMove.confirmTitle": "Levar {bot} para o Cloud?","cloudSend.botMove.confirmBody": "As conversas, skills, memória e rotinas de {bot} vão junto, e a partir daí ele trabalha no Cloud. Seus outros bots ficam neste computador.",+ "cloudSend.botMove.dataStays": "As tabelas que {bot} carregou em Dados não são transferidas: ficam neste computador, onde {bot} não consegue abri-las depois que passa a viver no My Cloud.","cloudSend.botMove.confirm": "Levar","cloudSend.botMove.moving": "Levando {bot} para o Cloud…","cloudSend.botMove.movingMany": "Levando {count} bots para o Cloud…",@@ -7683,6 +7686,7 @@"teamMove.goes": "Vão com {bot}: instruções, habilidades, arquivos, rotinas e suas conversas com {bot}","teamMove.private": "Suas conversas continuam privadas lá: só você pode vê-las.","teamMove.staysOnMyCloud": "Ficam no My Cloud: o que {bot} lembra, suas conexões e o MausBot",+ "teamMove.dataStays": "As tabelas que {bot} carregou em Dados não são transferidas: ficam no My Cloud, onde {bot} não consegue abri-las depois que entra em {team}.","teamMove.noWayBack": "Não é possível desfazer: você não pode mover o bot de volta para o My Cloud.","teamMove.confirm": "Mover para {team}","teamMove.moving": "Movendo {bot} para {team}…",@@ -9841,6 +9845,10 @@"native.decider.routerRejected": "O OpenRouter recusou esta chave. Confira em openrouter.ai/keys e cole novamente.","serverError.decider.accountFormat": "decider.workersAiAccountId: o ID de uma conta da Cloudflare tem 32 letras e números","serverError.backup.recursiveLink": "Não é possível incluir no backup um link simbólico para a pasta que o contém: {path}",+ "serverError.backup.dataQueryRunning": "A consulta de Dados de {bot} ainda está em execução e não parou quando pedido. Feche totalmente e abra de novo o OpenMausBot (ou reinicie o servidor hospedado) para pará-la e tente de novo.",+ "serverError.backup.dataCloseFailed": "Não foi possível fechar as tabelas de Dados de {bot} para o backup ({detail}). Feche totalmente e abra de novo o OpenMausBot (ou reinicie o servidor hospedado) e tente de novo.",+ "serverError.backup.tooLargeData": "Esta instalação passa do limite de 10 GB do backup; {size} disso são tabelas de Dados dos bots.",+ "serverError.backup.legacyBursts": "Os registros de bursts deste backup (bursts.db) estão danificados, então nada foi restaurado e nada mudou aqui. Faça um novo backup onde ele foi criado.","chat.notice.exportedGoal.working": "{before}[Objetivo: em andamento]{content}","chat.notice.exportedGoal.completed": "{before}[Objetivo: concluído]{content}","chat.notice.exportedGoal.needs-input": "{before}[Objetivo: aguardando resposta]{content}",