Skip to content

Commit e4aab26

Browse files
authored
fix(cli): avoid repeated migration scans during local agent turns (#119051)
* fix(cli): avoid repeated state migration scans * fix(build): preserve source runtime provenance * fix(cli): persist state checkpoint before plugin convergence * fix(cli): invalidate migration checkpoints on input changes * fix(plugins): refresh changed doctor contracts * fix(plugins): preserve warm Doctor contract indexes * test(plugins): align manifest registry fixtures * test(cli): isolate ACP process state * fix(doctor): persist refreshed plugin indexes * fix(doctor): verify persisted plugin index from disk * fix(doctor): fence plugin index persistence * fix(doctor): retain validated migration lease * fix(plugins): canonicalize persisted build metadata * fix(plugins): preserve config policy during install repair
1 parent a8bcbf6 commit e4aab26

46 files changed

Lines changed: 2568 additions & 551 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,6 +1168,16 @@ jobs:
11681168
- name: Smoke test CLI launcher status json
11691169
run: node openclaw.mjs status --json --timeout 1
11701170

1171+
- name: Verify built Doctor plugin index persistence
1172+
run: |
1173+
if [[ -f test/scripts/doctor-config-preflight-plugin-index.built-cli.e2e.test.ts ]]; then
1174+
node scripts/run-vitest.mjs run \
1175+
--config test/vitest/vitest.e2e.config.ts \
1176+
test/scripts/doctor-config-preflight-plugin-index.built-cli.e2e.test.ts
1177+
else
1178+
echo "Selected target predates the built Doctor plugin index persistence proof."
1179+
fi
1180+
11711181
- name: Smoke test built bundled plugin singleton
11721182
run: pnpm test:build:singleton
11731183

‎scripts/build-all.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ export const BUILD_ALL_PROFILES = {
317317
"runtime-postbuild",
318318
"build-stamp",
319319
"runtime-postbuild-stamp",
320+
"write-build-info",
320321
"write-cli-startup-metadata",
321322
],
322323
cliStartup: [
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import type { PluginManifestRecord } from "../../plugins/manifest-registry.js";
2+
3+
export function createManifestRecord(
4+
id: string,
5+
overrides: Partial<PluginManifestRecord>,
6+
): PluginManifestRecord {
7+
const rootDir = `/fixtures/${id}`;
8+
return {
9+
id,
10+
origin: "bundled",
11+
channels: [],
12+
providers: [],
13+
cliBackends: [],
14+
skills: [],
15+
hooks: [],
16+
rootDir,
17+
source: `${rootDir}/index.ts`,
18+
manifestPath: `${rootDir}/openclaw.plugin.json`,
19+
...overrides,
20+
};
21+
}

‎src/agents/embedded-agent-runner/model.static-catalog.test.ts‎

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { createManifestRecord } from "./model.static-catalog.test-helpers.js";
23

34
const manifestMocks = vi.hoisted(() => ({
45
getCurrentPluginMetadataSnapshot: vi.fn(),
@@ -662,11 +663,9 @@ describe("resolveBundledProviderStaticCatalogModel", () => {
662663
providerMocks.resolveBundledProviderCompatPluginIds.mockReturnValue(["google"]);
663664
manifestMocks.loadPluginManifestRegistry.mockReturnValue({
664665
plugins: [
665-
{
666-
id: "google",
667-
origin: "bundled",
666+
createManifestRecord("google", {
668667
providerDiscoverySource: "/fixtures/google/provider-discovery.ts",
669-
},
668+
}),
670669
],
671670
});
672671
providerMocks.resolveRuntimePluginDiscoveryProviders.mockResolvedValue([provider]);
@@ -729,16 +728,12 @@ describe("resolveBundledProviderStaticCatalogModel", () => {
729728
providerMocks.resolveBundledProviderCompatPluginIds.mockReturnValue(["google", "minimax"]);
730729
manifestMocks.loadPluginManifestRegistry.mockReturnValue({
731730
plugins: [
732-
{
733-
id: "google",
734-
origin: "bundled",
731+
createManifestRecord("google", {
735732
providerDiscoverySource: "/fixtures/google/provider-discovery.ts",
736-
},
737-
{
738-
id: "minimax",
739-
origin: "bundled",
733+
}),
734+
createManifestRecord("minimax", {
740735
providerDiscoverySource: "/fixtures/minimax/provider-discovery.ts",
741-
},
736+
}),
742737
],
743738
});
744739
providerMocks.resolveRuntimePluginDiscoveryProviders.mockImplementation(

‎src/cli/acp-cli-exit.process.test.ts‎

Lines changed: 71 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@ import {
55
spawnSync,
66
type ChildProcessWithoutNullStreams,
77
} from "node:child_process";
8-
import { mkdtempSync, rmSync } from "node:fs";
98
import { createServer } from "node:http";
10-
import { tmpdir } from "node:os";
119
import path from "node:path";
1210
import { promisify } from "node:util";
1311
import { describe, expect, it } from "vitest";
1412
import { type RawData, WebSocketServer } from "ws";
13+
import {
14+
closeOpenClawStateDatabaseByPath,
15+
openOpenClawStateDatabase,
16+
} from "../state/openclaw-state-db.js";
17+
import { createOpenClawTestState } from "../test-utils/openclaw-test-state.js";
1518

1619
const execFileAsync = promisify(execFile);
1720
const CHILD_PROCESS_TIMEOUT_MS = 30_000;
@@ -29,16 +32,32 @@ const INITIALIZE_FRAME = {
2932
},
3033
};
3134

32-
function createAcpProcessEnv(stateDir?: string): NodeJS.ProcessEnv {
35+
async function createPreparedAcpProcessState() {
36+
const state = await createOpenClawTestState({
37+
applyEnv: false,
38+
label: "acp-process",
39+
scenario: "minimal",
40+
});
41+
try {
42+
// These cases assert bridge stderr after normal startup. Prepare canonical
43+
// shared state so the one-time migration diagnostic is not part of that signal.
44+
const database = openOpenClawStateDatabase({ env: state.env });
45+
closeOpenClawStateDatabaseByPath(database.path);
46+
return state;
47+
} catch (error) {
48+
await state.cleanup();
49+
throw error;
50+
}
51+
}
52+
53+
function createAcpProcessEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
3354
return {
34-
...process.env,
55+
...baseEnv,
3556
NODE_ENV: undefined,
3657
NODE_OPTIONS: "--use-openssl-ca",
3758
NODE_USE_SYSTEM_CA: "0",
3859
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
39-
OPENCLAW_CONFIG_PATH: stateDir ? path.join(stateDir, "openclaw.json") : undefined,
4060
OPENCLAW_NO_RESPAWN: "1",
41-
OPENCLAW_STATE_DIR: stateDir,
4261
VITEST: undefined,
4362
};
4463
}
@@ -102,24 +121,29 @@ describe("ACP CLI process exit", () => {
102121
])(
103122
"exits promptly after $args",
104123
async ({ args, usage }) => {
105-
const result = await execFileAsync(
106-
process.execPath,
107-
["--import", "tsx", "src/entry.ts", ...args],
108-
{
109-
cwd: path.resolve("."),
110-
encoding: "utf8",
111-
env: {
112-
...createAcpProcessEnv(),
113-
NODE_OPTIONS: process.platform === "darwin" ? "--use-system-ca" : undefined,
114-
NODE_USE_SYSTEM_CA: undefined,
124+
const state = await createPreparedAcpProcessState();
125+
try {
126+
const result = await execFileAsync(
127+
process.execPath,
128+
["--import", "tsx", "src/entry.ts", ...args],
129+
{
130+
cwd: path.resolve("."),
131+
encoding: "utf8",
132+
env: {
133+
...createAcpProcessEnv(state.env),
134+
NODE_OPTIONS: process.platform === "darwin" ? "--use-system-ca" : undefined,
135+
NODE_USE_SYSTEM_CA: undefined,
136+
},
137+
killSignal: "SIGKILL",
138+
timeout: CHILD_PROCESS_TIMEOUT_MS,
115139
},
116-
killSignal: "SIGKILL",
117-
timeout: CHILD_PROCESS_TIMEOUT_MS,
118-
},
119-
);
140+
);
120141

121-
expect(result.stderr).toBe("");
122-
expect(result.stdout).toContain(usage);
142+
expect(result.stderr).toBe("");
143+
expect(result.stdout).toContain(usage);
144+
} finally {
145+
await state.cleanup();
146+
}
123147
},
124148
CHILD_PROCESS_TIMEOUT_MS + 5_000,
125149
);
@@ -130,28 +154,33 @@ describe("ACP CLI process exit", () => {
130154
name: "an initialize frame",
131155
input: `${JSON.stringify(INITIALIZE_FRAME)}\n`,
132156
},
133-
])("exits when the bridge starts with $name and the client disconnects", ({ input }) => {
134-
const result = spawnSync(
135-
process.execPath,
136-
["--import", "tsx", "src/entry.ts", "acp", "--require-existing"],
137-
{
138-
cwd: path.resolve("."),
139-
encoding: "utf8",
140-
env: createAcpProcessEnv(),
141-
input,
142-
killSignal: "SIGKILL",
143-
timeout: CHILD_PROCESS_TIMEOUT_MS,
144-
},
145-
);
157+
])("exits when the bridge starts with $name and the client disconnects", async ({ input }) => {
158+
const state = await createPreparedAcpProcessState();
159+
try {
160+
const result = spawnSync(
161+
process.execPath,
162+
["--import", "tsx", "src/entry.ts", "acp", "--require-existing"],
163+
{
164+
cwd: path.resolve("."),
165+
encoding: "utf8",
166+
env: createAcpProcessEnv(state.env),
167+
input,
168+
killSignal: "SIGKILL",
169+
timeout: CHILD_PROCESS_TIMEOUT_MS,
170+
},
171+
);
146172

147-
expect(result.error).toBeUndefined();
148-
expect(result.signal).toBeNull();
149-
expect(result.status).toBe(0);
150-
expect(result.stderr).toBe("");
173+
expect(result.error).toBeUndefined();
174+
expect(result.signal).toBeNull();
175+
expect(result.status).toBe(0);
176+
expect(result.stderr).toBe("");
177+
} finally {
178+
await state.cleanup();
179+
}
151180
});
152181

153182
it("processes an initialize frame buffered before Gateway hello", async () => {
154-
const stateDir = mkdtempSync(path.join(tmpdir(), "openclaw-acp-exit-"));
183+
const state = await createPreparedAcpProcessState();
155184
const server = createServer();
156185
const wss = new WebSocketServer({ server });
157186
let child: ChildProcessWithoutNullStreams | undefined;
@@ -219,7 +248,7 @@ describe("ACP CLI process exit", () => {
219248
],
220249
{
221250
cwd: path.resolve("."),
222-
env: createAcpProcessEnv(stateDir),
251+
env: createAcpProcessEnv(state.env),
223252
stdio: ["pipe", "pipe", "pipe"],
224253
},
225254
);
@@ -255,7 +284,7 @@ describe("ACP CLI process exit", () => {
255284
await new Promise<void>((resolve, reject) => {
256285
server.close((error) => (error ? reject(error) : resolve()));
257286
});
258-
rmSync(stateDir, { force: true, recursive: true });
287+
await state.cleanup();
259288
}
260289
}, 40_000);
261290
});

‎src/cli/plugins-cli.install.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1273,8 +1273,23 @@ describe("plugins cli install", () => {
12731273
plugins: [{ id: "alpha", kind: "provider" }],
12741274
diagnostics: [],
12751275
});
1276+
const alphaRoot = cliInstallPath("alpha");
12761277
loadPluginManifestRegistry.mockReturnValue({
1277-
plugins: [{ id: "alpha", kind: "memory" }],
1278+
plugins: [
1279+
{
1280+
id: "alpha",
1281+
kind: "memory",
1282+
origin: "global",
1283+
channels: [],
1284+
providers: [],
1285+
cliBackends: [],
1286+
skills: [],
1287+
hooks: [],
1288+
rootDir: alphaRoot,
1289+
source: `${alphaRoot}/index.js`,
1290+
manifestPath: `${alphaRoot}/openclaw.plugin.json`,
1291+
},
1292+
],
12781293
diagnostics: [],
12791294
});
12801295
applyExclusiveSlotSelection.mockReturnValue({

‎src/cli/program/config-guard.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ describe("ensureConfigReady", () => {
202202
migrateState: true,
203203
migrateLegacyConfig: false,
204204
invalidConfigNote: false,
205+
requireStateMigrationCheckpoint: true,
205206
});
206207
}
207208
});
@@ -238,6 +239,7 @@ describe("ensureConfigReady", () => {
238239
migrateLegacyConfig: false,
239240
invalidConfigNote: false,
240241
observe: false,
242+
requireStateMigrationCheckpoint: true,
241243
});
242244
});
243245

@@ -273,6 +275,7 @@ describe("ensureConfigReady", () => {
273275
migrateLegacyConfig: false,
274276
invalidConfigNote: false,
275277
observe: false,
278+
requireStateMigrationCheckpoint: true,
276279
});
277280
},
278281
);
@@ -288,6 +291,7 @@ describe("ensureConfigReady", () => {
288291
migrateLegacyConfig: false,
289292
invalidConfigNote: false,
290293
observe: false,
294+
requireStateMigrationCheckpoint: true,
291295
});
292296
});
293297

@@ -323,13 +327,14 @@ describe("ensureConfigReady", () => {
323327
expect(runtime.exit).toHaveBeenCalledWith(78);
324328
});
325329

326-
it("does not require a startup migration checkpoint for gateway probes", async () => {
330+
it("uses only the state migration checkpoint for gateway probes", async () => {
327331
await runEnsureConfigReady(["gateway", "health"]);
328332

329333
expect(loadAndMaybeMigrateDoctorConfigMock).toHaveBeenCalledWith({
330334
migrateState: true,
331335
migrateLegacyConfig: false,
332336
invalidConfigNote: false,
337+
requireStateMigrationCheckpoint: true,
333338
});
334339
});
335340

@@ -353,6 +358,21 @@ describe("ensureConfigReady", () => {
353358
migrateState: true,
354359
migrateLegacyConfig: false,
355360
invalidConfigNote: false,
361+
requireStateMigrationCheckpoint: true,
362+
});
363+
});
364+
365+
it("checkpoints migration discovery for established canonical agent state", async () => {
366+
const root = useTempOpenClawHome();
367+
writeStateMarker(root, "agents/main/sessions/sessions.json");
368+
369+
await runEnsureConfigReady(["agent"]);
370+
371+
expect(loadAndMaybeMigrateDoctorConfigMock).toHaveBeenCalledWith({
372+
migrateState: true,
373+
migrateLegacyConfig: false,
374+
invalidConfigNote: false,
375+
requireStateMigrationCheckpoint: true,
356376
});
357377
});
358378

@@ -377,6 +397,7 @@ describe("ensureConfigReady", () => {
377397
migrateState: true,
378398
migrateLegacyConfig: false,
379399
invalidConfigNote: false,
400+
requireStateMigrationCheckpoint: true,
380401
});
381402
expect(setRuntimeConfigSnapshotMock).toHaveBeenCalledWith(
382403
migratedSnapshot.runtimeConfig,

‎src/cli/program/config-guard.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ export async function ensureConfigReady(
246246
...(commandName === "status" ? { observe: false } : {}),
247247
...(shouldRequireStartupMigrationCheckpoint(commandPath)
248248
? { requireStartupMigrationCheckpoint: true }
249-
: {}),
249+
: { requireStateMigrationCheckpoint: true }),
250250
...(params.beforeStateMigrations
251251
? { beforeStateMigrations: params.beforeStateMigrations }
252252
: {}),

0 commit comments

Comments
 (0)