Skip to content

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

data-format: a bad marker never stops a healthy install; say what it does not protect yet

milind-sonia566a43cd015
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 18167e5620..03155ab52f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -173,6 +173,43 @@ sessions into `engine-homes/`, the old data folder's rename). They stay as
they are. The marker does not replace them; it adds the one thing they cannot
do, which is to stop an older version at the door.
+**What the marker protects today: nothing yet.** Both numbers are 1 and no
+version writes format 2, so the marker has never stopped a server, and a
+rollback of one release can still lose data without it noticing:
+
+- Many JSON stores accept only `"version": 1` and throw, or start empty, on
+ anything else: among them `server/command-allowlist.ts`, `server/fleet.ts`,
+ `server/bot-directory.ts`, `server/data/sheet.ts`, `server/pages/store.ts`,
+ `server/sentinel/store.ts` and `server/boat-delete-journal.ts`. A release
+ that raised one of those versions without raising `writes` would pass every
+ check here, and the release before it would start on that data and drop it.
+- The SQLite databases (`messages.db`, `runtime.db`, the cloud-sync store)
+ have no `PRAGMA user_version`. Their schema is judged by looking for
+ columns, so a change an older `INSERT` or `SELECT` breaks on is not seen.
+- Nothing ties a store's `version` or a schema change to `DATA_FORMAT`. The
+ rule holds only when whoever makes the change raises the numbers; review is
+ the only check.
+- The marker is one number for the whole folder. A workspace backup does not
+ carry it (it describes the folder it is in), so a backup a newer version
+ made, restored into an older server, is not stopped by it.
+- A marker that cannot be read (empty or full of NULs after a power loss, not
+ readable by the server's user) counts as format 1 while `writes` is 1, and
+ a marker that cannot be written is said in the log and skipped: the check
+ must never be the reason a healthy install does not start.
+
+For the rule to hold by itself, these would have to change:
+
+1. A test that fails when a store's `version`, a JSON store's shape or a
+ database's tables change without a change to `DATA_FORMAT`: every store's
+ version and every table's columns, recorded in the tree and compared.
+2. A store that meets a `version` higher than it knows refuses to start, with
+ the same plain line, instead of starting empty, so a missed bump stops the
+ server rather than losing the data.
+3. `PRAGMA user_version` on each SQLite database, raised with its schema and
+ checked when it opens.
+4. A workspace backup that records the format it was made in, and a restore
+ that refuses it in a server whose `reads` is lower.
+
## Adding a provider driver
The SPI in [`server/contracts.ts`](server/contracts.ts) is deliberately small. A driver PR should:
diff --git a/server/data-format.test.ts b/server/data-format.test.ts
index 91d98b1126..b60b31b455 100644
--- a/server/data-format.test.ts
+++ b/server/data-format.test.ts
@@ -1,8 +1,8 @@
import { spawn } from "node:child_process";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
checkDataFormat, DATA_FORMAT, DATA_FORMAT_FILE, DataFormatError, dataFormatStepProblem, readDataFormat, stampDataFormat, type ReleasedDataFormat,
@@ -82,12 +82,91 @@ describe("the data folder's format marker", () => {
expect(() => checkDataFormat(dir, "0.2.0", 3)).not.toThrow();
});
- it("refuses a marker it cannot read rather than guess the format", () => {
- for (const text of ["{", "{}", '{"format":"2"}', '{"format":0}', '{"format":1.5}']) {
+ // What a power loss, an editor or a restore by hand can leave behind.
+ const GARBLED = ["", "\0".repeat(64), "{", "{}", "null", '{"format":"2"}', '{"format":0}', '{"format":1.5}'];
+
+ it("takes a marker it cannot read as format 1 while no version writes a newer one, and puts a good one back", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ for (const text of GARBLED) {
+ const dir = dataDir();
+ writeFileSync(join(dir, DATA_FORMAT_FILE), text);
+ expect(() => checkDataFormat(dir, "0.1.152", 1, 1), JSON.stringify(text)).not.toThrow();
+ stampDataFormat(dir, "0.1.152", { writes: 1, reads: 1 });
+ expect(readDataFormat(dir), JSON.stringify(text)).toMatchObject({ format: 1, writtenBy: "0.1.152" });
+ }
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining("cannot be read; taking the data as format 1"));
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it("refuses a marker it cannot read once a version writes a newer format, since the data may then be in it", () => {
+ for (const text of GARBLED) {
const dir = dataDir();
writeFileSync(join(dir, DATA_FORMAT_FILE), text);
- expect(() => checkDataFormat(dir, "0.1.152"), text).toThrow(/cannot be read, so this version cannot tell/);
+ expect(() => checkDataFormat(dir, "0.1.160", 2, 2), JSON.stringify(text)).toThrow(/cannot be read, so this version cannot tell/);
+ expect(readFileSync(join(dir, DATA_FORMAT_FILE), "utf8")).toBe(text);
+ }
+ });
+
+ it("reads a marker behind a byte-order mark, and still refuses a newer format there", () => {
+ const dir = dataDir();
+ writeFileSync(join(dir, DATA_FORMAT_FILE), `\uFEFF${JSON.stringify({ format: 1, writtenBy: "0.1.151", writtenAt: "" })}`);
+ expect(readDataFormat(dir)).toMatchObject({ format: 1, writtenBy: "0.1.151" });
+ writeFileSync(join(dir, DATA_FORMAT_FILE), `\uFEFF${JSON.stringify({ format: 3, writtenBy: "0.2.0", writtenAt: "" })}`);
+ expect(() => checkDataFormat(dir, "0.1.152", 1, 1)).toThrow("written by a newer OpenMausBot (0.2.0)");
+ });
+
+ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)("starts on a marker this user cannot read, and on a folder it cannot write", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const dir = dataDir();
+ writeFileSync(join(dir, DATA_FORMAT_FILE), JSON.stringify({ format: 1, writtenBy: "0.1.151", writtenAt: "" }));
+ chmodSync(join(dir, DATA_FORMAT_FILE), 0o000);
+ chmodSync(dir, 0o555);
+ try {
+ expect(() => checkDataFormat(dir, "0.1.152", 1, 1)).not.toThrow();
+ // The stamp cannot replace it (EACCES): said in the log, and the start goes on.
+ expect(() => stampDataFormat(dir, "0.1.152", { writes: 1, reads: 1 })).not.toThrow();
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(/could not write .*data-format\.json .*starting without it/));
+ expect(readdirSync(dir)).toEqual([DATA_FORMAT_FILE]);
+ } finally {
+ chmodSync(dir, 0o755);
+ chmodSync(join(dir, DATA_FORMAT_FILE), 0o644);
+ warn.mockRestore();
+ }
+ });
+
+ it("never ends a start over a marker it cannot write: a Windows file held open, a full disk", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ for (const code of ["EPERM", "EACCES", "ENOSPC", "EROFS"]) {
+ const dir = dataDir();
+ const failing = () => {
+ throw Object.assign(new Error(`${code}: operation not permitted, rename`), { code });
+ };
+ expect(() => stampDataFormat(dir, "0.1.152", DATA_FORMAT, failing), code).not.toThrow();
+ expect(readDataFormat(dir)).toBeNull();
+ }
+ } finally {
+ warn.mockRestore();
}
+ // The real write is the atomic one: it leaves the whole file and nothing beside it.
+ const dir = dataDir();
+ stampDataFormat(dir, "0.1.152");
+ expect(readdirSync(dir)).toEqual([DATA_FORMAT_FILE]);
+ });
+
+ it("lets the Admin roll a Cloud back one image, and forward again, on the same data", () => {
+ const dir = dataDir();
+ stampDataFormat(dir, VERSION, DATA_FORMAT);
+ const stamped = readFileSync(join(dir, DATA_FORMAT_FILE), "utf8");
+ // The image before: the last release, with the numbers it was released with.
+ expect(() => checkDataFormat(dir, `${released.version}-previous`, released.reads, released.writes)).not.toThrow();
+ stampDataFormat(dir, `${released.version}-previous`, released);
+ expect(readFileSync(join(dir, DATA_FORMAT_FILE), "utf8")).toBe(stamped);
+ stampDataFormat(dir, VERSION, DATA_FORMAT);
+ expect(readFileSync(join(dir, DATA_FORMAT_FILE), "utf8")).toBe(stamped);
});
});
@@ -127,6 +206,30 @@ describe("a server starting on a data folder", () => {
expect(readdirSync(data)).toEqual([DATA_FORMAT_FILE]);
}, 60_000);
+ it("starts, and puts a good marker back, on a marker a power loss left empty or full of NULs", async () => {
+ for (const text of ["", "\0".repeat(64)]) {
+ const dir = dataDir();
+ const data = join(dir, "data");
+ mkdirSync(data);
+ writeFileSync(join(data, DATA_FORMAT_FILE), text);
+ const marker = join(data, DATA_FORMAT_FILE);
+ const { stderr } = await start(dir, () => existsSync(join(data, "environment-id")) && readFileSync(marker, "utf8").includes('"format"'));
+ expect(stderr).not.toContain("startup failed");
+ expect(JSON.parse(readFileSync(marker, "utf8"))).toMatchObject({ format: DATA_FORMAT.writes, writtenBy: VERSION });
+ }
+ }, 120_000);
+
+ it("starts on data the next version marked, as after the Admin rolls a Cloud back one image", async () => {
+ const dir = dataDir();
+ const data = join(dir, "data");
+ mkdirSync(data);
+ const marker = `${JSON.stringify({ format: DATA_FORMAT.writes, writtenBy: "99.0.0", writtenAt: "2027-01-01T00:00:00.000Z" }, null, 2)}\n`;
+ writeFileSync(join(data, DATA_FORMAT_FILE), marker);
+ const { stderr } = await start(dir, () => existsSync(join(data, "environment-id")));
+ expect(stderr).not.toContain("startup failed");
+ expect(readFileSync(join(data, DATA_FORMAT_FILE), "utf8")).toBe(marker);
+ }, 60_000);
+
it("marks a new data folder with the format it writes", async () => {
const dir = dataDir();
const marker = join(dir, "data", DATA_FORMAT_FILE);
diff --git a/server/data-format.ts b/server/data-format.ts
index 980146faea..8824f5b70a 100644
--- a/server/data-format.ts
+++ b/server/data-format.ts
@@ -1,8 +1,9 @@
// The data folder's format marker, and the rule that makes an update safe to roll back: what version N writes, version
// N-1 can still read (CONTRIBUTING.md, "Changing how data is stored"). A server that finds data in a format it cannot
// read refuses to start before it touches a file.
-import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
+import { writeFileAtomic } from "./atomic.ts";
/**
* `writes`: the format this version leaves the data folder in. `reads`: the newest format it can read, which may be
@@ -26,39 +27,72 @@ export class DataFormatError extends Error {
override name = "DataFormatError";
}
-/** Null when the folder has no marker. Throws when the marker cannot be read: its format is then unknown. */
-export function readDataFormat(dataDir: string): DataFormatMarker | null {
+/** The marker in the folder; null when there is none, "unreadable" when there is one whose format cannot be told. */
+function markerIn(dataDir: string): DataFormatMarker | null | "unreadable" {
const file = join(dataDir, DATA_FORMAT_FILE);
if (!existsSync(file)) return null;
try {
- const marker = JSON.parse(readFileSync(file, "utf8")) as Partial<DataFormatMarker>;
- if (typeof marker.format === "number" && Number.isInteger(marker.format) && marker.format >= 1) {
+ // A byte-order mark is what some editors put in front of JSON; the format behind it is still readable.
+ const marker = JSON.parse(readFileSync(file, "utf8").replace(/^\uFEFF/, "")) as Partial<DataFormatMarker> | null;
+ if (marker && typeof marker.format === "number" && Number.isInteger(marker.format) && marker.format >= 1) {
return { format: marker.format, writtenBy: typeof marker.writtenBy === "string" ? marker.writtenBy : "unknown", writtenAt: typeof marker.writtenAt === "string" ? marker.writtenAt : "" };
}
} catch {
}
+ return "unreadable";
+}
+
+/**
+ * Null when the folder has no marker. A marker that cannot be read (empty or NUL-filled after a power loss, not
+ * readable by this user) is format 1 while no version writes anything newer (`writes` 1): there is then no newer format
+ * it could have recorded, and refusing would stop a healthy install. Once a version writes format 2 its format is
+ * unknown, and this throws.
+ */
+export function readDataFormat(dataDir: string, writes: number = DATA_FORMAT.writes): DataFormatMarker | null {
+ const marker = markerIn(dataDir);
+ if (marker !== "unreadable") return marker;
+ const file = join(dataDir, DATA_FORMAT_FILE);
+ if (writes <= 1) {
+ console.warn(`[data-format] ${file} cannot be read; taking the data as format 1, the only format any version has written.`);
+ return null;
+ }
throw new DataFormatError(`OpenMausBot startup failed: ${file} cannot be read, so this version cannot tell whether it understands the data in ${dataDir}. Nothing was changed. Restore that file from a backup, or the whole folder from the copy taken before the last update.`);
}
/** Throws, having changed nothing, when a newer version left the data in a format `reads` does not cover. */
-export function checkDataFormat(dataDir: string, version: string, reads: number = DATA_FORMAT.reads): void {
- const marker = readDataFormat(dataDir);
- if (!marker || marker.format <= reads) return;
- throw new DataFormatError(
+export function checkDataFormat(dataDir: string, version: string, reads: number = DATA_FORMAT.reads, writes: number = DATA_FORMAT.writes): void {
+ const marker = readDataFormat(dataDir, writes);
+ if (marker && marker.format > reads) throw newerData(dataDir, version, marker);
+}
+
+function newerData(dataDir: string, version: string, marker: DataFormatMarker): DataFormatError {
+ return new DataFormatError(
`OpenMausBot startup failed: the data in ${dataDir} was written by a newer OpenMausBot (${marker.writtenBy}), in a format this version (${version}) cannot read. Nothing was changed. `
+ `Install OpenMausBot ${marker.writtenBy} or newer, or put back the copy of the data taken before that update.`,
);
}
-/** Records that this version has run on the folder. Never lowers a marker: an older version that could read the data leaves it. */
-export function stampDataFormat(dataDir: string, version: string, format: { writes: number; reads: number } = DATA_FORMAT): void {
- checkDataFormat(dataDir, version, format.reads);
- const marker = readDataFormat(dataDir);
+/**
+ * Records that this version has run on the folder. Never lowers a marker: an older version that could read the data
+ * leaves it. Throws only DataFormatError, for data it cannot read; a marker it cannot write (a read-only folder, a file
+ * Windows holds open past the retries) is said in the log and the start goes on, since the data itself is fine.
+ */
+export function stampDataFormat(
+ dataDir: string,
+ version: string,
+ format: { writes: number; reads: number } = DATA_FORMAT,
+ write: (path: string, text: string) => void = writeFileAtomic,
+): void {
+ const marker = readDataFormat(dataDir, format.writes);
+ if (marker && marker.format > format.reads) throw newerData(dataDir, version, marker);
if (marker && marker.format >= format.writes) return;
const file = join(dataDir, DATA_FORMAT_FILE);
const next: DataFormatMarker = { format: format.writes, writtenBy: version, writtenAt: new Date().toISOString() };
- writeFileSync(`${file}.${process.pid}.tmp`, `${JSON.stringify(next, null, 2)}\n`);
- renameSync(`${file}.${process.pid}.tmp`, file);
+ try {
+ write(file, `${JSON.stringify(next, null, 2)}\n`);
+ } catch (error) {
+ console.warn(`[data-format] could not write ${file} (${error instanceof Error ? error.message : String(error)}); starting without it.`);
+ }
}
export interface ReleasedDataFormat {
diff --git a/server/workspace-backup.test.ts b/server/workspace-backup.test.ts
index f110c304ce..96e1335f60 100644
--- a/server/workspace-backup.test.ts
+++ b/server/workspace-backup.test.ts
@@ -66,6 +66,7 @@ function fixture(root: string): DatabaseSync {
json(join(root, "sessions.json"), { identity: "source-session" });
json(join(root, "cloud-owner.json"), { identity: "source-owner-record" });
writeFileSync(join(root, "environment-id"), "source-environment");
+ json(join(root, "data-format.json"), { format: 2, writtenBy: "99.0.0", writtenAt: "2027-01-01T00:00:00.000Z" });
mkdirSync(join(root, "tools"));
writeFileSync(join(root, "tools", "downloaded"), "reinstallable");
mkdirSync(join(root, "decider-log"));
@@ -181,6 +182,7 @@ describe("encrypted full workspace backups", () => {
const targetComputers = { version: 1, environmentId: "target-environment", computers: [{ id: "target-computer", name: "Destination desktop", section: null }] };
json(join(target, "team-computers.json"), targetComputers);
writeFileSync(join(target, "environment-id"), "target-environment");
+ json(join(target, "data-format.json"), { format: 1, writtenBy: "0.1.151", writtenAt: "2026-11-01T00:00:00.000Z" });
writeFileSync(join(target, "openmausbot-server.lease"), "live-lease");
writeFileSync(join(target, "messages.db-wal"), "old database WAL must not enter the new DB");
writeFileSync(join(target, "messages.db-shm"), "old database shared memory");
@@ -193,6 +195,7 @@ describe("encrypted full workspace backups", () => {
expect(existsSync(join(data, "bots.json"))).toBe(true);
expect(existsSync(join(data, "runtime.db"))).toBe(true);
expect(existsSync(join(data, "cloud-owner.json"))).toBe(false);
+ expect(existsSync(join(data, "data-format.json"))).toBe(false);
expect(readJson(join(data, "config.json"))).toEqual({ language: "ja" });
expect(readJson(join(data, "webhooks.json")).webhooks[0]).not.toHaveProperty("secretHash");
expect(readFileSync(join(data, "webhooks.json"), "utf8")).not.toContain("sealed-");
@@ -211,6 +214,7 @@ describe("encrypted full workspace backups", () => {
expect(readJson(join(target, "cloud-owner.json"))).toEqual({ identity: "target-owner-record" });
expect(readJson(join(target, "team-computers.json"))).toEqual(targetComputers);
expect(readFileSync(join(target, "environment-id"), "utf8")).toBe("target-environment");
+ expect(readJson(join(target, "data-format.json"))).toMatchObject({ format: 1, writtenBy: "0.1.151" });
expect(readFileSync(join(target, "openmausbot-server.lease"), "utf8")).toBe("live-lease");
expect(existsSync(join(target, "messages.db-wal"))).toBe(false);
expect(readFileSync(join(result.safetyCopyPath!, "data", "messages.db-wal"), "utf8")).toBe("old database WAL must not enter the new DB");
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index c20216f93d..a28a5b691e 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -45,6 +45,9 @@ const EXCLUDED = new Set([
// folder, which no admin reads.
"engine-homes",
WAITS_FILE,
+ // The data folder's format marker (data-format.ts) describes the folder it is in. Carried into a server older than the
+ // one that wrote it, it would stop that server on every start; the destination keeps its own.
+ "data-format.json",
]);
const EXCLUSION_NOTES = [
"Device pairing, server identity, live leases and runtime files (existing destination identities are preserved).",