Skip to content

Commit ad5536d

Browse files
authored
fix(plugins): resolve CLI plugin metadata once per invocation (#131884)
loadOpenClawPluginCliRegistry is the only path that executes a plugin's register() in CLI-metadata mode, and unlike the sibling runtime loader it had no registry reuse. A single CLI invocation resolves plugin CLI metadata from several independent bootstrap stages (machine-output probe, plugin-root ownership probe, unowned-command surface owner, command registration), so each stage rebuilt a registry from scratch, re-imported every legacy external plugin module, re-ran its register, and re-emitted its diagnostics. The producer now serves and populates the existing lifecycle-owned registry cache under a cli-metadata:: key namespace, keyed by the cacheKey that resolvePluginLoadCacheContext already computes (allowlist, plugin entries, onlyPluginIds, SDK resolution, workspace). The namespace is required because a runtime load with activate:false shares that cacheKey but produces a completely different registry. Intentionally distinct scopes still get their own pass: the allowlist-agnostic diagnostic lookup and root help's narrower legacy-external scope are not collapsed. The duplicated "is registry caching allowed" predicate moves into isPluginRegistryCacheEnabled so both loaders share one policy. Real CLI proof with a fixture legacy external plugin whose register throws (default config, isolated state dir): duplicate register diagnostics drop from 3 to 1 for `openclaw <unknown-cmd>`, `openclaw <plugin-cmd> --help`, and `openclaw plugins list`.
1 parent 95f9d86 commit ad5536d

4 files changed

Lines changed: 123 additions & 1 deletion

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Pins one plugin register execution per CLI invocation across independent bootstrap stages.
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
import { afterAll, afterEach, describe, expect, it } from "vitest";
5+
import type { OpenClawConfig } from "../config/types.openclaw.js";
6+
import { loadPluginCliDescriptors, resolvePluginCliRootOwnerIds } from "./cli-registry-loader.js";
7+
import { getPluginCliCommandDescriptors } from "./cli-root-descriptors.js";
8+
import {
9+
cleanupPluginLoaderFixturesForTest,
10+
makePluginLoaderTempDir,
11+
resetPluginLoaderTestStateForTest,
12+
useNoBundledPlugins,
13+
writePlugin,
14+
} from "./loader.test-fixtures.js";
15+
16+
afterEach(() => {
17+
resetPluginLoaderTestStateForTest();
18+
});
19+
20+
afterAll(() => {
21+
cleanupPluginLoaderFixturesForTest();
22+
});
23+
24+
function countRegisterRuns(markerPath: string): number {
25+
return fs.existsSync(markerPath)
26+
? fs.readFileSync(markerPath, "utf8").split("\n").filter(Boolean).length
27+
: 0;
28+
}
29+
30+
function setupCountingCliPlugin(): { config: OpenClawConfig; markerPath: string } {
31+
useNoBundledPlugins();
32+
const pluginDir = makePluginLoaderTempDir();
33+
const markerPath = path.join(makePluginLoaderTempDir(), "register-runs.log");
34+
writePlugin({
35+
id: "counting-cli",
36+
dir: pluginDir,
37+
filename: "index.cjs",
38+
body: `const fs = require("node:fs");
39+
module.exports = {
40+
id: "counting-cli",
41+
register(api) {
42+
fs.appendFileSync(${JSON.stringify(markerPath)}, "register\\n");
43+
api.registerCli(() => {}, {
44+
commands: ["counting-cli"],
45+
descriptors: [
46+
{ name: "counting-cli", description: "Counting CLI", hasSubcommands: false },
47+
],
48+
});
49+
},
50+
};`,
51+
});
52+
return {
53+
config: {
54+
plugins: {
55+
load: { paths: [path.join(pluginDir, "index.cjs")] },
56+
allow: ["counting-cli"],
57+
},
58+
} as OpenClawConfig,
59+
markerPath,
60+
};
61+
}
62+
63+
describe("plugin CLI metadata registration count", () => {
64+
it("runs a legacy external plugin register once across CLI bootstrap stages", async () => {
65+
const { config, markerPath } = setupCountingCliPlugin();
66+
67+
// Stage order mirrors one `openclaw counting-cli --help` invocation: the unowned-primary
68+
// guard resolves plugin CLI root ownership, then command registration resolves descriptors
69+
// for the same primary. Both stages resolve CLI metadata for the same load scope.
70+
const ownerIds = await resolvePluginCliRootOwnerIds({
71+
cfg: config,
72+
env: process.env,
73+
primaryCommand: "counting-cli",
74+
});
75+
const descriptors = await loadPluginCliDescriptors({
76+
cfg: config,
77+
env: process.env,
78+
primaryCommand: "counting-cli",
79+
});
80+
81+
expect(ownerIds).toEqual(["counting-cli"]);
82+
expect(descriptors.map((entry) => entry.name)).toContain("counting-cli");
83+
expect(countRegisterRuns(markerPath)).toBe(1);
84+
});
85+
86+
it("keeps distinct load scopes on separate register passes", async () => {
87+
const { config, markerPath } = setupCountingCliPlugin();
88+
// Root help executes only the legacy external plugins it could not read from manifests, so
89+
// its narrower scope must not be served the full-scope registry (or vice versa).
90+
await loadPluginCliDescriptors({ cfg: config, env: process.env });
91+
await getPluginCliCommandDescriptors(config, process.env);
92+
93+
expect(countRegisterRuns(markerPath)).toBe(2);
94+
});
95+
});

‎src/plugins/loader-cache.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ export function getReusableCachedPluginRegistry(cacheKey: string): PluginRegistr
1818
return pluginLoaderCacheState.get(cacheKey);
1919
}
2020

21+
/** Registry reuse is off for explicit opt-outs and for raw env-substituted config loads. */
22+
export function isPluginRegistryCacheEnabled(options: PluginLoadOptions): boolean {
23+
return options.cache !== false && options.resolveRawConfigEnvVars !== true;
24+
}
25+
2126
export function clearPluginRegistryLoadCache(): void {
2227
clearPluginRuntimeArtifactResolutionMemo();
2328
pluginLoaderCacheState.clearCachedRegistries();

‎src/plugins/loader-cli-registry.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import {
1111
} from "./config-state.js";
1212
import { isPluginEnabledByDefaultForPlatform } from "./default-enablement.js";
1313
import { shouldRejectHardlinkedPluginFiles } from "./hardlink-policy.js";
14+
import {
15+
getReusableCachedPluginRegistry,
16+
isPluginRegistryCacheEnabled,
17+
setCachedPluginRegistry,
18+
} from "./loader-cache.js";
1419
import { resolvePluginLoadDiscovery } from "./loader-discovery.js";
1520
import { resolvePluginLoadCacheContext } from "./loader-load-context.js";
1621
import {
@@ -48,6 +53,19 @@ export async function loadOpenClawPluginCliRegistry(
4853
options: PluginLoadOptions = {},
4954
): Promise<PluginRegistry> {
5055
const context = resolvePluginLoadCacheContext({ ...options, activate: false });
56+
// One CLI invocation resolves descriptors from several bootstrap stages; without reuse each
57+
// stage re-executes every legacy external plugin's register and re-emits its diagnostics.
58+
// The namespace is required: a runtime load with activate:false shares this cacheKey but
59+
// produces a completely different registry. Diagnostics ride the cached registry, so only
60+
// the duplicate log emission is dropped.
61+
const cacheKey = `cli-metadata::${context.cacheKey}`;
62+
const cacheEnabled = isPluginRegistryCacheEnabled(options);
63+
if (cacheEnabled) {
64+
const cached = getReusableCachedPluginRegistry(cacheKey);
65+
if (cached) {
66+
return cached;
67+
}
68+
}
5169
const logger = options.logger ?? createPluginLoaderLogger();
5270
const onlyPluginIdSet = createPluginIdScopeSet(context.onlyPluginIds);
5371
const loadPluginModule = createPluginModuleLoader({
@@ -346,6 +364,9 @@ export async function loadOpenClawPluginCliRegistry(
346364
});
347365
}
348366
}
367+
if (cacheEnabled) {
368+
setCachedPluginRegistry(cacheKey, registry);
369+
}
349370
return registry;
350371
}
351372

‎src/plugins/loader-runtime-load.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { resolveEffectivePluginActivationState } from "./config-state.js";
88
import { isPluginEnabledByDefaultForPlatform } from "./default-enablement.js";
99
import {
1010
getReusableCachedPluginRegistry,
11+
isPluginRegistryCacheEnabled,
1112
pluginLoaderCacheState,
1213
setCachedPluginRegistry,
1314
} from "./loader-cache.js";
@@ -99,7 +100,7 @@ function loadOpenClawPluginsInternal(
99100
const logger = options.logger ?? createPluginLoaderLogger();
100101
const validateOnly = options.mode === "validate";
101102
const onlyPluginIdSet = createPluginIdScopeSet(context.onlyPluginIds);
102-
const cacheEnabled = options.cache !== false && options.resolveRawConfigEnvVars !== true;
103+
const cacheEnabled = isPluginRegistryCacheEnabled(options);
103104
if (cacheEnabled) {
104105
const cached = getReusableCachedPluginRegistry(context.cacheKey);
105106
if (cached) {

0 commit comments

Comments
 (0)