Skip to content

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

Mark the data folder's format, and refuse data a newer version wrote

milind-soni9c2b54b21079
diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml
index d3d3876814..56177b60e6 100644
--- a/.github/workflows/prepare-release.yml
+++ b/.github/workflows/prepare-release.yml
@@ -97,8 +97,9 @@ jobs:
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git switch -c "release/v$VERSION"
node scripts/tighten-ratchets.mjs
+ node scripts/record-data-format.mjs
node scripts/generate-locale.mjs --record-hashes
- git add package.json scripts/testing/file-size-ratchet.test.ts scripts/testing/index-route-ratchet.test.ts src/locales/source-hashes.json
+ git add package.json server/data-format-released.json scripts/testing/file-size-ratchet.test.ts scripts/testing/index-route-ratchet.test.ts src/locales/source-hashes.json
git commit -m "chore(release): bump version to $VERSION"
git push --set-upstream origin "release/v$VERSION"
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 72abe62cb1..18167e5620 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -107,6 +107,72 @@ House rules for tests:
- Fake CLI shebang scripts must be launched through `spawnCli`/`execCli`, which resolve them through
Node on Windows. Only gate a test when the behavior itself is genuinely platform-specific.
+## Changing how data is stored
+
+**The rule: what version N writes, version N-1 can read.** A self-hosted server
+is updated with a way back: the updater keeps a copy of the data, and when the
+new version does not come up it puts the old version and the copy back. A
+server that was rolled back by hand, or a Cloud moved back one release, starts
+the old version on data the new one has already touched. That must work.
+
+The data folder says which format it is in: `data-format.json`
+(`{ "format": 1, "writtenBy": "0.1.152", … }`), written at start by
+[`server/data-format.ts`](server/data-format.ts). Two numbers in that file
+describe a version: `writes`, the format it leaves the folder in, and `reads`,
+the newest format it understands. A server whose `reads` is below the folder's
+format refuses to start, before it creates, migrates or locks anything, with
+one line that says which version wrote the data and what to do. A folder with
+no marker is format 1.
+
+Most changes need no new format. These are fine in one release, and are how
+every migration so far works:
+
+- a new file, table, index or nullable column; a new optional field in a JSON
+ file whose older readers ignore fields they do not know;
+- a one-time fill of a new field, guarded by a marker file or by the field
+ being absent.
+
+A change needs a new format when the previous release, started on the changed
+data, would fail, lose something, or quietly undo it. Typical cases: a file or
+folder moves or is renamed; a field older code relies on changes meaning or
+goes away; a value older code deletes because it does not recognise it (the
+store's start-up clean-up of `bots.json` does this); the `version` of a JSON
+store goes up (older code treats a higher version as unreadable and starts
+empty); a table changes in a way an older `INSERT` or `SELECT` breaks on.
+
+Such a change ships in **two releases**:
+
+1. **Read it first.** Add the code that reads the new format beside the old,
+ keep writing the old one, and raise `reads` by one. Release.
+2. **Write it one release later.** Start writing the new format and raise
+ `writes` to match. The release before can already read it.
+
+The rule is between one release and the next. The stable channel may skip
+releases, so going back from one stable version to the one before it can cross
+both steps; there the updater's copy of the data is the way back, and the
+marker makes the old version say so instead of running on data it would
+damage.
+
+`server/data-format.test.ts` fails the build on any other step. It compares
+the two numbers with `server/data-format-released.json`, the numbers of the
+last release, which **Prepare next release** records with the version bump
+(`scripts/record-data-format.mjs`); do not edit that file by hand. Raising
+`writes` past what the last release reads fails with the two steps spelled
+out.
+
+What exists today, all of it format 1: the server has no numbered migrations.
+Each store repairs or extends its own files when it opens them, and decides
+by looking (a column that is missing, a legacy file that is still there, a
+marker file such as `thread-model-copies-cleared`), so every one of them is
+safe to run twice. Most are additive: the SQLite `ADD COLUMN`s and
+`CREATE … IF NOT EXISTS` in `server/message-db.ts`, `server/cloud-sync-store.ts`
+and `server/runtime/store.ts`, and the field fills in `server/store.ts`. A few
+are one-way moves from formats that predate every supported version (JSON
+transcripts into `messages.db`, per-bot skills into the library, engine
+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.
+
## Adding a provider driver
The SPI in [`server/contracts.ts`](server/contracts.ts) is deliberately small. A driver PR should:
diff --git a/apps/docs/content/docs/self-hosting/deploy-vps.mdx b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
index 41b94bd3dd..9490d2f4bc 100644
--- a/apps/docs/content/docs/self-hosting/deploy-vps.mdx
+++ b/apps/docs/content/docs/self-hosting/deploy-vps.mdx
@@ -346,6 +346,8 @@ Read this before putting anything else in front of the server.
**`serve --tunnel` says "no account on this machine yet".** Run `npx openmausbot login` on this machine first; the credentials are per machine.
+**The server does not start and says its data "was written by a newer OpenMausBot".** An older version was started on data a newer one had already changed, which happens when a version is put back without its data. Nothing was changed. Install the version the message names (or a newer one), or put back the copy of the data from before that update.
+
**The tunnel stays on "retrying".** The server is running and usable locally; the public hop is not verified yet. Wait a minute (Cloudflare needs a moment on a fresh address), then check `journalctl`/the terminal for the reason. If it never comes up, `npx openmausbot logout && npx openmausbot login` issues a fresh address.
**Path B: the page never loads or shows a certificate error.** Caddy could not get a certificate. Check that the name resolves to the server and that ports 80 and 443 are open; `docker compose logs caddy` shows the reason.
diff --git a/docs/deploy-vps.md b/docs/deploy-vps.md
index 4ec5e9eb25..9e8876c509 100644
--- a/docs/deploy-vps.md
+++ b/docs/deploy-vps.md
@@ -326,6 +326,8 @@ Read this before putting anything else in front of the server.
**`serve --tunnel` says "no account on this machine yet".** Run `npx openmausbot login` on this machine first; the credentials are per machine.
+**The server does not start and says its data "was written by a newer OpenMausBot".** An older version was started on data a newer one had already changed, which happens when a version is put back without its data. Nothing was changed. Install the version the message names (or a newer one), or put back the copy of the data from before that update.
+
**The tunnel stays on "retrying".** The server is running and usable locally; the public hop is not verified yet. Wait a minute (Cloudflare needs a moment on a fresh address), then check `journalctl`/the terminal for the reason. If it never comes up, `npx openmausbot logout && npx openmausbot login` issues a fresh address.
**Path B: the page never loads or shows a certificate error.** Caddy could not get a certificate. Check that the name resolves to the server and that ports 80 and 443 are open; `docker compose logs caddy` shows the reason.
diff --git a/docs/releasing.md b/docs/releasing.md
index 70485641d9..718fe25f29 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -47,6 +47,17 @@ Configure the optional Vercel hook below to rebuild the docs immediately after
publication; otherwise the live cache or the next normal docs deployment
refreshes it.
+## Data format and rollback
+
+Each release records the data-folder formats it writes and reads:
+**Prepare next release** runs `scripts/record-data-format.mjs`, which writes
+`server/data-format-released.json` into the version-bump commit. The next
+release's changes are tested against that record, so a version never writes
+data the release before it cannot read
+([CONTRIBUTING.md, "Changing how data is stored"](../CONTRIBUTING.md#changing-how-data-is-stored)).
+A version bump made by hand needs the same command, or
+`server/data-format.test.ts` fails on the mismatched version.
+
## Updater migration invariant
`app-update.yml` is baked into every packaged desktop app. Builds through
diff --git a/scripts/record-data-format.mjs b/scripts/record-data-format.mjs
new file mode 100644
index 0000000000..2d8ae7c8d9
--- /dev/null
+++ b/scripts/record-data-format.mjs
@@ -0,0 +1,22 @@
+// Writes server/data-format-released.json: the data formats the release being prepared writes and reads, which the
+// next release's changes are held against (server/data-format.test.ts). prepare-release.yml runs it with the version bump.
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+const ROOT = new URL("../", import.meta.url);
+
+/** The numbers of `export const DATA_FORMAT = { writes: N, reads: M }` in server/data-format.ts. */
+export function declaredDataFormat(source) {
+ const match = /export const DATA_FORMAT = \{ writes: (\d+), reads: (\d+) \} as const;/.exec(source);
+ if (!match) throw new Error("server/data-format.ts no longer declares DATA_FORMAT as { writes: N, reads: M }");
+ return { writes: Number(match[1]), reads: Number(match[2]) };
+}
+
+export function releasedRecord(version, source) {
+ return `${JSON.stringify({ version, ...declaredDataFormat(source) }, null, 2)}\n`;
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const { version } = JSON.parse(readFileSync(new URL("package.json", ROOT), "utf8"));
+ writeFileSync(new URL("server/data-format-released.json", ROOT), releasedRecord(version, readFileSync(new URL("server/data-format.ts", ROOT), "utf8")));
+}
diff --git a/scripts/testing/record-data-format.test.ts b/scripts/testing/record-data-format.test.ts
new file mode 100644
index 0000000000..ac35a71d43
--- /dev/null
+++ b/scripts/testing/record-data-format.test.ts
@@ -0,0 +1,20 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { declaredDataFormat, releasedRecord } from "../record-data-format.mjs";
+import { DATA_FORMAT } from "../../server/data-format.ts";
+
+const source = readFileSync(join(import.meta.dirname, "..", "..", "server", "data-format.ts"), "utf8");
+
+describe("record-data-format", () => {
+ it("reads the two numbers the server declares", () => {
+ expect(declaredDataFormat(source)).toEqual(DATA_FORMAT);
+ expect(declaredDataFormat("export const DATA_FORMAT = { writes: 2, reads: 3 } as const;")).toEqual({ writes: 2, reads: 3 });
+ expect(() => declaredDataFormat("export const DATA_FORMAT = formats();")).toThrow("no longer declares DATA_FORMAT");
+ });
+
+ it("records them under the version being released", () => {
+ expect(JSON.parse(releasedRecord("9.9.9", source))).toEqual({ version: "9.9.9", ...DATA_FORMAT });
+ });
+});
diff --git a/server/data-format-released.json b/server/data-format-released.json
new file mode 100644
index 0000000000..b03eb79bc2
--- /dev/null
+++ b/server/data-format-released.json
@@ -0,0 +1,5 @@
+{
+ "version": "0.1.151",
+ "writes": 1,
+ "reads": 1
+}
diff --git a/server/data-format.test.ts b/server/data-format.test.ts
new file mode 100644
index 0000000000..91d98b1126
--- /dev/null
+++ b/server/data-format.test.ts
@@ -0,0 +1,136 @@
+import { spawn } from "node:child_process";
+import { 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 {
+ checkDataFormat, DATA_FORMAT, DATA_FORMAT_FILE, DataFormatError, dataFormatStepProblem, readDataFormat, stampDataFormat, type ReleasedDataFormat,
+} from "./data-format.ts";
+import { freePortBlock } from "./testing/ports.ts";
+
+const ROOT = join(import.meta.dirname, "..");
+const { version: VERSION } = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string };
+const released = JSON.parse(readFileSync(join(import.meta.dirname, "data-format-released.json"), "utf8")) as ReleasedDataFormat;
+const dirs: string[] = [];
+const dataDir = () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-data-format-"));
+ dirs.push(dir);
+ return dir;
+};
+afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe("the N-1 rule", () => {
+ it("holds for this tree: the last release can read the data this version writes", () => {
+ expect(dataFormatStepProblem(DATA_FORMAT, released)).toBeNull();
+ });
+
+ it("is held against the release this tree follows, recorded by the release tooling and not by hand", () => {
+ expect(released.version, "server/data-format-released.json is for another release: run `node scripts/record-data-format.mjs` only as part of a version bump").toBe(VERSION);
+ expect(readFileSync(join(ROOT, ".github", "workflows", "prepare-release.yml"), "utf8")).toContain("node scripts/record-data-format.mjs");
+ });
+
+ it("fails a format bump that skips the two-release step", () => {
+ const last = { version: "0.1.151", writes: 1, reads: 1 };
+ expect(dataFormatStepProblem({ writes: 1, reads: 1 }, last)).toBeNull();
+ expect(dataFormatStepProblem({ writes: 2, reads: 2 }, last)).toContain("release 0.1.151 reads only up to 1");
+ expect(dataFormatStepProblem({ writes: 2, reads: 2 }, last)).toContain("Raise reads to 2 now");
+ // Release one: read the new format. Release two: write it.
+ expect(dataFormatStepProblem({ writes: 1, reads: 2 }, last)).toBeNull();
+ expect(dataFormatStepProblem({ writes: 2, reads: 2 }, { version: "0.1.152", writes: 1, reads: 2 })).toBeNull();
+ expect(dataFormatStepProblem({ writes: 2, reads: 3 }, { version: "0.1.152", writes: 1, reads: 2 })).toBeNull();
+ expect(dataFormatStepProblem({ writes: 1, reads: 3 }, last)).toContain("one format at a time");
+ expect(dataFormatStepProblem({ writes: 2, reads: 1 }, last)).toContain("a version reads what it writes");
+ expect(dataFormatStepProblem({ writes: 1, reads: 1 }, { version: "0.1.152", writes: 1, reads: 2 })).toContain("went down");
+ expect(dataFormatStepProblem({ writes: 1, reads: 2 }, { version: "0.1.153", writes: 2, reads: 2 })).toContain("went down");
+ });
+});
+
+describe("the data folder's format marker", () => {
+ it("is written on first start and left alone after that", () => {
+ const dir = dataDir();
+ expect(readDataFormat(dir)).toBeNull();
+ stampDataFormat(dir, "0.1.152");
+ const first = readFileSync(join(dir, DATA_FORMAT_FILE), "utf8");
+ expect(JSON.parse(first)).toMatchObject({ format: DATA_FORMAT.writes, writtenBy: "0.1.152" });
+ stampDataFormat(dir, "0.1.153");
+ expect(readFileSync(join(dir, DATA_FORMAT_FILE), "utf8")).toBe(first);
+ expect(readdirSync(dir)).toEqual([DATA_FORMAT_FILE]);
+ });
+
+ it("moves up when a version writes a newer format, and an older version that can still read it leaves it there", () => {
+ const dir = dataDir();
+ stampDataFormat(dir, "0.1.152", { writes: 1, reads: 2 });
+ stampDataFormat(dir, "0.1.153", { writes: 2, reads: 2 });
+ expect(readDataFormat(dir)).toMatchObject({ format: 2, writtenBy: "0.1.153" });
+ // The rollback the rule exists for: 0.1.152 reads format 2, and does not pretend the data is format 1 again.
+ expect(() => stampDataFormat(dir, "0.1.152", { writes: 1, reads: 2 })).not.toThrow();
+ expect(readDataFormat(dir)).toMatchObject({ format: 2, writtenBy: "0.1.153" });
+ });
+
+ it("refuses data a newer version left in a format it cannot read, in plain words, and changes nothing", () => {
+ const dir = dataDir();
+ const marker = `${JSON.stringify({ format: 3, writtenBy: "0.2.0", writtenAt: "2027-01-01T00:00:00.000Z" })}\n`;
+ writeFileSync(join(dir, DATA_FORMAT_FILE), marker);
+ const refusal = `OpenMausBot startup failed: the data in ${dir} was written by a newer OpenMausBot (0.2.0), in a format this version (0.1.152) cannot read. Nothing was changed. Install OpenMausBot 0.2.0 or newer, or put back the copy of the data taken before that update.`;
+ expect(() => checkDataFormat(dir, "0.1.152", 2)).toThrow(new DataFormatError(refusal));
+ expect(() => stampDataFormat(dir, "0.1.152", { writes: 2, reads: 2 })).toThrow(DataFormatError);
+ expect(readFileSync(join(dir, DATA_FORMAT_FILE), "utf8")).toBe(marker);
+ expect(readdirSync(dir)).toEqual([DATA_FORMAT_FILE]);
+ 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}']) {
+ 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/);
+ }
+ });
+});
+
+describe("a server starting on a data folder", () => {
+ /** The real server on `dir`, until it exits or `until` holds. */
+ async function start(dir: string, until: () => boolean): Promise<{ code: number | null; stderr: string }> {
+ const child = spawn(process.execPath, [join(import.meta.dirname, "index.ts")], {
+ cwd: ROOT,
+ env: {
+ ...(process.env.PATH ? { PATH: process.env.PATH } : {}),
+ ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
+ HOME: dir, USERPROFILE: dir, OMB_DATA_DIR: join(dir, "data"), OMB_PORT: String(await freePortBlock([0, 1])),
+ },
+ stdio: ["ignore", "ignore", "pipe"],
+ });
+ let stderr = "";
+ child.stderr!.on("data", (chunk) => (stderr += chunk));
+ const exited = new Promise<number | null>((resolve) => child.once("close", resolve));
+ const watch = setInterval(() => { if (until()) child.kill("SIGTERM"); }, 50);
+ try {
+ return { code: await exited, stderr };
+ } finally {
+ clearInterval(watch);
+ }
+ }
+
+ it("exits with the one plain line, and creates nothing, when a newer version wrote the data", async () => {
+ const dir = dataDir();
+ const data = join(dir, "data");
+ mkdirSync(data);
+ writeFileSync(join(data, DATA_FORMAT_FILE), JSON.stringify({ format: DATA_FORMAT.reads + 1, writtenBy: "99.0.0", writtenAt: "2027-01-01T00:00:00.000Z" }));
+ const { code, stderr } = await start(dir, () => false);
+ expect(code).toBe(1);
+ expect(stderr.trim().split("\n").at(-1)).toBe(
+ `OpenMausBot startup failed: the data in ${data} was written by a newer OpenMausBot (99.0.0), in a format this version (${VERSION}) cannot read. Nothing was changed. Install OpenMausBot 99.0.0 or newer, or put back the copy of the data taken before that update.`,
+ );
+ expect(readdirSync(data)).toEqual([DATA_FORMAT_FILE]);
+ }, 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);
+ await start(dir, () => existsSync(marker));
+ expect(JSON.parse(readFileSync(marker, "utf8"))).toMatchObject({ format: DATA_FORMAT.writes, writtenBy: VERSION });
+ }, 60_000);
+});
diff --git a/server/data-format.ts b/server/data-format.ts
new file mode 100644
index 0000000000..980146faea
--- /dev/null
+++ b/server/data-format.ts
@@ -0,0 +1,99 @@
+// 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 { join } from "node:path";
+
+/**
+ * `writes`: the format this version leaves the data folder in. `reads`: the newest format it can read, which may be
+ * one ahead. A change the previous release cannot read takes two releases: raise `reads` (and ship the code that reads
+ * the new format) in one, raise `writes` in the next. server/data-format.test.ts fails on any other step.
+ */
+export const DATA_FORMAT = { writes: 1, reads: 1 } as const;
+
+export const DATA_FORMAT_FILE = "data-format.json";
+
+export interface DataFormatMarker {
+ /** The newest format a server has left this folder in. A folder without the file is format 1. */
+ format: number;
+ /** The version that wrote it. */
+ writtenBy: string;
+ writtenAt: string;
+}
+
+/** `message` is whole sentences for the server's owner, and the only line the server prints before it exits. */
+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 {
+ 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) {
+ return { format: marker.format, writtenBy: typeof marker.writtenBy === "string" ? marker.writtenBy : "unknown", writtenAt: typeof marker.writtenAt === "string" ? marker.writtenAt : "" };
+ }
+ } catch {
+ }
+ 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(
+ `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);
+ 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);
+}
+
+export interface ReleasedDataFormat {
+ version: string;
+ writes: number;
+ reads: number;
+}
+
+/**
+ * Why `current` may not follow `released` (the last release's formats), or null. The last release must be able to read
+ * what this one writes, and no number goes down or skips.
+ */
+export function dataFormatStepProblem(current: { writes: number; reads: number }, released: ReleasedDataFormat): string | null {
+ if (current.reads < current.writes) return `reads (${current.reads}) is below writes (${current.writes}): a version reads what it writes`;
+ if (current.writes < released.writes || current.reads < released.reads) return `the data format went down from release ${released.version} (writes ${released.writes}, reads ${released.reads})`;
+ if (current.writes > released.reads) {
+ return `writes is ${current.writes}, and release ${released.version} reads only up to ${released.reads}: rolling back to it would leave data it cannot read. `
+ + `Raise reads to ${current.writes} now, with the code that reads the new format, and raise writes in the release after that one`;
+ }
+ if (current.reads > released.reads + 1) return `reads went from ${released.reads} to ${current.reads}: one format at a time`;
+ return null;
+}
+
+/**
+ * At start: `check` before anything in the folder is created, migrated or locked, `stamp` once the folder is this
+ * server's (after a pending restore, which may bring another marker). Unreadable data ends the process with the one
+ * plain line, last in the log, where an updater looks for why the new version did not start.
+ */
+export function dataFormatAtStart(step: "check" | "stamp", dataDir: string, version: string): void {
+ try {
+ if (step === "check") checkDataFormat(dataDir, version);
+ else stampDataFormat(dataDir, version);
+ } catch (error) {
+ if (!(error instanceof DataFormatError)) throw error;
+ console.error(error.message);
+ process.exit(1);
+ }
+}
diff --git a/server/index.ts b/server/index.ts
index 5aeadecdab..ab9d693cad 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -523,7 +523,7 @@ import {
import { createGracefulShutdown } from "./graceful-shutdown.ts";
import { acquireDataDirLeaseForProcess } from "./data-dir-lease.ts";
import { 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 { environmentDescriptor, loadEnvironmentId, OWNER_LENDING, serverVersion } from "./environment.ts"; import { dataFormatAtStart } from "./data-format.ts";
import { WorkspaceBackupMaintenance } from "./workspace-backup-maintenance.ts";
import { createWorkspaceBackupRoutes, isWorkspaceBackupSessionControl } from "./workspace-backup-http.ts";
import { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRestoreResult } from "./workspace-backup.ts";
@@ -652,7 +652,7 @@ const WEBHOOK_PORT = Number(process.env.OMB_WEBHOOK_PORT || PORT + 1);
const WEBHOOK_PUBLIC_URL = process.env.OMB_WEBHOOK_PUBLIC_URL || undefined;
const STATIC_DIR = process.env.OMB_STATIC_DIR || null;
-ensureDirs();
+dataFormatAtStart("check", DATA_DIR, serverVersion()); ensureDirs();
// Acquire before any durable identity, sessions, config or Store state is loaded.
const dataDirLease = acquireDataDirLeaseForProcess(DATA_DIR);
let dataDirLeaseReleaseAttempted = false;
@@ -673,7 +673,7 @@ if (existsSync(join(DATA_DIR, ".backups"))) {
workspaceRestore = applyPendingWorkspaceRestore(DATA_DIR);
if (workspaceRestore.restored) restoredAtStart = workspaceRestore.id;
if (!workspaceRestore.restored && !workspaceRestore.rolledBack) workspaceRestore = readLastWorkspaceRestore(DATA_DIR) ?? workspaceRestore;
-}
+} dataFormatAtStart("stamp", DATA_DIR, serverVersion());
const workspaceMaintenance = new WorkspaceBackupMaintenance(), moveFreeze = createMoveFreeze({ dataDir: DATA_DIR, exportOnly: (process.env.OMB_CLOUD_ROLE === "home" || process.env.OMB_CLOUD_ROLE === "team") && process.env.OMB_CLOUD_EXPORT_ONLY === "1" });
// Only after ensureDirs(), whose one-time legacy data-dir rename must not find ~/.openmausbot already there.
const ENVIRONMENT_ID = loadEnvironmentId(DATA_DIR);