Skip to content

Commit eef59b5

Browse files
fix(doctor): stop stale builds before repair guidance (#117913)
* fix(doctor): refuse newer database schemas before repairs * fix(doctor): preserve update before schema refusal
1 parent 1704ea5 commit eef59b5

5 files changed

Lines changed: 168 additions & 14 deletions

File tree

‎src/commands/doctor.e2e-harness.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,13 +61,13 @@ function createLegacyConfigSnapshot() {
6161
} as const;
6262
}
6363

64-
const readConfigFileSnapshot = vi.fn() as unknown as MockFn;
64+
export const readConfigFileSnapshot = vi.fn() as unknown as MockFn;
6565
export const confirm = vi.fn().mockResolvedValue(true) as unknown as MockFn;
6666
const select = vi.fn().mockResolvedValue("node") as unknown as MockFn;
6767
const note = vi.fn() as unknown as MockFn;
6868
export const writeConfigFile = vi.fn().mockResolvedValue(undefined) as unknown as MockFn;
69-
const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null) as unknown as MockFn;
70-
const runGatewayUpdate = vi
69+
export const resolveOpenClawPackageRoot = vi.fn().mockResolvedValue(null) as unknown as MockFn;
70+
export const runGatewayUpdate = vi
7171
.fn()
7272
.mockResolvedValue(createGatewayUpdateResult()) as unknown as MockFn;
7373
const collectRelevantDoctorPluginIds = vi.fn(() => []) as unknown as MockFn;
@@ -87,7 +87,7 @@ const runExec = vi.fn().mockResolvedValue({
8787
stdout: "",
8888
stderr: "",
8989
}) as unknown as MockFn;
90-
const runCommandWithTimeout = vi
90+
export const runCommandWithTimeout = vi
9191
.fn()
9292
.mockResolvedValue(createCommandWithTimeoutResult()) as unknown as MockFn;
9393

@@ -133,7 +133,7 @@ export const callGateway = vi
133133
.fn()
134134
.mockRejectedValue(new Error("gateway closed")) as unknown as MockFn;
135135

136-
const autoMigrateLegacyStateDir = vi.fn().mockResolvedValue({
136+
export const autoMigrateLegacyStateDir = vi.fn().mockResolvedValue({
137137
migrated: false,
138138
skipped: false,
139139
changes: [],
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { beforeEach, describe, expect, it, vi } from "vitest";
4+
import { requireNodeSqlite } from "../infra/node-sqlite.js";
5+
import { OPENCLAW_STATE_SCHEMA_VERSION } from "../state/openclaw-state-db.js";
6+
import { resolveOpenClawStateSqlitePath } from "../state/openclaw-state-db.paths.js";
7+
import {
8+
autoMigrateLegacyStateDir,
9+
createDoctorRuntime,
10+
mockDoctorConfigSnapshot,
11+
readConfigFileSnapshot,
12+
resolveOpenClawPackageRoot,
13+
runCommandWithTimeout,
14+
runGatewayUpdate,
15+
} from "./doctor.e2e-harness.js";
16+
17+
let doctorCommand: typeof import("./doctor.js").doctorCommand;
18+
19+
describe("doctor database schema preflight", () => {
20+
beforeEach(async () => {
21+
vi.resetModules();
22+
({ doctorCommand } = await import("./doctor.js"));
23+
vi.clearAllMocks();
24+
});
25+
26+
it("lets a successful interactive update replace the stale doctor", async () => {
27+
writeStateSchemaVersion(OPENCLAW_STATE_SCHEMA_VERSION + 1);
28+
mockDoctorConfigSnapshot();
29+
mockInteractiveGitUpdate("ok");
30+
31+
await expect(doctorCommand(createDoctorRuntime())).resolves.toBeUndefined();
32+
33+
expect(runGatewayUpdate).toHaveBeenCalledOnce();
34+
expect(autoMigrateLegacyStateDir).not.toHaveBeenCalled();
35+
expect(readConfigFileSnapshot).not.toHaveBeenCalled();
36+
});
37+
38+
it("refuses after an interactive update does not handle doctor", async () => {
39+
writeStateSchemaVersion(OPENCLAW_STATE_SCHEMA_VERSION + 1);
40+
mockDoctorConfigSnapshot();
41+
mockInteractiveGitUpdate("skipped");
42+
43+
await expect(doctorCommand(createDoctorRuntime())).rejects.toThrow(
44+
/Doctor refused to continue.*database schema.*newer than this build/iu,
45+
);
46+
47+
expect(runGatewayUpdate).toHaveBeenCalledOnce();
48+
expect(autoMigrateLegacyStateDir).not.toHaveBeenCalled();
49+
expect(readConfigFileSnapshot).not.toHaveBeenCalled();
50+
});
51+
52+
it("refuses before config repair flows when updates are disabled", async () => {
53+
writeStateSchemaVersion(OPENCLAW_STATE_SCHEMA_VERSION + 1);
54+
mockDoctorConfigSnapshot();
55+
56+
await expect(doctorCommand(createDoctorRuntime(), { nonInteractive: true })).rejects.toThrow(
57+
/Doctor refused to continue.*database schema.*newer than this build/iu,
58+
);
59+
60+
expect(runGatewayUpdate).not.toHaveBeenCalled();
61+
expect(autoMigrateLegacyStateDir).not.toHaveBeenCalled();
62+
expect(readConfigFileSnapshot).not.toHaveBeenCalled();
63+
});
64+
});
65+
66+
function mockInteractiveGitUpdate(status: "ok" | "skipped"): void {
67+
delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
68+
resolveOpenClawPackageRoot.mockResolvedValue("/repo");
69+
runCommandWithTimeout.mockResolvedValue({
70+
stdout: "/repo\n",
71+
stderr: "",
72+
code: 0,
73+
signal: null,
74+
killed: false,
75+
});
76+
runGatewayUpdate.mockResolvedValue({
77+
status,
78+
mode: "git",
79+
root: "/repo",
80+
steps: [],
81+
durationMs: 0,
82+
});
83+
}
84+
85+
function writeStateSchemaVersion(version: number): void {
86+
const statePath = resolveOpenClawStateSqlitePath(process.env);
87+
fs.mkdirSync(path.dirname(statePath), { recursive: true });
88+
const { DatabaseSync } = requireNodeSqlite();
89+
const database = new DatabaseSync(statePath);
90+
try {
91+
database.exec(`PRAGMA user_version = ${version};`);
92+
} finally {
93+
database.close();
94+
}
95+
}

‎src/flows/doctor-health.ts‎

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,26 @@ const outro = (message: string) => clackOutro(stylePromptTitle(message) ?? messa
1414

1515
const loadConfigModule = createLazyRuntimeModule(() => import("../config/config.js"));
1616

17+
async function assertDoctorDatabaseSchemasCompatible(): Promise<void> {
18+
const [databasePreflight, agentDatabase, stateDatabase] = await Promise.all([
19+
import("../state/openclaw-database-preflight.js"),
20+
import("../state/openclaw-agent-db.js"),
21+
import("../state/openclaw-state-db.js"),
22+
]);
23+
const databaseSchemas = databasePreflight.preflightOpenClawDatabaseSchemas({
24+
env: process.env,
25+
supportedVersions: {
26+
state: stateDatabase.OPENCLAW_STATE_SCHEMA_VERSION,
27+
agent: agentDatabase.OPENCLAW_AGENT_SCHEMA_VERSION,
28+
},
29+
});
30+
if (databaseSchemas.incompatible.length > 0) {
31+
throw new databasePreflight.OpenClawDatabaseSchemaPreflightError(databaseSchemas.incompatible, {
32+
operation: "doctor",
33+
});
34+
}
35+
}
36+
1737
function stateDirectoryExistsAtDoctorStart(): boolean {
1838
try {
1939
return fs.statSync(resolveStateDir()).isDirectory();
@@ -28,14 +48,10 @@ export async function doctorCommand(runtime?: RuntimeEnv, options: DoctorOptions
2848
// Config loading can initialize SQLite-backed state before integrity runs.
2949
// Preserve the entry fact so doctor can report that automatic initialization.
3050
const stateDirExistedAtStart = stateDirectoryExistsAtDoctorStart();
31-
if (options.repair === true || options.yes === true || options.generateGatewayToken === true) {
32-
const { assertConfigWriteAllowedInCurrentMode } = await loadConfigModule();
33-
assertConfigWriteAllowedInCurrentMode();
34-
}
51+
intro("OpenClaw doctor");
3552

3653
const { createDoctorPrompter } = await import("../commands/doctor-prompter.js");
3754
const prompter = createDoctorPrompter({ runtime: effectiveRuntime, options });
38-
intro("OpenClaw doctor");
3955

4056
const { resolveOpenClawPackageRoot } = await import("../infra/openclaw-root.js");
4157
const root = await resolveOpenClawPackageRoot({
@@ -56,6 +72,14 @@ export async function doctorCommand(runtime?: RuntimeEnv, options: DoctorOptions
5672
return;
5773
}
5874

75+
// A stale source checkout may update itself, but no diagnostic or repair may
76+
// touch state until the surviving build proves it understands every database.
77+
await assertDoctorDatabaseSchemasCompatible();
78+
if (options.repair === true || options.yes === true || options.generateGatewayToken === true) {
79+
const { assertConfigWriteAllowedInCurrentMode } = await loadConfigModule();
80+
assertConfigWriteAllowedInCurrentMode();
81+
}
82+
5983
// Keep side-effect-heavy legacy checks before structured contributions until fully migrated.
6084
const { maybeRepairUiProtocolFreshness } = await import("../commands/doctor-ui.js");
6185
const { noteSourceInstallIssues } = await import("../commands/doctor-install.js");

‎src/state/openclaw-database-preflight.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,23 @@ describe("OpenClaw database schema preflight", () => {
3131
});
3232
});
3333

34+
it("accepts a supported state schema", () => {
35+
const stateDir = makeTempDir(tempDirs, "openclaw-database-preflight-supported-");
36+
const env = { OPENCLAW_STATE_DIR: stateDir };
37+
openOpenClawStateDatabase({ env });
38+
closeOpenClawStateDatabaseForTest();
39+
40+
expect(
41+
preflightOpenClawDatabaseSchemas({
42+
env,
43+
supportedVersions: {
44+
state: OPENCLAW_STATE_SCHEMA_VERSION,
45+
agent: OPENCLAW_AGENT_SCHEMA_VERSION,
46+
},
47+
}),
48+
).toEqual({ incompatible: [], indeterminate: [] });
49+
});
50+
3451
it("collects newer state and registered agent schemas with writer builds", () => {
3552
const stateDir = makeTempDir(tempDirs, "openclaw-database-preflight-");
3653
const env = { OPENCLAW_STATE_DIR: stateDir };

‎src/state/openclaw-database-preflight.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,12 +44,30 @@ export type OpenClawDatabaseSchemaPreflight = {
4444

4545
type AgentRegistryDatabase = Pick<OpenClawStateKyselyDatabase, "agent_databases">;
4646

47-
/** Fatal Gateway refusal when persisted schemas were written by a newer build. */
47+
type OpenClawDatabaseSchemaPreflightOperation = "doctor" | "gateway-startup";
48+
49+
function formatDoctorIncompatibleDatabase(database: IncompatibleOpenClawDatabase): string {
50+
const agent = database.agentId ? ` for agent ${database.agentId}` : "";
51+
const writer = database.writerAppVersion ? `; writer build ${database.writerAppVersion}` : "";
52+
return `${database.kind} database${agent} ${database.path} uses schema ${database.foundVersion}; this build supports ${database.supportedVersion}${writer}.`;
53+
}
54+
55+
/** Fatal refusal when persisted schemas were written by a newer build. */
4856
export class OpenClawDatabaseSchemaPreflightError extends Error {
49-
constructor(readonly incompatibleDatabases: readonly IncompatibleOpenClawDatabase[]) {
57+
constructor(
58+
readonly incompatibleDatabases: readonly IncompatibleOpenClawDatabase[],
59+
options: { operation?: OpenClawDatabaseSchemaPreflightOperation } = {},
60+
) {
61+
const operation = options.operation ?? "gateway-startup";
62+
const prefix =
63+
operation === "doctor" ? "Doctor refused to continue" : "Gateway refused startup";
64+
const doctorGuidance =
65+
operation === "doctor"
66+
? ` ${incompatibleDatabases.map(formatDoctorIncompatibleDatabase).join(" ")} Run Doctor with the OpenClaw install that wrote this state (typically the active Gateway install), or another build that supports these schemas.`
67+
: "";
5068
super(
51-
`Gateway refused startup because ${incompatibleDatabases.length} OpenClaw database schema(s) are newer than this build. ` +
52-
`Refused by ${describeRunningOpenClawBuild()}. See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`,
69+
`${prefix} because ${incompatibleDatabases.length} OpenClaw database schema(s) are newer than this build. ` +
70+
`Refused by ${describeRunningOpenClawBuild()}.${doctorGuidance} See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`,
5371
);
5472
this.name = "OpenClawDatabaseSchemaPreflightError";
5573
}

0 commit comments

Comments
 (0)