Skip to content

Commit 6334c31

Browse files
authored
fix(cli): avoid unnecessary migrations on pristine startup (#134090)
* fix(cli): avoid unnecessary migrations on pristine startup * test(agents): keep prompt fixtures on prepared provider handles * test(agents): derive prompt fixture handle identity from attempt * test(doctor): separate pristine startup process coverage
1 parent 7f989bc commit 6334c31

6 files changed

Lines changed: 337 additions & 150 deletions

‎src/agents/embedded-agent-runner/run/attempt-system-prompt.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@ import type { AgentTool } from "../../runtime/index.js";
88
import { makeProviderModelFixture } from "../../test-helpers/provider-model-fixture.js";
99
import type { EmbeddedRunAttemptParams } from "./types.js";
1010

11+
// Prompt assembly consumes a prepared provider handle; discovery belongs to attempt setup.
12+
vi.mock("../../../plugins/providers.runtime.js", () => {
13+
const rejectProviderDiscovery = () => {
14+
throw new Error("Prompt fixture unexpectedly discovered provider runtime");
15+
};
16+
return {
17+
isPluginProvidersLoadInFlight: rejectProviderDiscovery,
18+
resolvePluginProvidersCore: rejectProviderDiscovery,
19+
};
20+
});
21+
1122
let buildAttemptSystemPrompt: typeof import("./attempt-system-prompt.js").buildAttemptSystemPrompt;
1223
let prepareEmbeddedAttemptSystemPrompt: typeof import("./attempt-system-prompt-prepare.js").prepareEmbeddedAttemptSystemPrompt;
1324
const tempDirs = useAutoCleanupTempDirTracker(afterEach);

‎src/cli/run-main.exit.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2621,7 +2621,7 @@ describe("runCli exit behavior", () => {
26212621

26222622
it.each([
26232623
["worker", { observe: false, pluginValidation: "core-only" }],
2624-
["run", { skipPluginValidation: true }],
2624+
["run", { observe: false, skipPluginValidation: true }],
26252625
])(
26262626
"preserves node %s config ownership when startup tracing is enabled",
26272627
async (subcommand, readOptions) => {

‎src/cli/run-main.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1273,11 +1273,9 @@ async function runCliWithPreparedOutputMode(
12731273
return configIo.readSourceConfigBestEffort();
12741274
}
12751275
const readOptions: Parameters<typeof configIo.readBestEffortConfig>[0] = {
1276-
...(isolateProxyConfigEnv ? { isolateEnv: true, observe: false } : {}),
1277-
...(bestEffortConfigStartupPolicy.skipConfigGuard ||
1278-
bestEffortConfigStartupPolicy.validateConfigOnly
1279-
? { observe: false }
1280-
: {}),
1276+
// Routing must not create state before Doctor decides whether migrations are needed.
1277+
observe: false,
1278+
...(isolateProxyConfigEnv ? { isolateEnv: true } : {}),
12811279
...(bestEffortConfigStartupPolicy.validateConfigOnly
12821280
? { pluginValidation: "core-only" }
12831281
: { skipPluginValidation: true }),
Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
// Process regressions for pristine startup eligibility and deferred config observation.
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { pathToFileURL } from "node:url";
5+
import { afterAll, describe, expect, it } from "vitest";
6+
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
7+
import type { OpenClawConfig } from "../config/types.openclaw.js";
8+
import { hasActiveStartupMigrationLease } from "../infra/startup-migration-checkpoint.js";
9+
import {
10+
createSourceRuntime,
11+
runIsolatedModuleScript,
12+
} from "./doctor-config-preflight.process.test-support.js";
13+
14+
const tempDirs = useAutoCleanupTempDirTracker(afterAll);
15+
16+
describe("gateway startup-migration refusal", () => {
17+
it("skips state-only checkpoint work when config and state remain absent", async () => {
18+
const root = await fs.promises.realpath(tempDirs.make("openclaw-configless-checkpoint-"));
19+
const runtimeRoot = createSourceRuntime(root);
20+
const stateDir = path.join(root, "state");
21+
const configPath = path.join(root, "openclaw.json");
22+
const env: NodeJS.ProcessEnv = {
23+
...process.env,
24+
HOME: root,
25+
USERPROFILE: root,
26+
OPENCLAW_BUNDLED_PLUGINS_DIR: path.join(root, "bundled"),
27+
OPENCLAW_CONFIG_PATH: configPath,
28+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
29+
OPENCLAW_STATE_DIR: stateDir,
30+
OPENCLAW_TEST_FAST: "1",
31+
NO_COLOR: "1",
32+
};
33+
delete env.NODE_ENV;
34+
delete env.OPENCLAW_HOME;
35+
delete env.VITEST;
36+
delete env.VITEST_POOL_ID;
37+
delete env.VITEST_WORKER_ID;
38+
39+
const preflightUrl = pathToFileURL(
40+
path.join(runtimeRoot, "src", "commands", "doctor-config-preflight.ts"),
41+
).href;
42+
const checkpointUrl = pathToFileURL(
43+
path.join(runtimeRoot, "src", "infra", "startup-migration-checkpoint.ts"),
44+
).href;
45+
const script = `
46+
const steps = [];
47+
const { runDoctorConfigPreflight } = await import(${JSON.stringify(preflightUrl)});
48+
const { hasActiveStartupMigrationLease } = await import(${JSON.stringify(checkpointUrl)});
49+
await runDoctorConfigPreflight({
50+
migrateLegacyConfig: false,
51+
invalidConfigNote: false,
52+
observe: false,
53+
requireStateMigrationCheckpoint: true,
54+
measure: async (name, run) => {
55+
steps.push(name);
56+
return await run();
57+
},
58+
});
59+
console.log("__RESULT__" + JSON.stringify({
60+
activeLease: hasActiveStartupMigrationLease({ env: process.env }),
61+
stateMigrationsImported: steps.includes(
62+
"doctor.config-preflight.state-migrations-import",
63+
),
64+
}));
65+
`;
66+
const run = () =>
67+
runIsolatedModuleScript(env, script, {
68+
runtimeRoot,
69+
timeoutMs: 60_000,
70+
});
71+
const readResult = (result: Awaited<ReturnType<typeof runIsolatedModuleScript>>) => {
72+
const resultLine = result.stdout.split("\n").find((line) => line.startsWith("__RESULT__"));
73+
expect(resultLine, `${result.stderr}\n${result.stdout}`).toBeDefined();
74+
return JSON.parse(resultLine!.slice("__RESULT__".length)) as {
75+
activeLease: boolean;
76+
stateMigrationsImported: boolean;
77+
};
78+
};
79+
80+
const first = readResult(await run());
81+
const second = readResult(await run());
82+
83+
// This direct preflight is state-only. Gateway refusal coverage remains in
84+
// doctor-config-preflight.process.test.ts and still requires the readiness checkpoint.
85+
expect(first).toEqual({ activeLease: false, stateMigrationsImported: false });
86+
expect(second).toEqual({ activeLease: false, stateMigrationsImported: false });
87+
expect(fs.existsSync(configPath)).toBe(false);
88+
expect(fs.existsSync(stateDir)).toBe(false);
89+
}, 150_000);
90+
});
91+
92+
describe("CLI pristine startup after early config observation", () => {
93+
it.each([
94+
{ name: "explicit Gateway target", explicit: true, existingState: false, stateful: false },
95+
{ name: "configured Gateway target", explicit: false, existingState: false, stateful: false },
96+
{ name: "existing shared state", explicit: true, existingState: true, stateful: false },
97+
{ name: "stateful authored config", explicit: true, existingState: false, stateful: true },
98+
])(
99+
"preserves the migration decision for $name",
100+
async ({ explicit, existingState, stateful }) => {
101+
const root = fs.realpathSync(tempDirs.make("openclaw-cli-pristine-observation-"));
102+
const runtimeRoot = createSourceRuntime(root);
103+
const stateDir = path.join(root, "state");
104+
const configPath = path.join(root, "openclaw.json");
105+
const timelinePath = path.join(root, "timeline.jsonl");
106+
const config = {
107+
gateway: { mode: "local", port: 19876, auth: { mode: "token", token: "test-token" } },
108+
agents: { defaults: { workspace: path.join(root, "workspace") } },
109+
logging: { file: path.join(root, "openclaw.log") },
110+
// Inherited plugin selectors must not add unrelated convergence work to this fixture.
111+
plugins: { enabled: false },
112+
...(stateful ? { messages: { ackReaction: "ok" } } : {}),
113+
} satisfies OpenClawConfig;
114+
const configRaw = JSON.stringify(config);
115+
fs.writeFileSync(configPath, configRaw);
116+
const env: NodeJS.ProcessEnv = {
117+
...process.env,
118+
OPENCLAW_STATE_DIR: stateDir,
119+
OPENCLAW_CONFIG_PATH: configPath,
120+
OPENCLAW_DIAGNOSTICS: "1",
121+
OPENCLAW_DIAGNOSTICS_TIMELINE_PATH: timelinePath,
122+
OPENCLAW_HIDE_BANNER: "1",
123+
XDG_CONFIG_HOME: path.join(root, "xdg-config"),
124+
XDG_DATA_HOME: path.join(root, "xdg-data"),
125+
XDG_STATE_HOME: path.join(root, "xdg-state"),
126+
XDG_CACHE_HOME: path.join(root, "cache"),
127+
TMPDIR: root,
128+
NO_COLOR: "1",
129+
};
130+
delete env.NODE_ENV;
131+
delete env.VITEST;
132+
delete env.VITEST_POOL_ID;
133+
delete env.VITEST_WORKER_ID;
134+
delete env.OPENCLAW_PROFILE;
135+
delete env.OPENCLAW_CONTAINER;
136+
delete env.OPENCLAW_GATEWAY_URL;
137+
delete env.OPENCLAW_GATEWAY_TOKEN;
138+
delete env.OPENCLAW_GATEWAY_PASSWORD;
139+
// Check the authored input without warming the CLI child's startup graph.
140+
const { planPristineStartupConfigMigrations } =
141+
await import("./doctor/shared/pristine-startup-state.js");
142+
expect(planPristineStartupConfigMigrations(config, env)).toEqual({
143+
skipAllStateMigrations: !stateful,
144+
skipCoreStateMigrations: !stateful,
145+
});
146+
const sourceUrl = (relative: string) =>
147+
pathToFileURL(path.join(runtimeRoot, "src", relative)).href;
148+
const args = [
149+
"attach",
150+
"movies-a1166b81",
151+
...(explicit ? ["--url", "ws://127.0.0.1:19877", "--token", "test-token"] : []),
152+
];
153+
const rpcSource = `
154+
export * from ${JSON.stringify(sourceUrl("gateway/call.ts"))};
155+
export async function callGateway(options) {
156+
if (options.method !== "sessions.resolve") throw new Error("Unexpected RPC: " + options.method);
157+
globalThis[Symbol.for("openclaw.test.pristineStartupRpcCalls")].push({
158+
method: options.method, params: options.params, url: options.url ?? null,
159+
configMode: options.config?.gateway?.mode, configPort: options.config?.gateway?.port,
160+
});
161+
return { ok: false, candidates: [
162+
{ key: "agent:main:task:a1166b81-1111-4111-8111-111111111111", displayName: "first" },
163+
{ key: "agent:main:task:a1166b81-2222-4222-8222-222222222222", displayName: "second" },
164+
] };
165+
}
166+
`;
167+
// Exercise the real early read, Commander preaction and Doctor decision. Only the
168+
// resolution RPC is synthetic; ambiguity stops before grants or an external client.
169+
const script = `
170+
import fs from "node:fs";
171+
import path from "node:path";
172+
import { DatabaseSync } from "node:sqlite";
173+
import { registerHooks } from "node:module";
174+
const calls = globalThis[Symbol.for("openclaw.test.pristineStartupRpcCalls")] = [];
175+
registerHooks({
176+
resolve(specifier, context, nextResolve) {
177+
const parent = context.parentURL ?? "";
178+
if (specifier.endsWith("/gateway/call.js") &&
179+
(parent.endsWith("/cli/session-target.ts") || parent.endsWith("/cli/session-target.js"))) {
180+
return { shortCircuit: true,
181+
url: "data:text/javascript," + encodeURIComponent(${JSON.stringify(rpcSource)}) };
182+
}
183+
return nextResolve(specifier, context);
184+
},
185+
});
186+
if (${existingState}) {
187+
const { openOpenClawStateDatabase, closeOpenClawStateDatabase } =
188+
await import(${JSON.stringify(sourceUrl("state/openclaw-state-db.ts"))});
189+
openOpenClawStateDatabase({ env: process.env });
190+
closeOpenClawStateDatabase();
191+
}
192+
const databasePath = path.join(process.env.OPENCLAW_STATE_DIR, "state", "openclaw.sqlite");
193+
const databaseExistedBefore = fs.existsSync(databasePath);
194+
const { runCli } = await import(${JSON.stringify(sourceUrl("cli/run-main.ts"))});
195+
process.argv = [process.execPath, "openclaw", ...${JSON.stringify(args)}];
196+
let message;
197+
try { await runCli(process.argv); }
198+
catch (error) { message = error instanceof Error ? error.message : String(error); }
199+
const { flushDiagnosticsTimeline } =
200+
await import(${JSON.stringify(sourceUrl("infra/diagnostics-timeline.ts"))});
201+
flushDiagnosticsTimeline();
202+
const events = fs.readFileSync(process.env.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH, "utf8")
203+
.trim().split("\\n").map(line => JSON.parse(line));
204+
const stages = events.filter(event => event.type === "span.end" &&
205+
event.name === "cli.command-startup").map(event => event.attributes?.stage);
206+
const database = new DatabaseSync(databasePath, { readOnly: true });
207+
let health;
208+
try { health = database.prepare("SELECT last_known_good_json FROM config_health_entries WHERE config_path = ?")
209+
.get(process.env.OPENCLAW_CONFIG_PATH); }
210+
finally { database.close(); }
211+
process.stdout.write("__RESULT__" + JSON.stringify({
212+
message, calls, stages, databaseExistedBefore,
213+
observedConfigMode: health ? JSON.parse(health.last_known_good_json).gatewayMode : null,
214+
}) + "\\n");
215+
`;
216+
const result = await runIsolatedModuleScript(env, script, { runtimeRoot, timeoutMs: 60_000 });
217+
const output = `${result.stderr}\n${result.stdout}`;
218+
const resultLines = result.stdout.split("\n").filter((line) => line.startsWith("__RESULT__"));
219+
expect(resultLines, output).toHaveLength(1);
220+
const observed = JSON.parse(resultLines[0]!.slice("__RESULT__".length));
221+
expect(observed.message).toContain("Session reference is ambiguous:");
222+
expect(observed.message).toContain("first");
223+
expect(observed.message).toContain("second");
224+
expect(observed.calls).toEqual([
225+
{
226+
method: "sessions.resolve",
227+
params: { shortId: "a1166b81", slugHint: "movies" },
228+
url: explicit ? "ws://127.0.0.1:19877" : null,
229+
configMode: "local",
230+
configPort: 19876,
231+
},
232+
]);
233+
expect(observed.databaseExistedBefore).toBe(existingState);
234+
expect(observed.observedConfigMode).toBe("local");
235+
expect(observed.stages).toContain("config-ready");
236+
expect(observed.stages).toContain("doctor.config-preflight.config-snapshot");
237+
expect(observed.stages.includes("doctor.config-preflight.state-migrations-import")).toBe(
238+
existingState || stateful,
239+
);
240+
expect(fs.readFileSync(configPath, "utf8")).toBe(configRaw);
241+
expect(hasActiveStartupMigrationLease({ env })).toBe(false);
242+
},
243+
75_000,
244+
);
245+
});
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { execFile, spawnSync } from "node:child_process";
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { promisify } from "node:util";
5+
6+
const execFileAsync = promisify(execFile);
7+
// The fixture owns its package assets; resolving linked source back to the checkout
8+
// makes Doctor repair that checkout instead, including building its Control UI.
9+
const SOURCE_RUNTIME_NODE_ARGS = ["--preserve-symlinks", "--preserve-symlinks-main"];
10+
11+
export function runSourceRuntime(
12+
runtimeRoot: string,
13+
env: NodeJS.ProcessEnv,
14+
args: string[],
15+
timeout: number,
16+
) {
17+
return spawnSync(process.execPath, [...SOURCE_RUNTIME_NODE_ARGS, "--import", "tsx", ...args], {
18+
cwd: runtimeRoot,
19+
encoding: "utf8",
20+
env,
21+
timeout,
22+
});
23+
}
24+
25+
export function runIsolatedModuleScript(
26+
env: NodeJS.ProcessEnv,
27+
script: string,
28+
options: { runtimeRoot?: string; timeoutMs?: number } = {},
29+
) {
30+
return execFileAsync(
31+
process.execPath,
32+
[
33+
...(options.runtimeRoot ? SOURCE_RUNTIME_NODE_ARGS : []),
34+
"--import",
35+
"tsx",
36+
"--input-type=module",
37+
"--eval",
38+
script,
39+
],
40+
{
41+
cwd: options.runtimeRoot ?? path.resolve("."),
42+
encoding: "utf8",
43+
env,
44+
maxBuffer: 4 * 1024 * 1024,
45+
timeout: options.timeoutMs ?? 30_000,
46+
},
47+
);
48+
}
49+
50+
export function createSourceRuntime(root: string): string {
51+
const runtimeRoot = path.join(root, "runtime");
52+
fs.mkdirSync(path.join(runtimeRoot, "dist"), { recursive: true });
53+
for (const dirname of ["node_modules", "packages", "scripts", "src"]) {
54+
fs.symlinkSync(
55+
path.resolve(dirname),
56+
path.join(runtimeRoot, dirname),
57+
process.platform === "win32" ? "junction" : "dir",
58+
);
59+
}
60+
for (const filename of ["node-version.mjs", "package.json", "tsconfig.json"]) {
61+
fs.copyFileSync(path.resolve(filename), path.join(runtimeRoot, filename));
62+
}
63+
fs.writeFileSync(
64+
path.join(runtimeRoot, "dist", "build-info.json"),
65+
JSON.stringify({ builtAt: "2026-08-05T00:00:00.000Z" }),
66+
);
67+
const uiDir = path.join(runtimeRoot, "dist", "control-ui");
68+
fs.mkdirSync(uiDir, { recursive: true });
69+
fs.writeFileSync(path.join(uiDir, "index.html"), "<!doctype html>\n");
70+
return runtimeRoot;
71+
}

0 commit comments

Comments
 (0)