Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Doctor: check and safely repair a server's data, on update and on demand
milind-soni0bbe6142f657
diff --git a/deploy/update.sh b/deploy/update.shindex 142df1ea25..565f92b6af 100755--- a/deploy/update.sh+++ b/deploy/update.sh@@ -545,6 +545,29 @@ wait_whole() {fi}+# The new version did not become healthy. Its own doctor may repair what stopped it (a cut-short save, a lease a killed+# server left): `openmausbot doctor --data --fix` in the server's container while it is up, else, with the server+# stopped, in a one-off container of the new image. The doctor changes nothing while a server uses the data, copies what+# it changes into the data folder first, and repairs only what cannot lose data. Succeeds when it repaired something,+# and the new version is then started once more. A version without the doctor answers a usage error: nothing repaired.+doctor_repaired() {+ local out cid+ say "Running $(new_name)'s doctor on the data before going back…"+ cid=$(container)+ if [ -n "$cid" ] && [ "$(inspect '{{.State.Running}}' "$cid")" = true ]; then+ out=$(compose exec -T "$SERVICE" openmausbot doctor --data --fix --json </dev/null 2>>"$LOG")+ else+ compose stop "$SERVICE" >>"$LOG" 2>&1+ out=$(compose run --rm --no-deps -T "$SERVICE" openmausbot doctor --data --fix --json </dev/null 2>>"$LOG")+ fi+ printf '%s\n' "$out" >>"$LOG"+ printf '%s\n' "$out" | grep -Eq '"fixed": ?[1-9]' || return 1+ say "The doctor repaired the data (see $LOG). Starting $(new_name) once more…"+ # New containers: the one that kept stopping carries its restart count (and Caddy, in a Compose file that runs it in+ # the server's network, must join the new one's).+ compose up -d --no-build --force-recreate >>"$LOG" 2>&1+}+finish() {cp "$JOURNAL" "$LAST.tmp" && mv "$LAST.tmp" "$LAST"rm -f "$JOURNAL"@@ -901,6 +924,11 @@ fiphase waitsay "Waiting for it to answer and to be able to start bots…"if ! wait_healthy "$J_target_id" "$J_version" || ! wait_whole; then- roll_back "The update to $(new_name) did not work: $WHY." 1+ first_why=$WHY+ if doctor_repaired; then+ if ! wait_healthy "$J_target_id" "$J_version" || ! wait_whole; then roll_back "The update to $(new_name) did not work: $WHY." 1; fi+ else+ roll_back "The update to $(new_name) did not work: $first_why." 1+ fififinishdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 56f7815adf..de168c982b 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -1824,3 +1824,43 @@ engine credentials, browser state, and external workspaces. For Docker, thewhole `/data` volume includes the CLI homes. See the[backup and restore instructions](deploy-vps.md#back-up) for the exact scopeand stop/start commands.++### The doctor: checking and repairing the data++The doctor checks a server's data folder and repairs what can be repaired+without losing anything. It runs by itself on the first start of each new+version, before the server reads its data. It writes one log line for each+thing it found, and adds a short `doctor` summary to `/api/health` (as seen by+the owner): the names of the checks it fixed and of those left for you, never a+path. When the new version fails its health check, `update.sh` runs that+version's doctor with `--fix`. If the doctor repairs something, the update+starts the new version once more; otherwise it rolls back as before.++You can run it yourself, as the server's user:++```sh+openmausbot doctor --data # check and report; changes nothing+openmausbot doctor --data --fix # also apply the safe repairs (stop the server first)+openmausbot doctor --data --json # the report as JSON+docker compose exec omb openmausbot doctor --data # Docker+```++`--data-dir DIR` points it at another folder. It exits 0 when everything is+fine (after `--fix`, fine now) and 8 when a problem is left.++| Check | Looks at | Repaired by `--fix` |+|---|---|---|+| Data format | `data-format.json` | Never. Data from a newer version stops every repair: install that version, or roll back. |+| Data folder lease | `openmausbot-server.lease` | A lease a dead process on this machine left is retired. A live server means nothing is changed. |+| Folders | the data folder, `events`, `native` | Missing folders are made. |+| Bots and rooms | `bots.json`, `groups.json` | An unreadable file is put back from the whole temp file of a save that was cut short. With no such copy, a copy of the damaged file is kept and you are told how to restore it. |+| Unfinished saves | `<file>.<pid>.<id>.tmp` at the top of the data folder | Moved into the backup. |+| Engine-run records | `engine-runs/` | Records with neither a server nor a process to stop are moved into the backup. |+| Messages database | `messages.db` | A large write-ahead log is folded back into the database. A damaged database is reported, never rewritten. |+| Private files | `config.json`, `sessions.json`, `bots.json`, `messages.db`, … | Made owner-only (0600). Not on Windows. |+| Settings file | `config.json` | Never: it tells you `openmausbot config restore latest` when dated copies exist. |++Before changing anything, a repair copies it into+`<data>/doctor-backups/<time>/`, with a `manifest.json` that lists what changed+(for a file mode, the old mode). These copies stay on that computer and are not+part of a workspace backup. Delete them once the server runs well.diff --git a/electron/data-dir-lease.d.mts b/electron/data-dir-lease.d.mtsindex 0db231d3de..5026db4bc8 100644--- a/electron/data-dir-lease.d.mts+++ b/electron/data-dir-lease.d.mts@@ -38,3 +38,9 @@ export declare function inMacSyncedFolder(path: string, home: string): boolean;export declare function clearRecordsFromEarlierRunOfThisContainer(dataDir: string,): { path: string; host: string; pid: number }[];++export type DataDirLeaseHolder =+ | { state: "none" | "invalid"; path: string }+ | { state: "alive" | "dead" | "other-machine"; path: string; pid: number; host: string; createdAt: number };++export declare function describeDataDirLease(dataDir: string): DataDirLeaseHolder;diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjsindex 0dab9bf325..dd4f0863a4 100644--- a/electron/data-dir-lease.mjs+++ b/electron/data-dir-lease.mjs@@ -791,6 +791,30 @@ function clearRecords(dataDir, stale) {return cleared;}+/**+ * Who holds the data directory's lease, read only (`openmausbot doctor`): "none"; "alive", a running process on this+ * machine; "dead", a process of this machine that is gone, which the next acquireDataDirLease() retires; "other-machine";+ * or "invalid", a record that cannot be read, which acquireDataDirLease() refuses. Never changes a file.+ */+export function describeDataDirLease(dataDir) {+ const path = join(validateDataDir(dataDir), LEASE_NAME);+ let owner;+ try {+ owner = readOwner(path);+ } catch {+ return { state: "invalid", path };+ }+ if (!owner) return { state: "none", path };+ const holder = { path, pid: owner.pid, host: owner.host, createdAt: owner.createdAt };+ if (!sameMachine(owner, dataDir)) return { state: "other-machine", ...holder };+ try {+ return { state: ownerIsAlive(owner) ? "alive" : "dead", ...holder };+ } catch {+ // Liveness that cannot be told is taken as alive, as acquiring would refuse it.+ return { state: "alive", ...holder };+ }+}+export function acquireDataDirLeaseForProcess(dataDir, environment = process.env) {const encoded = consumeChildCapability(environment);return encoded === nulldiff --git a/scripts/testing/deploy-update.test.ts b/scripts/testing/deploy-update.test.tsindex bf4643e67f..e28e6e1f0d 100644--- a/scripts/testing/deploy-update.test.ts+++ b/scripts/testing/deploy-update.test.ts@@ -174,6 +174,51 @@ describe.skipIf(!posix)("deploy/update.sh", () => {expect(tree(box.data)["started-by.txt"]).toBe("0.1.150\n0.1.150\n");});+ it("runs the new version's doctor on data that stops it from starting, and keeps the update when it then starts", () => {+ const box = install({ behaviour: "repairable", doctor: "repairs" });+ const done = box.run();+ expect(done.status, done.stdout + done.stderr).toBe(0);+ expect(done.said).toEqual([+ "Downloading 0.1.151…",+ "Stopping the server and copying its data aside…",+ "Starting 0.1.151…",+ "Waiting for it to answer and to be able to start bots…",+ "Running 0.1.151's doctor on the data before going back…",+ expect.stringMatching(/^The doctor repaired the data \(see .*\)\. Starting 0\.1\.151 once more…$/),+ "Updated from 0.1.150 to 0.1.151.",+ `The data from before the update is kept in the Docker volume ${box.copies()[0]} until the next update.`,+ "To go back to it: ./update.sh --rollback",+ ]);+ // It kept stopping as it started, so it ran in its own container with the server stopped.+ expect(box.state().doctorRuns).toEqual(["run"]);+ expect(box.calls()).toContain("compose run --rm --no-deps -T omb openmausbot doctor --data --fix --json");+ expect(box.state().containers.omb).toMatchObject({ image: NEW.id, status: "running" });+ expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);+ });++ it("rolls back as before when the doctor repairs nothing, or the new version has none", () => {+ for (const target of [{ behaviour: "crashes", doctor: "nothing" }, { behaviour: "crashes" }, { behaviour: "silent", doctor: "nothing" }]) {+ const box = install(target);+ const failed = box.run();+ expect(failed.status, JSON.stringify(target)).toBe(1);+ expect(failed.said).toContain("Running 0.1.151's doctor on the data before going back…");+ expect(failed.stdout).not.toContain("once more");+ expect(failed.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");+ expect(box.state().containers.omb.image).toBe(OLD.id);+ // A server still up is asked in its own container; one that stopped, in a one-off container.+ expect(box.state().doctorRuns).toEqual([target.behaviour === "silent" ? "exec" : "run"]);+ }+ });++ it("rolls back when the version the doctor repaired still does not start", () => {+ const box = install({ behaviour: "crashes", doctor: "repairs", lastWords: "still broken" });+ const failed = box.run();+ expect(failed.status).toBe(1);+ expect(failed.stdout).toContain("once more");+ expect(failed.stdout).toContain("The update to 0.1.151 did not work: it kept stopping as it started (still broken).");+ expect(box.state().containers.omb.image).toBe(OLD.id);+ });+it.each([[{ engine: false }, "no engine can start a bot on it, and one could before"],[{ behaviour: "no-caddy" }, "Caddy, which serves it to the internet, did not start again"],diff --git a/scripts/testing/fake-compose-docker.mjs b/scripts/testing/fake-compose-docker.mjsindex 8975b0baa3..86f31de3ae 100644--- a/scripts/testing/fake-compose-docker.mjs+++ b/scripts/testing/fake-compose-docker.mjs@@ -40,7 +40,8 @@ function composeUp() {const wanted = image(composeImage());if (!wanted) fail(`pull access denied for ${composeImage()}`);if (state.failUp === wanted.id) fail("Error response from daemon: driver failed programming external connectivity");- const crashes = wanted.behaviour === "crashes";+ // `repairable`: it crashes until its doctor has repaired the data (`doctor --data --fix`, below).+ const crashes = wanted.behaviour === "crashes" || (wanted.behaviour === "repairable" && !state.repaired);state.containers.omb = { id: `omb-${++state.serial}`, image: wanted.id, status: crashes ? "restarting" : "running", restarts: crashes ? 5 : 0, started: `start-${state.serial}` };state.containers.caddy = { id: `caddy-${state.serial}`, status: wanted.behaviour === "no-caddy" ? "exited" : "running" };// A server that starts writes to its data, as a new version's migrations do.@@ -61,6 +62,7 @@ function compose(rest) {}if (verb === "up") return composeUp();if (verb === "logs") return out(image(omb?.image)?.lastWords ?? "");+ if (more.includes("doctor") && more.includes("--fix")) return doctor(verb, omb);if (verb === "exec") {// As the real one does: `docker compose exec` forwards its standard input to the container, so it takes whatever is// waiting there, an answer meant for update.sh's question included.@@ -78,6 +80,26 @@ function compose(rest) {fail(`fake docker: unknown compose command: ${line}`, 64);}+/** `openmausbot doctor --data --fix --json`, run by `compose exec` in the running server or by `compose run` with it+ * stopped. `doctor`: what the image's doctor finds, "repairs" (and then the next start works) or "nothing"; an image+ * without one answers as a version before the doctor: a usage error. */+function doctor(verb, omb) {+ const serving = image(verb === "exec" ? omb?.image : composeImage());+ if (verb === "exec" && omb?.status !== "running") fail("service omb is not running");+ if (verb === "run" && omb?.status === "running") fail("fake docker: the doctor's one-off container beside a running server", 64);+ state.doctorRuns = [...(state.doctorRuns ?? []), verb];+ if (serving?.doctor === "repairs") {+ state.repaired = true;+ return out(JSON.stringify({ ok: true, counts: { checked: 9, problems: 0, fixed: 2, blocking: 0 } }, null, 2));+ }+ if (serving?.doctor === "nothing") {+ out(JSON.stringify({ ok: false, counts: { checked: 9, problems: 1, fixed: 0, blocking: 0 } }, null, 2));+ save();+ process.exit(8);+ }+ fail("openmausbot doctor: unknown option '--data'", 2);+}+function inspect(format, target) {const omb = state.containers.omb;if (!omb || omb.id !== target) fail(`No such object: ${target}`);diff --git a/server/cli-usage.ts b/server/cli-usage.tsindex 35b7e61e2d..cb2ef399ca 100644--- a/server/cli-usage.ts+++ b/server/cli-usage.ts@@ -3,6 +3,7 @@ export { HEADLESS_VERBS as HEADLESS_VERB_NAMES } from "./headless/args.ts";export const HEADLESS_USAGE = `Drive a running workspace (scripts, CI, other agents):openmausbot doctor check the server answers and an engine is readyopenmausbot doctor --host check this Linux machine can run a server (exit 7 if not)+ openmausbot doctor --data [--fix] check (and safely repair) this computer's data folder (exit 8 if a problem is left)openmausbot bots | channels | models your bots, your rooms, the engines and their modelsopenmausbot run BOT "do this" give a bot one job and wait until it and every teammate it asked are doneopenmausbot send BOT "text" send one message and return at oncediff --git a/server/data-dir-lease.ts b/server/data-dir-lease.tsindex 582d1af2fb..d8ba404d9f 100644--- a/server/data-dir-lease.ts+++ b/server/data-dir-lease.ts@@ -7,10 +7,12 @@ export {clearRecordsFromEarlierRunOfThisContainer,clearRecordsFromOtherMachines,DataDirLeaseError,+ describeDataDirLease,} from "../electron/data-dir-lease.mjs";export type {DataDirLease,+ DataDirLeaseHolder,DelegatedDataDirLease,OwnedDataDirLease,} from "../electron/data-dir-lease.mjs";diff --git a/server/doctor/backup.ts b/server/doctor/backup.tsnew file mode 100644index 0000000000..dbf723df87--- /dev/null+++ b/server/doctor/backup.ts@@ -0,0 +1,87 @@+// <data>/doctor-backups/<time>/: every fix puts what it is about to change here first, at the same path it has in the+// data folder, and writes a line in manifest.json. Made on the first fix of a run, so a run that changes nothing leaves+// no folder. Owner-only: it holds copies of the registries.+import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from "node:fs";+import { dirname, join, relative, sep } from "node:path";++export const DOCTOR_BACKUPS_DIR = "doctor-backups";++export type BackupEntry = { check: string; action: string; path: string; savedAs?: string; mode?: string };++export class DoctorBackup {+ private folder: string | null = null;+ private readonly entries: BackupEntry[] = [];++ private readonly dataDir: string;+ private readonly now: () => number;++ constructor(dataDir: string, now: () => number) {+ this.dataDir = dataDir;+ this.now = now;+ }++ /** The run's folder, once anything was put in it. */+ get path(): string | null {+ return this.folder;+ }++ private open(): string {+ if (this.folder) return this.folder;+ const root = join(this.dataDir, DOCTOR_BACKUPS_DIR);+ mkdirSync(root, { recursive: true, mode: 0o700 });+ tighten(root, 0o700);+ // No colons: the folder name is valid on Windows too.+ const base = new Date(this.now()).toISOString().replace(/\.\d+Z$/, "Z").replaceAll(":", "-");+ let name = base;+ for (let n = 2; existsSync(join(root, name)); n += 1) name = `${base}-${n}`;+ const folder = join(root, name);+ mkdirSync(folder, { mode: 0o700 });+ this.folder = folder;+ return folder;+ }++ private target(path: string): string {+ const inData = relative(this.dataDir, path);+ const safe = !inData || inData.startsWith("..") || inData.includes(`..${sep}`) ? path.split(/[\\/]/).filter(Boolean).join("_") : inData;+ const to = join(this.open(), safe);+ mkdirSync(dirname(to), { recursive: true, mode: 0o700 });+ return to;+ }++ /** A copy of `path` (a file or a folder); the original stays. Returns where the copy is. */+ copy(check: string, path: string, action = "copied before the fix"): string {+ const to = this.target(path);+ if (statSync(path).isDirectory()) cpSync(path, to, { recursive: true, errorOnExist: true, force: false });+ else {+ copyFileSync(path, to);+ tighten(to, 0o600);+ }+ this.record({ check, action, path, savedAs: to });+ return to;+ }++ /** Moves `path` into the backup (one rename, the data folder and its backups being one filesystem). */+ move(check: string, path: string, action = "moved out of the data folder"): string {+ const to = this.target(path);+ renameSync(path, to);+ this.record({ check, action, path, savedAs: to });+ return to;+ }++ /** A change with nothing to copy (a mode, a folder made): written down only. */+ note(check: string, action: string, path: string, mode?: number): void {+ this.open();+ this.record({ check, action, path, ...(mode !== undefined ? { mode: `0${(mode & 0o777).toString(8)}` } : {}) });+ }++ private record(entry: BackupEntry): void {+ this.entries.push(entry);+ const manifest = join(this.open(), "manifest.json");+ writeFileSync(manifest, `${JSON.stringify({ entries: this.entries }, null, 2)}\n`, { mode: 0o600 });+ }+}++function tighten(path: string, mode: number): void {+ if (process.platform === "win32") return;+ try { chmodSync(path, mode); } catch {}+}diff --git a/server/doctor/checks/data-format.test.ts b/server/doctor/checks/data-format.test.tsnew file mode 100644index 0000000000..158b7404b8--- /dev/null+++ b/server/doctor/checks/data-format.test.ts@@ -0,0 +1,37 @@+import { existsSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { context, dataFolder, NOW, UUID } from "../../testing/doctor-folders.ts";+import { DOCTOR_BACKUPS_DIR } from "../backup.ts";+import { runDoctor } from "../run.ts";+import { dataFormatCheck } from "./data-format.ts";+import { tempFilesCheck } from "./temp-files.ts";++describe("data-format check", () => {+ it("takes a folder without a marker, or with one this version reads, as fine", () => {+ const data = dataFolder();+ expect(dataFormatCheck().check(context(data)).status).toBe("ok");+ writeFileSync(join(data, "data-format.json"), JSON.stringify({ format: 1, writtenBy: "0.1.160", writtenAt: "" }));+ expect(dataFormatCheck().check(context(data)).status).toBe("ok");+ });++ it("refuses a newer format, never fixes it, and then lets no other fix run", () => {+ const data = dataFolder();+ writeFileSync(join(data, "data-format.json"), JSON.stringify({ format: 2, writtenBy: "0.2.0", writtenAt: "" }));+ const finding = dataFormatCheck().check(context(data));+ expect(finding).toMatchObject({ status: "problem", blocking: true });+ expect(finding.fixable).toBeFalsy();+ expect(finding.instruction).toContain("0.2.0");++ const stray = join(data, `bots.json.999999.${UUID}.tmp`);+ writeFileSync(stray, "[]");+ const report = runDoctor({ dataDir: data, version: "0.1.170", mode: "command", fix: true, now: () => NOW, pidAlive: () => false,+ checks: [dataFormatCheck(), tempFilesCheck()], acquireLease: () => ({ release() {} }) });+ expect(report.fix).toMatchObject({ asked: true, ran: false });+ expect(report.fix.why).toContain("newer OpenMausBot");+ expect(report.checks.map((result) => result.status)).toEqual(["problem", "problem"]);+ expect(existsSync(stray)).toBe(true);+ expect(existsSync(join(data, DOCTOR_BACKUPS_DIR))).toBe(false);+ });+});diff --git a/server/doctor/checks/data-format.ts b/server/doctor/checks/data-format.tsnew file mode 100644index 0000000000..7f17e3461c--- /dev/null+++ b/server/doctor/checks/data-format.ts@@ -0,0 +1,29 @@+// A data folder a newer version left in a format this one cannot read. Never fixed: the only safe way is the version+// that wrote it, or the copy from before that update.+import { DATA_FORMAT, DataFormatError, readDataFormat } from "../../data-format.ts";+import type { DoctorCheck } from "../types.ts";++export function dataFormatCheck(format: { reads: number; writes: number } = DATA_FORMAT): DoctorCheck {+ return {+ id: "data-format",+ title: "Data format",+ looksAt: "data-format.json",+ check(ctx) {+ let marker;+ try {+ marker = readDataFormat(ctx.dataDir, format.writes);+ } catch (error) {+ if (!(error instanceof DataFormatError)) throw error;+ return { status: "problem", blocking: true, summary: "data-format.json cannot be read, so this version cannot tell whether it understands the data.",+ instruction: "Restore data-format.json from a backup, or the whole data folder from the copy taken before the last update (./update.sh --rollback)." };+ }+ if (!marker) return { status: "ok", summary: "No marker: the data is in format 1." };+ if (marker.format > format.reads) {+ return { status: "problem", blocking: true,+ summary: `The data was written by a newer OpenMausBot (${marker.writtenBy}) in format ${marker.format}; this version (${ctx.version}) reads up to format ${format.reads}.`,+ instruction: `Install OpenMausBot ${marker.writtenBy} or newer, or put back the copy of the data taken before that update (./update.sh --rollback). Nothing was changed.` };+ }+ return { status: "ok", summary: `Format ${marker.format}, which this version reads.` };+ },+ };+}diff --git a/server/doctor/checks/engine-runs.test.ts b/server/doctor/checks/engine-runs.test.tsnew file mode 100644index 0000000000..cf5cc1c80e--- /dev/null+++ b/server/doctor/checks/engine-runs.test.ts@@ -0,0 +1,44 @@+import { existsSync, mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, NOW } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { engineRunsCheck } from "./engine-runs.ts";++const tag = (n: number) => n.toString(16).padStart(32, "0");++describe("engine-runs check", () => {+ it("moves records with neither a server nor a process into the backup, and leaves every other", () => {+ const data = dataFolder();+ const runs = join(data, "engine-runs");+ const orphan = join(runs, tag(1)), withServer = join(runs, tag(2)), clean = join(runs, tag(3));+ for (const dir of [orphan, withServer, clean]) mkdirSync(dir, { recursive: true });+ writeFileSync(join(orphan, "server.json"), "");+ writeFileSync(join(withServer, "server.json"), JSON.stringify({ pid: 12, start: "x" }));+ writeFileSync(join(clean, "clean"), "");+ mkdirSync(join(runs, "not-a-run"));+ expect(engineRunsCheck().check(context(data))).toMatchObject({ status: "problem", fixable: true });++ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [engineRunsCheck()] });+ expect(report.checks[0]).toMatchObject({ status: "fixed", fixed: "Moved 1 into the backup." });+ expect(existsSync(orphan)).toBe(false);+ expect(existsSync(join(backupFolder(data)!, "engine-runs", tag(1), "server.json"))).toBe(true);+ for (const dir of [withServer, clean, join(runs, "not-a-run")]) expect(existsSync(dir)).toBe(true);+ });++ it("leaves a record that names processes but not its server for a person", () => {+ const data = dataFolder();+ const unknown = join(data, "engine-runs", tag(4));+ mkdirSync(unknown, { recursive: true });+ writeFileSync(join(unknown, "777.json"), JSON.stringify({ pid: 777, start: "y" }));+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [engineRunsCheck()] });+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.checks[0]!.instruction).toContain("may still be running");+ expect(existsSync(join(unknown, "777.json"))).toBe(true);+ });++ it("is fine without the folder", () => {+ expect(engineRunsCheck().check(context(dataFolder())).status).toBe("ok");+ });+});diff --git a/server/doctor/checks/engine-runs.ts b/server/doctor/checks/engine-runs.tsnew file mode 100644index 0000000000..cae8830beb--- /dev/null+++ b/server/doctor/checks/engine-runs.ts@@ -0,0 +1,62 @@+// engine-runs/<tag>/ (engine-records.ts): what each server run started, so the next start can stop what a dead one left.+// A run whose server.json cannot be read is never swept, and stays forever; when it also names no process, nothing in+// it can ever be stopped, and it is moved into the backup. One that names processes is left for a person: they may+// still run. Live runs and this server's own are never touched.+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import { ENGINE_RUNS_DIR, engineRunTag } from "../../engine-records.ts";+import type { DoctorCheck } from "../types.ts";++const TAG = /^[0-9a-f]{32}$/;++function readable(file: string): boolean {+ try {+ const record = JSON.parse(readFileSync(file, "utf8")) as { pid?: unknown };+ return Number.isInteger(record?.pid) && (record.pid as number) > 0;+ } catch {+ return false;+ }+}++export function engineRunsCheck(): DoctorCheck {+ return {+ id: "engine-runs",+ title: "Engine-run records",+ looksAt: `${ENGINE_RUNS_DIR}/`,+ check(ctx) {+ const root = join(ctx.dataDir, ENGINE_RUNS_DIR);+ let names: string[];+ try { names = readdirSync(root); } catch { return { status: "ok", summary: "None." }; }+ const own = engineRunTag();+ const orphaned: string[] = [];+ let unknown = 0;+ for (const name of names) {+ if (!TAG.test(name) || name === own) continue;+ const dir = join(root, name);+ try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }+ if (existsSync(join(dir, "clean")) || readable(join(dir, "server.json"))) continue;+ let leaders: string[];+ try { leaders = readdirSync(dir).filter((file) => /^\d+\.json$/.test(file)); } catch { continue; }+ if (leaders.length) unknown += 1;+ else orphaned.push(dir);+ }+ if (!orphaned.length && !unknown) return { status: "ok", summary: `${names.length} run record${names.length === 1 ? "" : "s"}, each with its server.` };+ return {+ status: "problem",+ fixable: orphaned.length > 0,+ summary: [+ orphaned.length ? `${orphaned.length} run record${orphaned.length === 1 ? "" : "s"} without a server and without a process to stop.` : "",+ unknown ? `${unknown} run record${unknown === 1 ? "" : "s"} name processes, but not the server that started them.` : "",+ ].filter(Boolean).join(" "),+ ...(unknown ? { instruction: `Engines those runs started may still be running. Stop any you do not recognise (ps -ef), then delete those folders in ${root}.` } : {}),+ detail: orphaned,+ };+ },+ fix(_ctx, finding, backup) {+ const dirs = finding.detail as string[];+ for (const dir of dirs) backup.move("engine-runs", dir);+ return `Moved ${dirs.length} into the backup.`;+ },+ };+}diff --git a/server/doctor/checks/folders.test.ts b/server/doctor/checks/folders.test.tsnew file mode 100644index 0000000000..fef808a760--- /dev/null+++ b/server/doctor/checks/folders.test.ts@@ -0,0 +1,39 @@+import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, manifest, NOW } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { foldersCheck } from "./folders.ts";++const run = (data: string) => runDoctor({ dataDir: data, version: "9.9.9", mode: "command", fix: true, now: () => NOW, checks: [foldersCheck()], acquireLease: () => ({ release() {} }) });++describe("folders check", () => {+ it("makes the server's missing folders and writes down that it did", () => {+ const data = dataFolder();+ mkdirSync(join(data, "events"));+ expect(foldersCheck().check(context(data))).toMatchObject({ status: "problem", fixable: true, summary: "Missing folder: native." });+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ status: "fixed", fixed: "Made native." });+ expect(statSync(join(data, "native")).isDirectory()).toBe(true);+ expect(manifest(backupFolder(data)!).entries).toEqual([{ check: "folders", action: "folder made", path: join(data, "native") }]);+ });++ it("does not make a data folder that is not there, nor anything in it", () => {+ const data = join(dataFolder(), "not-here");+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.fix.ran).toBe(false);+ expect(existsSync(data)).toBe(false);+ });++ it("leaves a file where a folder should be for a person", () => {+ const data = dataFolder();+ mkdirSync(join(data, "events"));+ writeFileSync(join(data, "native"), "");+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.checks[0]!.instruction).toContain(join(data, "native"));+ expect(statSync(join(data, "native")).isFile()).toBe(true);+ });+});diff --git a/server/doctor/checks/folders.ts b/server/doctor/checks/folders.tsnew file mode 100644index 0000000000..080c64865f--- /dev/null+++ b/server/doctor/checks/folders.ts@@ -0,0 +1,44 @@+// The folders a server writes into from its first moment (config.ts ensureDirs). A missing one is made; a file where a+// folder should be, or a data folder this user cannot write, is for a person.+import { accessSync, constants, existsSync, mkdirSync, statSync } from "node:fs";+import { join } from "node:path";++import type { DoctorCheck } from "../types.ts";++export const SERVER_FOLDERS = ["events", "native"] as const;++export function foldersCheck(): DoctorCheck {+ return {+ id: "folders",+ title: "Folders",+ looksAt: `the data folder, ${SERVER_FOLDERS.join(", ")}`,+ check(ctx) {+ let data;+ try { data = statSync(ctx.dataDir); } catch {+ return { status: "problem", summary: `There is no data folder at ${ctx.dataDir}.`,+ instruction: "Check the path (--data-dir, or OMB_DATA_DIR). A server starting there makes a new, empty one." };+ }+ if (!data.isDirectory()) return { status: "problem", summary: `${ctx.dataDir} is a file, not a folder.`, instruction: "Move that file away, or point the server at its data folder." };+ try { accessSync(ctx.dataDir, constants.W_OK); } catch {+ return { status: "problem", summary: "This user cannot write to the data folder.",+ instruction: `Give the user the server runs as the folder back (for example: chown -R <user> ${ctx.dataDir}).` };+ }+ const notFolders = SERVER_FOLDERS.filter((name) => existsSync(join(ctx.dataDir, name)) && !statSync(join(ctx.dataDir, name)).isDirectory());+ if (notFolders.length) {+ return { status: "problem", summary: `${notFolders.join(", ")} should be a folder, and is a file.`,+ instruction: `Move ${notFolders.map((name) => join(ctx.dataDir, name)).join(", ")} out of the data folder, then start the server.` };+ }+ const missing = SERVER_FOLDERS.filter((name) => !existsSync(join(ctx.dataDir, name)));+ if (missing.length) return { status: "problem", fixable: true, summary: `Missing folder${missing.length === 1 ? "" : "s"}: ${missing.join(", ")}.`, detail: missing };+ return { status: "ok", summary: "All there." };+ },+ fix(ctx, finding, backup) {+ const missing = finding.detail as string[];+ for (const name of missing) {+ mkdirSync(join(ctx.dataDir, name), { recursive: true });+ backup.note("folders", "folder made", join(ctx.dataDir, name));+ }+ return `Made ${missing.join(", ")}.`;+ },+ };+}diff --git a/server/doctor/checks/lease.test.ts b/server/doctor/checks/lease.test.tsnew file mode 100644index 0000000000..c5b551270e--- /dev/null+++ b/server/doctor/checks/lease.test.ts@@ -0,0 +1,65 @@+import { randomUUID } from "node:crypto";+import { existsSync, readFileSync, writeFileSync } from "node:fs";+import { hostname } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, deadPid, NOW } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { leaseCheck } from "./lease.ts";++const LEASE = "openmausbot-server.lease";+const lease = (data: string, pid: number) => {+ const record = `${JSON.stringify({ version: 1, pid, host: hostname(), token: randomUUID(), createdAt: NOW })}\n`;+ writeFileSync(join(data, LEASE), record, { mode: 0o600 });+ return record;+};+const run = (data: string, fix = true) => runDoctor({ dataDir: data, version: "9.9.9", mode: "command", fix, now: () => NOW, checks: [leaseCheck()] });++describe("lease check", () => {+ it("is the server's own as it starts", () => {+ expect(leaseCheck().check(context(dataFolder(), { mode: "start" }))).toMatchObject({ status: "ok", summary: "This server holds it." });+ });++ it("finds no lease fine", () => {+ expect(leaseCheck().check(context(dataFolder())).status).toBe("ok");+ });++ it("retires a lease a dead process of this machine left, keeping a copy, by taking the lease and letting it go", () => {+ const data = dataFolder();+ const record = lease(data, deadPid());+ expect(leaseCheck().check(context(data))).toMatchObject({ status: "problem", fixable: true });++ const report = run(data);+ expect(report.checks[0]).toMatchObject({ id: "lease", status: "fixed" });+ expect(existsSync(join(data, LEASE))).toBe(false);+ expect(readFileSync(join(backupFolder(data)!, LEASE), "utf8")).toBe(record);+ });++ it("changes nothing while a live process holds the lease", () => {+ const data = dataFolder();+ const record = lease(data, process.pid);+ expect(leaseCheck().check(context(data))).toMatchObject({ status: "ok" });+ const report = run(data);+ expect(report.fix).toMatchObject({ ran: false });+ expect(report.fix.why).toContain(`process ${process.pid}`);+ expect(readFileSync(join(data, LEASE), "utf8")).toBe(record);+ expect(backupFolder(data)).toBeNull();+ });++ it("reports another machine's lease with what to do, and changes nothing", () => {+ const data = dataFolder();+ const other = leaseCheck(() => ({ state: "other-machine", path: join(data, LEASE), pid: 42, host: "elsewhere", createdAt: NOW }));+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "command", fix: true, now: () => NOW, checks: [other], acquireLease: () => { throw new Error("must not be taken"); } });+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.checks[0]!.instruction).toContain("delete");+ expect(report.fix.ran).toBe(false);+ });++ it("reports a lease record that cannot be read", () => {+ const data = dataFolder();+ writeFileSync(join(data, LEASE), "{not json");+ expect(leaseCheck().check(context(data))).toMatchObject({ status: "problem", summary: "The lease record cannot be read." });+ expect(run(data).fix.ran).toBe(false);+ });+});diff --git a/server/doctor/checks/lease.ts b/server/doctor/checks/lease.tsnew file mode 100644index 0000000000..8ff24d255d--- /dev/null+++ b/server/doctor/checks/lease.ts@@ -0,0 +1,33 @@+// The data folder's lease (electron/data-dir-lease.mjs): which process may use the folder. A lease a dead process of+// this machine left is retired by taking the lease, with the lease module's own recovery, which the runner does before+// any other fix (run.ts); a live one means the server is running, and no fix runs beside it.+import { describeDataDirLease, type DataDirLeaseHolder } from "../../data-dir-lease.ts";+import type { DoctorCheck } from "../types.ts";++export function leaseCheck(describe: (dataDir: string) => DataDirLeaseHolder = describeDataDirLease): DoctorCheck {+ return {+ id: "lease",+ title: "Data folder lease",+ looksAt: "openmausbot-server.lease",+ check(ctx) {+ if (ctx.mode === "start") return { status: "ok", summary: "This server holds it." };+ const holder = describe(ctx.dataDir);+ switch (holder.state) {+ case "none":+ return { status: "ok", summary: "No server is using the data folder.", detail: holder };+ case "alive":+ return { status: "ok", summary: `A server is using the data folder (process ${holder.pid}).`, detail: holder };+ case "dead":+ return { status: "problem", fixable: true, detail: holder,+ summary: `Process ${holder.pid}, which is no longer running, left its lease on the data folder.` };+ case "other-machine":+ return { status: "problem", detail: holder,+ summary: `The lease names a process on another machine or container (${holder.host}, process ${holder.pid}).`,+ instruction: `If no OpenMausBot runs there on this folder, stop this server and delete ${holder.path}; it starts again without it.` };+ default:+ return { status: "problem", detail: holder, summary: "The lease record cannot be read.",+ instruction: `If no OpenMausBot is running on this folder, delete ${holder.path} and start the server again.` };+ }+ },+ };+}diff --git a/server/doctor/checks/messages-db.test.ts b/server/doctor/checks/messages-db.test.tsnew file mode 100644index 0000000000..872f0632cd--- /dev/null+++ b/server/doctor/checks/messages-db.test.ts@@ -0,0 +1,75 @@+import { existsSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, manifest, NOW } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { messagesDbCheck } from "./messages-db.ts";++function database(data: string, rows = 10): DatabaseSync {+ const db = new DatabaseSync(join(data, "messages.db"));+ db.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0; CREATE TABLE messages (id TEXT, text TEXT)");+ const insert = db.prepare("INSERT INTO messages VALUES (?, ?)");+ for (let n = 0; n < rows; n += 1) insert.run(String(n), "x".repeat(2000));+ return db;+}++describe("messages-db check", () => {+ it("finds a sound database fine, and a missing one", () => {+ const data = dataFolder();+ expect(messagesDbCheck().check(context(data)).status).toBe("ok");+ database(data).close();+ expect(messagesDbCheck().check(context(data))).toMatchObject({ status: "ok", summary: "SQLite finds it sound." });+ });++ it("reports a damaged database with what to do, and never fixes it", () => {+ const data = dataFolder();+ writeFileSync(join(data, "messages.db"), Buffer.alloc(8192, 7));+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [messagesDbCheck()] });+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.checks[0]!.instruction).toContain("does not rewrite it");+ expect(backupFolder(data)).toBeNull();+ });++ it("folds a large write-ahead log back after copying the database and the log", () => {+ const data = dataFolder();+ const writer = database(data, 200);+ try {+ const wal = statSync(join(data, "messages.db-wal")).size;+ expect(wal).toBeGreaterThan(100_000);+ const check = messagesDbCheck({ largeWalBytes: 100_000, freeBytes: () => null });+ expect(check.check(context(data))).toMatchObject({ status: "problem", fixable: true });+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [check] });+ expect(report.checks[0]).toMatchObject({ status: "fixed", fixed: "Folded the write-ahead log back into the database." });+ expect(statSync(join(data, "messages.db-wal")).size).toBe(0);+ const backup = backupFolder(data)!;+ expect(statSync(join(backup, "messages.db-wal")).size).toBe(wal);+ expect(manifest(backup).entries.map((entry) => entry.path)).toContain(join(data, "messages.db"));+ expect((writer.prepare("SELECT count(*) AS n FROM messages").get() as { n: number }).n).toBe(200);+ } finally {+ writer.close();+ }+ });++ it("does not copy into a disk without room for it", () => {+ const data = dataFolder();+ const writer = database(data, 200);+ try {+ const finding = messagesDbCheck({ largeWalBytes: 100_000, freeBytes: () => 1024 }).check(context(data));+ expect(finding).toMatchObject({ status: "problem", fixable: false });+ expect(finding.instruction).toContain("free some disk");+ } finally {+ writer.close();+ }+ });++ it("skips the full read of a large database at start, and not on the command", () => {+ const data = dataFolder();+ writeFileSync(join(data, "messages.db"), Buffer.alloc(8192, 7));+ const check = messagesDbCheck({ startCheckMaxBytes: 1024 });+ expect(check.check(context(data, { mode: "start" })).status).toBe("ok");+ expect(check.check(context(data, { mode: "command" })).status).toBe("problem");+ expect(existsSync(join(data, "messages.db-wal"))).toBe(false);+ });+});diff --git a/server/doctor/checks/messages-db.ts b/server/doctor/checks/messages-db.tsnew file mode 100644index 0000000000..7c39315fc1--- /dev/null+++ b/server/doctor/checks/messages-db.ts@@ -0,0 +1,74 @@+// messages.db: every conversation's messages. SQLite's own check says whether the file is sound; a damaged one is for a+// person (the doctor never rewrites it). A write-ahead log grown large while no server folds it back makes each start+// slower; folding it in (a checkpoint) is SQLite's own step, taken after both files are copied into the backup.+import { existsSync, statfsSync, statSync } from "node:fs";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";++import type { DoctorCheck } from "../types.ts";++const DB = "messages.db";+/** Above this, the check at start is skipped (it reads the whole file, and the update waits on the start). */+export const START_CHECK_MAX_BYTES = 256 * 1024 * 1024;+/** A log this big is folded back into the database. */+export const LARGE_WAL_BYTES = 64 * 1024 * 1024;++const size = (path: string) => { try { return statSync(path).size; } catch { return 0; } };++export function messagesDbCheck(limits: { startCheckMaxBytes?: number; largeWalBytes?: number; freeBytes?: (dir: string) => number | null } = {}): DoctorCheck {+ const startMax = limits.startCheckMaxBytes ?? START_CHECK_MAX_BYTES, largeWal = limits.largeWalBytes ?? LARGE_WAL_BYTES;+ const freeBytes = limits.freeBytes ?? ((dir: string) => {+ try { const stats = statfsSync(dir); return Number(stats.bavail) * Number(stats.bsize); } catch { return null; }+ });+ return {+ id: "messages-db",+ title: "Messages database",+ looksAt: `${DB}, ${DB}-wal`,+ check(ctx) {+ const file = join(ctx.dataDir, DB);+ if (!existsSync(file)) return { status: "ok", summary: "Not there yet." };+ const dbBytes = size(file), walBytes = size(`${file}-wal`);+ const full = ctx.mode === "command";+ let verdict: string | null = null;+ if (full || dbBytes <= startMax) {+ let db: DatabaseSync | null = null;+ try {+ db = new DatabaseSync(file, { readOnly: true });+ const rows = db.prepare(full ? "PRAGMA integrity_check(20)" : "PRAGMA quick_check(20)").all() as Record<string, unknown>[];+ const lines = rows.map((row) => String(Object.values(row)[0]));+ verdict = lines.length === 1 && lines[0] === "ok" ? "ok" : `${lines.length} problem${lines.length === 1 ? "" : "s"} (first: ${lines[0]?.slice(0, 160) ?? "unknown"})`;+ } catch (error) {+ verdict = `it cannot be opened (${error instanceof Error ? error.message.slice(0, 160) : String(error)})`;+ } finally {+ try { db?.close(); } catch {}+ }+ }+ if (verdict && verdict !== "ok") {+ return { status: "problem", summary: `SQLite finds the database damaged: ${verdict}.`,+ instruction: "Stop the server and put back messages.db from the copy taken before the last update (./update.sh --rollback) or from a workspace backup. The doctor does not rewrite it." };+ }+ const checked = verdict === "ok" ? "SQLite finds it sound" : `${Math.round(dbBytes / 1024 / 1024)} MB: checked only by openmausbot doctor --data`;+ if (walBytes > largeWal) {+ const free = freeBytes(ctx.dataDir);+ const room = free === null || free > 2 * (dbBytes + walBytes);+ return { status: "problem", fixable: room, detail: { file },+ summary: `${checked}; its write-ahead log is ${Math.round(walBytes / 1024 / 1024)} MB.`,+ ...(room ? {} : { instruction: "There is not room to copy it first: free some disk, then run openmausbot doctor --data --fix." }) };+ }+ return { status: "ok", summary: `${checked}.` };+ },+ fix(_ctx, finding, backup) {+ const { file } = finding.detail as { file: string };+ backup.copy("messages-db", file);+ for (const extra of [`${file}-wal`, `${file}-shm`]) if (existsSync(extra)) backup.copy("messages-db", extra);+ const db = new DatabaseSync(file);+ try {+ const [row] = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").all() as { busy?: number }[];+ if (row?.busy) throw new Error("another connection holds the database");+ } finally {+ db.close();+ }+ return "Folded the write-ahead log back into the database.";+ },+ };+}diff --git a/server/doctor/checks/registry.test.ts b/server/doctor/checks/registry.test.tsnew file mode 100644index 0000000000..b2ccba6b9a--- /dev/null+++ b/server/doctor/checks/registry.test.ts@@ -0,0 +1,61 @@+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, manifest, NOW, UUID } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { registryCheck } from "./registry.ts";+import { tempFilesCheck } from "./temp-files.ts";++const run = (data: string, pidAlive = (_pid: number) => false) =>+ runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, pidAlive, checks: [registryCheck(), tempFilesCheck()] });++describe("registry check", () => {+ it("finds readable or missing registries fine", () => {+ const data = dataFolder();+ expect(registryCheck().check(context(data)).status).toBe("ok");+ writeFileSync(join(data, "bots.json"), "[]");+ expect(registryCheck().check(context(data)).status).toBe("ok");+ });++ it("puts back an unreadable bots.json from the whole copy an interrupted save left, keeping the damaged one", () => {+ const data = dataFolder();+ const whole = JSON.stringify([{ id: "b1", name: "Ada" }]);+ writeFileSync(join(data, "bots.json"), "[{\"id\":\"b1\",\"na");+ writeFileSync(join(data, `bots.json.4242.${UUID}.tmp`), whole);+ expect(registryCheck().check(context(data))).toMatchObject({ status: "problem", fixable: true });++ const report = run(data);+ expect(report.checks[0]).toMatchObject({ id: "registry", status: "fixed" });+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe(whole);+ if (process.platform !== "win32") expect(statSync(join(data, "bots.json")).mode & 0o777).toBe(0o600);+ // The temp file became bots.json: nothing is left for the temp-file check.+ expect(report.checks[1]).toMatchObject({ id: "temp-files", status: "ok" });+ const backup = backupFolder(data)!;+ expect(readFileSync(join(backup, "bots.json"), "utf8")).toBe("[{\"id\":\"b1\",\"na");+ expect(manifest(backup).entries.map((entry) => entry.action)).toEqual(["moved aside: could not be read", "the copy put in its place"]);+ });++ it("keeps a copy of an unreadable file it cannot repair, leaves the file, and says what to do", () => {+ const data = dataFolder();+ writeFileSync(join(data, "groups.json"), "");+ writeFileSync(join(data, "bots.json"), "{}");+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.checks[0]!.fixed).toContain("kept a copy of the unreadable groups.json");+ expect(report.checks[0]!.instruction).toContain("./update.sh --rollback");+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("{}");+ expect(readFileSync(join(backupFolder(data)!, "bots.json"), "utf8")).toBe("{}");+ expect(existsSync(join(backupFolder(data)!, "groups.json"))).toBe(true);+ });++ it("never takes the temp file of a save still running", () => {+ const data = dataFolder();+ writeFileSync(join(data, "bots.json"), "nope");+ writeFileSync(join(data, `bots.json.4242.${UUID}.tmp`), "[]");+ const report = run(data, (pid) => pid === 4242);+ expect(report.checks[0]!.fixable).toBe(false);+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("nope");+ expect(existsSync(join(data, `bots.json.4242.${UUID}.tmp`))).toBe(true);+ });+});diff --git a/server/doctor/checks/registry.ts b/server/doctor/checks/registry.tsnew file mode 100644index 0000000000..8c6e646158--- /dev/null+++ b/server/doctor/checks/registry.ts@@ -0,0 +1,57 @@+// bots.json and groups.json (registry-store.ts). The Store takes one it cannot read for an empty list, and the next save+// writes over it. Fixed only from a whole copy the server itself wrote: the temp file of a save that was interrupted+// after it was written and before it was renamed, which is newer than anything else. Otherwise a copy of the damaged+// file goes into the backup before the server starts, so a later save cannot take the last of it.+import { chmodSync, renameSync } from "node:fs";+import { join } from "node:path";++import { leftoverTemps, registryState, type LeftoverTemp } from "../files.ts";+import type { DoctorCheck } from "../types.ts";++export const REGISTRY_FILES = ["bots.json", "groups.json"] as const;++type Damage = { file: string; path: string; copy: LeftoverTemp | null };++export function registryCheck(): DoctorCheck {+ return {+ id: "registry",+ title: "Bots and rooms",+ looksAt: REGISTRY_FILES.join(", "),+ check(ctx) {+ const damaged: Damage[] = [];+ for (const file of REGISTRY_FILES) {+ const path = join(ctx.dataDir, file);+ if (registryState(path) !== "unreadable") continue;+ const copies = leftoverTemps(ctx).filter((temp) => temp.of === file && registryState(temp.path) === "ok").sort((a, b) => b.mtimeMs - a.mtimeMs);+ damaged.push({ file, path, copy: copies[0] ?? null });+ }+ if (!damaged.length) return { status: "ok", summary: "Both read as lists (or are not there yet)." };+ const lost = damaged.filter((damage) => !damage.copy);+ return {+ status: "problem",+ fixable: lost.length === 0,+ keepCopy: lost.length > 0,+ summary: damaged.map((damage) => `${damage.file} cannot be read${damage.copy ? ", and a whole copy from an interrupted save is there" : ""}.`).join(" "),+ ...(lost.length ? { instruction: `Stop the server and put back ${lost.map((damage) => damage.file).join(" and ")} from the copy taken before the last update (./update.sh --rollback) or from a workspace backup. Until then the server shows no ${lost.some((damage) => damage.file === "bots.json") ? "bots" : "rooms"}.` } : {}),+ detail: damaged,+ };+ },+ fix(_ctx, finding, backup) {+ const done: string[] = [];+ for (const damage of finding.detail as Damage[]) {+ if (!damage.copy) {+ // Not a repair: the damaged file stays, and its bytes are kept where a later save cannot reach them.+ backup.copy("registry", damage.path, "kept: could not be read, and no whole copy was found");+ done.push(`kept a copy of the unreadable ${damage.file}`);+ continue;+ }+ backup.move("registry", damage.path, "moved aside: could not be read");+ backup.copy("registry", damage.copy.path, "the copy put in its place");+ renameSync(damage.copy.path, damage.path);+ if (process.platform !== "win32") chmodSync(damage.path, 0o600);+ done.push(`put back ${damage.file} from the save process ${damage.copy.pid} did not finish`);+ }+ return `${done.join("; ")}.`;+ },+ };+}diff --git a/server/doctor/checks/secret-modes.test.ts b/server/doctor/checks/secret-modes.test.tsnew file mode 100644index 0000000000..ebe44c08dd--- /dev/null+++ b/server/doctor/checks/secret-modes.test.ts@@ -0,0 +1,32 @@+import { chmodSync, readdirSync, statSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, manifest, NOW } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { secretModesCheck } from "./secret-modes.ts";++describe.skipIf(process.platform === "win32")("secret-modes check", () => {+ it("makes private files others can read owner-only, writing down the old mode and copying nothing", () => {+ const data = dataFolder();+ for (const name of ["config.json", "sessions.json", "notes.txt"]) writeFileSync(join(data, name), "{\"key\":\"secret\"}");+ chmodSync(join(data, "config.json"), 0o644);+ chmodSync(join(data, "sessions.json"), 0o600);+ chmodSync(join(data, "notes.txt"), 0o644);+ expect(secretModesCheck().check(context(data))).toMatchObject({ status: "problem", fixable: true, summary: "Others can read config.json (0644)." });++ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [secretModesCheck()] });+ expect(report.checks[0]).toMatchObject({ status: "fixed" });+ expect(statSync(join(data, "config.json")).mode & 0o777).toBe(0o600);+ expect(statSync(join(data, "notes.txt")).mode & 0o777).toBe(0o644);+ const backup = backupFolder(data)!;+ expect(readdirSync(backup)).toEqual(["manifest.json"]);+ expect(manifest(backup).entries).toEqual([{ check: "secret-modes", action: "made owner-only (0600); the old mode is here", path: join(data, "config.json"), mode: "0644" }]);+ });+});++describe("secret-modes check on Windows", () => {+ it("does not look", () => {+ expect(secretModesCheck("win32").check(context(dataFolder())).summary).toBe("Not checked on Windows.");+ });+});diff --git a/server/doctor/checks/secret-modes.ts b/server/doctor/checks/secret-modes.tsnew file mode 100644index 0000000000..7eea711785--- /dev/null+++ b/server/doctor/checks/secret-modes.ts@@ -0,0 +1,44 @@+// Files holding keys, sign-ins or conversations are the server user's alone (0600). A file others can read (restored+// from an archive, copied by hand) is made owner-only again; its old mode is written down in the backup, and its+// contents are not copied there: a second copy of a secret is what this check is against. Not on Windows, whose files+// have no such bits.+import { chmodSync, lstatSync } from "node:fs";+import { join } from "node:path";++import type { DoctorCheck } from "../types.ts";++export const SECRET_FILES = [+ "config.json", "sessions.json", "bots.json", "groups.json", "messages.db", "webhooks.json", "tunnel-account.json", "browser-engine-key",+] as const;++type Loose = { name: string; path: string; mode: number };++export function secretModesCheck(platform: NodeJS.Platform = process.platform): DoctorCheck {+ return {+ id: "secret-modes",+ title: "Private files",+ looksAt: SECRET_FILES.join(", "),+ check(ctx) {+ if (platform === "win32") return { status: "ok", summary: "Not checked on Windows." };+ const loose: Loose[] = [];+ for (const name of SECRET_FILES) {+ const path = join(ctx.dataDir, name);+ try {+ const stat = lstatSync(path);+ if (stat.isFile() && (stat.mode & 0o077) !== 0) loose.push({ name, path, mode: stat.mode & 0o777 });+ } catch {}+ }+ if (!loose.length) return { status: "ok", summary: "Only the server's user can read them." };+ return { status: "problem", fixable: true, detail: loose,+ summary: `Others can read ${loose.map((file) => `${file.name} (0${file.mode.toString(8)})`).join(", ")}.` };+ },+ fix(_ctx, finding, backup) {+ const loose = finding.detail as Loose[];+ for (const file of loose) {+ backup.note("secret-modes", "made owner-only (0600); the old mode is here", file.path, file.mode);+ chmodSync(file.path, 0o600);+ }+ return `Made ${loose.map((file) => file.name).join(", ")} owner-only.`;+ },+ };+}diff --git a/server/doctor/checks/settings-file.test.ts b/server/doctor/checks/settings-file.test.tsnew file mode 100644index 0000000000..ad343fcc65--- /dev/null+++ b/server/doctor/checks/settings-file.test.ts@@ -0,0 +1,32 @@+import { writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { context, dataFolder } from "../../testing/doctor-folders.ts";+import { settingsFileCheck } from "./settings-file.ts";++describe("settings-file check", () => {+ it("finds a readable or missing config.json fine", () => {+ const data = dataFolder();+ expect(settingsFileCheck().check(context(data)).status).toBe("ok");+ writeFileSync(join(data, "config.json"), "{\"instances\":{}}");+ expect(settingsFileCheck().check(context(data)).status).toBe("ok");+ });++ it("points at the dated copies for one it cannot understand, never quoting it, never fixing it", () => {+ const data = dataFolder();+ writeFileSync(join(data, "config.json"), "{\"anthropic\":{\"key\":\"sk-ant-secret\"");+ writeFileSync(join(data, "config.json.bak.20261116-101010"), "{}");+ const finding = settingsFileCheck().check(context(data));+ expect(finding).toMatchObject({ status: "problem" });+ expect(finding.fixable).toBeFalsy();+ expect(finding.instruction).toContain("openmausbot config restore latest");+ expect(JSON.stringify(finding)).not.toContain("sk-ant-secret");+ });++ it("without dated copies, points at the copy from before the update", () => {+ const data = dataFolder();+ writeFileSync(join(data, "config.json"), "[]");+ expect(settingsFileCheck().check(context(data)).instruction).toContain("./update.sh --rollback");+ });+});diff --git a/server/doctor/checks/settings-file.ts b/server/doctor/checks/settings-file.tsnew file mode 100644index 0000000000..74bb11cfa0--- /dev/null+++ b/server/doctor/checks/settings-file.ts@@ -0,0 +1,32 @@+// config.json: a server that cannot read it starts on defaults, without its keys and connections. Putting back a dated+// copy is the settings' own command (config-backup.ts), which keeps the file it replaces; the doctor only says so.+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import type { DoctorCheck } from "../types.ts";++export function settingsFileCheck(): DoctorCheck {+ return {+ id: "settings-file",+ title: "Settings file",+ looksAt: "config.json",+ check(ctx) {+ const file = join(ctx.dataDir, "config.json");+ let text: string;+ try { text = readFileSync(file, "utf8"); } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { status: "ok", summary: "Not there yet." };+ return { status: "problem", summary: "config.json cannot be read by this user.", instruction: `Give the server's user the file back (chown <user> ${file}).` };+ }+ try {+ const parsed: unknown = JSON.parse(text.replace(/^/, ""));+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return { status: "ok", summary: "Reads." };+ } catch {}+ let copies = 0;+ try { copies = readdirSync(ctx.dataDir).filter((name) => /^config\.json\.bak\.\d{8}-\d{6}(?:-\d+)?$/.test(name)).length; } catch {}+ return { status: "problem", summary: "config.json cannot be understood, so the server runs on default settings, without its keys.",+ instruction: copies+ ? `Stop the server, then: openmausbot config backups, and openmausbot config restore latest (${copies} dated cop${copies === 1 ? "y" : "ies"} kept). The file it replaces is kept too.`+ : "Stop the server and put back config.json from a backup, or the data folder from the copy taken before the last update (./update.sh --rollback)." };+ },+ };+}diff --git a/server/doctor/checks/temp-files.test.ts b/server/doctor/checks/temp-files.test.tsnew file mode 100644index 0000000000..a602554660--- /dev/null+++ b/server/doctor/checks/temp-files.test.ts@@ -0,0 +1,31 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { backupFolder, context, dataFolder, manifest, NOW, UUID } from "../../testing/doctor-folders.ts";+import { runDoctor } from "../run.ts";+import { tempFilesCheck } from "./temp-files.ts";++describe("temp-files check", () => {+ it("moves the temp files of saves whose process is gone into the backup, and nothing else", () => {+ const data = dataFolder();+ const dead = `config.json.31337.${UUID}.tmp`, live = `routines.json.4242.${UUID}.tmp`, own = `sessions.json.${process.pid}.${UUID}.tmp`;+ for (const name of [dead, live, own, "notes.123.tmp", "bots.json"]) writeFileSync(join(data, name), name);+ mkdirSync(join(data, "bots"));+ writeFileSync(join(data, "bots", `work.31337.${UUID}.tmp`), "a person's file");+ const pidAlive = (pid: number) => pid === 4242;+ expect(tempFilesCheck().check(context(data, { pidAlive }))).toMatchObject({ status: "problem", fixable: true, summary: "1 temp file left by save that did not finish (config.json)." });++ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, pidAlive, checks: [tempFilesCheck()] });+ expect(report.checks[0]).toMatchObject({ status: "fixed", fixed: "Moved 1 into the backup." });+ expect(existsSync(join(data, dead))).toBe(false);+ expect(readFileSync(join(backupFolder(data)!, dead), "utf8")).toBe(dead);+ expect(manifest(backupFolder(data)!).entries).toHaveLength(1);+ for (const name of [live, own, "notes.123.tmp", "bots.json"]) expect(existsSync(join(data, name))).toBe(true);+ expect(existsSync(join(data, "bots", `work.31337.${UUID}.tmp`))).toBe(true);+ });++ it("is fine with none", () => {+ expect(tempFilesCheck().check(context(dataFolder())).status).toBe("ok");+ });+});diff --git a/server/doctor/checks/temp-files.ts b/server/doctor/checks/temp-files.tsnew file mode 100644index 0000000000..17757221fc--- /dev/null+++ b/server/doctor/checks/temp-files.ts@@ -0,0 +1,25 @@+// Temp files of saves that never finished (atomic.ts: a crash between the write and the rename). The file they were+// for is whole as it was before that save; the temp files are moved into the backup, never deleted. Only the data+// folder's own top level is looked at: bots' work folders hold the person's files.+import { leftoverTemps } from "../files.ts";+import type { DoctorCheck } from "../types.ts";++export function tempFilesCheck(): DoctorCheck {+ return {+ id: "temp-files",+ title: "Unfinished saves",+ looksAt: "<file>.<pid>.<id>.tmp in the data folder",+ check(ctx) {+ const temps = leftoverTemps(ctx);+ if (!temps.length) return { status: "ok", summary: "None." };+ const files = [...new Set(temps.map((temp) => temp.of))];+ return { status: "problem", fixable: true, detail: temps.map((temp) => temp.path),+ summary: `${temps.length} temp file${temps.length === 1 ? "" : "s"} left by save${temps.length === 1 ? "" : "s"} that did not finish (${files.slice(0, 5).join(", ")}${files.length > 5 ? ", …" : ""}).` };+ },+ fix(_ctx, finding, backup) {+ const paths = finding.detail as string[];+ for (const path of paths) backup.move("temp-files", path);+ return `Moved ${paths.length} into the backup.`;+ },+ };+}diff --git a/server/doctor/command.ts b/server/doctor/command.tsnew file mode 100644index 0000000000..d50fddbf37--- /dev/null+++ b/server/doctor/command.ts@@ -0,0 +1,34 @@+// `openmausbot doctor --data [--fix] [--data-dir DIR] [--json]`: the doctor on this computer's data folder, without the+// server. It reports; with --fix it applies the safe repairs, only while no server uses the folder.+import { join, resolve } from "node:path";++import { dataHome } from "../data-dir.ts";+import { serverVersion } from "../environment.ts";+import { EXIT, flag } from "../headless/args.ts";+import type { VerbContext, VerbOutcome } from "../headless/context.ts";+import { runDoctor } from "./run.ts";+import type { DoctorReport } from "./types.ts";++const MARK: Record<string, string> = { ok: "ok", fixed: "fixed", problem: "PROBLEM", failed: "FAILED" };++export function dataDoctorOutcome(report: DoctorReport): VerbOutcome {+ const { problems, fixed } = report.counts;+ const human = [+ `Data folder: ${report.dataDir} (checked by ${report.version})`,+ ...report.checks.flatMap((result) => [+ `${MARK[result.status]!.padEnd(8)}${result.title}: ${result.summary}`,+ ...(result.fixed ? [` done: ${result.fixed}`] : []),+ ...(result.status !== "ok" && result.status !== "fixed" && result.instruction ? [` what to do: ${result.instruction}`] : []),+ ...(result.status === "problem" && result.fixable && !report.fix.ran ? [" openmausbot doctor --data --fix repairs it"] : []),+ ]),+ ...(report.fix.asked && !report.fix.ran && report.fix.why ? [`No fixes ran: ${report.fix.why}`] : []),+ ...(report.backup ? [`What was changed was copied to ${report.backup} first.`] : []),+ problems ? `${problems} problem${problems === 1 ? "" : "s"} left${fixed ? `, ${fixed} fixed` : ""}.` : fixed ? `All fine now: ${fixed} fixed.` : "All fine.",+ ];+ return { result: { ok: problems === 0, ...report }, exitCode: problems ? EXIT.dataProblems : EXIT.done, human };+}++export async function dataDoctor(ctx: VerbContext): Promise<VerbOutcome> {+ const dataDir = resolve(flag(ctx.flags, "data-dir") ?? (ctx.env.OMB_DATA_DIR || join(dataHome(), ".openmausbot")));+ return dataDoctorOutcome(runDoctor({ dataDir, version: serverVersion(), mode: "command", fix: ctx.flags.fix === true }));+}diff --git a/server/doctor/doctor.e2e.test.ts b/server/doctor/doctor.e2e.test.tsnew file mode 100644index 0000000000..f731fb8602--- /dev/null+++ b/server/doctor/doctor.e2e.test.ts@@ -0,0 +1,146 @@+// Real server: a data folder damaged in every way the doctor repairs, then repaired by `openmausbot doctor --data --fix`+// or by the server's own first start of a new version, after which the server starts with its bots back.+import { spawn, spawnSync, type ChildProcess } from "node:child_process";+import { randomUUID } from "node:crypto";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { hostname, tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, expect, it } from "vitest";++import { verificationServerEnvironment } from "../../scripts/control-omb.ts";+import { removeTempDir, waitForExit } from "../testing/cleanup.ts";+import { freePortBlock } from "../testing/ports.ts";++const ROOT = fileURLToPath(new URL("../..", import.meta.url));+const FAKE_CLI = join(ROOT, "server/testing/fake-claude-cli.ts");+const UUID = "0b4d8f7a-3c2e-4f1a-9b6d-5e7c8a9f0d1e";+const WAL_BYTES = 70 * 1024 * 1024;++const homes: string[] = [];+const children: ChildProcess[] = [];++afterEach(async () => {+ for (const child of children.splice(0)) await waitForExit(child, { signal: "SIGTERM" });+ for (const home of homes.splice(0)) await removeTempDir(home);+});++function freshHome(): string {+ const home = mkdtempSync(join(tmpdir(), "omb-doctor-e2e-"));+ homes.push(home);+ mkdirSync(join(home, "tmp"), { recursive: true });+ writeFileSync(join(home, "config.json"), JSON.stringify({+ instances: { claude: { driver: "claudeAgent", displayName: "Verification fixture", config: { cli: FAKE_CLI } } },+ }));+ return home;+}++async function boot(home: string) {+ const port = await freePortBlock([0, 1]);+ const base = `http://127.0.0.1:${port}`;+ const child = spawn(process.execPath, ["--experimental-strip-types", join(ROOT, "server/index.ts")], {+ cwd: ROOT, env: verificationServerEnvironment(process.env, home, port), stdio: ["ignore", "pipe", "pipe"],+ });+ children.push(child);+ let output = "";+ child.stdout!.on("data", (chunk) => { output += chunk; });+ child.stderr!.on("data", (chunk) => { output += chunk; });+ await expect.poll(async () => {+ if (child.exitCode !== null) throw new Error(`server exited during boot:\n${output}`);+ try { return (await fetch(`${base}/api/health`)).ok; } catch { return false; }+ }, { timeout: 30_000, interval: 50 }).toBe(true);+ const get = async (path: string) => {+ const response = await fetch(base + path, { headers: { origin: base } });+ expect(response.status).toBe(200);+ return response.json() as Promise<any>;+ };+ return { get, output: () => output, stop: () => waitForExit(child, { signal: "SIGTERM" }) };+}++function doctor(home: string, ...args: string[]) {+ const done = spawnSync(process.execPath, ["--experimental-strip-types", join(ROOT, "server/openmausbot.ts"), "doctor", "--data", "--json", ...args], {+ cwd: ROOT, env: verificationServerEnvironment(process.env, home, 1), encoding: "utf8", timeout: 120_000,+ });+ return { code: done.status, report: JSON.parse(done.stdout) as { ok: boolean; checks: { id: string; status: string; fixable: boolean }[]; backup: string | null } };+}++const deadPid = () => spawnSync(process.execPath, ["-e", ""]).pid!;++/** Every kind of damage the doctor repairs. Returns the bots.json the server had. */+function damage(home: string): string {+ const bots = readFileSync(join(home, "bots.json"), "utf8");+ const dead = deadPid();+ // A save of bots.json cut short, its whole temp file still there.+ writeFileSync(join(home, "bots.json"), bots.slice(0, Math.floor(bots.length / 2)));+ writeFileSync(join(home, `bots.json.${dead}.${UUID}.tmp`), bots);+ // Another save that never finished.+ writeFileSync(join(home, `webhooks.json.${dead}.${randomUUID()}.tmp`), "{}");+ // A lease a killed server left.+ writeFileSync(join(home, "openmausbot-server.lease"), `${JSON.stringify({ version: 1, pid: dead, host: hostname(), token: randomUUID(), createdAt: Date.now() })}\n`, { mode: 0o600 });+ // A run record whose server.json was never written.+ mkdirSync(join(home, "engine-runs", "f".repeat(32)), { recursive: true });+ writeFileSync(join(home, "engine-runs", "f".repeat(32), "server.json"), "");+ // Folders gone.+ for (const name of ["events", "native"]) rmSync(join(home, name), { recursive: true, force: true });+ // A private file others can read.+ if (process.platform !== "win32") chmodSync(join(home, "config.json"), 0o644);+ // A write-ahead log no server folded back (a process killed while it held the database).+ const filler = spawnSync(process.execPath, ["-e", `+ const { DatabaseSync } = require("node:sqlite");+ const db = new DatabaseSync(process.argv[1]);+ db.exec("PRAGMA journal_mode = WAL; PRAGMA wal_autocheckpoint = 0; CREATE TABLE IF NOT EXISTS doctor_e2e (x TEXT)");+ const insert = db.prepare("INSERT INTO doctor_e2e VALUES (?)");+ for (let n = 0; n < ${Math.ceil(WAL_BYTES / 100_000)}; n += 1) insert.run("x".repeat(100000));+ process.kill(process.pid, "SIGKILL");+ `, join(home, "messages.db")]);+ expect(filler.status === 0 && filler.signal === null).toBe(false);+ expect(statSync(join(home, "messages.db-wal")).size).toBeGreaterThan(64 * 1024 * 1024);+ // The data as an older version left it, so the next start is a new version's first.+ writeFileSync(join(home, "doctor-state.json"), JSON.stringify({ version: "0.0.1", summary: { at: "", version: "0.0.1", checked: 0, fixed: [], problems: [] } }));+ return bots;+}++const FIXED = ["lease", "folders", "registry", "temp-files", "engine-runs", "messages-db", ...(process.platform === "win32" ? [] : ["secret-modes"])];++async function serverHasItsBots(home: string, bots: string) {+ const server = await boot(home);+ const listed = (await server.get("/api/bots?messages=0")).bots as { id: string }[];+ expect(listed.map((bot) => bot.id).sort()).toEqual((JSON.parse(bots) as { id: string }[]).map((bot) => bot.id).sort());+ return server;+}++it("openmausbot doctor --data finds each problem, --fix repairs them all, and the server starts with its bots", async () => {+ const home = freshHome();+ const first = await boot(home);+ await first.stop();+ const bots = damage(home);++ const looked = doctor(home);+ expect(looked.code).toBe(8);+ for (const id of FIXED) expect(looked.report.checks.find((check) => check.id === id), id).toMatchObject({ status: "problem", fixable: true });+ expect(looked.report.backup).toBeNull();++ const fixed = doctor(home, "--fix");+ expect(fixed.report.checks.filter((check) => check.status !== "ok" && check.status !== "fixed")).toEqual([]);+ expect(fixed.code).toBe(0);+ for (const id of FIXED) expect(fixed.report.checks.find((check) => check.id === id)!.status, id).toBe("fixed");+ expect(existsSync(join(fixed.report.backup!, "bots.json"))).toBe(true);+ expect(statSync(join(home, "messages.db-wal")).size).toBe(0);++ await serverHasItsBots(home, bots);+}, 180_000);++it("a new version's first start repairs the same damage itself and reports it in the health report", async () => {+ const home = freshHome();+ const first = await boot(home);+ await first.stop();+ const bots = damage(home);++ const server = await serverHasItsBots(home, bots);+ const health = await server.get("/api/health");+ // The server retires a dead lease itself as it takes the lease, before the doctor runs; ensureDirs() makes the folders.+ expect(health.doctor).toMatchObject({ thisStart: true, problems: [] });+ for (const id of FIXED.filter((id) => id !== "lease" && id !== "folders")) expect(health.doctor.fixed).toContain(id);+ expect(server.output()).toMatch(/\[doctor\] registry: bots\.json cannot be read.* Fixed: put back bots\.json/);+ expect(existsSync(join(home, `bots.json`))).toBe(true);+}, 180_000);diff --git a/server/doctor/files.ts b/server/doctor/files.tsnew file mode 100644index 0000000000..d1022dc4b3--- /dev/null+++ b/server/doctor/files.ts@@ -0,0 +1,48 @@+// What the checks share about files: the temp file an interrupted atomic write leaves (atomic.ts), and whether a+// registry file holds a list.+import { readdirSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";++import type { DoctorContext } from "./types.ts";++/** atomic.ts writeWhole's temp file, `<file>.<pid>.<uuid>.tmp`, exactly; nothing else is ever taken for one. */+const ATOMIC_TEMP = /^(.+)\.([1-9]\d{0,9})\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp$/;++export type LeftoverTemp = { name: string; path: string; of: string; pid: number; mtimeMs: number };++/** The temp files in `dir` (not below it) whose writer is no longer running: never this process's, never a live one's. */+export function leftoverTemps(ctx: DoctorContext, dir: string = ctx.dataDir): LeftoverTemp[] {+ let names: string[];+ try { names = readdirSync(dir); } catch { return []; }+ const found: LeftoverTemp[] = [];+ for (const name of names) {+ const match = ATOMIC_TEMP.exec(name);+ if (!match) continue;+ const pid = Number(match[2]);+ if (pid === process.pid || ctx.pidAlive(pid)) continue;+ const path = join(dir, name);+ try {+ const stat = statSync(path);+ if (stat.isFile()) found.push({ name, path, of: match[1]!, pid, mtimeMs: stat.mtimeMs });+ } catch {}+ }+ return found;+}++/** "missing", "ok" when the file parses as a JSON list, else "unreadable" (empty, cut short, not a list, not readable). */+export function registryState(path: string): "missing" | "ok" | "unreadable" {+ let text: string;+ try { text = readFileSync(path, "utf8"); } catch (error) {+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable";+ }+ try { return Array.isArray(JSON.parse(text)) ? "ok" : "unreadable"; } catch { return "unreadable"; }+}++export function pidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "EPERM";+ }+}diff --git a/server/doctor/run.ts b/server/doctor/run.tsnew file mode 100644index 0000000000..c7fbb16fb5--- /dev/null+++ b/server/doctor/run.ts@@ -0,0 +1,144 @@+// Runs the checks, and with `fix` the repairs that cannot lose data. Every check is looked at first; repairs run only+// when nothing blocks (a data format this version cannot read), and only in a process that holds the data folder's lease:+// the server as it starts, or `openmausbot doctor --data --fix`, which takes the lease for its run and changes nothing+// while a server uses the folder. Each repair looks again right before it runs, and once more after.+import { acquireDataDirLease, type DataDirLeaseHolder } from "../data-dir-lease.ts";+import { DoctorBackup } from "./backup.ts";+import { dataFormatCheck } from "./checks/data-format.ts";+import { engineRunsCheck } from "./checks/engine-runs.ts";+import { foldersCheck } from "./checks/folders.ts";+import { leaseCheck } from "./checks/lease.ts";+import { messagesDbCheck } from "./checks/messages-db.ts";+import { registryCheck } from "./checks/registry.ts";+import { secretModesCheck } from "./checks/secret-modes.ts";+import { settingsFileCheck } from "./checks/settings-file.ts";+import { tempFilesCheck } from "./checks/temp-files.ts";+import { pidAlive } from "./files.ts";+import type { CheckResult, DoctorCheck, DoctorContext, DoctorReport, Finding } from "./types.ts";++/** In this order: the registry looks at temp files before they are moved aside, since one may be its only whole copy. */+export function defaultChecks(): DoctorCheck[] {+ return [dataFormatCheck(), leaseCheck(), foldersCheck(), registryCheck(), tempFilesCheck(), engineRunsCheck(), messagesDbCheck(), secretModesCheck(), settingsFileCheck()];+}++export interface RunDoctorOptions {+ dataDir: string;+ version: string;+ mode: DoctorContext["mode"];+ fix: boolean;+ checks?: DoctorCheck[];+ now?: () => number;+ pidAlive?: (pid: number) => boolean;+ /** "command" mode only: takes the data folder's lease for the repairs. */+ acquireLease?: (dataDir: string) => { release(): unknown };+}++const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)).slice(0, 300);++function look(check: DoctorCheck, ctx: DoctorContext): Finding & { failed?: boolean } {+ try {+ return check.check(ctx);+ } catch (error) {+ return { status: "problem", failed: true, summary: `The check itself failed: ${errorText(error)}` };+ }+}++function resultOf(check: DoctorCheck, finding: Finding & { failed?: boolean }): CheckResult {+ return {+ id: check.id, title: check.title, looksAt: check.looksAt,+ status: finding.failed ? "failed" : finding.status,+ summary: finding.summary,+ // The lease is repaired by taking it, which the runner does itself before any fix.+ fixable: Boolean(finding.fixable && (check.fix || check.id === "lease")),+ blocking: Boolean(finding.blocking),+ ...(finding.instruction ? { instruction: finding.instruction } : {}),+ };+}++const wantsFix = (check: DoctorCheck, finding: Finding) => Boolean(check.fix && finding.status === "problem" && (finding.fixable || finding.keepCopy));++export function runDoctor(options: RunDoctorOptions): DoctorReport {+ const now = options.now ?? Date.now;+ const ctx: DoctorContext = { dataDir: options.dataDir, version: options.version, mode: options.mode, now, pidAlive: options.pidAlive ?? pidAlive };+ const checks = options.checks ?? defaultChecks();+ const findings = checks.map((check) => look(check, ctx));+ const results = checks.map((check, at) => resultOf(check, findings[at]!));+ const backup = new DoctorBackup(options.dataDir, now);+ const fix: DoctorReport["fix"] = { asked: options.fix, ran: false };++ if (options.fix) {+ let release: (() => void) | null = null;+ const blocked = results.find((result) => result.blocking);+ const leaseAt = checks.findIndex((check) => check.id === "lease");+ const holder = leaseAt >= 0 ? findings[leaseAt]!.detail as DataDirLeaseHolder | undefined : undefined;+ const foldersAt = checks.findIndex((check) => check.id === "folders");+ const noFolder = foldersAt >= 0 && findings[foldersAt]!.status === "problem" && !findings[foldersAt]!.fixable;+ if (blocked) fix.why = `${blocked.title}: ${blocked.summary} Nothing was changed.`;+ else if (noFolder) fix.why = `${results[foldersAt]!.summary} Nothing was changed.`;+ else if (options.mode === "command") {+ if (holder?.state === "alive") fix.why = `A server is using the data folder (process ${holder.pid}). Stop it, then run this again. Nothing was changed.`;+ else if (holder?.state === "other-machine" || holder?.state === "invalid") fix.why = `${results[leaseAt]!.summary} Nothing was changed.`;+ else {+ try {+ if (holder?.state === "dead") backup.copy("lease", holder.path, "the lease a dead process left, before it was retired");+ const lease = (options.acquireLease ?? acquireDataDirLease)(options.dataDir);+ release = () => { lease.release(); };+ if (holder?.state === "dead") Object.assign(results[leaseAt]!, { status: "fixed", fixed: `Retired the lease process ${holder.pid} left.` });+ } catch (error) {+ fix.why = `The data folder's lease could not be taken (${errorText(error)}). Nothing was changed.`;+ }+ }+ }+ if (!fix.why) {+ fix.ran = true;+ try {+ checks.forEach((check, at) => {+ if (check.id === "lease" || !wantsFix(check, findings[at]!)) return;+ const fresh = look(check, ctx);+ if (!wantsFix(check, fresh)) {+ results[at] = resultOf(check, fresh);+ return;+ }+ let did: string;+ try {+ did = check.fix!(ctx, fresh, backup);+ } catch (error) {+ results[at] = { ...resultOf(check, fresh), status: "failed", summary: `${fresh.summary} The fix failed: ${errorText(error)}` };+ return;+ }+ const after = look(check, ctx);+ results[at] = after.status === "ok"+ ? { ...resultOf(check, fresh), status: "fixed", fixable: false, fixed: did }+ : { ...resultOf(check, after), fixed: did };+ });+ } finally {+ try { release?.(); } catch {}+ }+ }+ }++ const problems = results.filter((result) => result.status === "problem" || result.status === "failed").length;+ return {+ dataDir: options.dataDir,+ version: options.version,+ at: new Date(now()).toISOString(),+ fix,+ checks: results,+ backup: backup.path,+ counts: {+ checked: results.length,+ problems,+ fixed: results.filter((result) => result.fixed !== undefined).length,+ blocking: results.filter((result) => result.blocking).length,+ },+ };+}++/** One line per check that is not simply ok, for a log. */+export function reportLines(report: DoctorReport): string[] {+ const lines = report.checks.filter((result) => result.status !== "ok").map((result) => result.status === "fixed"+ ? `${result.id}: ${result.summary} Fixed: ${result.fixed}`+ : `${result.id}: ${result.summary}${result.fixed ? ` (${result.fixed})` : ""}${result.instruction ? ` ${result.instruction}` : ""}`);+ if (report.fix.asked && !report.fix.ran && report.fix.why) lines.push(`no fixes ran: ${report.fix.why}`);+ return lines;+}diff --git a/server/doctor/start.test.ts b/server/doctor/start.test.tsnew file mode 100644index 0000000000..187fd8b1a6--- /dev/null+++ b/server/doctor/start.test.ts@@ -0,0 +1,82 @@+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { dataFolder, NOW, UUID } from "../testing/doctor-folders.ts";+import { dataDoctorOutcome } from "./command.ts";+import { runDoctor } from "./run.ts";+import { DOCTOR_STATE_FILE, doctorAtStart, doctorSummary } from "./start.ts";+import type { DoctorCheck } from "./types.ts";++const stray = (data: string) => {+ // A server's folder as ensureDirs() leaves it, so the only finding is the temp file.+ for (const name of ["events", "native"]) mkdirSync(join(data, name), { recursive: true });+ const name = `config.json.31337.${UUID}.tmp`;+ writeFileSync(join(data, name), "{}");+ return join(data, name);+};++describe("the doctor at start", () => {+ it("runs on the first start of a version, fixes, logs a line each, records the version, and keeps a summary", () => {+ const data = dataFolder();+ const temp = stray(data);+ const lines: string[] = [];+ const summary = doctorAtStart(data, "1.2.3", { now: () => NOW, pidAlive: () => false, log: (line) => lines.push(line) });+ expect(existsSync(temp)).toBe(false);+ expect(summary).toMatchObject({ version: "1.2.3", fixed: ["temp-files"], problems: [], thisStart: true });+ expect(doctorSummary()).toEqual(summary);+ expect(lines).toHaveLength(2);+ expect(lines[0]).toMatch(/^\[doctor\] temp-files: 1 temp file .* Fixed: Moved 1 into the backup\.$/);+ expect(lines.at(-1)).toMatch(/^\[doctor\] first start of 1\.2\.3: 9 checks, 1 fixed, 0 need a person; what was changed was copied to .*doctor-backups/);+ expect(JSON.parse(readFileSync(join(data, DOCTOR_STATE_FILE), "utf8"))).toMatchObject({ version: "1.2.3" });+ // The summary names checks and counts, never a path.+ expect(JSON.stringify(summary)).not.toContain(data);+ });++ it("does not run again for the same version, and runs for the next one", () => {+ const data = dataFolder();+ doctorAtStart(data, "1.2.3", { now: () => NOW, pidAlive: () => false, log: () => {} });+ const temp = stray(data);+ const lines: string[] = [];+ expect(doctorAtStart(data, "1.2.3", { now: () => NOW, pidAlive: () => false, log: (line) => lines.push(line) })).toMatchObject({ thisStart: false, version: "1.2.3" });+ expect(lines).toEqual([]);+ expect(existsSync(temp)).toBe(true);+ doctorAtStart(data, "1.2.4", { now: () => NOW, pidAlive: () => false, log: (line) => lines.push(line) });+ expect(existsSync(temp)).toBe(false);+ expect(lines.at(-1)).toContain("first start of 1.2.4 (last: 1.2.3)");+ });++ it("never throws: a check that fails is a finding, and the server goes on", () => {+ const data = dataFolder();+ const broken: DoctorCheck = { id: "broken", title: "Broken", looksAt: "nothing", check() { throw new Error("boom"); } };+ const lines: string[] = [];+ const summary = doctorAtStart(data, "1.0.0", { checks: [broken], now: () => NOW, log: (line) => lines.push(line) });+ expect(summary).toMatchObject({ problems: ["broken"] });+ expect(lines[0]).toBe("[doctor] broken: The check itself failed: boom");+ });+});++describe("openmausbot doctor --data", () => {+ it("reports without changing anything, and says --fix repairs it; exit 8 while a problem is left", () => {+ const data = dataFolder();+ const temp = stray(data);+ const outcome = dataDoctorOutcome(runDoctor({ dataDir: data, version: "1.0.0", mode: "command", fix: false, now: () => NOW, pidAlive: () => false }));+ expect(outcome.exitCode).toBe(8);+ expect(existsSync(temp)).toBe(true);+ expect(outcome.human).toContain(" openmausbot doctor --data --fix repairs it");+ expect(outcome.result).toMatchObject({ ok: false, counts: { problems: expect.any(Number), fixed: 0 } });+ });++ it("with --fix takes the lease for its run, repairs, and exits 0 when all is fine", () => {+ const data = dataFolder();+ const temp = stray(data);+ const report = runDoctor({ dataDir: data, version: "1.0.0", mode: "command", fix: true, now: () => NOW, pidAlive: () => false });+ const outcome = dataDoctorOutcome(report);+ expect(report.checks.filter((result) => result.status !== "ok" && result.status !== "fixed")).toEqual([]);+ expect(outcome.exitCode).toBe(0);+ expect(outcome.human.at(-1)).toMatch(/^All fine now: \d+ fixed\.$/);+ expect(existsSync(temp)).toBe(false);+ // The lease was let go.+ expect(existsSync(join(data, "openmausbot-server.lease"))).toBe(false);+ });+});diff --git a/server/doctor/start.ts b/server/doctor/start.tsnew file mode 100644index 0000000000..b6c82177e3--- /dev/null+++ b/server/doctor/start.ts@@ -0,0 +1,78 @@+// The doctor as a server starts: on the first start of a version (the version that last started is kept in+// doctor-state.json), after the folder's lease is this server's and before anything loads the registries or the+// messages. It applies the safe fixes, logs a line for each finding, and keeps a short summary for /api/health. It+// never stops the server: the one thing that would make starting damage data, a newer data format, has already+// stopped it (data-format.ts), and anything that throws here is logged and passed over.+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { writeFileAtomic } from "../atomic.ts";+import { reportLines, runDoctor, type RunDoctorOptions } from "./run.ts";+import type { DoctorReport } from "./types.ts";++export const DOCTOR_STATE_FILE = "doctor-state.json";++/** For the health report: counts and check names, never a path or a file's contents. */+export type DoctorSummary = {+ /** When the doctor last ran on this folder, and for which version. */+ at: string;+ version: string;+ checked: number;+ fixed: string[];+ problems: string[];+ /** Whether it ran as this server started (false: it ran at an earlier start of this version). */+ thisStart: boolean;+};++type DoctorState = { version: string; summary: Omit<DoctorSummary, "thisStart"> };++let current: DoctorSummary | null = null;++export function doctorSummary(): DoctorSummary | null {+ return current;+}++function readState(dataDir: string): DoctorState | null {+ try {+ const state = JSON.parse(readFileSync(join(dataDir, DOCTOR_STATE_FILE), "utf8")) as Partial<DoctorState>;+ return typeof state?.version === "string" && state.summary && typeof state.summary === "object" ? state as DoctorState : null;+ } catch {+ return null;+ }+}++export function summaryOf(report: DoctorReport): Omit<DoctorSummary, "thisStart"> {+ return {+ at: report.at,+ version: report.version,+ checked: report.counts.checked,+ fixed: report.checks.filter((result) => result.fixed !== undefined).map((result) => result.id),+ problems: report.checks.filter((result) => result.status === "problem" || result.status === "failed").map((result) => result.id),+ };+}++export function doctorAtStart(dataDir: string, version: string, options: Partial<RunDoctorOptions> & { log?: (line: string) => void } = {}): DoctorSummary | null {+ const log = options.log ?? ((line: string) => console.log(line));+ try {+ const state = readState(dataDir);+ if (state && state.version === version) {+ current = { ...state.summary, thisStart: false };+ return current;+ }+ const report = runDoctor({ ...options, dataDir, version, mode: "start", fix: true });+ const lines = reportLines(report);+ for (const line of lines) log(`[doctor] ${line}`);+ log(`[doctor] ${state ? `first start of ${version} (last: ${state.version})` : `first start of ${version}`}: ${report.counts.checked} checks, ${report.counts.fixed} fixed, ${report.counts.problems} need a person${report.backup ? `; what was changed was copied to ${report.backup} first` : ""}.`);+ const summary = summaryOf(report);+ current = { ...summary, thisStart: true };+ try {+ writeFileAtomic(join(dataDir, DOCTOR_STATE_FILE), `${JSON.stringify({ version, summary } satisfies DoctorState, null, 2)}\n`, { mode: 0o600 });+ } catch (error) {+ log(`[doctor] could not record this version in ${DOCTOR_STATE_FILE} (${error instanceof Error ? error.message : String(error)}); it runs again at the next start.`);+ }+ return current;+ } catch (error) {+ log(`[doctor] did not run: ${error instanceof Error ? error.message : String(error)}`);+ return null;+ }+}diff --git a/server/doctor/types.ts b/server/doctor/types.tsnew file mode 100644index 0000000000..31a43a76ea--- /dev/null+++ b/server/doctor/types.ts@@ -0,0 +1,66 @@+// The doctor's parts: a check looks at one thing in a server's data folder and says ok or what is wrong; a check whose+// problem has a repair that cannot lose data also has `fix`, which the runner calls only after the data is this+// process's (it holds the folder's lease) and after the backup has taken a copy of what the repair changes.+import type { DoctorBackup } from "./backup.ts";++export interface DoctorContext {+ dataDir: string;+ /** The version running the checks. */+ version: string;+ /** "start": the server's own run as it starts, holding the lease; "command": `openmausbot doctor --data`. */+ mode: "start" | "command";+ now(): number;+ /** Whether a process with this pid runs on this machine (EPERM counts as running). */+ pidAlive(pid: number): boolean;+}++export type Finding = {+ status: "ok" | "problem";+ /** One plain sentence: what was found. Never a secret, never a file's contents. */+ summary: string;+ /** `fix` can repair this, or the part of it that is safe to, without losing anything. */+ fixable?: boolean;+ /** Not repairable, but `fix` still runs to keep a copy of what is damaged where nothing will overwrite it. */+ keepCopy?: boolean;+ /** A problem that makes starting unsafe; no fix of any check runs while one is found. */+ blocking?: boolean;+ /** What a person does about a problem the doctor does not fix. */+ instruction?: string;+ /** What `fix` needs, from the same look. */+ detail?: unknown;+};++export interface DoctorCheck {+ id: string;+ title: string;+ /** What it reads, in a few words. */+ looksAt: string;+ check(ctx: DoctorContext): Finding;+ /** Repairs the problem `finding` describes; copies what it changes into `backup` first. Returns what it did. */+ fix?(ctx: DoctorContext, finding: Finding, backup: DoctorBackup): string;+}++export type CheckResult = {+ id: string;+ title: string;+ looksAt: string;+ status: "ok" | "problem" | "fixed" | "failed";+ summary: string;+ fixable: boolean;+ blocking: boolean;+ instruction?: string;+ /** What the fix did, when it ran. */+ fixed?: string;+};++export type DoctorReport = {+ dataDir: string;+ version: string;+ at: string;+ /** Whether fixes were asked for, and whether they could run. */+ fix: { asked: boolean; ran: boolean; why?: string };+ checks: CheckResult[];+ /** The folder this run copied things into before changing them, when it changed anything. */+ backup: string | null;+ counts: { checked: number; problems: number; fixed: number; blocking: number };+};diff --git a/server/headless/args.ts b/server/headless/args.tsindex a8dd82c776..c698926ee7 100644--- a/server/headless/args.ts+++ b/server/headless/args.ts@@ -11,6 +11,8 @@ export const EXIT = {changes: 6,/** `doctor --host`: this machine is missing something the server needs. */hostMissing: 7,+ /** `doctor --data`: the data folder has a problem left (after --fix, one it could not repair). */+ dataProblems: 8,interrupted: 130,} as const;@@ -56,7 +58,7 @@ const WAITING = {} satisfies ParseArgsOptionsConfig;const VERBS: Record<string, { options: ParseArgsOptionsConfig; positionals: number }> = {- doctor: { options: { wait: { type: "string" }, host: { type: "boolean" }, "data-dir": { type: "string" }, domain: { type: "string" } }, positionals: 0 },+ doctor: { options: { wait: { type: "string" }, host: { type: "boolean" }, data: { type: "boolean" }, fix: { type: "boolean" }, "data-dir": { type: "string" }, domain: { type: "string" } }, positionals: 0 },bots: { options: {}, positionals: 0 },channels: { options: {}, positionals: 0 },models: { options: {}, positionals: 0 },diff --git a/server/headless/commands.ts b/server/headless/commands.tsindex f02038595a..db9137dcf7 100644--- a/server/headless/commands.ts+++ b/server/headless/commands.ts@@ -73,9 +73,14 @@ async function doctorOnce(ctx: VerbContext): Promise<VerbOutcome> {export async function doctor(ctx: VerbContext): Promise<VerbOutcome> {if (ctx.flags.host === true) {if (flag(ctx.flags, "wait") !== undefined || flag(ctx.flags, "url") !== undefined) throw usageError("doctor --host checks this machine: drop --wait and --url");+ if (ctx.flags.data === true || ctx.flags.fix === true) throw usageError("doctor --host and doctor --data are two runs");return (await import("./host-doctor.ts")).hostDoctor(ctx);}- if (flag(ctx.flags, "data-dir") !== undefined || flag(ctx.flags, "domain") !== undefined) throw usageError("--data-dir and --domain go with doctor --host");+ if (ctx.flags.data === true || ctx.flags.fix === true) {+ if (["wait", "url", "port", "token-file", "domain"].some((name) => flag(ctx.flags, name) !== undefined)) throw usageError("doctor --data checks this computer's data folder: drop --wait, --url, --port, --token-file and --domain");+ return (await import("../doctor/command.ts")).dataDoctor(ctx);+ }+ if (flag(ctx.flags, "data-dir") !== undefined || flag(ctx.flags, "domain") !== undefined) throw usageError("--data-dir goes with doctor --host or doctor --data, --domain with doctor --host");const raw = flag(ctx.flags, "wait");const deadline = Date.now() + (raw ? parseDuration(raw, "--wait") : 0);for (;;) {diff --git a/server/headless/doctor.test.ts b/server/headless/doctor.test.tsindex 642562b74a..364b3c0f4d 100644--- a/server/headless/doctor.test.ts+++ b/server/headless/doctor.test.ts@@ -52,3 +52,42 @@ describe("doctor on a shared server, without a session", () => {expect(code).not.toBe(0);});});++describe("doctor --data", () => {+ async function local(argv: string[], dataDir?: string) {+ const out: string[] = [], err: string[] = [];+ const io: HeadlessIo = { out: (text) => out.push(text), err: (text) => err.push(text), readStdin: async () => "" };+ const callTool = vi.fn(async () => { throw new Error("doctor --data must not reach a server"); });+ const code = await runHeadless(argv, { env: dataDir ? { OMB_DATA_DIR: dataDir } : {}, io, callTool: callTool as any });+ return { code, out, err, callTool };+ }++ it("checks this computer's data folder without a server, and --fix alone means --data", async () => {+ const { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } = await import("node:fs");+ const { tmpdir } = await import("node:os");+ const { join } = await import("node:path");+ const data = mkdtempSync(join(tmpdir(), "omb-doctor-cli-"));+ try {+ for (const name of ["events", "native"]) mkdirSync(join(data, name));+ const stray = join(data, "config.json.999999.0b4d8f7a-3c2e-4f1a-9b6d-5e7c8a9f0d1e.tmp");+ writeFileSync(stray, "{}");+ const looked = await local(["doctor", "--data", "--json"], data);+ expect(looked.code).toBe(8);+ expect(JSON.parse(looked.out.at(-1)!)).toMatchObject({ ok: false, dataDir: data, fix: { asked: false } });+ expect(existsSync(stray)).toBe(true);+ const fixed = await local(["doctor", "--fix", "--data-dir", data]);+ expect(fixed.code).toBe(0);+ expect(fixed.out.at(-1)).toBe("All fine now: 1 fixed.");+ expect(existsSync(stray)).toBe(false);+ expect(looked.callTool).not.toHaveBeenCalled();+ } finally {+ rmSync(data, { recursive: true, force: true });+ }+ });++ it("refuses options that are about a server, and mixing it with --host", async () => {+ expect((await local(["doctor", "--data", "--url", "http://127.0.0.1:1"])).code).toBe(2);+ expect((await local(["doctor", "--fix", "--wait", "1m"])).code).toBe(2);+ expect((await local(["doctor", "--host", "--data"])).code).toBe(2);+ });+});diff --git a/server/headless/main.ts b/server/headless/main.tsindex 30ccbb72df..44a16988e6 100644--- a/server/headless/main.ts+++ b/server/headless/main.ts@@ -22,7 +22,13 @@ export const VERB_HELP: Record<string, string> = {openmausbot doctor --host [--data-dir DIR] [--port 8799] [--domain HOST]Check this Linux machine can run the server and the bots' sandbox: the system, Docker or Podman, usernamespaces, seccomp, cgroup v2, free disk, size, ports and the clock. Each problem says its fix.- Exit 0 ready (warnings allowed), 7 something is missing. On macOS and Windows it says it is for Linux.`,+ Exit 0 ready (warnings allowed), 7 something is missing. On macOS and Windows it says it is for Linux.+openmausbot doctor --data [--fix] [--data-dir DIR]+ Check this computer's data folder without the server: the data format, the folder's lease, folders, bots.json and+ groups.json, saves that did not finish, engine-run records, messages.db, private files' modes and config.json.+ --fix applies the repairs that cannot lose data, only while no server uses the folder; whatever a repair changes is+ copied to DIR/doctor-backups/<time>/ first. Anything else is reported with what to do.+ Exit 0 fine (after --fix: fine now), 8 a problem is left.`,bots: "openmausbot bots\n Your bots and what each is doing.",channels: "openmausbot channels\n Your rooms (group chats) and who is in them.",models: "openmausbot models\n The engines and the models each offers (use them as INSTANCE/MODEL).",diff --git a/server/index.ts b/server/index.tsindex d0fa5c8057..bdde3fad8f 100644--- a/server/index.ts+++ b/server/index.ts@@ -521,7 +521,7 @@ import {import { createGracefulShutdown } from "./graceful-shutdown.ts";import { acquireDataDirLeaseForProcess, releaseOnceAtExit } from "./data-dir-lease.ts"; import { markEngineRunClean, startEngineRecords } from "./engine-records.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 { dataFormatAtStart } from "./data-format.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 { applyPendingWorkspaceRestore, readLastWorkspaceRestore, type WorkspaceRestoreResult } from "./workspace-backup.ts";@@ -669,7 +669,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());+} dataFormatAtStart("stamp", DATA_DIR, serverVersion()); doctorAtStart(DATA_DIR, serverVersion()); // the first start of a version: safe repairs, before anything reads the dataconst 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);diff --git a/server/routes/status.ts b/server/routes/status.tsindex 2244609517..ce42b345b3 100644--- a/server/routes/status.ts+++ b/server/routes/status.ts@@ -4,6 +4,7 @@ import { loadBrand } from "../brand.ts";import { browserEngineStatus, ensureChrome, installAgentBrowserBinary, resolveAgentBrowserBinary } from "../browser-engine.ts";import { DATA_DIR, EVENTS_DIR, NATIVE_DIR, instanceConfigs, type AppConfig } from "../config.ts";import { boundRetentionDays, decisionsCsv, readDecisionRange, readDecisions, type DecisionRow } from "../decision-log.ts";+import { doctorSummary } from "../doctor/start.ts";import { flushNativeLog } from "../drivers/native.ts";import { editionForMembers, editionStatus, entitled } from "../enterprise.ts";import { reportableServerVersion } from "../environment.ts";@@ -52,10 +53,12 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {const decision = deps.records?.decisionRow(auth) ?? ((row: DecisionRow) => row);// The packaged app's port fallback: the forked child proves it is ours by echoing its pid.if (method === "GET" && path === "/api/health") {+ // The data checks of this version's first start (server/doctor/start.ts): counts and check names only.+ const doctor = doctorSummary();return json(res, 200, { app: "openmausbot", ...(version ? { version } : {}), pid: process.pid, static: Boolean(STATIC_DIR), capabilities: {guardedMessages: 1, guardedRequests: 1, guardedFullAccess: 1, guardedOnBehalfOf: 1,...(sharedWorkspaceFullAccessEnabled() ? { sharedWorkspaceFullAccess: 1 } : {}),- }, ...(deps.boxOn ? { box: deps.boxOn() ? "on" : "off" } : {}) });+ }, ...(deps.boxOn ? { box: deps.boxOn() ? "on" : "off" } : {}), ...(doctor ? { doctor } : {}) });}// JSON-only, so a form posted from another local page cannot start the install. One install at a time.if (method === "POST" && path === "/api/browser-engine/install") {diff --git a/server/testing/doctor-folders.ts b/server/testing/doctor-folders.tsnew file mode 100644index 0000000000..667d12c228--- /dev/null+++ b/server/testing/doctor-folders.ts@@ -0,0 +1,46 @@+// For the doctor's tests: a fresh data folder each, removed after the test, and a context with a fixed clock.+import { spawnSync } from "node:child_process";+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach } from "vitest";++import { DOCTOR_BACKUPS_DIR } from "../doctor/backup.ts";+import type { DoctorContext } from "../doctor/types.ts";++export const NOW = Date.UTC(2026, 10, 17, 9, 30, 0);+/** A uuid in the shape atomic.ts puts in a temp file's name. */+export const UUID = "0b4d8f7a-3c2e-4f1a-9b6d-5e7c8a9f0d1e";++const folders: string[] = [];+afterEach(() => {+ for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true });+});++export function dataFolder(): string {+ const folder = mkdtempSync(join(tmpdir(), "omb-doctor-"));+ folders.push(folder);+ return folder;+}++export function context(dataDir: string, more: Partial<DoctorContext> = {}): DoctorContext {+ return { dataDir, version: "9.9.9", mode: "command", now: () => NOW, pidAlive: () => false, ...more };+}++/** The pid of a process that has ended. */+export function deadPid(): number {+ const done = spawnSync(process.execPath, ["-e", ""]);+ return done.pid!;+}++/** The single backup folder a run made, or null. */+export function backupFolder(dataDir: string): string | null {+ let names: string[];+ try { names = readdirSync(join(dataDir, DOCTOR_BACKUPS_DIR)); } catch { return null; }+ if (names.length !== 1) throw new Error(`expected one backup folder, found ${names.length}`);+ return join(dataDir, DOCTOR_BACKUPS_DIR, names[0]!);+}++export function manifest(folder: string): { entries: { check: string; action: string; path: string; savedAs?: string; mode?: string }[] } {+ return JSON.parse(readFileSync(join(folder, "manifest.json"), "utf8"));+}diff --git a/server/workspace-backup.ts b/server/workspace-backup.tsindex 2884a41d92..62b1ab49d6 100644--- a/server/workspace-backup.ts+++ b/server/workspace-backup.ts@@ -54,6 +54,9 @@ const EXCLUDED = new Set([// 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",+ // The doctor's copies of what it repaired, and the version it last ran for (doctor/backup.ts, doctor/start.ts): this+ // folder's own history, and copies of files a backup already holds.+ "doctor-backups", "doctor-state.json",]);const EXCLUSION_NOTES = ["Device pairing, server identity, live leases and runtime files (existing destination identities are preserved).",