Skip to content

Commit a7933a7

Browse files
Galin IlievCopilot
andcommitted
fix: recover gateway startup state migrations
Co-authored-by: Copilot <[email protected]> Copilot-Session: e61bf540-058b-4337-ae97-98fb7c39ef02
1 parent 7a819da commit a7933a7

8 files changed

Lines changed: 1352 additions & 72 deletions

‎src/commands/doctor-state-migrations.test.ts‎

Lines changed: 411 additions & 0 deletions
Large diffs are not rendered by default.

‎src/infra/state-migrations.doctor.ts‎

Lines changed: 246 additions & 54 deletions
Large diffs are not rendered by default.

‎src/infra/state-migrations.legacy-sessions.ts‎

Lines changed: 150 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fs from "node:fs";
22
import path from "node:path";
33
import type { SessionEntry } from "../config/sessions.js";
44
import { buildAgentMainSessionKey } from "../routing/session-key.js";
5+
import { resolveSqliteDatabaseFilePaths } from "./sqlite-files.js";
56
import {
67
ensureMigrationDir,
78
fileExists,
@@ -26,6 +27,105 @@ import {
2627
} from "./state-migrations.session-store.js";
2728
import type { LegacyStateDetection } from "./state-migrations.types.js";
2829

30+
type LegacyAgentRelocation = NonNullable<LegacyStateDetection["agentDir"]["relocation"]>;
31+
32+
function pathEntryExists(pathname: string): boolean {
33+
try {
34+
fs.lstatSync(pathname);
35+
return true;
36+
} catch (error) {
37+
const code = (error as NodeJS.ErrnoException).code;
38+
if (code === "ENOENT") {
39+
return false;
40+
}
41+
if (code === "ENOTDIR") {
42+
return true;
43+
}
44+
throw error;
45+
}
46+
}
47+
48+
function sourceRelocationBlocker(relocation: LegacyAgentRelocation): string | undefined {
49+
try {
50+
const source = fs.lstatSync(relocation.sourcePath);
51+
if (relocation.kind === "database") {
52+
return source.isFile()
53+
? undefined
54+
: `Refused relocating agent database because source ${relocation.sourcePath} is no longer a regular file.`;
55+
}
56+
if (!source.isDirectory()) {
57+
return `Refused relocating legacy agent directory because source ${relocation.sourcePath} is no longer a directory.`;
58+
}
59+
const database = fs.lstatSync(path.join(relocation.sourcePath, "openclaw-agent.sqlite"));
60+
return database.isFile()
61+
? undefined
62+
: `Refused relocating legacy agent directory because ${relocation.sourcePath} no longer contains a regular agent database.`;
63+
} catch (error) {
64+
return `Refused relocating agent database because source ${relocation.sourcePath} is unavailable: ${String(error)}.`;
65+
}
66+
}
67+
68+
/**
69+
* Reject partial SQLite moves and any destination that would turn a rename
70+
* into a merge. The migration lock serializes OpenClaw writers, not outside
71+
* filesystem changes, so callers check this before dependent session moves.
72+
*/
73+
export function getLegacyAgentRelocationBlocker(
74+
relocation: LegacyAgentRelocation,
75+
): string | undefined {
76+
const sourceBlocker = sourceRelocationBlocker(relocation);
77+
if (sourceBlocker) {
78+
return sourceBlocker;
79+
}
80+
if (relocation.kind === "directory") {
81+
// One same-filesystem directory rename keeps the primary, WAL, SHM, and
82+
// rollback journal together as one SQLite generation.
83+
return pathEntryExists(relocation.targetPath)
84+
? `Refused relocating legacy agent directory because destination already exists at ${relocation.targetPath}; left source files untouched.`
85+
: undefined;
86+
}
87+
88+
if (relocation.sourceHasDataSidecars) {
89+
return "Refused relocating misplaced agent database because SQLite sidecars are present or ambiguous; left source files untouched.";
90+
}
91+
return resolveSqliteDatabaseFilePaths(relocation.targetPath).some((pathname) =>
92+
pathEntryExists(pathname),
93+
)
94+
? "Refused relocating misplaced agent database because a canonical destination or SQLite sidecar already exists; left source files untouched."
95+
: undefined;
96+
}
97+
98+
export function clearTransientAgentDatabaseSidecars(
99+
relocation: LegacyAgentRelocation,
100+
): string | undefined {
101+
if (relocation.kind === "directory") {
102+
return undefined;
103+
}
104+
105+
const [, walPath, shmPath, journalPath] = resolveSqliteDatabaseFilePaths(relocation.sourcePath);
106+
for (const [pathname, containsRecoveryData] of [
107+
[walPath, true],
108+
[shmPath, false],
109+
[journalPath, true],
110+
] as const) {
111+
if (!pathname) {
112+
continue;
113+
}
114+
try {
115+
const stat = fs.lstatSync(pathname);
116+
if (!stat.isFile() || (containsRecoveryData && stat.size > 0)) {
117+
return "Refused relocating misplaced agent database because SQLite sidecars appeared after detection; left source files untouched.";
118+
}
119+
fs.unlinkSync(pathname);
120+
} catch (error) {
121+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
122+
return `Failed clearing transient SQLite sidecar ${pathname}: ${String(error)}`;
123+
}
124+
}
125+
}
126+
return undefined;
127+
}
128+
29129
function normalizeMergedSessionStore(
30130
merged: Record<string, SessionEntryLike>,
31131
protectedKeys: ReadonlySet<string>,
@@ -55,9 +155,10 @@ export async function migrateLegacySessions(
55155
): Promise<{ changes: string[]; warnings: string[] }> {
56156
const changes: string[] = [];
57157
const warnings: string[] = [];
58-
if (!detected.sessions.hasLegacy) {
158+
if (!detected.sessions.hasLegacy || detected.agentDir.migrationBlockedReason) {
59159
return { changes, warnings };
60160
}
161+
const targetAgentId = detected.targetAgentId;
61162

62163
ensureMigrationDir(detected.sessions.targetDir);
63164

@@ -113,7 +214,7 @@ export async function migrateLegacySessions(
113214

114215
const canonicalizedTarget = canonicalizeSessionStore({
115216
store: targetStore,
116-
agentId: detected.targetAgentId,
217+
agentId: targetAgentId,
117218
mainKey: detected.targetMainKey,
118219
scope: detected.targetScope,
119220
skipCrossAgentRemap: detected.sessions.preserveAmbiguousKeys,
@@ -123,7 +224,7 @@ export async function migrateLegacySessions(
123224
});
124225
const canonicalizedLegacy = canonicalizeSessionStore({
125226
store: legacyStore,
126-
agentId: detected.targetAgentId,
227+
agentId: targetAgentId,
127228
mainKey: detected.targetMainKey,
128229
scope: detected.targetScope,
129230
preserveCanonicalAgentOwner: true,
@@ -162,7 +263,7 @@ export async function migrateLegacySessions(
162263
}
163264

164265
const mainKey = buildAgentMainSessionKey({
165-
agentId: detected.targetAgentId,
266+
agentId: targetAgentId,
166267
mainKey: detected.targetMainKey,
167268
});
168269
let migratedDirectChatKey: string | undefined;
@@ -251,7 +352,7 @@ export async function migrateLegacySessions(
251352
}
252353
try {
253354
fs.renameSync(from, to);
254-
changes.push(`Moved ${entry.name} → agents/${detected.targetAgentId}/sessions`);
355+
changes.push(`Moved ${entry.name} → agents/${targetAgentId}/sessions`);
255356
} catch (err) {
256357
warnings.push(`Failed moving ${from}: ${String(err)}`);
257358
}
@@ -291,6 +392,48 @@ export async function migrateLegacyAgentDir(
291392
if (!detected.agentDir.hasLegacy) {
292393
return { changes, warnings };
293394
}
395+
const targetAgentId = detected.targetAgentId;
396+
if (detected.agentDir.migrationBlockedReason) {
397+
return { changes, warnings: [detected.agentDir.migrationBlockedReason] };
398+
}
399+
if (detected.agentDir.relocation) {
400+
const { relocation } = detected.agentDir;
401+
const relocationBlocker = getLegacyAgentRelocationBlocker(relocation);
402+
if (relocationBlocker) {
403+
return {
404+
changes,
405+
warnings: [relocationBlocker],
406+
};
407+
}
408+
const transientSidecarWarning = clearTransientAgentDatabaseSidecars(relocation);
409+
if (transientSidecarWarning) {
410+
return {
411+
changes,
412+
warnings: [transientSidecarWarning],
413+
};
414+
}
415+
try {
416+
ensureMigrationDir(path.dirname(relocation.targetPath));
417+
try {
418+
fs.renameSync(relocation.sourcePath, relocation.targetPath);
419+
} catch (error) {
420+
warnings.push(
421+
`Failed relocating agent database from ${relocation.sourcePath} to ${relocation.targetPath}; the registry relocation intent remains prepared. Rerun openclaw doctor --fix: ${String(error)}`,
422+
);
423+
return { changes, warnings };
424+
}
425+
changes.push(
426+
relocation.kind === "directory"
427+
? `Moved agent dir → agents/${targetAgentId}/agent`
428+
: `Relocated agent database → ${path.relative(detected.stateDir, relocation.targetPath)}`,
429+
);
430+
} catch (err) {
431+
warnings.push(`Failed relocating agent database: ${String(err)}`);
432+
}
433+
if (relocation.kind === "directory" || warnings.length > 0) {
434+
return { changes, warnings };
435+
}
436+
}
294437

295438
ensureMigrationDir(detected.agentDir.targetDir);
296439

@@ -303,7 +446,7 @@ export async function migrateLegacyAgentDir(
303446
}
304447
try {
305448
fs.renameSync(from, to);
306-
changes.push(`Moved agent file ${entry.name} → agents/${detected.targetAgentId}/agent`);
449+
changes.push(`Moved agent file ${entry.name} → agents/${targetAgentId}/agent`);
307450
} catch (err) {
308451
warnings.push(`Failed moving ${from}: ${String(err)}`);
309452
}
@@ -314,7 +457,7 @@ export async function migrateLegacyAgentDir(
314457
const backupDir = path.join(
315458
detected.stateDir,
316459
"agents",
317-
detected.targetAgentId,
460+
targetAgentId,
318461
`agent.legacy-${now()}`,
319462
);
320463
try {

‎src/infra/state-migrations.types.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ export type LegacyStateDetection = {
4242
legacyDir: string;
4343
targetDir: string;
4444
hasLegacy: boolean;
45+
migrationBlockedReason?: string;
46+
relocation?:
47+
| { kind: "directory"; ownerAgentId: string; sourcePath: string; targetPath: string }
48+
| {
49+
kind: "database";
50+
ownerAgentId: string;
51+
sourcePath: string;
52+
targetPath: string;
53+
sourceHasDataSidecars: boolean;
54+
};
4555
};
4656
pluginPlans?: {
4757
hasLegacy: boolean;

0 commit comments

Comments
 (0)