Skip to content

Commit 92c7400

Browse files
authored
perf(cli): finish cold read paths (#117957)
* perf(cli): finish cold read paths * test(cli): satisfy cold path lint gates * test(cli): fix cold path fixture typing
1 parent 9cf1273 commit 92c7400

14 files changed

Lines changed: 360 additions & 24 deletions

‎extensions/memory-core/src/cli-runtime-common.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ async function loadMemoryCommandConfig(
5555
commandName: string,
5656
mode?: "enforce_resolved" | "read_only_status",
5757
) {
58-
const config = getRuntimeConfig();
58+
const config = getRuntimeConfig({ skipPluginValidation: true });
5959
try {
6060
const { resolvedConfig, diagnostics } = await resolveCommandSecretRefsViaGateway({
6161
config,

‎extensions/memory-core/src/cli.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,8 @@ describe("memory cli", () => {
502502
const log = spyRuntimeLogs(defaultRuntime);
503503
await runMemoryCli(["status"]);
504504

505+
expect(getRuntimeConfig).toHaveBeenCalledWith({ skipPluginValidation: true });
506+
505507
expect(probeVectorAvailability).not.toHaveBeenCalled();
506508
expectLogged(log, "Vector store: ready");
507509
expectLogged(log, "Semantic vectors: ready");
@@ -1744,6 +1746,8 @@ describe("memory cli", () => {
17441746
const writeJson = spyRuntimeJson(defaultRuntime);
17451747
await runMemoryCli(["search", "hidden codeword", "--agent", "main", "--json"]);
17461748

1749+
expect(getRuntimeConfig).toHaveBeenCalledWith({ skipPluginValidation: true });
1750+
17471751
expect(firstWrittenJsonArg(writeJson)).toEqual({
17481752
results: [],
17491753
stale: true,
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
// Real CLI processes must keep unrelated plugin runtimes cold on read-only command paths.
2+
import { execFile } from "node:child_process";
3+
import fs from "node:fs";
4+
import { createServer, type Server } from "node:http";
5+
import os from "node:os";
6+
import path from "node:path";
7+
import { promisify } from "node:util";
8+
import { afterAll, beforeAll, expect, it } from "vitest";
9+
import {
10+
createColdPluginFixture,
11+
isColdPluginRuntimeLoaded,
12+
} from "../plugins/test-helpers/cold-plugin-fixtures.js";
13+
14+
const execFileAsync = promisify(execFile);
15+
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-cold-commands-"));
16+
let clawHubServer: Server;
17+
let clawHubUrl: string;
18+
19+
beforeAll(async () => {
20+
clawHubServer = createServer((_request, response) => {
21+
response.writeHead(200, { "content-type": "application/json" });
22+
response.end('{"results":[]}');
23+
});
24+
await new Promise<void>((resolve) => {
25+
clawHubServer.listen(0, "127.0.0.1", resolve);
26+
});
27+
const address = clawHubServer.address();
28+
if (!address || typeof address === "string") {
29+
throw new Error("failed to bind the ClawHub fixture server");
30+
}
31+
clawHubUrl = `http://127.0.0.1:${address.port}`;
32+
});
33+
34+
afterAll(async () => {
35+
await new Promise<void>((resolve, reject) => {
36+
clawHubServer.close((error) => (error ? reject(error) : resolve()));
37+
});
38+
fs.rmSync(tempRoot, { recursive: true, force: true });
39+
});
40+
41+
const cases = [
42+
{ label: "hooks", args: ["hooks", "--json"], needsMemoryOwner: false },
43+
{
44+
label: "skills-search",
45+
args: ["skills", "search", "fixture", "--json"],
46+
needsMemoryOwner: false,
47+
},
48+
{
49+
label: "skills-info",
50+
args: ["skills", "info", "fixture-skill", "--json"],
51+
needsMemoryOwner: false,
52+
},
53+
{
54+
label: "memory-status",
55+
args: ["memory", "status", "--agent", "main", "--json"],
56+
needsMemoryOwner: true,
57+
},
58+
{
59+
label: "memory-search",
60+
args: ["memory", "search", "no-hit", "--agent", "main", "--json"],
61+
needsMemoryOwner: true,
62+
},
63+
] as const;
64+
65+
it.each(cases)(
66+
"keeps an unrelated plugin runtime cold for $label",
67+
async ({ args, label, needsMemoryOwner }) => {
68+
const root = path.join(tempRoot, label);
69+
const stateDir = path.join(root, "state");
70+
const workspaceDir = path.join(root, "workspace");
71+
const pluginDir = path.join(root, "cold-plugin");
72+
const memoryOwnerDir = path.join(root, "memory-owner");
73+
fs.mkdirSync(path.join(workspaceDir, "skills", "fixture-skill"), { recursive: true });
74+
fs.mkdirSync(pluginDir, { recursive: true });
75+
fs.writeFileSync(
76+
path.join(workspaceDir, "skills", "fixture-skill", "SKILL.md"),
77+
"---\nname: fixture-skill\ndescription: Cold path fixture\n---\n",
78+
);
79+
const fixture = createColdPluginFixture({
80+
rootDir: pluginDir,
81+
pluginId: `cold-${label}`,
82+
runtimeMessage: `${label} imported an unrelated plugin runtime`,
83+
manifest: { providers: [], channels: [], providerAuthChoices: [], channelConfigs: {} },
84+
});
85+
if (needsMemoryOwner) {
86+
// Keep this fixture about the ownership boundary: the selected CLI owner must
87+
// execute while the unrelated sentinel stays cold. memory-core behavior has
88+
// its own focused CLI suite, including the stale-search result contract.
89+
fs.mkdirSync(memoryOwnerDir, { recursive: true });
90+
fs.writeFileSync(
91+
path.join(memoryOwnerDir, "package.json"),
92+
JSON.stringify({
93+
name: "@example/openclaw-memory-owner",
94+
version: "1.0.0",
95+
type: "commonjs",
96+
openclaw: { extensions: ["./index.cjs"] },
97+
}),
98+
);
99+
fs.writeFileSync(
100+
path.join(memoryOwnerDir, "openclaw.plugin.json"),
101+
JSON.stringify({
102+
id: "memory-owner",
103+
name: "Memory Owner",
104+
configSchema: { type: "object", additionalProperties: false, properties: {} },
105+
commandAliases: [{ name: "fixture-memory", kind: "runtime-slash", cliCommand: "memory" }],
106+
}),
107+
);
108+
fs.writeFileSync(
109+
path.join(memoryOwnerDir, "index.cjs"),
110+
[
111+
'const fs = require("node:fs");',
112+
"module.exports = {",
113+
' id: "memory-owner",',
114+
" register(api) {",
115+
' fs.writeFileSync(process.env.MEMORY_OWNER_MARKER, "loaded", "utf8");',
116+
" api.registerCli(({ program }) => {",
117+
' const memory = program.command("memory");',
118+
' memory.command("status").option("--agent <id>").option("--json").action(() => console.log("[]"));',
119+
' memory.command("search").argument("<query>").option("--agent <id>").option("--json").action(() => console.log("{\\\"results\\\":[]}"));',
120+
' }, { descriptors: [{ name: "memory", description: "Memory fixture", hasSubcommands: true }] });',
121+
" },",
122+
"};",
123+
"",
124+
].join("\n"),
125+
);
126+
}
127+
fs.mkdirSync(stateDir, { recursive: true });
128+
const configPath = path.join(stateDir, "openclaw.json");
129+
fs.writeFileSync(
130+
configPath,
131+
JSON.stringify({
132+
agents: { defaults: { workspace: workspaceDir } },
133+
plugins: {
134+
load: { paths: [pluginDir, ...(needsMemoryOwner ? [memoryOwnerDir] : [])] },
135+
entries: {
136+
[fixture.pluginId]: { enabled: true },
137+
...(needsMemoryOwner ? { "memory-owner": { enabled: true } } : {}),
138+
},
139+
},
140+
}),
141+
);
142+
143+
const result = await execFileAsync(
144+
process.execPath,
145+
["--import", "tsx", "src/entry.ts", ...args],
146+
{
147+
cwd: path.resolve("."),
148+
env: {
149+
...process.env,
150+
NODE_ENV: undefined,
151+
VITEST: undefined,
152+
OPENCLAW_CLAWHUB_URL: clawHubUrl,
153+
OPENCLAW_CONFIG_PATH: configPath,
154+
MEMORY_OWNER_MARKER: path.join(root, "memory-owner-loaded"),
155+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
156+
OPENCLAW_DEV_SOURCE_ROOT: path.resolve("."),
157+
OPENCLAW_HOME: path.join(root, "home"),
158+
OPENCLAW_STATE_DIR: stateDir,
159+
},
160+
maxBuffer: 4 * 1024 * 1024,
161+
timeout: 60_000,
162+
},
163+
);
164+
expect(`${result.stdout}\n${result.stderr}`).not.toContain(
165+
`${label} imported an unrelated plugin runtime`,
166+
);
167+
expect(isColdPluginRuntimeLoaded(fixture)).toBe(false);
168+
if (needsMemoryOwner) {
169+
expect(fs.existsSync(path.join(root, "memory-owner-loaded"))).toBe(true);
170+
}
171+
},
172+
150_000,
173+
);

‎src/cli/command-catalog.ts‎

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,11 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
383383
{ commandPath: ["exec-approvals"], policy: { networkProxy: "bypass" } },
384384
{ commandPath: ["exec-policy"], policy: { networkProxy: "bypass" } },
385385
{ commandPath: ["hooks"], policy: { networkProxy: "bypass" } },
386+
{
387+
commandPath: ["hooks"],
388+
exact: true,
389+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
390+
},
386391
{ commandPath: ["logs"], policy: { networkProxy: "bypass" } },
387392
{ commandPath: ["mcp"], policy: { networkProxy: "bypass" } },
388393
{
@@ -538,14 +543,36 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
538543
exact: true,
539544
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
540545
},
541-
{ commandPath: ["skills", "info"], exact: true, policy: { networkProxy: "bypass" } },
546+
{
547+
commandPath: ["skills", "info"],
548+
exact: true,
549+
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
550+
},
542551
{ commandPath: ["skills", "install"], exact: true },
543552
{
544553
commandPath: ["skills", "list"],
545554
exact: true,
546555
policy: { configGuard: "skip", loadPlugins: "never", networkProxy: "bypass" },
547556
},
548-
{ commandPath: ["skills", "search"], exact: true },
557+
{
558+
commandPath: ["skills", "search"],
559+
exact: true,
560+
policy: { configGuard: "skip", loadPlugins: "never" },
561+
},
562+
{
563+
commandPath: ["memory", "search"],
564+
exact: true,
565+
policy: { configGuard: "skip", loadPlugins: "never" },
566+
},
567+
{
568+
commandPath: ["memory", "status"],
569+
exact: true,
570+
policy: {
571+
configGuard: ({ argv }) =>
572+
hasFlag(argv, "--index") || hasFlag(argv, "--fix") ? "run" : "skip",
573+
loadPlugins: "never",
574+
},
575+
},
549576
{ commandPath: ["skills", "update"], exact: true },
550577
{ commandPath: ["skills", "verify"], exact: true },
551578
];

‎src/cli/command-path-policy.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,39 @@ describe("command-path-policy", () => {
350350
loadPlugins: "never",
351351
networkProxy: "bypass",
352352
});
353+
for (const commandPath of [["hooks"], ["skills", "info"]]) {
354+
expectResolvedPolicy(commandPath, {
355+
configGuard: "skip",
356+
loadPlugins: "never",
357+
networkProxy: "bypass",
358+
});
359+
}
360+
for (const commandPath of [
361+
["skills", "search"],
362+
["memory", "search"],
363+
]) {
364+
expectResolvedPolicy(commandPath, {
365+
configGuard: "skip",
366+
loadPlugins: "never",
367+
});
368+
}
369+
const memoryStatusPolicy = resolveCliCommandPathPolicy(["memory", "status"]);
370+
expectConfigGuardResolver(memoryStatusPolicy);
371+
expect(memoryStatusPolicy.loadPlugins).toBe("never");
372+
expect(
373+
memoryStatusPolicy.configGuard({
374+
argv: ["node", "openclaw", "memory", "status"],
375+
commandPath: ["memory", "status"],
376+
}),
377+
).toBe("skip");
378+
for (const flag of ["--index", "--fix"]) {
379+
expect(
380+
memoryStatusPolicy.configGuard({
381+
argv: ["node", "openclaw", "memory", "status", flag],
382+
commandPath: ["memory", "status"],
383+
}),
384+
).toBe("run");
385+
}
353386
});
354387

355388
it("keeps routed and Commander config reads ahead of observing startup guards", () => {

‎src/cli/command-startup-policy.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@ describe("command-startup-policy", () => {
3939
["skills"],
4040
["skills", "list"],
4141
["skills", "check"],
42+
["skills", "info"],
43+
["skills", "search"],
44+
["hooks"],
45+
["memory", "search"],
46+
["memory", "status"],
4247
["gateway", "stability"],
4348
["gateway", "usage-cost"],
4449
]) {
@@ -57,6 +62,14 @@ describe("command-startup-policy", () => {
5762
}).skipConfigGuard,
5863
).toBe(false);
5964
expect(resolvePolicy({ commandPath: ["config", "set"] }).skipConfigGuard).toBe(false);
65+
for (const flag of ["--index", "--fix"]) {
66+
expect(
67+
resolvePolicy({
68+
argv: ["node", "openclaw", "memory", "status", flag],
69+
commandPath: ["memory", "status"],
70+
}).skipConfigGuard,
71+
).toBe(false);
72+
}
6073
});
6174

6275
it("keeps every route-first command on the same config guard declaration as Commander", () => {

‎src/cli/hooks-cli.process.test.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ async function createLingeringPluginFixture(): Promise<{
5959
JSON.stringify({
6060
id: "linger",
6161
name: "Linger",
62+
activation: { onCapabilities: ["hook"] },
6263
configSchema: { type: "object", additionalProperties: false, properties: {} },
6364
}),
6465
);
@@ -69,8 +70,9 @@ async function createLingeringPluginFixture(): Promise<{
6970
"export default {",
7071
' id: "linger",',
7172
' name: "Linger",',
72-
" register() {",
73+
" register(api) {",
7374
' fs.writeFileSync(process.env.LINGER_MARKER, "registered\\n");',
75+
' api.registerHook("command:new", () => {}, { name: "fixture-hook", description: "Fixture hook" });',
7476
" setInterval(() => {}, 60_000);",
7577
" },",
7678
"};",
@@ -408,7 +410,9 @@ describe("hooks CLI process lifecycle", () => {
408410

409411
expect(listResult, listResult.stderr).toMatchObject({ code: 0, signal: null });
410412
expect(listResult.stderr).not.toContain("Error:");
411-
expect(JSON.parse(listResult.stdout)).toMatchObject({ hooks: expect.any(Array) });
413+
expect(JSON.parse(listResult.stdout)).toMatchObject({
414+
hooks: expect.arrayContaining([expect.objectContaining({ name: "fixture-hook" })]),
415+
});
412416
await expect(fs.readFile(fixture.markerPath, "utf8")).resolves.toBe("registered\n");
413417
expect(relayResult, relayResult.stderr).toMatchObject({ code: 0, signal: null });
414418
expect(JSON.parse(relayResult.stdout)).toMatchObject({

‎src/cli/hooks-cli.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { resolveHookEntries } from "../hooks/policy.js";
1818
import type { HookEntry } from "../hooks/types.js";
1919
import { loadWorkspaceHookEntries } from "../hooks/workspace.js";
2020
import { formatErrorMessage } from "../infra/errors.js";
21+
import { resolveGatewayStartupPluginIds } from "../plugins/channel-plugin-ids.js";
2122
import { buildPluginDiagnosticsReport } from "../plugins/status.js";
2223
import { defaultRuntime } from "../runtime.js";
2324
import { shortenHomePath } from "../utils.js";
@@ -54,7 +55,14 @@ function buildHooksReport(config: OpenClawConfig): HookStatusReport {
5455
// Plugin-managed and workspace hooks share one resolved policy view for status/actions.
5556
const workspaceDir = resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config));
5657
const workspaceEntries = loadWorkspaceHookEntries(workspaceDir, { config });
57-
const pluginReport = buildPluginDiagnosticsReport({ config, workspaceDir });
58+
// Native plugin hooks only exist after registration. Match the Gateway's startup
59+
// plan so active hooks remain visible without executing unrelated installed plugins.
60+
const onlyPluginIds = resolveGatewayStartupPluginIds({
61+
config,
62+
workspaceDir,
63+
env: process.env,
64+
});
65+
const pluginReport = buildPluginDiagnosticsReport({ config, workspaceDir, onlyPluginIds });
5866
const pluginEntries = pluginReport.hooks.map((hook) => hook.entry);
5967
const entries = mergeHookEntries(pluginEntries, workspaceEntries);
6068
return buildWorkspaceHookStatus(workspaceDir, { config, entries });
@@ -622,7 +630,7 @@ export function registerHooksCli(program: Command): void {
622630

623631
hooks.action(async (opts: HooksListOptions) =>
624632
runOneShotHooksCliAction(async () => {
625-
const config = getRuntimeConfig();
633+
const config = getRuntimeConfig({ skipPluginValidation: true });
626634
const report = buildHooksReport(config);
627635
const json = hasJsonOutput(opts);
628636
writeHooksOutput(formatHooksList(report, { ...opts, json }), json);

0 commit comments

Comments
 (0)