Skip to content

Commit e6937fb

Browse files
fix(update): gate restart on plugin readiness
1 parent 9aa82b1 commit e6937fb

18 files changed

Lines changed: 588 additions & 25 deletions

‎docs/cli/update.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,10 @@ then refreshes service metadata, restarts the service, and verifies the
287287
restarted Gateway before reporting `Gateway: restarted and verified.`.
288288
Doctor repair and plugin validation run before restart; a verified restart
289289
does not run another Doctor from the old updater process.
290+
After plugin convergence, the updated CLI also runs any plugin-owned
291+
post-update readiness checks against an isolated state snapshot. An error keeps
292+
the Gateway stopped and returns the check's remediation before restart; this
293+
gate does not run interactive setup, download models, or change config.
290294
Package-manager updates additionally verify the restarted Gateway reports the
291295
expected package version; git-checkout updates verify gateway health and
292296
service readiness after the rebuild.

‎extensions/memory-core/src/doctor-health.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@ function context(stateDir: string, provider: string): HealthCheckContext {
7171

7272
describe("managed local embedding setup health check", () => {
7373
it("stays opt-in outside an explicit pre-cutover selection", () => {
74-
expect(captureCheck()).toMatchObject({ defaultEnabled: false });
74+
expect(captureCheck()).toMatchObject({
75+
defaultEnabled: false,
76+
updateReadiness: "post-plugin",
77+
});
7578
});
7679

7780
it("refreshes current host state and re-registers after a registry reset", async () => {

‎extensions/memory-core/src/doctor-health.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,15 @@ type MemoryCoreDoctorRegistrationState = Pick<
3838
"inspectEmbeddingProviderSetup" | "memoryCoreActive"
3939
>;
4040

41+
type MemoryCoreDoctorCheck = HealthCheck & {
42+
readonly defaultEnabled: false;
43+
readonly updateReadiness: "post-plugin";
44+
};
45+
4146
const registrationsByHost = new WeakMap<
4247
MemoryCoreDoctorRegistrationHost["registerHealthCheck"],
4348
{
44-
readonly check: HealthCheck & { readonly defaultEnabled: false };
49+
readonly check: MemoryCoreDoctorCheck;
4550
readonly state: MemoryCoreDoctorRegistrationState;
4651
}
4752
>();
@@ -64,12 +69,13 @@ function resolveSelectedMemoryProvider(
6469

6570
function createManagedLocalEmbeddingSetupCheck(
6671
state: MemoryCoreDoctorRegistrationState,
67-
): HealthCheck & { readonly defaultEnabled: false } {
72+
): MemoryCoreDoctorCheck {
6873
return {
6974
id: MEMORY_MANAGED_LOCAL_EMBEDDING_SETUP_CHECK_ID,
7075
kind: "plugin",
7176
source: "memory-core",
7277
defaultEnabled: false,
78+
updateReadiness: "post-plugin",
7379
description: "Checks existing semantic indexes for required managed local embedding setup.",
7480
async detect(ctx) {
7581
if (!state.memoryCoreActive) {

‎src/cli/update-cli.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,18 @@ vi.mock("../process/exec.js", () => ({
283283
})),
284284
}));
285285

286+
vi.mock("./update-cli/update-command-post-plugin-readiness.js", async (importOriginal) => {
287+
const actual =
288+
await importOriginal<typeof import("./update-cli/update-command-post-plugin-readiness.js")>();
289+
return {
290+
...actual,
291+
applyPostPluginUpdateReadiness: vi.fn(
292+
async (params: Parameters<typeof actual.applyPostPluginUpdateReadiness>[0]) =>
293+
params.pluginUpdate,
294+
),
295+
};
296+
});
297+
286298
vi.mock("../utils.js", async (importOriginal) => {
287299
const [actual, { isRecord }] = await Promise.all([
288300
importOriginal<typeof import("../utils.js")>(),
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { PostCorePluginUpdateResult } from "./update-command-plugins.js";
3+
4+
const mocks = vi.hoisted(() => ({
5+
readConfig: vi.fn(),
6+
resolveEntrypoint: vi.fn(),
7+
runExec: vi.fn(),
8+
}));
9+
10+
vi.mock("../../config/config.js", async (importOriginal) => ({
11+
...(await importOriginal<typeof import("../../config/config.js")>()),
12+
readConfigFileSnapshot: mocks.readConfig,
13+
}));
14+
15+
vi.mock("../../daemon/gateway-entrypoint.js", () => ({
16+
resolveGatewayInstallEntrypoint: mocks.resolveEntrypoint,
17+
}));
18+
19+
vi.mock("../../process/exec.js", () => ({
20+
runExec: mocks.runExec,
21+
}));
22+
23+
vi.mock("../../runtime.js", () => ({
24+
defaultRuntime: { error: vi.fn(), log: vi.fn() },
25+
}));
26+
27+
vi.mock("./shared.js", async (importOriginal) => ({
28+
...(await importOriginal<typeof import("./shared.js")>()),
29+
resolveNodeRunner: vi.fn(() => "/usr/bin/node"),
30+
}));
31+
32+
import { completePostCorePluginUpdate } from "./update-command-fresh-doctor.js";
33+
34+
const pluginUpdate: PostCorePluginUpdateResult = {
35+
status: "ok",
36+
changed: true,
37+
sync: {
38+
changed: false,
39+
switchedToBundled: [],
40+
switchedToNpm: [],
41+
warnings: [],
42+
errors: [],
43+
},
44+
npm: { changed: false, outcomes: [] },
45+
integrityDrifts: [],
46+
warnings: [],
47+
};
48+
49+
const validConfigSnapshot = {
50+
valid: true as const,
51+
parsed: {},
52+
config: {},
53+
runtimeConfig: {},
54+
sourceConfig: {},
55+
warnings: [],
56+
issues: [],
57+
legacyIssues: [],
58+
};
59+
60+
describe("post-plugin update readiness", () => {
61+
beforeEach(() => {
62+
mocks.readConfig.mockReset().mockResolvedValue(validConfigSnapshot);
63+
mocks.resolveEntrypoint.mockReset().mockResolvedValue("/opt/openclaw/dist/index.js");
64+
mocks.runExec.mockReset().mockImplementation(async (_command, args: string[]) => ({
65+
stdout: args.includes("--lint")
66+
? `${JSON.stringify({ ok: true, checksRun: 1, checksSkipped: 0, findings: [] })}\n`
67+
: "",
68+
stderr: "",
69+
}));
70+
});
71+
72+
it("runs declared readiness checks in the updated process before accepting restart", async () => {
73+
await completePostCorePluginUpdate({
74+
root: "/opt/openclaw",
75+
pluginUpdate,
76+
freshDoctorRequired: true,
77+
yes: true,
78+
json: true,
79+
timeoutMs: 5_000,
80+
});
81+
82+
expect(mocks.runExec.mock.calls.map(([, args]) => args)).toEqual([
83+
[
84+
"/opt/openclaw/dist/index.js",
85+
"doctor",
86+
"--repair",
87+
"--non-interactive",
88+
"--no-workspace-suggestions",
89+
"--yes",
90+
],
91+
["/opt/openclaw/dist/index.js", "config", "validate", "--json"],
92+
["/opt/openclaw/dist/index.js", "doctor", "--lint", "--json", "--severity-min", "error"],
93+
]);
94+
expect(mocks.runExec.mock.calls[2]?.[2]).toMatchObject({
95+
env: { OPENCLAW_UPDATE_POST_CORE_CONVERGENCE: "1" },
96+
});
97+
});
98+
99+
it("runs updated readiness checks even when no plugin package changed", async () => {
100+
await completePostCorePluginUpdate({
101+
root: "/opt/openclaw",
102+
pluginUpdate: { ...pluginUpdate, changed: false },
103+
freshDoctorRequired: false,
104+
yes: true,
105+
json: true,
106+
timeoutMs: 5_000,
107+
});
108+
109+
expect(mocks.runExec.mock.calls.map(([, args]) => args)).toEqual([
110+
["/opt/openclaw/dist/index.js", "doctor", "--lint", "--json", "--severity-min", "error"],
111+
]);
112+
});
113+
114+
it("returns the owner-provided remediation and refuses restart when readiness fails", async () => {
115+
mocks.runExec.mockImplementation(async (_command, args: string[]) => {
116+
if (args.includes("--lint")) {
117+
throw Object.assign(new Error("readiness failed"), {
118+
exitCode: 1,
119+
stdout: `${JSON.stringify({
120+
ok: false,
121+
checksRun: 1,
122+
checksSkipped: 0,
123+
findings: [
124+
{
125+
checkId: "memory-core/managed-local-embedding-setup",
126+
severity: "error",
127+
source: "memory-core",
128+
message: "Managed local embeddings are unavailable.",
129+
fixHint:
130+
"Run `openclaw models --agent main auth login --provider llama-cpp --method local`.",
131+
},
132+
],
133+
})}\n`,
134+
stderr: "",
135+
});
136+
}
137+
return { stdout: "", stderr: "" };
138+
});
139+
140+
const result = await completePostCorePluginUpdate({
141+
root: "/opt/openclaw",
142+
pluginUpdate,
143+
freshDoctorRequired: true,
144+
yes: true,
145+
json: true,
146+
timeoutMs: 5_000,
147+
});
148+
149+
expect(result.pluginUpdate).toMatchObject({
150+
status: "error",
151+
reason: "post-plugin-update-readiness-failed",
152+
warnings: [
153+
{
154+
pluginId: "memory-core",
155+
reason: "memory-core/managed-local-embedding-setup",
156+
message: "Managed local embeddings are unavailable.",
157+
guidance: [
158+
"Run `openclaw models --agent main auth login --provider llama-cpp --method local`.",
159+
],
160+
},
161+
],
162+
});
163+
});
164+
165+
it.each([
166+
{
167+
label: "malformed output",
168+
stdout: "{not-json\n",
169+
},
170+
{
171+
label: "no declared check",
172+
stdout: `${JSON.stringify({ ok: true, checksRun: 0, checksSkipped: 0, findings: [] })}\n`,
173+
},
174+
])("fails closed on $label from the updated readiness child", async ({ stdout }) => {
175+
mocks.runExec.mockImplementation(async (_command, args: string[]) => ({
176+
stdout: args.includes("--lint") ? stdout : "",
177+
stderr: "",
178+
}));
179+
180+
const result = await completePostCorePluginUpdate({
181+
root: "/opt/openclaw",
182+
pluginUpdate,
183+
freshDoctorRequired: true,
184+
yes: true,
185+
json: true,
186+
timeoutMs: 5_000,
187+
});
188+
189+
expect(result.pluginUpdate).toMatchObject({
190+
status: "error",
191+
reason: "post-plugin-update-readiness-execution-failed",
192+
warnings: [
193+
expect.objectContaining({
194+
message: "Updated plugin readiness checks could not be completed before restart.",
195+
}),
196+
],
197+
});
198+
});
199+
});

‎src/cli/update-cli/update-command-fresh-doctor.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Runs the post-plugin migration pass without retaining pre-update plugin modules.
1+
// Runs post-plugin convergence checks without retaining pre-update plugin modules.
22
import { isRecord } from "@openclaw/normalization-core/record-coerce";
33
import {
44
UPDATE_DEFER_CONFIGURED_PLUGIN_INSTALL_REPAIR_ENV,
@@ -13,6 +13,7 @@ import { runExec } from "../../process/exec.js";
1313
import { defaultRuntime } from "../../runtime.js";
1414
import { resolveNodeRunner } from "./shared.js";
1515
import type { PostCorePluginUpdateResult } from "./update-command-plugins.js";
16+
import { applyPostPluginUpdateReadiness } from "./update-command-post-plugin-readiness.js";
1617
import {
1718
applyPostPluginConfigValidation,
1819
POST_PLUGIN_DOCTOR_EXECUTION_FAILED_REASON,
@@ -218,6 +219,15 @@ async function applyFreshPostPluginDoctor(params: {
218219
pluginUpdate = createPostPluginDoctorExecutionFailure(params.pluginUpdate, String(err));
219220
}
220221
const configValid = await validatePostPluginConfigInFreshProcess({ ...params, entryPath });
222+
if (configValid) {
223+
pluginUpdate = await applyPostPluginUpdateReadiness({
224+
root: params.root,
225+
entryPath,
226+
pluginUpdate,
227+
timeoutMs: params.timeoutMs,
228+
...(params.nodeRunner ? { nodeRunner: params.nodeRunner } : {}),
229+
});
230+
}
221231
return { pluginUpdate, configValid };
222232
}
223233

@@ -248,6 +258,13 @@ export async function completePostCorePluginUpdate(params: {
248258
});
249259
pluginUpdate = freshResult.pluginUpdate;
250260
freshConfigValid = freshResult.configValid;
261+
} else if (pluginUpdate.status !== "error") {
262+
pluginUpdate = await applyPostPluginUpdateReadiness({
263+
root: params.root,
264+
pluginUpdate,
265+
timeoutMs: params.timeoutMs,
266+
...(params.nodeRunner ? { nodeRunner: params.nodeRunner } : {}),
267+
});
251268
}
252269

253270
const configSnapshot = await withNormalConfigValidation(() => readConfigFileSnapshot());

‎src/cli/update-cli/update-command-lease.test-support.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export type LeaseScenario = {
1010
preDoctorChannel?: string;
1111
invalidConfig?: boolean;
1212
failDoctor?: "pre" | "post";
13+
readinessFailure?: "finding" | "execution";
1314
hostVersion?: string;
1415
doctorWrites?: boolean;
1516
writerConfig?: OpenClawConfig;
@@ -47,6 +48,36 @@ export async function runUpdateLeaseChild(): Promise<void> {
4748
process.exitCode = scenario.invalidConfig ? 1 : 0;
4849
return;
4950
}
51+
if (command === "doctor" && process.argv[3] === "--lint") {
52+
assert.deepEqual(process.argv.slice(3), ["--lint", "--json", "--severity-min", "error"]);
53+
assert.equal(process.env.OPENCLAW_UPDATE_POST_CORE_CONVERGENCE, "1");
54+
await record("readiness");
55+
if (scenario.readinessFailure === "execution") {
56+
throw new Error("readiness fixture failure");
57+
}
58+
const findings =
59+
scenario.readinessFailure === "finding"
60+
? [
61+
{
62+
checkId: "fixture/post-plugin-readiness",
63+
severity: "error",
64+
source: "fixture",
65+
message: "Fixture plugin is not ready.",
66+
fixHint: "Run the fixture repair command.",
67+
},
68+
]
69+
: [];
70+
process.stdout.write(
71+
`${JSON.stringify({
72+
ok: findings.length === 0,
73+
checksRun: 1,
74+
checksSkipped: 0,
75+
findings,
76+
})}\n`,
77+
);
78+
process.exitCode = findings.length === 0 ? 0 : 1;
79+
return;
80+
}
5081
const { withPluginLifecycleLease } = await import("../../plugins/plugin-lifecycle-lease.js");
5182
if (command === "doctor") {
5283
const phase = process.env.OPENCLAW_UPDATE_POST_CORE_CONVERGENCE === "1" ? "post" : "pre";

0 commit comments

Comments
 (0)