Skip to content

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

fix(config): keep the copies ordered and unique, refuse a restore that loses the file, and answer a help request

David Neyra64f9fbd6294b
diff --git a/apps/docs/content/docs/self-hosting/data-and-backups.mdx b/apps/docs/content/docs/self-hosting/data-and-backups.mdx
index ef182dbc68..c67ac3197d 100644
--- a/apps/docs/content/docs/self-hosting/data-and-backups.mdx
+++ b/apps/docs/content/docs/self-hosting/data-and-backups.mdx
@@ -124,7 +124,8 @@ Every save of `~/.openmausbot/config.json` keeps a copy of the file as it was,
named `config.json.bak.YYYYMMDD-HHMMSS`, beside it; the last ten are kept. A
save never replaces a settings file it could not read or understand: it fails
and says so, so a file that cannot be read is never overwritten by a partial
-one.
+one. A save that cannot keep its dated copy fails as well, so the settings file
+is never replaced without a copy of it to go back to.
To go back to an earlier copy, stop the server and run:
@@ -134,8 +135,10 @@ openmausbot config restore latest
```
The file a restore replaces is kept as a dated copy too, so the restore can be
-undone. These copies hold the saved keys and connections of the settings file:
-they stay on that computer and are not part of a workspace backup.
+undone. A restore only puts back a copy that is a settings file the server can
+read, and never over a file it could not read or keep: nothing is lost to put a
+copy back. These copies hold the saved keys and connections of the settings
+file: they stay on that computer and are not part of a workspace backup.
## Do not copy secrets casually
diff --git a/server/cli.ts b/server/cli.ts
index 3456ef5b64..3be77fd227 100644
--- a/server/cli.ts
+++ b/server/cli.ts
@@ -271,9 +271,7 @@ async function serverUp(port: number, pid?: number): Promise<boolean> {
try {
const { status, body } = await api(port, "/api/health");
return status === 200 && body?.app === "openmausbot" && (pid === undefined || body.pid === pid);
- } catch {
- return false;
- }
+ } catch { return false; }
}
/** Never attach to another workspace just because it listens on the requested port. */
diff --git a/server/config-backup.test.ts b/server/config-backup.test.ts
index 271f898beb..d1a59cbedb 100644
--- a/server/config-backup.test.ts
+++ b/server/config-backup.test.ts
@@ -44,7 +44,8 @@ describe("a save that cannot read the file", () => {
writeFileSync(configPath(dir), "{ not json");
const read = readConfigFile(configPath(dir));
expect(read.state).toBe("invalid");
- const error = configSaveRefusal(read as { state: string; reason: string }, configPath(dir));
+ if (read.state !== "invalid") throw new Error(`expected an invalid settings file, got ${read.state}`);
+ const error = configSaveRefusal(read, configPath(dir));
expect((error as { status?: number }).status).toBe(503);
expect(error.message).toContain(configPath(dir));
expect(error.message).toContain("openmausbot config restore");
@@ -54,7 +55,8 @@ describe("a save that cannot read the file", () => {
const dir = tempDir();
writeFileSync(configPath(dir), "{ not json");
const read = readConfigFile(configPath(dir));
- configSaveRefusal(read as { state: string; reason: string }, configPath(dir));
+ if (read.state !== "invalid") throw new Error(`expected an invalid settings file, got ${read.state}`);
+ configSaveRefusal(read, configPath(dir));
const aside = readdirSync(dir).filter((name) => name.startsWith("config.json.unreadable-"));
expect(aside).toHaveLength(1);
expect(readFileSync(join(dir, aside[0]!), "utf8")).toBe("{ not json");
@@ -67,7 +69,7 @@ describe("the dated copies", () => {
const name = writeConfigBackup(configPath(dir), "{\"a\":1}", new Date("2026-11-16T00:30:00Z"));
expect(name).toBe("config.json.bak.20261116-003000");
expect(readFileSync(join(dir, name!), "utf8")).toBe("{\"a\":1}");
- expect(statSync(join(dir, name!)).mode & 0o777).toBe(0o600);
+ if (process.platform !== "win32") expect(statSync(join(dir, name!)).mode & 0o777).toBe(0o600);
});
it("do not overwrite each other within a second", () => {
@@ -93,6 +95,24 @@ describe("the dated copies", () => {
writeConfigBackup(configPath(dir), "b", new Date("2026-11-16T01:00:00Z"));
expect(listConfigBackups(dir).map((copy) => copy.stamp)).toEqual(["20261116-000000", "20261116-010000"]);
});
+
+ it("keep the order of the copies taken in the same second", () => {
+ const dir = tempDir();
+ const now = new Date("2026-11-16T00:30:00Z");
+ for (let index = 0; index < CONFIG_BACKUP_KEEP + 1; index += 1) writeConfigBackup(configPath(dir), `copy ${index}`, now);
+ const names = listConfigBackups(dir).map((copy) => copy.name);
+ expect(names).toEqual(Array.from({ length: CONFIG_BACKUP_KEEP }, (_, index) => `config.json.bak.20261116-003000-${index + 1}`));
+ });
+
+ it("never use again a name that retention removed", () => {
+ const dir = tempDir();
+ const now = new Date("2026-11-16T00:30:00Z");
+ for (let index = 0; index < CONFIG_BACKUP_KEEP + 1; index += 1) writeConfigBackup(configPath(dir), `copy ${index}`, now);
+ const name = writeConfigBackup(configPath(dir), "the last one", now);
+ expect(name).not.toBe("config.json.bak.20261116-003000");
+ expect(readFileSync(join(dir, name!), "utf8")).toBe("the last one");
+ expect(listConfigBackups(dir).some((copy) => copy.name === name)).toBe(true);
+ });
});
describe("putting a copy back", () => {
@@ -152,4 +172,32 @@ describe("putting a copy back", () => {
expect(restoreConfigBackup(dir, "../secret").ok).toBe(false);
expect(restoreConfigBackup(dir, "/etc/passwd").ok).toBe(false);
});
+
+ it("refuses a copy the server would not read as a settings file", () => {
+ const dir = tempDir();
+ writeFileSync(join(dir, "config.json.bak.20261116-003000"), JSON.stringify({ threads: { maxConcurrentPerBot: "broken" } }));
+ writeFileSync(configPath(dir), JSON.stringify({ new: true }));
+ const restored = restoreConfigBackup(dir, "config.json.bak.20261116-003000", { check: () => "threads.maxConcurrentPerBot: expected number" });
+ expect(restored.ok).toBe(false);
+ expect(readFileSync(configPath(dir), "utf8")).toBe(JSON.stringify({ new: true }));
+ });
+
+ it("never puts a copy back over a file it cannot read", () => {
+ const dir = tempDir();
+ writeFileSync(join(dir, "config.json.bak.20261116-003000"), JSON.stringify({ old: true }));
+ mkdirSync(configPath(dir));
+ expect(restoreConfigBackup(dir, "config.json.bak.20261116-003000").ok).toBe(false);
+ expect(restoreConfigBackup(dir, "config.json.bak.20261116-003000", { dryRun: true }).ok).toBe(false);
+ expect(statSync(configPath(dir)).isDirectory()).toBe(true);
+ });
+
+ it("never puts a copy back when the file it replaces cannot be kept", () => {
+ const dir = tempDir();
+ writeFileSync(join(dir, "config.json.bak.20261116-003000"), JSON.stringify({ old: true }));
+ writeFileSync(configPath(dir), "{ not json");
+ for (let index = 0; index < 5; index += 1) writeFileSync(join(dir, `config.json.unreadable-${String(index).padStart(12, "0")}`), "kept");
+ const restored = restoreConfigBackup(dir, "config.json.bak.20261116-003000");
+ expect(restored.ok).toBe(false);
+ expect(readFileSync(configPath(dir), "utf8")).toBe("{ not json");
+ });
});
diff --git a/server/config-backup.ts b/server/config-backup.ts
index 082e6b4410..39ac2724c6 100644
--- a/server/config-backup.ts
+++ b/server/config-backup.ts
@@ -15,7 +15,7 @@ export const CONFIG_BACKUP_PREFIX = "config.json.bak.";
/** How many dated copies are kept; the oldest go first. */
export const CONFIG_BACKUP_KEEP = 10;
-const BACKUP_NAME = /^config\.json\.bak\.(\d{8})-(\d{6})(?:-\d+)?$/;
+const BACKUP_NAME = /^config\.json\.bak\.(\d{8})-(\d{6})(?:-(\d+))?$/;
export interface ConfigBackup {
/** The file name, which carries the moment the copy was taken. */
@@ -32,6 +32,12 @@ export type ConfigFileRead =
| { state: "unreadable"; reason: string }
| { state: "invalid"; reason: string };
+/** The moment a copy carries, and the number it was given inside that second. */
+function backupOrder(name: string): { stamp: string; order: number } {
+ const match = BACKUP_NAME.exec(name)!;
+ return { stamp: `${match[1]}-${match[2]}`, order: match[3] ? Number(match[3]) : 0 };
+}
+
/** The settings file as it is on disk. A file that is there but cannot be understood is never taken for an empty
* one: it is reported, so a save can refuse to replace it. */
export function readConfigFile(path: string): ConfigFileRead {
@@ -63,6 +69,15 @@ export function configSaveRefusal(read: { state: "unreadable" | "invalid"; reaso
);
}
+/** The error a save refuses with when its dated copy could not be written: without that copy the file would be
+ * replaced with nothing to go back to. */
+export function configBackupRefusal(path: string): Error {
+ return Object.assign(
+ new Error(`The settings file ${path} was left as it is because its dated copy could not be written, so nothing was saved.`),
+ { status: 503 },
+ );
+}
+
function stampOf(now: Date): string {
const pad = (value: number) => String(value).padStart(2, "0");
return `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`;
@@ -73,8 +88,14 @@ function stampOf(now: Date): string {
export function writeConfigBackup(path: string, text: string, now: Date = new Date(), skip?: string): string | null {
const dir = dirname(path);
const base = CONFIG_BACKUP_PREFIX + stampOf(now);
- for (let taken = 0; taken < 100; taken += 1) {
+ // The number continues above the ones already there, so a name that retention removed is never used again.
+ let taken = 0;
+ for (const copy of listConfigBackups(dir)) {
+ if (copy.name.startsWith(base)) taken = Math.max(taken, backupOrder(copy.name).order + 1);
+ }
+ for (let attempt = 0; attempt < 100; attempt += 1) {
const name = taken === 0 ? base : `${base}-${taken}`;
+ taken += 1;
if (name === skip) continue;
const target = join(dir, name);
if (existsSync(target)) continue;
@@ -89,7 +110,8 @@ export function writeConfigBackup(path: string, text: string, now: Date = new Da
return null;
}
-/** The dated copies kept beside the settings file, oldest first. */
+/** The dated copies kept beside the settings file, oldest first. Copies taken in the same second are ordered by the
+ * number they carry, not by their name, so the tenth of a second comes after the ninth. */
export function listConfigBackups(dir: string): ConfigBackup[] {
let names: string[];
try {
@@ -97,16 +119,23 @@ export function listConfigBackups(dir: string): ConfigBackup[] {
} catch {
return [];
}
- return names.filter((name) => BACKUP_NAME.test(name)).sort().map((name) => {
- const path = join(dir, name);
- let bytes = 0;
- try {
- bytes = statSync(path).size;
- } catch {
- }
- const stamp = BACKUP_NAME.exec(name)!;
- return { name, path, stamp: `${stamp[1]}-${stamp[2]}`, bytes };
- });
+ return names
+ .filter((name) => BACKUP_NAME.test(name))
+ .sort((one, two) => {
+ const first = backupOrder(one);
+ const second = backupOrder(two);
+ if (first.stamp !== second.stamp) return first.stamp < second.stamp ? -1 : 1;
+ return first.order - second.order;
+ })
+ .map((name) => {
+ const path = join(dir, name);
+ let bytes = 0;
+ try {
+ bytes = statSync(path).size;
+ } catch {
+ }
+ return { name, path, stamp: backupOrder(name).stamp, bytes };
+ });
}
function pruneConfigBackups(dir: string): void {
@@ -121,9 +150,13 @@ function pruneConfigBackups(dir: string): void {
export type ConfigRestore = { ok: true; name: string; kept: string | null; restored: boolean } | { ok: false; error: string };
+/** Checks that a copy is a settings file the server can read: it returns the reason it is not, or null when it is. */
+export type ConfigBackupCheck = (text: string) => string | null;
+
/** Puts a dated copy back as the settings file. The file it replaces is kept, so the restore is itself reversible.
- * A dry run reports what it would do and changes nothing. */
-export function restoreConfigBackup(dir: string, name: string, options: { dryRun?: boolean } = {}): ConfigRestore {
+ * A dry run reports what it would do and changes nothing. Nothing is put back over a file that cannot be read or
+ * kept: a restore never loses what it finds. */
+export function restoreConfigBackup(dir: string, name: string, options: { dryRun?: boolean; check?: ConfigBackupCheck } = {}): ConfigRestore {
if (!BACKUP_NAME.test(name)) return { ok: false, error: `${name} is not a dated copy of the settings file; run openmausbot config backups to see the copies` };
const source = join(dir, name);
let text: string;
@@ -138,14 +171,22 @@ export function restoreConfigBackup(dir: string, name: string, options: { dryRun
} catch {
return { ok: false, error: `The copy ${name} is not valid JSON, so it was not put back` };
}
+ const problem = options.check?.(text);
+ if (problem) return { ok: false, error: `The copy ${name} is not a settings file (${problem}), so it was not put back` };
const target = join(dir, "config.json");
const current = readConfigFile(target);
+ if (current.state === "unreadable") return { ok: false, error: `The file ${target} could not be read, so it was left as it is and nothing was put back` };
if (options.dryRun) return { ok: true, name, kept: null, restored: false };
let kept: string | null = null;
if (current.state === "ok") {
const copy = writeConfigBackup(target, current.text, new Date(), name);
- kept = copy ? join(dir, copy) : null;
- } else if (current.state === "invalid") kept = keepUnreadableAside(target);
+ if (!copy) return { ok: false, error: `The file ${target} could not be kept as a dated copy, so it was left as it is and nothing was put back` };
+ kept = join(dir, copy);
+ } else if (current.state === "invalid") {
+ const aside = keepUnreadableAside(target);
+ if (!aside) return { ok: false, error: `The file ${target} could not be kept as a copy, so it was left as it is and nothing was put back` };
+ kept = aside;
+ }
writeFileAtomic(target, text, { mode: 0o600 });
return { ok: true, name, kept, restored: true };
}
diff --git a/server/config-cli.ts b/server/config-cli.ts
index 343a5c245f..a7ed1c6cfa 100644
--- a/server/config-cli.ts
+++ b/server/config-cli.ts
@@ -2,6 +2,8 @@ import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { listConfigBackups, restoreConfigBackup } from "./config-backup.ts";
+import { parseStoredConfig } from "./config.ts";
+import { parseJson } from "./schema.ts";
export const CONFIG_USAGE = `openmausbot config backups [--data-dir DIR] [--json]
openmausbot config restore NAME [--data-dir DIR] [--dry-run] [--json]
@@ -21,7 +23,7 @@ restore put a copy back, by name or "latest"; the file it replaces is kept,
--json print the result as JSON`;
export interface ConfigCliArgs {
- command: "backups" | "restore";
+ command: "backups" | "restore" | "help";
dataDir: string;
name: string | undefined;
json: boolean;
@@ -34,6 +36,17 @@ export interface ConfigCliError {
json: boolean;
}
+/** A copy is only put back when it is a settings file the server can read: a file the loader would reject would
+ * change the settings without saying so. */
+function settingsProblem(text: string): string | null {
+ try {
+ parseStoredConfig(parseJson(text));
+ return null;
+ } catch (error) {
+ return error instanceof Error ? error.message : "it does not match the settings format";
+ }
+}
+
export function parseConfigArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): ConfigCliArgs | ConfigCliError {
const json = argv.includes("--json");
const help = argv.includes("--help") || argv.includes("-h");
@@ -44,6 +57,8 @@ export function parseConfigArgs(argv: string[], env: NodeJS.ProcessEnv = process
const words = argv.filter((arg) => arg !== "--json" && arg !== "--help" && arg !== "-h" && arg !== "--dry-run");
const command = words[0];
if (command !== "backups" && command !== "restore") {
+ // A request for the help is answered with the help, whatever else it says.
+ if (help) return { command: "help", dataDir, name: undefined, json, help, dryRun };
return fail(command ? `unknown command "${command}"; say "backups" or "restore"` : "say what to do: \"backups\" or \"restore\"");
}
for (let index = 1; index < words.length; index += 1) {
@@ -56,7 +71,8 @@ export function parseConfigArgs(argv: string[], env: NodeJS.ProcessEnv = process
} else if (command === "restore" && name === undefined && !arg.startsWith("-")) name = arg;
else return fail(`unknown argument "${arg}"; see openmausbot config --help`);
}
- if (command === "restore" && name === undefined) return fail("restore needs the name of a copy, or \"latest\"; run openmausbot config backups to see them");
+ // The help comes before the name is asked for: "config restore --help" is a question, not a request.
+ if (command === "restore" && name === undefined && !help) return fail("restore needs the name of a copy, or \"latest\"; run openmausbot config backups to see them");
return { command, dataDir, name, json, help, dryRun };
}
@@ -88,7 +104,7 @@ export function runConfigCli(
else io.error(`config: there is no dated copy to put back in ${args.dataDir}; a copy is taken at every save`);
return 1;
}
- const restored = restoreConfigBackup(args.dataDir, name, { dryRun: args.dryRun });
+ const restored = restoreConfigBackup(args.dataDir, name, { dryRun: args.dryRun, check: settingsProblem });
if (!restored.ok) {
if (args.json) io.log(JSON.stringify({ ok: false, error: restored.error }));
else io.error(`config: ${restored.error}`);
diff --git a/server/config.ts b/server/config.ts
index f7c7cd483b..d736d7aec6 100644
--- a/server/config.ts
+++ b/server/config.ts
@@ -10,7 +10,7 @@ import type { ImageGenerationConfig } from "../shared/image-generation.ts";
import { imageGenConfigSchema, imageGenPatchSchema, keepKeysOutOfImageModels, type ImageGenCredentialPatch } from "./image-generation-config.ts";
import { botAvatarUrlSchema } from "../shared/bot-avatar.ts";
import { writeFileAtomic } from "./atomic.ts";
-import { configSaveRefusal, readConfigFile, writeConfigBackup } from "./config-backup.ts";
+import { configBackupRefusal, configSaveRefusal, readConfigFile, writeConfigBackup } from "./config-backup.ts";
import { defaultBotThreads, MAX_CONCURRENT_BOT_THREADS } from "./bot-thread-limits.ts";
import { anthropicKeyEnv } from "./anthropic-key-env.ts";
import { withoutComputerEngine } from "./computer-engine-removal.ts";
@@ -1002,9 +1002,7 @@ export function saveConfig(
}
}
mkdirSync(DATA_DIR, { recursive: true });
- if (read.state === "ok" && !writeConfigBackup(p, read.text)) {
- console.warn(`config: the dated copy of ${p} could not be written, so this save has no rollback point`);
- }
+ if (read.state === "ok" && !writeConfigBackup(p, read.text)) throw configBackupRefusal(p);
writeFileAtomic(p, JSON.stringify(disk, null, 2), { mode: 0o600 });
storedConfig.forget();
for (const listener of configSaveListeners) {