Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Doctor: an unopenable file is not checked, not damaged; registry repair never leaves bots.json absent
milind-soni60bead28e8e6
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 4755d21100..f6125ead46 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -1846,25 +1846,29 @@ 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.+fine (after `--fix`, fine now) and 8 when a problem is left. `--fix` changes+nothing when it runs as a user other than the data folder's owner (Linux and+macOS).| 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. |+| Bots and rooms | `bots.json`, `groups.json` | A damaged file (not a whole list) 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. A file this user cannot read at all is reported as not checked and left alone. || 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` | SQLite's `quick_check`. A write-ahead log over 64 MB is folded back into the database. A damaged database is reported, never rewritten. |+| Messages database | `messages.db` | SQLite's `quick_check`. A write-ahead log over 64 MB is folded back into the database. A damaged database is reported, never rewritten. One that cannot be opened (permissions, another program's lock) is reported as not checked, not as damaged. || 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). The ten newest runs' copies are kept. They-stay on that computer and are not part of a workspace backup.+(for a file mode, the old mode). The ten newest runs' copies are kept, and the+older ones together stay under 2 GB; a run that kept a copy of `bots.json` or+`groups.json` is kept for at least 30 days either way. They stay on that+computer and are not part of a workspace backup.As a server starts, the doctor reads `messages.db` through and copies it before-a checkpoint only up to 256 MB, so an update never waits on a large database;+a checkpoint only while it and its write-ahead log come to 256 MB or less, so an update never waits on a large database;`openmausbot doctor --data` does both at any size.diff --git a/server/doctor/backup.ts b/server/doctor/backup.tsindex b67cdebd2c..271e98bbea 100644--- a/server/doctor/backup.ts+++ b/server/doctor/backup.ts@@ -1,12 +1,19 @@// <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, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";+import { chmodSync, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";import { dirname, join, relative, sep } from "node:path";export const DOCTOR_BACKUPS_DIR = "doctor-backups";/** The newest runs' copies kept; an older run's go when a new run copies something. */export const DOCTOR_BACKUPS_KEPT = 10;+/** A run that kept a copy of bots.json or groups.json is kept this long whatever else: it may be the only one left. */+export const DOCTOR_BACKUPS_REGISTRY_DAYS = 30;+/** The older runs together stay under this; the oldest go first. A run kept for its registry copy stays even past it+ * (those copies are small; a large run is a messages.db copy, which is not held). */+export const DOCTOR_BACKUPS_MAX_BYTES = 2 * 1024 * 1024 * 1024;++export type BackupLimits = { kept?: number; registryDays?: number; maxBytes?: number };export type BackupEntry = { check: string; action: string; path: string; savedAs?: string; mode?: string };@@ -16,10 +23,12 @@ export class DoctorBackup {private readonly dataDir: string;private readonly now: () => number;+ private readonly limits: BackupLimits;- constructor(dataDir: string, now: () => number) {+ constructor(dataDir: string, now: () => number, limits: BackupLimits = {}) {this.dataDir = dataDir;this.now = now;+ this.limits = limits;}/** The run's folder, once anything was put in it. */@@ -39,14 +48,30 @@ export class DoctorBackup {const folder = join(root, name);mkdirSync(folder, { mode: 0o700 });this.folder = folder;- // The names sort by time.- const runs = readdirSync(root).filter((entry) => /^\d{4}-\d{2}-\d{2}T/.test(entry)).sort();- for (const old of runs.slice(0, Math.max(0, runs.length - DOCTOR_BACKUPS_KEPT))) {- try { rmSync(join(root, old), { recursive: true, force: true }); } catch {}- }+ try { this.prune(root, name); } catch {}return folder;}+ /** Beyond the newest runs, and while the older runs together are over the size cap, the oldest go; never one that+ * kept a registry copy in the last 30 days. */+ private prune(root: string, current: string): void {+ const kept = this.limits.kept ?? DOCTOR_BACKUPS_KEPT, maxBytes = this.limits.maxBytes ?? DOCTOR_BACKUPS_MAX_BYTES;+ const holdSince = this.now() - (this.limits.registryDays ?? DOCTOR_BACKUPS_REGISTRY_DAYS) * 86_400_000;+ // The names sort by time.+ const runs = readdirSync(root).filter((entry) => entry !== current && /^\d{4}-\d{2}-\d{2}T/.test(entry)).sort();+ const held = (run: string) => (runTime(run) ?? Infinity) >= holdSince && holdsRegistry(join(root, run));+ const sizes = new Map(runs.map((run) => [run, bytesIn(join(root, run))]));+ let total = [...sizes.values()].reduce((sum, bytes) => sum + bytes, 0);+ runs.forEach((run, at) => {+ const beyond = runs.length - at > kept - 1;+ if ((!beyond && total <= maxBytes) || held(run)) return;+ try {+ rmSync(join(root, run), { recursive: true, force: true });+ total -= sizes.get(run)!;+ } catch {}+ });+ }+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;@@ -88,6 +113,34 @@ export class DoctorBackup {}}+/** When a run's folder was made, from its name (`2026-11-17T09-30-00Z`, maybe with `-2`). */+function runTime(run: string): number | null {+ const match = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})Z/.exec(run);+ if (!match) return null;+ const at = Date.parse(`${match[1]}T${match[2]}:${match[3]}:${match[4]}Z`);+ return Number.isNaN(at) ? null : at;+}++/** The run kept a copy of bots.json or groups.json; one whose manifest cannot be read is taken to have. */+function holdsRegistry(folder: string): boolean {+ try {+ const { entries } = JSON.parse(readFileSync(join(folder, "manifest.json"), "utf8")) as { entries?: BackupEntry[] };+ return !Array.isArray(entries) || entries.some((entry) => entry.check === "registry");+ } catch {+ return true;+ }+}++function bytesIn(path: string): number {+ try {+ const stat = lstatSync(path);+ if (!stat.isDirectory()) return stat.size;+ return readdirSync(path).reduce((sum, name) => sum + bytesIn(join(path, name)), 0);+ } catch {+ return 0;+ }+}+function tighten(path: string, mode: number): void {if (process.platform === "win32") return;try { chmodSync(path, mode); } catch {}diff --git a/server/doctor/checks/messages-db.test.ts b/server/doctor/checks/messages-db.test.tsindex 872f0632cd..eab5e0e19f 100644--- a/server/doctor/checks/messages-db.test.ts+++ b/server/doctor/checks/messages-db.test.ts@@ -1,4 +1,4 @@-import { existsSync, statSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { describe, expect, it } from "vitest";@@ -72,4 +72,104 @@ describe("messages-db check", () => {expect(check.check(context(data, { mode: "command" })).status).toBe("problem");expect(existsSync(join(data, "messages.db-wal"))).toBe(false);});++ it("reports what SQLite's own check finds damaged inside a database it can open", () => {+ const data = dataFolder();+ const db = new DatabaseSync(join(data, "messages.db"));+ db.exec("CREATE TABLE messages (id TEXT, text TEXT); CREATE INDEX by_text ON messages (text)");+ const insert = db.prepare("INSERT INTO messages VALUES (?, ?)");+ for (let n = 0; n < 500; n += 1) insert.run(String(n), `${"y".repeat(200)}${n}`);+ db.close();+ // Overwrite part of a page in the middle: the header still reads, the tree does not.+ const bytes = readFileSync(join(data, "messages.db"));+ bytes.fill(0x41, 4096 * 3, 4096 * 3 + 2000);+ writeFileSync(join(data, "messages.db"), bytes);+ const finding = messagesDbCheck({ busyTimeoutMs: 0 }).check(context(data));+ expect(finding).toMatchObject({ status: "problem", summary: expect.stringMatching(/^SQLite finds the database damaged: \d+ problems? /) });+ expect(finding.instruction).toContain("./update.sh --rollback");+ });++ it("takes a database it cannot open for not checked, never for damaged, and points at no restore", () => {+ const data = dataFolder();+ // A folder where the file goes: it cannot be opened on any platform.+ mkdirSync(join(data, "messages.db"));+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [messagesDbCheck({ busyTimeoutMs: 0 })] });+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false, summary: expect.stringMatching(/^Could not check messages\.db: /) });+ expect(report.checks[0]!.instruction).not.toContain("rollback");+ expect(report.checks[0]!.instruction).not.toContain("put back");+ expect(backupFolder(data)).toBeNull();+ });++ it("takes a database another program has locked for not checked, not damaged", () => {+ const data = dataFolder();+ const holder = new DatabaseSync(join(data, "messages.db"));+ try {+ holder.exec("CREATE TABLE messages (id TEXT); INSERT INTO messages VALUES ('1'); BEGIN EXCLUSIVE; INSERT INTO messages VALUES ('2')");+ const finding = messagesDbCheck({ busyTimeoutMs: 0 }).check(context(data));+ expect(finding).toMatchObject({ status: "problem", summary: "Could not check messages.db: database is locked." });+ expect(finding.instruction).not.toContain("rollback");+ } finally {+ holder.close();+ }+ expect(messagesDbCheck({ busyTimeoutMs: 0 }).check(context(data))).toMatchObject({ status: "ok", summary: "SQLite finds it sound." });+ });++ it.skipIf(process.platform === "win32" || (typeof process.getuid === "function" && process.getuid() === 0))("takes a database this user may not read for not checked", () => {+ const data = dataFolder();+ database(data).close();+ chmodSync(join(data, "messages.db"), 0o000);+ try {+ const finding = messagesDbCheck({ busyTimeoutMs: 0 }).check(context(data));+ expect(finding).toMatchObject({ status: "problem", summary: expect.stringMatching(/^Could not check messages\.db: /) });+ expect(finding.instruction).not.toContain("rollback");+ } finally {+ chmodSync(join(data, "messages.db"), 0o600);+ }+ });++ it("does not count a checkpoint another connection keeps from finishing as a repair", () => {+ const data = dataFolder();+ const writer = database(data, 200);+ const reader = new DatabaseSync(join(data, "messages.db"));+ try {+ // An open read transaction: the log cannot be emptied under it.+ reader.exec("BEGIN");+ reader.prepare("SELECT count(*) FROM messages").get();+ const check = messagesDbCheck({ largeWalBytes: 100_000, freeBytes: () => null, busyTimeoutMs: 0 });+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [check] });+ expect(report.checks[0]).toMatchObject({ status: "failed" });+ expect(report.checks[0]!.repaired).toBeFalsy();+ expect(report.counts.fixed).toBe(0);+ expect(statSync(join(data, "messages.db-wal")).size).toBeGreaterThan(100_000);+ // What it was about to change was copied first.+ expect(existsSync(join(backupFolder(data)!, "messages.db-wal"))).toBe(true);+ } finally {+ reader.close();+ writer.close();+ }+ });++ it("runs SQLite's check only in the first look; a look again takes the first look's verdict", () => {+ const data = dataFolder();+ writeFileSync(join(data, "messages.db"), Buffer.alloc(8192, 7));+ const check = messagesDbCheck({ busyTimeoutMs: 0 });+ const first = check.check(context(data));+ expect(first.summary).toMatch(/^SQLite finds the database damaged/);+ const sound = check.check(context(data, { earlier: { status: "ok", summary: "", detail: { verdict: { kind: "ok" } } } }));+ expect(sound).toMatchObject({ status: "ok", summary: "SQLite finds it sound." });+ });++ it("counts the log with the database against the size read at start", () => {+ const data = dataFolder();+ const writer = database(data, 200);+ try {+ const dbBytes = statSync(join(data, "messages.db")).size;+ const check = messagesDbCheck({ startCheckMaxBytes: dbBytes + 1024, largeWalBytes: 100_000, freeBytes: () => null, busyTimeoutMs: 0 });+ const finding = check.check(context(data, { mode: "start" }));+ expect(finding).toMatchObject({ status: "problem", fixable: false, summary: expect.stringContaining("checked only by openmausbot doctor --data") });+ expect(check.check(context(data, { mode: "command" }))).toMatchObject({ fixable: true, summary: expect.stringMatching(/^SQLite finds it sound; /) });+ } finally {+ writer.close();+ }+ });});diff --git a/server/doctor/checks/messages-db.ts b/server/doctor/checks/messages-db.tsindex 47aae559a6..ea65fd7116 100644--- a/server/doctor/checks/messages-db.ts+++ b/server/doctor/checks/messages-db.ts@@ -1,6 +1,8 @@// 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.+// slower; folding it in (a checkpoint) is SQLite's own step, taken after both files are copied into the backup. A file+// that cannot be opened or is locked is reported as not checked, never as damaged: only SQLite's own verdict on what it+// read is.import { existsSync, statfsSync, statSync } from "node:fs";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";@@ -16,8 +18,34 @@ 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 {+/** SQLite's own answer, from the first look: sound, damaged, or not looked at because the file could not be opened or+ * read (permissions, another program's lock), which says nothing about the file. Null: too large to read at start. */+type Verdict = { kind: "ok" } | { kind: "damaged"; text: string } | { kind: "unchecked"; reason: string } | null;++/** The result codes that mean the file itself is damaged: SQLITE_CORRUPT and SQLITE_NOTADB. */+const DAMAGED_CODES = new Set([11, 26]);++function quickCheck(file: string, busyTimeoutMs: number): Verdict {+ let db: DatabaseSync | null = null;+ try {+ db = new DatabaseSync(file, { readOnly: true, timeout: busyTimeoutMs });+ // SQLite's integrity check without the slow comparison of every index with its table.+ const rows = db.prepare("PRAGMA quick_check(20)").all() as Record<string, unknown>[];+ const lines = rows.map((row) => String(Object.values(row)[0]));+ return lines.length === 1 && lines[0] === "ok" ? { kind: "ok" }+ : { kind: "damaged", text: `${lines.length} problem${lines.length === 1 ? "" : "s"} (first: ${lines[0]?.slice(0, 160) ?? "unknown"})` };+ } catch (error) {+ const code = (error as { errcode?: unknown }).errcode;+ const text = error instanceof Error ? error.message.slice(0, 160) : String(error);+ return typeof code === "number" && DAMAGED_CODES.has(code & 0xff) ? { kind: "damaged", text } : { kind: "unchecked", reason: text };+ } finally {+ try { db?.close(); } catch {}+ }+}++export function messagesDbCheck(limits: { startCheckMaxBytes?: number; largeWalBytes?: number; freeBytes?: (dir: string) => number | null; busyTimeoutMs?: number } = {}): DoctorCheck {const startMax = limits.startCheckMaxBytes ?? START_CHECK_MAX_BYTES, largeWal = limits.largeWalBytes ?? LARGE_WAL_BYTES;+ const busyTimeoutMs = limits.busyTimeoutMs ?? 5000;const freeBytes = limits.freeBytes ?? ((dir: string) => {try { const stats = statfsSync(dir); return Number(stats.bavail) * Number(stats.bsize); } catch { return null; }});@@ -29,43 +57,36 @@ export function messagesDbCheck(limits: { startCheckMaxBytes?: number; largeWalBconst file = join(ctx.dataDir, DB);if (!existsSync(file)) return { status: "ok", summary: "Not there yet." };const dbBytes = size(file), walBytes = size(`${file}-wal`);- const atStart = ctx.mode === "start";- let verdict: string | null = null;- if (!atStart || dbBytes <= startMax) {- let db: DatabaseSync | null = null;- try {- db = new DatabaseSync(file, { readOnly: true });- // SQLite's integrity check without the slow comparison of every index with its table.- const rows = db.prepare("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}.`,+ // The check reads the log as well as the database.+ const readable = ctx.mode !== "start" || dbBytes + walBytes <= startMax;+ // SQLite's check runs in the first look only: a look again before or after a fix goes by the sizes.+ const verdict: Verdict = ctx.earlier+ ? (ctx.earlier.detail as { verdict?: Verdict } | undefined)?.verdict ?? null+ : readable ? quickCheck(file, busyTimeoutMs) : null;+ if (verdict?.kind === "damaged") {+ return { status: "problem", summary: `SQLite finds the database damaged: ${verdict.text}.`, detail: { 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 (verdict?.kind === "unchecked") {+ return { status: "problem", summary: `Could not check messages.db: ${verdict.reason}.`, detail: { verdict },+ instruction: "Make sure the server's user can read messages.db and no other program holds it, then run openmausbot doctor --data again." };+ }+ const checked = verdict ? "SQLite finds it sound" : `${Math.round((dbBytes + walBytes) / 1024 / 1024)} MB with its log: checked only by openmausbot doctor --data`;if (walBytes > largeWal) {const free = freeBytes(ctx.dataDir);const room = free === null || free > 2 * (dbBytes + walBytes);- const now = !atStart || dbBytes + walBytes <= startMax;- return { status: "problem", fixable: room && now, detail: { file },+ return { status: "problem", fixable: room && readable, detail: { file, verdict },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." }- : !now ? { instruction: "Too large to copy as the server starts: stop the server, then run openmausbot doctor --data --fix." } : {}) };+ : !readable ? { instruction: "Too large to copy as the server starts: stop the server, then run openmausbot doctor --data --fix." } : {}) };}- return { status: "ok", summary: `${checked}.` };+ return { status: "ok", summary: `${checked}.`, detail: { verdict } };},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);+ const db = new DatabaseSync(file, { timeout: busyTimeoutMs });try {const [row] = db.prepare("PRAGMA wal_checkpoint(TRUNCATE)").all() as { busy?: number }[];if (row?.busy) throw new Error("another connection holds the database");diff --git a/server/doctor/checks/registry.test.ts b/server/doctor/checks/registry.test.tsindex a79423cf4f..56faa9e7fd 100644--- a/server/doctor/checks/registry.test.ts+++ b/server/doctor/checks/registry.test.ts@@ -1,14 +1,16 @@-import { existsSync, readFileSync, statSync, utimesSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";import { join } from "node:path";import { describe, expect, it } from "vitest";+import { DOCTOR_BACKUPS_DIR } from "../backup.ts";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()] });+const run = (data: string, pidAlive = (_pid: number) => false, registry = registryCheck()) =>+ runDoctor({ dataDir: data, version: "9.9.9", mode: "start", fix: true, now: () => NOW, pidAlive, checks: [registry, tempFilesCheck()] });+const asRoot = typeof process.getuid === "function" && process.getuid() === 0;describe("registry check", () => {it("finds readable or missing registries fine", () => {@@ -33,7 +35,7 @@ describe("registry 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"]);+ expect(manifest(backup).entries.map((entry) => entry.action)).toEqual(["copied: damaged, then replaced", "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", () => {@@ -42,7 +44,7 @@ describe("registry check", () => {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]!.fixed).toContain("kept a copy of the damaged groups.json");expect(report.checks[0]!.repaired).toBe(false);expect(report.counts.fixed).toBe(0);expect(report.checks[0]!.instruction).toContain("./update.sh --rollback");@@ -75,4 +77,85 @@ describe("registry check", () => {expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("nope");expect(existsSync(join(data, `bots.json.4242.${UUID}.tmp`))).toBe(true);});++ it("takes a file it cannot read at all for not checked, never for damaged, and changes nothing", () => {+ const data = dataFolder();+ // A folder in its place: EISDIR everywhere.+ mkdirSync(join(data, "bots.json"));+ writeFileSync(join(data, `bots.json.4242.${UUID}.tmp`), "[]");+ const finding = registryCheck().check(context(data));+ expect(finding).toMatchObject({ status: "problem", summary: expect.stringMatching(/^Could not check bots\.json: E[A-Z]+\.$/) });+ expect(finding.fixable).toBeFalsy();+ expect(finding.keepCopy).toBeFalsy();+ expect(finding.instruction).not.toContain("rollback");+ expect(finding.instruction).not.toContain("put back");+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ status: "problem", fixable: false });+ expect(report.checks[0]!.fixed).toBeUndefined();+ expect(statSync(join(data, "bots.json")).isDirectory()).toBe(true);+ });++ it.skipIf(process.platform === "win32" || asRoot)("reports a bots.json this user may not read as not checked (EACCES), not damaged", () => {+ const data = dataFolder();+ writeFileSync(join(data, "bots.json"), JSON.stringify([{ id: "b1" }]));+ chmodSync(join(data, "bots.json"), 0o000);+ try {+ const finding = registryCheck().check(context(data));+ expect(finding).toMatchObject({ status: "problem", summary: "Could not check bots.json: EACCES." });+ expect(finding.instruction).not.toContain("rollback");+ expect(run(data).backup).toBeNull();+ } finally {+ chmodSync(join(data, "bots.json"), 0o600);+ }+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe(JSON.stringify([{ id: "b1" }]));+ });++ it("leaves bots.json and its whole copy in place when the rename fails halfway, and the temp-file check leaves the copy too", () => {+ const data = dataFolder();+ const temp = join(data, `bots.json.4242.${UUID}.tmp`);+ writeFileSync(join(data, "bots.json"), "[{\"id\":");+ writeFileSync(temp, "[]");+ const failing = registryCheck({ rename: () => { throw Object.assign(new Error("cross-device link not permitted"), { code: "EXDEV" }); } });+ const report = run(data, () => false, failing);+ expect(report.checks[0]).toMatchObject({ id: "registry", status: "failed", summary: expect.stringContaining("The fix failed: cross-device link not permitted") });+ expect(report.checks[1]).toMatchObject({ id: "temp-files", status: "ok" });+ expect(report.counts.fixed).toBe(0);+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("[{\"id\":");+ expect(readFileSync(temp, "utf8")).toBe("[]");+ // Both were copied before the rename was tried.+ expect(manifest(backupFolder(data)!).entries.map((entry) => entry.action)).toEqual(["copied: damaged, then replaced", "the copy put in its place"]);+ // The next run repairs it.+ rmBackups(data);+ expect(run(data).checks[0]).toMatchObject({ status: "fixed" });+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("[]");+ });++ it("changes nothing when the backup cannot take its copy", () => {+ const data = dataFolder();+ const temp = join(data, `bots.json.4242.${UUID}.tmp`);+ writeFileSync(join(data, "bots.json"), "[{\"id\":");+ writeFileSync(temp, "[]");+ // A file where the backups folder goes: nothing can be copied there.+ writeFileSync(join(data, DOCTOR_BACKUPS_DIR), "");+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ id: "registry", status: "failed" });+ expect(report.checks[1]).toMatchObject({ id: "temp-files", status: "ok" });+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("[{\"id\":");+ expect(readFileSync(temp, "utf8")).toBe("[]");+ });++ it("counts a repair of one file when the other has no copy to put back", () => {+ const data = dataFolder();+ writeFileSync(join(data, "bots.json"), "[{\"id\":");+ writeFileSync(join(data, `bots.json.4242.${UUID}.tmp`), "[]");+ writeFileSync(join(data, "groups.json"), "");+ const report = run(data);+ expect(report.checks[0]).toMatchObject({ status: "problem", repaired: true, summary: expect.stringContaining("groups.json is damaged") });+ expect(report.counts.fixed).toBe(1);+ expect(readFileSync(join(data, "bots.json"), "utf8")).toBe("[]");+ });});++function rmBackups(data: string): void {+ rmSync(join(data, DOCTOR_BACKUPS_DIR), { recursive: true, force: true });+}diff --git a/server/doctor/checks/registry.ts b/server/doctor/checks/registry.tsindex cda5d39f6c..b33afd951e 100644--- a/server/doctor/checks/registry.ts+++ b/server/doctor/checks/registry.ts@@ -1,41 +1,64 @@// 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 after the damaged file: the temp file of a save// that was interrupted after it was written and before it was renamed. 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, statSync } from "node:fs";+// file goes into the backup before the server starts, so a later save cannot take the last of it. A file this user+// cannot read at all is not taken for damaged: it is reported as not checked, and left alone.+import { chmodSync, statSync } from "node:fs";import { join } from "node:path";+import { renameWithRetry } from "../../atomic.ts";import { leftoverTemps, registryState, type LeftoverTemp } from "../files.ts";-import type { DoctorCheck } from "../types.ts";+import type { DoctorCheck, DoctorContext } from "../types.ts";export const REGISTRY_FILES = ["bots.json", "groups.json"] as const;type Damage = { file: string; path: string; copy: LeftoverTemp | null };+type Unchecked = { file: string; reason: string };-export function registryCheck(): DoctorCheck {+function look(ctx: DoctorContext): { damaged: Damage[]; unchecked: Unchecked[] } {+ const damaged: Damage[] = [], unchecked: Unchecked[] = [];+ for (const file of REGISTRY_FILES) {+ const path = join(ctx.dataDir, file);+ const state = registryState(path);+ if (state.state === "unreadable") unchecked.push({ file, reason: state.reason });+ if (state.state !== "damaged") continue;+ // Only a save begun after the damaged file was written: an older one would bring back a list from before it.+ let damagedAt = Infinity;+ try { damagedAt = statSync(path).mtimeMs; } catch {}+ const copies = leftoverTemps(ctx).filter((temp) => temp.of === file && temp.mtimeMs >= damagedAt && registryState(temp.path).state === "ok").sort((a, b) => b.mtimeMs - a.mtimeMs);+ damaged.push({ file, path, copy: copies[0] ?? null });+ }+ return { damaged, unchecked };+}++/** The temp files the registry would put in place of a damaged file: while one is still chosen (its fix has not run, or+ * failed), the temp-file check leaves it where it is. */+export function registryCopies(ctx: DoctorContext): Set<string> {+ return new Set(look(ctx).damaged.flatMap((damage) => damage.copy ? [damage.copy.path] : []));+}++export function registryCheck(options: { rename?: (from: string, to: string) => void } = {}): 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;- // Only a save begun after the damaged file was written: an older one would bring back a list from before it.- let damagedAt = Infinity;- try { damagedAt = statSync(path).mtimeMs; } catch {}- const copies = leftoverTemps(ctx).filter((temp) => temp.of === file && temp.mtimeMs >= damagedAt && 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 { damaged, unchecked } = look(ctx);+ if (!damaged.length && !unchecked.length) return { status: "ok", summary: "Both read as lists (or are not there yet)." };const lost = damaged.filter((damage) => !damage.copy);+ const instructions = [+ ...(lost.length ? [`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"}.`] : []),+ ...(unchecked.length ? [`Give the server's user ${unchecked.map((item) => item.file).join(" and ")} back as a file it can read, then run openmausbot doctor --data again.`] : []),+ ];return {status: "problem",fixable: lost.length < damaged.length,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"}.` } : {}),+ summary: [+ ...damaged.map((damage) => `${damage.file} is damaged (it does not read as a whole list)${damage.copy ? ", and a whole copy from an interrupted save is there" : ""}.`),+ ...unchecked.map((item) => `Could not check ${item.file}: ${item.reason}.`),+ ].join(" "),+ ...(instructions.length ? { instruction: instructions.join(" ") } : {}),detail: damaged,};},@@ -44,14 +67,18 @@ export function registryCheck(): DoctorCheck {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}`);+ backup.copy("registry", damage.path, "kept: damaged, and no whole copy was found");+ done.push(`kept a copy of the damaged ${damage.file}`);continue;}- backup.move("registry", damage.path, "moved aside: could not be read");+ // Both copied first, and then one rename puts the whole copy in place: at every step the live path holds a file,+ // and a step that fails leaves both where they were.+ backup.copy("registry", damage.path, "copied: damaged, then replaced");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);+ if (process.platform !== "win32") {+ try { chmodSync(damage.copy.path, 0o600); } catch {}+ }+ renameWithRetry(damage.copy.path, damage.path, options.rename);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/temp-files.ts b/server/doctor/checks/temp-files.tsindex 17757221fc..78bd2d4fb3 100644--- a/server/doctor/checks/temp-files.ts+++ b/server/doctor/checks/temp-files.ts@@ -1,7 +1,9 @@// 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.+// folder's own top level is looked at: bots' work folders hold the person's files. A temp file the registry check would+// put in place of a damaged bots.json or groups.json stays where it is, so its repair can run again.import { leftoverTemps } from "../files.ts";+import { registryCopies } from "./registry.ts";import type { DoctorCheck } from "../types.ts";export function tempFilesCheck(): DoctorCheck {@@ -10,7 +12,8 @@ export function tempFilesCheck(): DoctorCheck {title: "Unfinished saves",looksAt: "<file>.<pid>.<id>.tmp in the data folder",check(ctx) {- const temps = leftoverTemps(ctx);+ const keep = registryCopies(ctx);+ const temps = leftoverTemps(ctx).filter((temp) => !keep.has(temp.path));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),diff --git a/server/doctor/doctor.e2e.test.ts b/server/doctor/doctor.e2e.test.tsindex f731fb8602..04113b50c7 100644--- a/server/doctor/doctor.e2e.test.ts+++ b/server/doctor/doctor.e2e.test.ts@@ -125,7 +125,9 @@ it("openmausbot doctor --data finds each problem, --fix repairs them all, and thexpect(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);+ // Folded back: emptied, or removed as the last connection closed.+ const wal = join(home, "messages.db-wal");+ expect(existsSync(wal) ? statSync(wal).size : 0).toBe(0);await serverHasItsBots(home, bots);}, 180_000);@@ -141,6 +143,6 @@ it("a new version's first start repairs the same damage itself and reports it in// 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(server.output()).toMatch(/\[doctor\] registry: bots\.json is damaged.* 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.tsindex 23d5b72f70..449b5ec47a 100644--- a/server/doctor/files.ts+++ b/server/doctor/files.ts@@ -31,13 +31,19 @@ export function leftoverTemps(ctx: DoctorContext, dir: string = ctx.dataDir): Lereturn 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" {+/** "missing"; "ok" when the file parses as a JSON list; "damaged" when it was read and is not one (empty, cut short, not a+ * list); "unreadable" when it could not be read at all (permissions, a folder in its place): that says nothing about the+ * file, and is never repaired or reported as damage. */+export type RegistryState = { state: "missing" | "ok" | "damaged" } | { state: "unreadable"; reason: string };++export function registryState(path: string): RegistryState {let text: string;try { text = readFileSync(path, "utf8"); } catch (error) {- return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable";+ const code = (error as NodeJS.ErrnoException).code;+ // The code only: an fs message carries the full path.+ return code === "ENOENT" ? { state: "missing" } : { state: "unreadable", reason: code ?? "read error" };}- try { return Array.isArray(JSON.parse(text)) ? "ok" : "unreadable"; } catch { return "unreadable"; }+ try { return { state: Array.isArray(JSON.parse(text)) ? "ok" : "damaged" }; } catch { return { state: "damaged" }; }}export function pidAlive(pid: number): boolean {diff --git a/server/doctor/run.test.ts b/server/doctor/run.test.tsnew file mode 100644index 0000000000..71fd88b0b5--- /dev/null+++ b/server/doctor/run.test.ts@@ -0,0 +1,107 @@+import { existsSync, mkdirSync, readdirSync, statSync, 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 { DOCTOR_BACKUPS_DIR, DoctorBackup } from "./backup.ts";+import { tempFilesCheck } from "./checks/temp-files.ts";+import { runDoctor } from "./run.ts";+import type { DoctorCheck } from "./types.ts";++/** A check whose fix runs without error and changes nothing, as a chmod on a filesystem without modes does. */+function stubborn(): DoctorCheck & { looks: number } {+ const check = {+ looks: 0,+ id: "stubborn", title: "Stubborn", looksAt: "nothing",+ check: () => { check.looks += 1; return { status: "problem" as const, fixable: true, summary: "Still wrong." }; },+ fix: () => "Tried.",+ };+ return check;+}++describe("runDoctor", () => {+ it("does not count a fix that changed nothing as a repair", () => {+ const check = stubborn();+ const report = runDoctor({ dataDir: dataFolder(), version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [check] });+ expect(report.checks[0]).toMatchObject({ status: "problem", fixed: "Tried.", repaired: false });+ expect(report.counts.fixed).toBe(0);+ // The first look, the look right before the fix, and the look after it.+ expect(check.looks).toBe(3);+ });++ it("hands the first look to the looks before and after a fix", () => {+ const earlier: unknown[] = [];+ const check: DoctorCheck = {+ id: "seen", title: "Seen", looksAt: "nothing",+ check: (ctx) => {+ earlier.push(ctx.earlier?.detail);+ return earlier.length === 3 ? { status: "ok", summary: "Fine." } : { status: "problem", fixable: true, summary: "Wrong.", detail: earlier.length };+ },+ fix: () => "Done.",+ };+ const report = runDoctor({ dataDir: dataFolder(), version: "9.9.9", mode: "start", fix: true, now: () => NOW, checks: [check] });+ expect(earlier).toEqual([undefined, 1, 1]);+ expect(report.checks[0]).toMatchObject({ status: "fixed", repaired: true });+ });++ it.skipIf(process.platform === "win32")("changes nothing on the command when it runs as a user other than the data folder's owner", () => {+ const data = dataFolder();+ const temp = join(data, `config.json.31337.${UUID}.tmp`);+ writeFileSync(temp, "{}");+ const owner = statSync(data).uid;+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "command", fix: true, now: () => NOW, checks: [tempFilesCheck()], euid: () => owner + 1 });+ expect(report.fix).toMatchObject({ asked: true, ran: false, why: `The data folder belongs to user ${owner}, and this runs as user ${owner + 1}. Run it as the folder's owner. Nothing was changed.` });+ expect(existsSync(temp)).toBe(true);+ expect(existsSync(join(data, DOCTOR_BACKUPS_DIR))).toBe(false);+ // As the owner, it runs.+ expect(runDoctor({ dataDir: data, version: "9.9.9", mode: "command", fix: true, now: () => NOW, checks: [tempFilesCheck()], euid: () => owner }).fix.ran).toBe(true);+ expect(existsSync(temp)).toBe(false);+ });++ it("checks no owner where there is no user id", () => {+ const data = dataFolder();+ const report = runDoctor({ dataDir: data, version: "9.9.9", mode: "command", fix: true, now: () => NOW, checks: [stubborn()], euid: () => null });+ expect(report.fix.ran).toBe(true);+ });+});++describe("doctor backups kept", () => {+ const DAY = 86_400_000;+ const runName = (at: number) => new Date(at).toISOString().replace(/\.\d+Z$/, "Z").replaceAll(":", "-");++ function oldRun(data: string, at: number, check: string, bytes = 10): string {+ const name = runName(at);+ const folder = join(data, DOCTOR_BACKUPS_DIR, name);+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, "copy"), Buffer.alloc(bytes));+ writeFileSync(join(folder, "manifest.json"), JSON.stringify({ entries: [{ check, action: "copied before the fix", path: "x" }] }));+ return name;+ }++ it("keeps a run with a registry copy for 30 days beyond the newest runs, and not after", () => {+ const data = dataFolder();+ const recentRegistry = oldRun(data, NOW - 20 * DAY, "registry");+ const staleRegistry = oldRun(data, NOW - 40 * DAY, "registry");+ const oldTemps = oldRun(data, NOW - 19 * DAY, "temp-files");+ const newer = [1, 2].map((days) => oldRun(data, NOW - days * DAY, "temp-files"));+ new DoctorBackup(data, () => NOW, { kept: 3 }).note("test", "a note", data);+ const left = readdirSync(join(data, DOCTOR_BACKUPS_DIR));+ expect(left).toContain(recentRegistry);+ expect(left).not.toContain(staleRegistry);+ expect(left).not.toContain(oldTemps);+ for (const name of newer) expect(left).toContain(name);+ expect(left).toHaveLength(4);+ });++ it("keeps the older runs under the size cap, oldest first, but never a registry copy under 30 days", () => {+ const data = dataFolder();+ const big = [5, 4, 3].map((days) => oldRun(data, NOW - days * DAY, "messages-db", 1000));+ const registry = oldRun(data, NOW - 6 * DAY, "registry", 1000);+ new DoctorBackup(data, () => NOW, { kept: 10, maxBytes: 2500 }).note("test", "a note", data);+ const left = readdirSync(join(data, DOCTOR_BACKUPS_DIR));+ expect(left).toContain(registry);+ expect(left).not.toContain(big[0]);+ expect(left).not.toContain(big[1]);+ expect(left).toContain(big[2]);+ });+});diff --git a/server/doctor/run.ts b/server/doctor/run.tsindex 9fe9e6b65a..93a9f55fd8 100644--- a/server/doctor/run.ts+++ b/server/doctor/run.ts@@ -1,7 +1,10 @@// 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.+// while a server uses the folder, and only as the folder's owner. Each repair looks again right before it runs, and once+// more after; those looks skip what is slow to read (SQLite's check of messages.db) and take it from the first look.+import { statSync } from "node:fs";+import { acquireDataDirLease, type DataDirLeaseHolder } from "../data-dir-lease.ts";import { DoctorBackup } from "./backup.ts";import { dataFormatCheck } from "./checks/data-format.ts";@@ -32,6 +35,8 @@ export interface RunDoctorOptions {startedAt?: number;/** "command" mode only: takes the data folder's lease for the repairs. */acquireLease?: (dataDir: string) => { release(): unknown };+ /** "command" mode only: this process's effective user id, null where there is none (Windows). */+ euid?: () => number | null;}const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)).slice(0, 300);@@ -56,6 +61,18 @@ function resultOf(check: DoctorCheck, finding: Finding & { failed?: boolean }):};}+/** The user ids of this process and of the data folder's owner, when they differ (POSIX only). */+function otherOwner(dataDir: string, euid: () => number | null): { euid: number; owner: number } | null {+ if (process.platform === "win32") return null;+ const id = euid();+ if (id === null) return null;+ let owner: number;+ try { owner = statSync(dataDir).uid; } catch { return null; }+ return owner === id ? null : { euid: id, owner };+}++const defaultEuid = () => (typeof process.geteuid === "function" ? process.geteuid() : null);+const wantsFix = (check: DoctorCheck, finding: Finding) => Boolean(check.fix && finding.status === "problem" && (finding.fixable || finding.keepCopy));export function runDoctor(options: RunDoctorOptions): DoctorReport {@@ -78,7 +95,11 @@ export function runDoctor(options: RunDoctorOptions): DoctorReport {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.`;+ // What a fix moves keeps its owner, and what it copies or makes would be this user's: a server running as the+ // folder's owner could then not read or tidy it.+ const other = otherOwner(options.dataDir, options.euid ?? defaultEuid);+ if (other) fix.why = `The data folder belongs to user ${other.owner}, and this runs as user ${other.euid}. Run it as the folder's owner. Nothing was changed.`;+ else 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 {@@ -96,7 +117,8 @@ export function runDoctor(options: RunDoctorOptions): DoctorReport {try {checks.forEach((check, at) => {if (check.id === "lease" || !wantsFix(check, findings[at]!)) return;- const fresh = look(check, ctx);+ const again = { ...ctx, earlier: findings[at]! };+ const fresh = look(check, again);if (!wantsFix(check, fresh)) {results[at] = resultOf(check, fresh);return;@@ -108,8 +130,11 @@ export function runDoctor(options: RunDoctorOptions): DoctorReport {results[at] = { ...resultOf(check, fresh), status: "failed", summary: `${fresh.summary} The fix failed: ${errorText(error)}` };return;}- const after = look(check, ctx);- const repaired = Boolean(fresh.fixable);+ const after = look(check, again);+ // A repair is counted only when the look after it finds the repairable part gone: all fine, or what is left is+ // not repairable (a registry file with no whole copy, beside one that was put back). A fix that changed nothing+ // (a mode on a filesystem without modes) is not one.+ const repaired = Boolean(fresh.fixable) && (after.status === "ok" || !after.fixable);results[at] = after.status === "ok"? { ...resultOf(check, fresh), status: "fixed", fixable: false, fixed: did, repaired }: { ...resultOf(check, after), fixed: did, repaired };diff --git a/server/doctor/types.ts b/server/doctor/types.tsindex 684b862c61..dfe24a5cd3 100644--- a/server/doctor/types.ts+++ b/server/doctor/types.ts@@ -14,6 +14,9 @@ export interface DoctorContext {startedAt: number;/** Whether a process with this pid runs on this machine (EPERM counts as running). */pidAlive(pid: number): boolean;+ /** Set in the looks the runner takes again, right before and after a fix: what the first look found. A check whose+ * look reads a lot (messages.db) does that read only in the first look, and takes its verdict from here. */+ earlier?: Finding;}export type Finding = {