Skip to content

Commit e337059

Browse files
steipeteFinn763
andcommitted
fix(doctor): load Codex health from the selected trusted plugin
Resolve the managed Codex doctor API from the registry-selected bundled or trusted official install root instead of assuming core bundles the plugin. Preserve owner policy, hardlink boundaries, and both host registry callbacks; report missing or broken health surfaces instead of silently dropping checks. Extend selected-artifact regression coverage and the managed npm onboarding package scenario to exercise ordinary and targeted doctor lint. Fixes #128826 Adapted from #129276. Co-authored-by: Finn763 <[email protected]>
1 parent 80944da commit e337059

4 files changed

Lines changed: 192 additions & 64 deletions

File tree

‎scripts/e2e/lib/codex-on-demand/assertions.mjs‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Assertions for Codex on-demand plugin E2E scenarios.
2+
import { spawnSync } from "node:child_process";
23
import fs from "node:fs";
34
import path from "node:path";
45
import {
@@ -112,3 +113,28 @@ assertOpenAiEnvAuthProfileStore(authRaw, {
112113
rawKeyMessage: "auth profile persisted the raw OpenAI test key",
113114
rawKeyNeedle: "sk-openclaw-codex-on-demand-e2e",
114115
});
116+
117+
// Use the installed CLI after normal onboarding; a source-tree API would hide missing package surfaces.
118+
for (const only of [undefined, "codex/managed-app-server"]) {
119+
const args = ["doctor", "--lint", "--json", ...(only ? ["--only", only] : [])];
120+
const result = spawnSync("openclaw", args, { encoding: "utf8", timeout: 120_000 });
121+
if (result.error || (result.status !== 0 && result.status !== 1)) {
122+
throw new Error(
123+
`doctor failed before producing findings: ${result.error?.message ?? result.stderr}`,
124+
);
125+
}
126+
const report = JSON.parse(result.stdout);
127+
if (only) {
128+
if (
129+
result.status !== 0 ||
130+
report.ok !== true ||
131+
report.checksRun !== 1 ||
132+
report.findings.length !== 0
133+
) {
134+
throw new Error(`managed Codex doctor check failed: ${JSON.stringify(report)}`);
135+
}
136+
} else if (report.checksRun <= 1) {
137+
throw new Error(`ordinary doctor did not reach health checks: ${JSON.stringify(report)}`);
138+
}
139+
process.stdout.write(`[codex-doctor] ${only ?? "default"}: ${JSON.stringify(report)}\n`);
140+
}

‎src/flows/bundled-health-checks.test.ts‎

Lines changed: 142 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,37 @@
11
// Bundled health check tests cover built-in doctor checks and repair advice.
2-
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
2+
import { linkSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import type { OpenClawConfig } from "../config/types.openclaw.js";
7+
import { MissingPublicSurfaceError } from "../plugin-sdk/facade-loader.js";
68
import type { PluginManifestRegistry } from "../plugins/manifest-registry.js";
79
import type { ProviderPolicySurface } from "../plugins/provider-policy-surface.js";
810
import {
911
registerBundledHealthChecks,
1012
resolveBundledHealthCheckPluginStateMode,
1113
} from "./bundled-health-checks.js";
14+
import { clearHealthChecksForTest, getHealthCheck } from "./health-check-registry.js";
1215

1316
const STATE_DEFERRED_CHECK_ID = "memory-core/managed-local-embedding-setup";
1417

1518
const mocks = vi.hoisted(() => ({
16-
registerCodexManagedAppServerDoctorChecks: vi.fn(),
19+
registerCodexManagedAppServerDoctorChecks: vi.fn(() => {
20+
throw new Error("Unable to resolve bundled plugin public surface codex/api.js");
21+
}),
1722
inspectEmbeddingProviderSetup: vi.fn(),
1823
loadBundledPluginManifestRegistry: vi.fn(
1924
(): PluginManifestRegistry => ({
2025
plugins: [],
2126
diagnostics: [],
2227
}),
2328
),
24-
loadPluginManifestRegistryForPluginRegistry: vi.fn(() => ({
25-
plugins: [],
26-
diagnostics: [],
27-
})),
29+
loadPluginManifestRegistryForPluginRegistry: vi.fn(
30+
(): PluginManifestRegistry => ({
31+
plugins: [],
32+
diagnostics: [],
33+
}),
34+
),
2835
registerCuaDriverDoctorChecks: vi.fn(),
2936
registerMemoryCoreDoctorChecks: vi.fn(),
3037
registerPolicyDoctorChecks: vi.fn(),
@@ -44,10 +51,7 @@ const mocks = vi.hoisted(() => ({
4451
: dirName === "cua-computer"
4552
? { registerCuaDriverDoctorChecks: mocks.registerCuaDriverDoctorChecks }
4653
: dirName === "codex"
47-
? {
48-
registerCodexManagedAppServerDoctorChecks:
49-
mocks.registerCodexManagedAppServerDoctorChecks,
50-
}
54+
? mocks.registerCodexManagedAppServerDoctorChecks()
5155
: { registerPolicyDoctorChecks: mocks.registerPolicyDoctorChecks },
5256
),
5357
resolveProviderPolicySurface: vi.fn((): ProviderPolicySurface | null => ({
@@ -65,7 +69,8 @@ vi.mock("../plugins/manifest-registry.js", async (importOriginal) => ({
6569
vi.mock("../plugins/provider-public-artifacts.js", () => ({
6670
resolveProviderPolicySurface: mocks.resolveProviderPolicySurface,
6771
}));
68-
vi.mock("../plugins/public-surface-loader.js", () => ({
72+
vi.mock("../plugins/public-surface-loader.js", async (importOriginal) => ({
73+
...(await importOriginal<typeof import("../plugins/public-surface-loader.js")>()),
6974
loadBundledPluginPublicArtifactModuleFromCandidatesSync:
7075
mocks.loadBundledPluginPublicArtifactModuleFromCandidatesSync,
7176
loadBundledPluginPublicArtifactModuleSync: mocks.loadBundledPluginPublicArtifactModuleSync,
@@ -76,11 +81,17 @@ let workspaceDir: string;
7681
describe("registerBundledHealthChecks", () => {
7782
beforeEach(() => {
7883
vi.clearAllMocks();
84+
mocks.loadPluginManifestRegistryForPluginRegistry.mockReturnValue({
85+
plugins: [],
86+
diagnostics: [],
87+
});
7988
workspaceDir = join(tmpdir(), `bundled-health-${process.pid}-${Date.now()}`);
8089
mkdirSync(workspaceDir, { recursive: true });
90+
workspaceDir = realpathSync(workspaceDir);
8191
});
8292

8393
afterEach(() => {
94+
clearHealthChecksForTest();
8495
rmSync(workspaceDir, { recursive: true, force: true });
8596
});
8697

@@ -354,62 +365,136 @@ describe("registerBundledHealthChecks", () => {
354365
expect(mocks.registerWorkerProviderDoctorChecks).not.toHaveBeenCalled();
355366
});
356367

357-
it("loads managed Codex health when an effective model route selects Codex", () => {
358-
registerBundledHealthChecks({
359-
cfg: {
360-
agents: {
361-
defaults: {
362-
model: { primary: "openai/gpt-5.6-sol" },
363-
models: {
364-
"openai/gpt-5.6-sol": { agentRuntime: { id: "codex" } },
365-
},
366-
},
367-
},
368+
const codexConfig: OpenClawConfig = {
369+
agents: {
370+
defaults: {
371+
model: { primary: "openai/gpt-5.6-sol" },
372+
models: { "openai/gpt-5.6-sol": { agentRuntime: { id: "codex" } } },
368373
},
369-
cwd: workspaceDir,
370-
});
374+
},
375+
};
376+
377+
function codexRecord(origin: "bundled" | "global", trustedOfficialInstall?: boolean) {
378+
return {
379+
id: "codex",
380+
origin,
381+
trustedOfficialInstall,
382+
rootDir: workspaceDir,
383+
source: join(workspaceDir, "index.js"),
384+
manifestPath: join(workspaceDir, "openclaw.plugin.json"),
385+
channels: [],
386+
providers: [],
387+
cliBackends: [],
388+
skills: [],
389+
hooks: [],
390+
contracts: {},
391+
} satisfies PluginManifestRegistry["plugins"][number];
392+
}
393+
394+
it.each(["bundled", "global"] as const)(
395+
"registers and runs health from the selected %s Codex public artifact",
396+
async (origin) => {
397+
mkdirSync(join(workspaceDir, "dist"));
398+
writeFileSync(
399+
join(workspaceDir, "dist", "api.js"),
400+
`
401+
module.exports.registerCodexManagedAppServerDoctorChecks = (host) => {
402+
if (!host.getHealthCheck("codex/managed-app-server")) {
403+
host.registerHealthCheck({
404+
id: "codex/managed-app-server", kind: "plugin", source: "codex",
405+
description: "Selected artifact check", detect: async () => [],
406+
});
407+
}
408+
};
409+
`,
410+
);
411+
if (origin === "bundled") {
412+
linkSync(join(workspaceDir, "dist", "api.js"), join(workspaceDir, "api-copy.js"));
413+
}
414+
mocks.loadPluginManifestRegistryForPluginRegistry.mockReturnValue({
415+
plugins: [codexRecord(origin, origin === "global")],
416+
diagnostics: [],
417+
});
418+
const env = { ...process.env, OPENCLAW_STATE_DIR: join(workspaceDir, "state") };
419+
for (let attempt = 0; attempt < 2; attempt += 1) {
420+
registerBundledHealthChecks({ cfg: codexConfig, cwd: workspaceDir, env });
421+
}
422+
const check = getHealthCheck("codex/managed-app-server");
423+
expect(check?.description).toBe("Selected artifact check");
424+
await expect(
425+
check?.detect({
426+
cfg: codexConfig,
427+
env,
428+
mode: "lint",
429+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
430+
}),
431+
).resolves.toEqual([]);
432+
expect(mocks.loadPluginManifestRegistryForPluginRegistry).toHaveBeenCalledWith({
433+
config: codexConfig,
434+
workspaceDir,
435+
env,
436+
pluginIds: ["codex"],
437+
});
438+
expect(mocks.registerCodexManagedAppServerDoctorChecks).not.toHaveBeenCalled();
439+
},
440+
);
441+
442+
it.each(["missing", "untrusted", "missing-api", "missing-export", "broken-api"])(
443+
"fails visibly for a selected Codex install with %s state",
444+
(state) => {
445+
mocks.loadPluginManifestRegistryForPluginRegistry.mockReturnValue({
446+
plugins: state === "missing" ? [] : [codexRecord("global", state !== "untrusted")],
447+
diagnostics: [],
448+
});
449+
if (state === "untrusted") {
450+
writeFileSync(
451+
join(workspaceDir, "api.js"),
452+
'throw new Error("untrusted artifact executed");',
453+
);
454+
}
455+
if (state === "missing-export") {
456+
writeFileSync(join(workspaceDir, "api.js"), "module.exports = {};");
457+
}
458+
if (state === "broken-api") {
459+
writeFileSync(join(workspaceDir, "api.js"), 'throw new Error("selected artifact failed");');
460+
}
461+
expect(() => registerBundledHealthChecks({ cfg: codexConfig, cwd: workspaceDir })).toThrow(
462+
state === "broken-api"
463+
? "selected artifact failed"
464+
: state === "missing-export"
465+
? TypeError
466+
: MissingPublicSurfaceError,
467+
);
468+
expect(getHealthCheck("codex/managed-app-server")).toBeUndefined();
469+
expect(mocks.registerCodexManagedAppServerDoctorChecks).not.toHaveBeenCalled();
470+
},
471+
);
371472

372-
expect(mocks.loadBundledPluginPublicArtifactModuleSync).toHaveBeenCalledWith({
373-
dirName: "codex",
374-
artifactBasename: "api.js",
375-
});
376-
expect(mocks.registerCodexManagedAppServerDoctorChecks).toHaveBeenCalledWith({
377-
getHealthCheck: expect.any(Function),
378-
registerHealthCheck: expect.any(Function),
379-
});
473+
it.each([
474+
{ enabled: false },
475+
{ entries: { codex: { enabled: false } } },
476+
{ deny: ["codex"] },
477+
{ allow: ["telegram"] },
478+
])("preserves Codex owner policy without loading plugin code: %j", (plugins) => {
479+
registerBundledHealthChecks({ cfg: { ...codexConfig, plugins }, cwd: workspaceDir });
480+
expect(mocks.loadPluginManifestRegistryForPluginRegistry).not.toHaveBeenCalled();
481+
expect(mocks.registerCodexManagedAppServerDoctorChecks).not.toHaveBeenCalled();
380482
});
381483

382-
it("does not load managed Codex health for OpenClaw routes or disabled Codex", () => {
383-
for (const cfg of [
384-
{
385-
agents: {
386-
defaults: {
387-
model: { primary: "openai/gpt-5.6-sol" },
388-
models: {
389-
"openai/gpt-5.6-sol": { agentRuntime: { id: "openclaw" } },
390-
},
391-
},
392-
},
393-
},
394-
{
484+
it("does not load managed Codex health for an OpenClaw route", () => {
485+
registerBundledHealthChecks({
486+
cfg: {
395487
agents: {
396488
defaults: {
397489
model: { primary: "openai/gpt-5.6-sol" },
398-
models: {
399-
"openai/gpt-5.6-sol": { agentRuntime: { id: "codex" } },
400-
},
490+
models: { "openai/gpt-5.6-sol": { agentRuntime: { id: "openclaw" } } },
401491
},
402492
},
403-
plugins: { entries: { codex: { enabled: false } } },
404493
},
405-
]) {
406-
vi.clearAllMocks();
407-
registerBundledHealthChecks({ cfg, cwd: workspaceDir });
408-
expect(mocks.loadBundledPluginPublicArtifactModuleSync).not.toHaveBeenCalledWith({
409-
dirName: "codex",
410-
artifactBasename: "api.js",
411-
});
412-
}
494+
cwd: workspaceDir,
495+
});
496+
expect(mocks.loadPluginManifestRegistryForPluginRegistry).not.toHaveBeenCalled();
497+
expect(mocks.registerCodexManagedAppServerDoctorChecks).not.toHaveBeenCalled();
413498
});
414499

415500
it("does not use policy.jsonc existence as extension activation", () => {

‎src/flows/bundled-health-checks.ts‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { asOptionalObjectRecord as readRecord } from "@openclaw/normalization-core/record-coerce";
33
import { collectConfiguredAgentHarnessRuntimes } from "../agents/harness-runtimes.js";
44
import type { OpenClawConfig } from "../config/types.openclaw.js";
5+
import { MissingPublicSurfaceError } from "../plugin-sdk/facade-loader.js";
56
import { normalizePluginId, normalizePluginsConfig } from "../plugins/config-state.js";
67
import { passesManifestOwnerBasePolicy } from "../plugins/manifest-owner-policy.js";
78
import {
@@ -14,6 +15,7 @@ import { resolveProviderPolicySurface } from "../plugins/provider-public-artifac
1415
import {
1516
loadBundledPluginPublicArtifactModuleFromCandidatesSync,
1617
loadBundledPluginPublicArtifactModuleSync,
18+
loadPluginPublicArtifactModuleSync,
1719
} from "../plugins/public-surface-loader.js";
1820
import { collectConfiguredWorkerProviderIds } from "../plugins/worker-provider-config.js";
1921
import { listBundledWorkerProviderOwners } from "../plugins/worker-provider-manifest.js";
@@ -126,10 +128,27 @@ export function registerBundledHealthChecks(params: {
126128
memoryCoreActive: isMemoryCoreActive(params.cfg),
127129
});
128130
if (shouldRegisterCodexManagedHealth(params.cfg)) {
129-
loadBundledPluginPublicArtifactModuleSync<BundledHealthApi>({
130-
dirName: "codex",
131+
const registry = loadPluginManifestRegistryForPluginRegistry({
132+
config: params.cfg,
133+
workspaceDir: params.cwd,
134+
env,
135+
pluginIds: ["codex"],
136+
});
137+
const owner = registry.plugins.find((plugin) => plugin.id === "codex");
138+
// Doctor must inspect the selected runtime's artifact, including official external installs.
139+
// A bundled-first lookup can inspect a different version or bypass the selected owner's trust.
140+
if (!owner || (owner.origin !== "bundled" && owner.trustedOfficialInstall !== true)) {
141+
throw new MissingPublicSurfaceError(
142+
"Unable to resolve Codex doctor health API: install the official Codex plugin with openclaw plugins install @openclaw/codex",
143+
);
144+
}
145+
loadPluginPublicArtifactModuleSync<
146+
Required<Pick<BundledHealthApi, "registerCodexManagedAppServerDoctorChecks">>
147+
>({
148+
pluginRoot: owner.rootDir,
131149
artifactBasename: "api.js",
132-
}).registerCodexManagedAppServerDoctorChecks?.({ getHealthCheck, registerHealthCheck });
150+
origin: owner.origin === "bundled" ? "bundled" : "global",
151+
}).registerCodexManagedAppServerDoctorChecks({ getHealthCheck, registerHealthCheck });
133152
}
134153
if (shouldRegisterPolicyHealth(params)) {
135154
loadBundledPluginPublicArtifactModuleSync<BundledHealthApi>({
@@ -170,9 +189,6 @@ function shouldRegisterCodexManagedHealth(cfg: OpenClawConfig): boolean {
170189
if (!collectConfiguredAgentHarnessRuntimes(cfg).includes("codex")) {
171190
return false;
172191
}
173-
if (cfg.plugins?.entries?.codex?.enabled === false) {
174-
return false;
175-
}
176192
return passesManifestOwnerBasePolicy({
177193
plugin: { id: "codex" },
178194
normalizedConfig: normalizePluginsConfig(cfg.plugins),

‎src/plugins/public-surface-loader.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ export function loadBundledPluginPublicArtifactModuleSync<T extends object>(para
132132
export function loadPluginPublicArtifactModuleSync<T extends object>(params: {
133133
pluginRoot: string;
134134
artifactBasename: string;
135+
origin?: "bundled" | "global";
135136
}): T {
136137
const root = getPluginCacheRoot(params.pluginRoot);
137138
const key = `public:${params.artifactBasename}`;
@@ -150,7 +151,7 @@ export function loadPluginPublicArtifactModuleSync<T extends object>(params: {
150151
...location,
151152
boundaryLabel: "plugin root",
152153
surfaceLabel: `plugin public surface ${params.artifactBasename}`,
153-
origin: "global",
154+
origin: params.origin ?? "global",
154155
}) as T;
155156
}
156157

0 commit comments

Comments
 (0)