Skip to content

Commit 4ee2216

Browse files
authored
fix(cli): avoid repeated plugin preparation at startup (#131503)
* fix(cli): retain invocation-owned plugin startup facts Bind non-Gateway CLI work to one operation PluginCache while closing preparation authority before actions. Preserve selected-workspace execution and config-wide validation. Defer the config writer, broad runtime state, and complete SDK aliases until demanded; keep late CJS and ESM actions in their creating cache. Rebuild the startup-only fix on the canonical progressive plugin cache without restoring superseded metadata and cache layers. Startup split from the standalone relay investigation in #128379; updates #131503. * fix(doctor): preserve registry scope across metadata refreshes Give explicit post-lease and post-mutation reads a fresh metadata generation without retiring the invoking CLI or Gateway owner. Persist the original workspace index while retaining the complete config-wide validation view. Bind rebased snapshots to their creating cache so later consumers cannot borrow a stale or foreign generation. Replace mocked persistence assertions with real scoped-index, lease, checkpoint, schema and provenance regressions. Follow-up to the installed startup verification for #131503. * fix(cli): defer MCP serving and stabilize startup checks Load the existing channel MCP server only for the serve action, and use the already-eager client-runtime import for reload. Registration and probes no longer evaluate the unused serving owner. Initialize the config CLI runtime capture before hoisted mocks. Give the real Doctor checkpoint fixture explicit build provenance and verify durable rows for successful, interrupted, and unidentified builds without changing runtime checkpoint policy. Remove duplicate fixture initialization and avoid dumping captured environments on rejection failures. Refs: #131503 (CLI startup preparation) * test(plugins): follow runtime load context module split Import the canonical runtime context resolver from its new owning module in the CLI lifetime regression. Preserve the existing behavior assertions; the original CI TS2724 reproduces before the import correction and the same type program and 16 lifetime cases pass afterward. Refs: #131503 (CLI startup preparation) * test(plugins): drop duplicate alias memoization assertion Remove the case that compares the same cached alias object with itself. Keep the stronger identity/no-repeated-filesystem-read test, context-isolation cases, and real source/native loader coverage. No production API or behavior changes. Refs: #131503 (CLI startup preparation) * fix(ui): stop retired usage loads before requests Preserve main's canonical lazy Usage loading and check the router, transport epoch, and selected agent after the deferred import. Carry the existing route signal to all aggregate requests so obsolete navigation does not start new RPCs or retain client waits. Keep independent preload lifetime intact. Consolidate pending results to absorb the ownership checks with a net reduction of one production line. Real router/Gateway/selection regressions fail before the fix and pass afterward. Browser Back during a held service-worker fetch starts three obsolete Usage requests before the fix and none afterward; a fresh Usage visit still loads normally. This does not claim cancellation of server work already sent. Refs: #131503 (CLI startup preparation and integration repair) Related: #132140 (canonical Usage startup loading) * test(ui): assert fresh usage data after epoch changes Keep the waited fresh-result identity and stale-result rejection checks. Remove two redundant assertions that required the old two-argument request shape and rejected the newly forwarded cancellation signal. The same failure appeared in both Control UI and Node CI lanes. Both test entrypoints now pass, along with adjacent Usage/controller coverage, UI test types, lint, and formatting. No production code, mock response, timeout, or stale/fresh data assertion changes. Refs: #131503 (CLI startup and Usage lifecycle integration) CI: https://github.com/openclaw/openclaw/actions/runs/33224402718
1 parent 5b7485f commit 4ee2216

54 files changed

Lines changed: 3506 additions & 1021 deletions

Some content is hidden

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

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3476,7 +3476,6 @@ src/plugins/channel-presence-policy.ts 2
34763476
src/plugins/channel-validation.ts 1
34773477
src/plugins/clawhub.ts 10
34783478
src/plugins/cli-gateway-nodes-runtime.ts 2
3479-
src/plugins/cli.ts 1
34803479
src/plugins/command-registration.ts 3
34813480
src/plugins/computer-use-contract.ts 3
34823481
src/plugins/config-normalization-shared.ts 20
@@ -3528,7 +3527,7 @@ src/plugins/loader-channel-setup.ts 17
35283527
src/plugins/loader-cli-registry.ts 2
35293528
src/plugins/loader-discovery.ts 1
35303529
src/plugins/loader-load-context.ts 4
3531-
src/plugins/loader-module-runtime.ts 13
3530+
src/plugins/loader-module-runtime.ts 12
35323531
src/plugins/loader-records.ts 1
35333532
src/plugins/loader-runtime-candidate.ts 1
35343533
src/plugins/loader-runtime-load.ts 2

‎docs/plugins/architecture-internals.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,20 @@ execution. Consent checks use a fresh inspection after an awaited approval so
148148
changed artifacts cannot inherit approval for older capabilities. Failed module
149149
evaluation remains retryable; a successful import is shared across consumers.
150150

151+
The CLI invocation owns one operation cache across config reads, output metadata,
152+
command ownership, nested registration, and actions. Standalone registration uses
153+
its caller's active generation. Config validation covers every
154+
workspace; execution uses the original selected workspace snapshot, or shared
155+
roots when no workspace owner is proven. Exact config/source identities and
156+
revision checks fence retained registrars. Preparation closes before Commander
157+
actions, while its cache scope lasts through action completion for late imports.
158+
Changed package files require a new operation; changing activation inputs does
159+
not retire compatible package facts. SDK alias maps are prepared on first alias
160+
or transformer demand under their captured host and permission scope. State
161+
registration uses a light facade that the full runtime later adopts; only the
162+
registry proxy grants store access. Config reads import the writer only when an
163+
actual write begins.
164+
151165
Registered services, hooks, tools, session MCP overlays, generated skill-link
152166
publication, and activation state remain runtime-owned.
153167
An active registry pins its chosen artifact binding so source and built modules

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

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,15 @@ import {
1313
} from "../plugins/plugin-metadata.test-support.js";
1414
import type { ConfigSetDryRunResult } from "./config-set-dryrun.js";
1515
import { applyCliProfileEnv } from "./profile.js";
16-
import { createCliRuntimeCapture, mockRuntimeModule } from "./test-runtime-capture.js";
16+
17+
// The metadata fixture can reach the runtime mock before ordinary imports finish.
18+
const { defaultRuntime, resetRuntimeCapture, mockRuntimeModule } = await vi.hoisted(async () => {
19+
const runtimeHelpers = await import("./test-runtime-capture.js");
20+
return {
21+
...runtimeHelpers.createCliRuntimeCapture(),
22+
mockRuntimeModule: runtimeHelpers.mockRuntimeModule,
23+
};
24+
});
1725

1826
/**
1927
* Test for issue #6070:
@@ -215,7 +223,6 @@ vi.mock("../secrets/channel-contract-api.js", () => ({
215223
loadChannelSecretContractApiForRecord: () => undefined,
216224
}));
217225

218-
const { defaultRuntime, resetRuntimeCapture } = createCliRuntimeCapture();
219226
const mockLog = defaultRuntime.log;
220227
const mockWriteStdout = defaultRuntime.writeStdout;
221228
const mockError = defaultRuntime.error;
@@ -4613,7 +4620,6 @@ describe("config cli", () => {
46134620
},
46144621
};
46154622
setSnapshot(resolved, resolved);
4616-
setSnapshot(resolved, resolved);
46174623
mockCheckTouchedTextModelRefs.mockResolvedValueOnce({
46184624
refsChecked: 1,
46194625
refsTotal: 1,
@@ -4656,7 +4662,6 @@ describe("config cli", () => {
46564662
},
46574663
};
46584664
setSnapshot(resolved, resolved);
4659-
setSnapshot(resolved, resolved);
46604665

46614666
await runConfigCommand(["config", "unset", "tools.alsoAllow", "--dry-run", "--json"]);
46624667

@@ -4806,7 +4811,6 @@ describe("config cli", () => {
48064811
},
48074812
};
48084813
setSnapshot(resolved, resolved);
4809-
setSnapshot(resolved, resolved);
48104814
mockResolveSecretRefValue.mockRejectedValueOnce(new Error("provider removed"));
48114815

48124816
await expect(
@@ -4839,7 +4843,6 @@ describe("config cli", () => {
48394843
},
48404844
} as OpenClawConfig;
48414845
setSnapshot(resolved, resolved);
4842-
setSnapshot(resolved, resolved);
48434846

48444847
await runConfigCommand(["config", "unset", "secrets.defaults", "--dry-run"]);
48454848

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { Command } from "commander";
2+
import { expect, it, vi } from "vitest";
3+
4+
vi.mock("../mcp/channel-server.js", () => {
5+
throw new Error("MCP client commands must not load the channel-serving runtime");
6+
});
7+
8+
it("registers MCP commands and reloads client runtimes without channel serving", async () => {
9+
const { registerMcpCli } = await import("./mcp-cli.js");
10+
const program = new Command();
11+
program.exitOverride();
12+
registerMcpCli(program);
13+
14+
await expect(program.parseAsync(["mcp", "reload"], { from: "user" })).resolves.toBe(program);
15+
});

‎src/cli/mcp-cli.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,10 @@ import {
1111
} from "@openclaw/normalization-core/string-coerce";
1212
import { Command } from "commander";
1313
import { buildBundleMcpToolsFromCatalog } from "../agents/agent-bundle-mcp-materialize.js";
14-
import { createSessionMcpRuntime } from "../agents/agent-bundle-mcp-runtime.js";
14+
import {
15+
createSessionMcpRuntime,
16+
disposeAllSessionMcpRuntimes,
17+
} from "../agents/agent-bundle-mcp-runtime.js";
1518
import {
1619
setConfiguredMcpServer,
1720
unsetConfiguredMcpServer,
@@ -39,7 +42,6 @@ import {
3942
type OAuthLoopbackCallbackServer,
4043
} from "../infra/oauth-loopback-callback.js";
4144
import { resolveEnvironmentValue } from "../infra/process-env.js";
42-
import { serveOpenClawChannelMcp } from "../mcp/channel-server.js";
4345
import { defaultRuntime } from "../runtime.js";
4446
import { runTasksWithConcurrency } from "../utils/run-with-concurrency.js";
4547
import { formatCliCommand } from "./command-format.js";
@@ -670,6 +672,7 @@ export function registerMcpCli(program: Command) {
670672
) {
671673
throw new Error('Invalid --claude-channel-mode value. Use "auto", "on", or "off".');
672674
}
675+
const { serveOpenClawChannelMcp } = await import("../mcp/channel-server.js");
673676
await serveOpenClawChannelMcp({
674677
gatewayUrl: opts.url as string | undefined,
675678
gatewayToken,
@@ -1479,8 +1482,6 @@ export function registerMcpCli(program: Command) {
14791482
.command("reload")
14801483
.description("Dispose cached MCP runtimes so new config is used on the next turn")
14811484
.action(async () => {
1482-
const { disposeAllSessionMcpRuntimes } =
1483-
await import("../agents/agent-bundle-mcp-runtime.js");
14841485
await disposeAllSessionMcpRuntimes();
14851486
defaultRuntime.log(
14861487
"Disposed cached MCP runtimes. Active agents use new MCP config on their next runtime build.",

‎src/cli/run-main.exit.test.ts‎

Lines changed: 98 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { GATEWAY_SERVICE_RUNTIME_PID_ENV } from "../daemon/constants.js";
1111
import { setLoggerOverride } from "../logging/logger.js";
1212
import { loggingState } from "../logging/state.js";
1313
import { createSubsystemLogger } from "../logging/subsystem.js";
14+
import { getPluginCache, getScopedPluginCache, type PluginCache } from "../plugins/plugin-cache.js";
1415
import { withSecureTestNodeExecPath } from "../secrets/test-node-command.test-support.js";
1516
import type { LocalOnboardingState } from "../state/local-onboarding-state.js";
1617
import { captureEnv, withEnvAsync } from "../test-utils/env.js";
@@ -93,6 +94,13 @@ const registerCoreCliByNameMock = vi.hoisted(() => vi.fn());
9394
const registerSubCliByNameMock = vi.hoisted(() => vi.fn());
9495
const registerPluginCliCommandsFromValidatedConfigMock = vi.hoisted(() => vi.fn(async () => ({})));
9596
const resolvePluginCliRootOwnerIdsMock = vi.hoisted(() => vi.fn());
97+
const createPluginCliLoadSessionMock = vi.hoisted(() =>
98+
vi.fn(() => ({
99+
readConfig: <T>(read: () => Promise<T>) => read(),
100+
withCache: <T>(run: () => T) => run(),
101+
close: vi.fn(),
102+
})),
103+
);
96104
const loadPluginCliDescriptorsMock = vi.hoisted(() =>
97105
vi.fn<
98106
() => Promise<
@@ -179,7 +187,11 @@ const createCliProgressMock = vi.hoisted(() =>
179187
done: progressDoneMock,
180188
})),
181189
);
182-
const loadConfigMock = vi.hoisted(() => vi.fn(() => ({})));
190+
const loadConfigMock = vi.hoisted(() =>
191+
vi.fn<
192+
(...args: Parameters<typeof import("../config/io.js").readBestEffortConfig>) => OpenClawConfig
193+
>(() => ({})),
194+
);
183195
const readSourceConfigBestEffortMock = vi.hoisted(() => vi.fn(async () => ({})));
184196
const startProxyMock = vi.hoisted(() =>
185197
vi.fn<(config: unknown) => Promise<unknown>>(async () => null),
@@ -403,6 +415,7 @@ vi.mock("../plugins/cli.js", () => ({
403415

404416
vi.mock("../plugins/cli-registry-loader.js", () => ({
405417
loadPluginCliDescriptors: loadPluginCliDescriptorsMock,
418+
createPluginCliLoadSession: createPluginCliLoadSessionMock,
406419
resolvePluginCliRootOwnerIds: resolvePluginCliRootOwnerIdsMock,
407420
}));
408421

@@ -462,6 +475,9 @@ vi.mock("./progress.js", () => ({
462475

463476
vi.mock("../config/io.js", () => ({
464477
readBestEffortConfig: loadConfigMock,
478+
readBestEffortConfigSnapshot: async (...args: Parameters<typeof loadConfigMock>) => ({
479+
config: loadConfigMock(...args),
480+
}),
465481
readSourceConfigBestEffort: readSourceConfigBestEffortMock,
466482
}));
467483

@@ -613,6 +629,62 @@ describe("runCli exit behavior", () => {
613629
loggingState.forceConsoleToStderr = false;
614630
});
615631

632+
it("carries one lightweight generation through builtin reads, nested registration and actions", async () => {
633+
const outside = getPluginCache();
634+
const phases: PluginCache[] = [];
635+
loadConfigMock.mockImplementationOnce(() => {
636+
phases.push(getPluginCache());
637+
return {};
638+
});
639+
registerSubCliByNameMock.mockImplementationOnce(async () => {
640+
await Promise.resolve();
641+
phases.push(getPluginCache());
642+
});
643+
const parseAsync = vi.fn(async () => {
644+
await Promise.resolve();
645+
phases.push(getPluginCache());
646+
});
647+
const program = {
648+
commands: [{ name: () => "plugins", aliases: () => [] }],
649+
parseAsync,
650+
};
651+
buildProgramMock.mockReturnValueOnce(program).mockReturnValueOnce(program);
652+
tryRouteCliMock.mockResolvedValueOnce(false).mockResolvedValueOnce(false);
653+
654+
await runCli(["node", "openclaw", "plugins", "late"]);
655+
656+
expect(phases).toHaveLength(3);
657+
const owner = phases[0]!;
658+
expect(owner.kind).toBe("operation");
659+
expect(phases.every((cache) => cache === owner)).toBe(true);
660+
expect(owner).not.toBe(outside);
661+
expect(getPluginCache()).toBe(outside);
662+
expect(createPluginCliLoadSessionMock).not.toHaveBeenCalled();
663+
expect(registerPluginCliCommandsFromValidatedConfigMock).not.toHaveBeenCalled();
664+
665+
await runCli(["node", "openclaw", "plugins", "late"]);
666+
expect(phases.at(-1)).not.toBe(owner);
667+
expect(getPluginCache()).toBe(outside);
668+
});
669+
670+
it("does not replace Gateway's cache owner on the full Commander path", async () => {
671+
const owner = getPluginCache();
672+
const scoped = getScopedPluginCache();
673+
const parseAsync = vi.fn(async () => {
674+
await Promise.resolve();
675+
expect(getPluginCache()).toBe(owner);
676+
expect(getScopedPluginCache()).toBe(scoped);
677+
});
678+
buildProgramMock.mockReturnValueOnce({
679+
commands: [{ name: () => "gateway", aliases: () => [] }],
680+
parseAsync,
681+
});
682+
tryRouteCliMock.mockResolvedValueOnce(false);
683+
await runCli(["node", "openclaw", "--log-level", "debug", "gateway", "run"]);
684+
expect(parseAsync).toHaveBeenCalledTimes(1);
685+
expect(getPluginCache()).toBe(owner);
686+
});
687+
616688
it("does not load inactive provider cleanup modules for cold help", async () => {
617689
const parseAsync = vi.fn().mockResolvedValueOnce(undefined);
618690
buildProgramMock.mockReturnValueOnce({
@@ -2741,17 +2813,17 @@ describe("runCli exit behavior", () => {
27412813
exists: true,
27422814
valid: true,
27432815
sourceConfig: {
2744-
env: { vars: { OPENCLAW_TEST_PROXY_SELECTION: "selected" } },
2816+
env: { vars: { OPENCLAW_TEST_PROXY_SELECTION: "http://127.0.0.1:19876" } },
27452817
gateway: { mode: "local" },
27462818
},
27472819
});
27482820
loadConfigMock.mockImplementationOnce(() => ({
2749-
proxy: { selected: process.env.OPENCLAW_TEST_PROXY_SELECTION },
2821+
proxy: { proxyUrl: process.env.OPENCLAW_TEST_PROXY_SELECTION },
27502822
}));
27512823

27522824
await runCli(["node", "openclaw", "gateway", "run"]);
27532825

2754-
expect(startProxyMock).toHaveBeenCalledWith({ selected: "selected" });
2826+
expect(startProxyMock).toHaveBeenCalledWith({ proxyUrl: "http://127.0.0.1:19876" });
27552827
});
27562828
});
27572829

@@ -3138,7 +3210,12 @@ describe("runCli exit behavior", () => {
31383210
program,
31393211
undefined,
31403212
undefined,
3141-
{ mode: "lazy", primary: "workboard", skipPluginValidation: false },
3213+
{
3214+
mode: "lazy",
3215+
primary: "workboard",
3216+
skipPluginValidation: false,
3217+
session: createPluginCliLoadSessionMock.mock.results.at(-1)?.value,
3218+
},
31423219
);
31433220
expect(program.parseAsync).not.toHaveBeenCalled();
31443221
});
@@ -3282,7 +3359,12 @@ describe("runCli exit behavior", () => {
32823359
expect.anything(),
32833360
undefined,
32843361
undefined,
3285-
{ mode: "lazy", primary: "memory", skipPluginValidation: true },
3362+
{
3363+
mode: "lazy",
3364+
primary: "memory",
3365+
skipPluginValidation: true,
3366+
session: createPluginCliLoadSessionMock.mock.results.at(-1)?.value,
3367+
},
32863368
);
32873369
expect(stderrDuringPluginRegistration).toBe(true);
32883370
expect(stderrDuringParse).toBe(true);
@@ -3389,7 +3471,16 @@ describe("runCli exit behavior", () => {
33893471
expect.anything(),
33903472
undefined,
33913473
undefined,
3392-
{ mode: "lazy", primary: "memory", skipPluginValidation: false },
3474+
{
3475+
mode: "lazy",
3476+
primary: "memory",
3477+
skipPluginValidation: false,
3478+
session: createPluginCliLoadSessionMock.mock.results.at(-1)?.value,
3479+
},
3480+
);
3481+
const session = createPluginCliLoadSessionMock.mock.results.at(-1)?.value;
3482+
expect(session?.close.mock.invocationCallOrder[0]).toBeLessThan(
3483+
parseAsync.mock.invocationCallOrder[0]!,
33933484
);
33943485
expect(stderrDuringPluginRegistration).toBe(false);
33953486
expect(loggingState.forceConsoleToStderr).toBe(false);

0 commit comments

Comments
 (0)