Skip to content

Commit 1c871de

Browse files
committed
fix(config): preserve plugin metadata for missing config
Punchcard-Session: amber-orchard-valley-s4
1 parent 50c7444 commit 1c871de

3 files changed

Lines changed: 202 additions & 11 deletions

File tree

‎src/commands/doctor-config-preflight.process.test.ts‎

Lines changed: 117 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import fs from "node:fs";
44
import os from "node:os";
55
import path from "node:path";
66
import { DatabaseSync } from "node:sqlite";
7+
import { pathToFileURL } from "node:url";
78
import { afterEach, describe, expect, it } from "vitest";
89
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
910
import type { OpenClawConfig } from "../config/types.openclaw.js";
@@ -18,14 +19,48 @@ const STARTUP_REFUSAL =
1819
"OpenClaw startup migrations did not complete cleanly; refusing to report the gateway ready.";
1920
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
2021

21-
function runIsolatedModuleScript(env: NodeJS.ProcessEnv, script: string) {
22-
return spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "--eval", script], {
23-
cwd: path.resolve("."),
24-
encoding: "utf8",
25-
env,
26-
maxBuffer: 4 * 1024 * 1024,
27-
timeout: 30_000,
28-
});
22+
function runIsolatedModuleScript(
23+
env: NodeJS.ProcessEnv,
24+
script: string,
25+
options: { runtimeRoot?: string; timeoutMs?: number } = {},
26+
) {
27+
return spawnSync(
28+
process.execPath,
29+
[
30+
...(options.runtimeRoot ? ["--preserve-symlinks"] : []),
31+
"--import",
32+
"tsx",
33+
"--input-type=module",
34+
"--eval",
35+
script,
36+
],
37+
{
38+
cwd: options.runtimeRoot ?? path.resolve("."),
39+
encoding: "utf8",
40+
env,
41+
maxBuffer: 4 * 1024 * 1024,
42+
timeout: options.timeoutMs ?? 30_000,
43+
},
44+
);
45+
}
46+
47+
function createSourceRuntime(root: string): string {
48+
const runtimeRoot = path.join(root, "runtime");
49+
fs.mkdirSync(path.join(runtimeRoot, "dist"), { recursive: true });
50+
for (const dirname of ["node_modules", "packages", "scripts", "src"]) {
51+
fs.symlinkSync(
52+
path.resolve(dirname),
53+
path.join(runtimeRoot, dirname),
54+
process.platform === "win32" ? "junction" : "dir",
55+
);
56+
}
57+
fs.copyFileSync(path.resolve("package.json"), path.join(runtimeRoot, "package.json"));
58+
fs.copyFileSync(path.resolve("tsconfig.json"), path.join(runtimeRoot, "tsconfig.json"));
59+
fs.writeFileSync(
60+
path.join(runtimeRoot, "dist", "build-info.json"),
61+
JSON.stringify({ builtAt: "2026-08-05T00:00:00.000Z" }),
62+
);
63+
return runtimeRoot;
2964
}
3065

3166
function seedPluginStateConflict(stateDir: string): void {
@@ -138,6 +173,80 @@ describe("gateway startup-migration refusal", () => {
138173
}
139174
}, 45_000);
140175

176+
it("reuses the state-migration checkpoint when the config file remains absent", async () => {
177+
const root = await fs.promises.realpath(tempDirs.make("openclaw-configless-checkpoint-"));
178+
const runtimeRoot = createSourceRuntime(root);
179+
const stateDir = path.join(root, "state");
180+
const configPath = path.join(root, "openclaw.json");
181+
const env: NodeJS.ProcessEnv = {
182+
...process.env,
183+
HOME: root,
184+
USERPROFILE: root,
185+
OPENCLAW_BUNDLED_PLUGINS_DIR: path.join(root, "bundled"),
186+
OPENCLAW_CONFIG_PATH: configPath,
187+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
188+
OPENCLAW_STATE_DIR: stateDir,
189+
OPENCLAW_TEST_FAST: "1",
190+
NO_COLOR: "1",
191+
};
192+
delete env.NODE_ENV;
193+
delete env.OPENCLAW_HOME;
194+
delete env.VITEST;
195+
delete env.VITEST_POOL_ID;
196+
delete env.VITEST_WORKER_ID;
197+
198+
const preflightUrl = pathToFileURL(
199+
path.join(runtimeRoot, "src", "commands", "doctor-config-preflight.ts"),
200+
).href;
201+
const checkpointUrl = pathToFileURL(
202+
path.join(runtimeRoot, "src", "infra", "startup-migration-checkpoint.ts"),
203+
).href;
204+
const script = `
205+
const steps = [];
206+
const { runDoctorConfigPreflight } = await import(${JSON.stringify(preflightUrl)});
207+
const { hasActiveStartupMigrationLease } = await import(${JSON.stringify(checkpointUrl)});
208+
await runDoctorConfigPreflight({
209+
migrateLegacyConfig: false,
210+
invalidConfigNote: false,
211+
observe: false,
212+
requireStateMigrationCheckpoint: true,
213+
measure: async (name, run) => {
214+
steps.push(name);
215+
return await run();
216+
},
217+
});
218+
console.log("__RESULT__" + JSON.stringify({
219+
activeLease: hasActiveStartupMigrationLease({ env: process.env }),
220+
stateMigrationsImported: steps.includes(
221+
"doctor.config-preflight.state-migrations-import",
222+
),
223+
}));
224+
`;
225+
const run = () =>
226+
runIsolatedModuleScript(env, script, {
227+
runtimeRoot,
228+
timeoutMs: 60_000,
229+
});
230+
const readResult = (result: ReturnType<typeof runIsolatedModuleScript>) => {
231+
expect(result.error, `${result.stderr}\n${result.stdout}`).toBeUndefined();
232+
expect(result.status, `${result.stderr}\n${result.stdout}`).toBe(0);
233+
expect(result.signal, `${result.stderr}\n${result.stdout}`).toBeNull();
234+
const resultLine = result.stdout.split("\n").find((line) => line.startsWith("__RESULT__"));
235+
expect(resultLine, `${result.stderr}\n${result.stdout}`).toBeDefined();
236+
return JSON.parse(resultLine!.slice("__RESULT__".length)) as {
237+
activeLease: boolean;
238+
stateMigrationsImported: boolean;
239+
};
240+
};
241+
242+
const first = readResult(run());
243+
const second = readResult(run());
244+
245+
expect(first).toEqual({ activeLease: false, stateMigrationsImported: true });
246+
expect(second).toEqual({ activeLease: false, stateMigrationsImported: false });
247+
expect(fs.existsSync(configPath)).toBe(false);
248+
}, 150_000);
249+
141250
it("persists a refreshed legacy plugin index for the next process", async () => {
142251
const root = await fs.promises.realpath(tempDirs.make("openclaw-plugin-index-checkpoint-"));
143252
const stateDir = path.join(root, "state");

‎src/config/io.snapshot.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
5+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
6+
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
7+
import { createConfigIoContext } from "./io.context.js";
8+
import {
9+
readConfigFileSnapshotFromContext,
10+
readConfigFileSnapshotWithPluginMetadataFromContext,
11+
} from "./io.snapshot.js";
12+
13+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
14+
15+
afterEach(() => {
16+
clearPluginMetadataLifecycleCaches();
17+
closeOpenClawStateDatabaseForTest();
18+
});
19+
20+
function createContext(root: string) {
21+
const configPath = path.join(root, "openclaw.json");
22+
const env: NodeJS.ProcessEnv = {
23+
HOME: root,
24+
USERPROFILE: root,
25+
OPENCLAW_CONFIG_PATH: configPath,
26+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
27+
OPENCLAW_STATE_DIR: path.join(root, "state"),
28+
VITEST: "true",
29+
};
30+
return createConfigIoContext({
31+
configPath,
32+
env,
33+
homedir: () => root,
34+
observe: false,
35+
});
36+
}
37+
38+
describe("config snapshot plugin metadata", () => {
39+
it("loads metadata for an explicit valid missing-config read without changing plain reads", async () => {
40+
const root = tempDirs.make("openclaw-config-snapshot-metadata-");
41+
const context = createContext(root);
42+
const loader = vi.spyOn(context, "createValidationPluginMetadataSnapshotLoader");
43+
44+
const plainSnapshot = await readConfigFileSnapshotFromContext(context);
45+
46+
expect(plainSnapshot).toMatchObject({ exists: false, valid: true });
47+
expect(loader).not.toHaveBeenCalled();
48+
49+
const result = await readConfigFileSnapshotWithPluginMetadataFromContext(context);
50+
51+
expect(result.snapshot).toMatchObject({ exists: false, valid: true });
52+
expect(loader).toHaveBeenCalledOnce();
53+
expect(result.pluginMetadataSnapshot?.configFingerprint).toMatch(/^[a-f0-9]{64}$/u);
54+
expect(result.pluginMetadataSnapshot?.index).toMatchObject({
55+
version: 1,
56+
hostContractVersion: expect.any(String),
57+
plugins: expect.any(Array),
58+
});
59+
});
60+
61+
it("does not invent plugin metadata for invalid snapshots", async () => {
62+
const root = tempDirs.make("openclaw-config-snapshot-invalid-");
63+
const context = createContext(root);
64+
fs.writeFileSync(context.configPath, "{ invalid", "utf8");
65+
const loader = vi.spyOn(context, "createValidationPluginMetadataSnapshotLoader");
66+
67+
const result = await readConfigFileSnapshotWithPluginMetadataFromContext(context);
68+
69+
expect(result.snapshot.valid).toBe(false);
70+
expect(result.pluginMetadataSnapshot).toBeUndefined();
71+
expect(loader).not.toHaveBeenCalled();
72+
});
73+
});

‎src/config/io.snapshot.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -370,11 +370,20 @@ export async function readConfigFileSnapshotWithPluginMetadataFromContext(
370370
recoverSuspicious: options.recoverSuspicious === true,
371371
allowSuspiciousRecovery: options.allowSuspiciousRecovery,
372372
});
373+
const pluginMetadataSnapshot =
374+
result.pluginMetadataSnapshot ??
375+
(result.snapshot.valid
376+
? context
377+
.createValidationPluginMetadataSnapshotLoader({
378+
effectiveConfigRaw: result.snapshot.sourceConfig,
379+
env: context.deps.env,
380+
allowCurrentPluginMetadata: options.allowCurrentPluginMetadata,
381+
})
382+
.load(result.snapshot.sourceConfig)
383+
: undefined);
373384
return {
374385
snapshot: result.snapshot,
375-
...(result.pluginMetadataSnapshot
376-
? { pluginMetadataSnapshot: result.pluginMetadataSnapshot }
377-
: {}),
386+
...(pluginMetadataSnapshot ? { pluginMetadataSnapshot } : {}),
378387
};
379388
}
380389

0 commit comments

Comments
 (0)