-
-
Notifications
You must be signed in to change notification settings - Fork 80.9k
Expand file tree
/
Copy pathdoctor-config-preflight.ts
More file actions
362 lines (340 loc) · 12.9 KB
/
Copy pathdoctor-config-preflight.ts
File metadata and controls
362 lines (340 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/** Config preflight for doctor: legacy config/state migration, recovery, and snapshot loading. */
import fs from "node:fs/promises";
import path from "node:path";
import { note } from "../../packages/terminal-core/src/note.js";
import {
readConfigFileSnapshot,
recoverConfigFromJsonRootSuffix,
recoverConfigFromLastKnownGood,
} from "../config/io.js";
import { formatConfigIssueLines } from "../config/issue-format.js";
import type { ConfigFileSnapshot, LegacyConfigIssue } from "../config/types.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { isTruthyEnvValue } from "../infra/env.js";
import type { StartupMigrationLease } from "../infra/startup-migration-checkpoint.js";
import { createLazyRuntimeModule } from "../shared/lazy-runtime.js";
import { resolveHomeDir } from "../utils.js";
import { noteIncludeConfinementWarning } from "./doctor-config-analysis.js";
import { findDoctorLegacyConfigIssues } from "./doctor/shared/legacy-config-issues.js";
import { resolveStateMigrationConfigInput } from "./doctor/shared/legacy-config-state-migration-input.js";
const loadDoctorStateMigrations = createLazyRuntimeModule(
() => import("./doctor-state-migrations.js"),
);
const loadDoctorCron = createLazyRuntimeModule(() => import("./doctor/cron/index.js"));
async function maybeMigrateLegacyConfig(): Promise<string[]> {
const changes: string[] = [];
const home = resolveHomeDir();
if (!home) {
return changes;
}
const targetDir = path.join(home, ".openclaw");
const targetPath = path.join(targetDir, "openclaw.json");
try {
await fs.access(targetPath);
return changes;
} catch {
// missing config
}
const legacyCandidates = [path.join(home, ".clawdbot", "clawdbot.json")];
let legacyPath: string | null = null;
for (const candidate of legacyCandidates) {
try {
await fs.access(candidate);
legacyPath = candidate;
break;
} catch {
// continue
}
}
if (!legacyPath) {
return changes;
}
await fs.mkdir(targetDir, { recursive: true });
try {
await fs.copyFile(legacyPath, targetPath, fs.constants.COPYFILE_EXCL);
changes.push(`Migrated legacy config: ${legacyPath} -> ${targetPath}`);
} catch {
// If it already exists, skip silently.
}
return changes;
}
export type DoctorConfigPreflightResult = {
snapshot: Awaited<ReturnType<typeof readConfigFileSnapshot>>;
baseConfig: OpenClawConfig;
};
function collectDoctorLegacyIssues(
snapshot: Awaited<ReturnType<typeof readConfigFileSnapshot>>,
): LegacyConfigIssue[] {
if (!snapshot.exists) {
return [];
}
const resolvedRaw = snapshot.sourceConfig ?? snapshot.config ?? {};
const sourceRaw = snapshot.parsed ?? resolvedRaw;
return findDoctorLegacyConfigIssues(resolvedRaw, sourceRaw);
}
function addDoctorLegacyIssues(
snapshot: Awaited<ReturnType<typeof readConfigFileSnapshot>>,
): Awaited<ReturnType<typeof readConfigFileSnapshot>> {
const legacyIssues = collectDoctorLegacyIssues(snapshot);
if (legacyIssues.length === 0) {
return snapshot;
}
return { ...snapshot, legacyIssues };
}
/** Returns true during updater-managed config rewrites where plugin validation may be stale. */
export function shouldSkipPluginValidationForDoctorConfigPreflight(
env: NodeJS.ProcessEnv = process.env,
): boolean {
return isTruthyEnvValue(env.OPENCLAW_UPDATE_IN_PROGRESS);
}
function noteStateMigrationResult(result: {
changes: string[];
warnings: string[];
notices?: string[];
}): void {
if (result.changes.length > 0) {
note(result.changes.map((entry) => `- ${entry}`).join("\n"), "Doctor changes");
}
const notices = result.notices ?? [];
if (notices.length > 0) {
note(notices.map((entry) => `- ${entry}`).join("\n"), "Doctor notices");
}
if (result.warnings.length > 0) {
note(result.warnings.map((entry) => `- ${entry}`).join("\n"), "Doctor warnings");
}
}
async function runStartupUpgradeConvergence(params: {
cfg: OpenClawConfig;
env: NodeJS.ProcessEnv;
}): Promise<string[]> {
const { runPostCorePluginConvergence } =
await import("../cli/update-cli/post-core-plugin-convergence.js");
const convergence = await runPostCorePluginConvergence({
cfg: params.cfg,
env: params.env,
});
if (convergence.changes.length > 0) {
note(convergence.changes.map((entry) => `- ${entry}`).join("\n"), "Doctor changes");
}
const notices = convergence.notices ?? [];
if (notices.length > 0) {
note(
notices.map((notice) => `- ${notice.message} ${notice.guidance.join(" ")}`.trim()).join("\n"),
"Doctor notices",
);
}
const warnings = convergence.warnings.map((warning) =>
`${warning.message} ${warning.guidance.join(" ")}`.trim(),
);
if (warnings.length > 0) {
note(warnings.map((warning) => `- ${warning}`).join("\n"), "Doctor warnings");
}
return warnings;
}
function formatStartupMigrationFailure(params: { warnings: string[]; blockers: string[] }): string {
const details = [
...params.warnings.map((warning) => `- ${warning}`),
...params.blockers.map((blocker) => `- ${blocker}`),
];
return [
"OpenClaw startup migrations did not complete cleanly; refusing to report the gateway ready.",
...details,
'Run "openclaw doctor --fix" against the mounted state/config, then restart the container.',
].join("\n");
}
/**
* Runs early doctor config checks before the main config repair flow.
*
* It may migrate legacy state/config paths, recover corrupt target config when requested, and
* returns the best-effort config snapshot used by later doctor checks.
*/
export async function runDoctorConfigPreflight(
options: {
migrateState?: boolean;
migrateLegacyConfig?: boolean;
repairPrefixedConfig?: boolean;
recoverCorruptTargetStore?: boolean;
invalidConfigNote?: string | false;
beforeStateMigrations?: (snapshot?: ConfigFileSnapshot) => Promise<boolean>;
requireStartupMigrationCheckpoint?: boolean;
} = {},
): Promise<DoctorConfigPreflightResult> {
const stateMigrations =
options.migrateState !== false ? await loadDoctorStateMigrations() : undefined;
const startupCheckpoint =
options.requireStartupMigrationCheckpoint === true
? await import("../infra/startup-migration-checkpoint.js")
: undefined;
let shouldRecordStartupCheckpoint = false;
let startupMigrationLease: StartupMigrationLease | undefined;
let startupMigrationHeartbeat: ReturnType<typeof setInterval> | undefined;
let startupMigrationHeartbeatError: unknown;
const startupMigrationWarnings: string[] = [];
const noteStartupStateMigrationResult = (result: {
changes: string[];
warnings: string[];
notices?: string[];
}) => {
startupMigrationWarnings.push(...result.warnings);
noteStateMigrationResult(result);
};
try {
// The gateway uses this last-moment guard to ensure its prepared config did not change before
// any automatic migration mutates state. A rejected guard skips every state migration stage.
const stateMigrationsAllowed =
stateMigrations === undefined ||
options.beforeStateMigrations === undefined ||
(await options.beforeStateMigrations());
if (startupCheckpoint && !stateMigrationsAllowed) {
throw new Error(
"OpenClaw startup migrations were skipped because the selected config changed during startup; refusing to report the gateway ready. Retry startup so the new config can be validated.",
);
}
if (startupCheckpoint) {
shouldRecordStartupCheckpoint = startupCheckpoint.needsStartupMigrationCheckpoint({
env: process.env,
});
startupMigrationLease = shouldRecordStartupCheckpoint
? startupCheckpoint.acquireStartupMigrationLease({ env: process.env })
: undefined;
if (startupMigrationLease) {
startupMigrationHeartbeat = setInterval(() => {
try {
startupMigrationLease?.heartbeat();
} catch (error) {
startupMigrationHeartbeatError = error;
}
}, 60_000);
startupMigrationHeartbeat.unref?.();
}
}
if (stateMigrations && stateMigrationsAllowed) {
const { autoMigrateLegacyStateDir } = stateMigrations;
const stateDirResult = await autoMigrateLegacyStateDir({ env: process.env });
noteStartupStateMigrationResult(stateDirResult);
}
if (options.migrateLegacyConfig !== false) {
const legacyConfigChanges = await maybeMigrateLegacyConfig();
if (legacyConfigChanges.length > 0) {
note(legacyConfigChanges.map((entry) => `- ${entry}`).join("\n"), "Doctor changes");
}
}
const readOptions = {
skipPluginValidation: shouldSkipPluginValidationForDoctorConfigPreflight(),
};
let snapshot = addDoctorLegacyIssues(await readConfigFileSnapshot(readOptions));
if (options.repairPrefixedConfig === true && snapshot.exists && !snapshot.valid) {
if (await recoverConfigFromJsonRootSuffix(snapshot)) {
note(
"Removed non-JSON prefix from openclaw.json; original saved as .clobbered.*.",
"Config",
);
snapshot = addDoctorLegacyIssues(await readConfigFileSnapshot(readOptions));
} else if (
await recoverConfigFromLastKnownGood({ snapshot, reason: "doctor-invalid-config" })
) {
note(
"Restored openclaw.json from last-known-good; original saved as .clobbered.*.",
"Config",
);
snapshot = addDoctorLegacyIssues(await readConfigFileSnapshot(readOptions));
}
}
const invalidConfigNote =
options.invalidConfigNote ?? "Config invalid; doctor will run with best-effort config.";
if (
invalidConfigNote &&
snapshot.exists &&
!snapshot.valid &&
snapshot.legacyIssues.length === 0
) {
note(invalidConfigNote, "Config");
noteIncludeConfinementWarning(snapshot);
}
const warnings = snapshot.warnings ?? [];
if (warnings.length > 0) {
note(formatConfigIssueLines(warnings, "-").join("\n"), "Config warnings");
}
const baseConfig = snapshot.sourceConfig ?? snapshot.config ?? {};
const stateMigrationInput = resolveStateMigrationConfigInput({ snapshot, baseConfig });
const configStateMigrationsAllowed =
stateMigrations !== undefined &&
stateMigrationsAllowed &&
(options.beforeStateMigrations === undefined ||
(await options.beforeStateMigrations(snapshot)));
if (stateMigrations && configStateMigrationsAllowed) {
const {
autoMigrateLegacyState,
autoMigrateLegacyPluginDoctorState,
autoMigrateLegacyTaskStateSidecars,
} = stateMigrations;
if (stateMigrationInput) {
if (stateMigrationInput.cfg) {
const { repairLegacyCronStoreWithoutPrompt } = await loadDoctorCron();
const cronResult = await repairLegacyCronStoreWithoutPrompt({
cfg: stateMigrationInput.cfg,
});
noteStartupStateMigrationResult(cronResult);
noteStartupStateMigrationResult(
await autoMigrateLegacyState({
cfg: stateMigrationInput.cfg,
...(stateMigrationInput.pluginDoctorConfig
? { pluginDoctorConfig: stateMigrationInput.pluginDoctorConfig }
: {}),
env: process.env,
recoverCorruptTargetStore: options.recoverCorruptTargetStore,
}),
);
} else if (stateMigrationInput.pluginDoctorConfig) {
noteStartupStateMigrationResult(
await autoMigrateLegacyPluginDoctorState({
config: stateMigrationInput.pluginDoctorConfig,
env: process.env,
}),
);
noteStartupStateMigrationResult(
await autoMigrateLegacyTaskStateSidecars({ env: process.env }),
);
}
} else {
noteStartupStateMigrationResult(
await autoMigrateLegacyTaskStateSidecars({ env: process.env }),
);
}
}
if (shouldRecordStartupCheckpoint) {
if (startupMigrationHeartbeatError) {
throw startupMigrationHeartbeatError instanceof Error
? startupMigrationHeartbeatError
: new Error("OpenClaw startup migration lease heartbeat failed.");
}
const blockers =
startupMigrationWarnings.length > 0
? []
: snapshot.valid
? await runStartupUpgradeConvergence({ cfg: baseConfig, env: process.env })
: ['OpenClaw config is invalid; run "openclaw doctor --fix" before startup.'];
if (startupMigrationWarnings.length > 0 || blockers.length > 0) {
throw new Error(
formatStartupMigrationFailure({
warnings: startupMigrationWarnings,
blockers,
}),
);
}
startupCheckpoint?.recordSuccessfulStartupMigrations({
env: process.env,
lease: startupMigrationLease,
});
}
return {
snapshot,
baseConfig,
};
} finally {
if (startupMigrationHeartbeat) {
clearInterval(startupMigrationHeartbeat);
}
startupMigrationLease?.release();
}
}