Skip to content

Commit 80da616

Browse files
vincentkocsteipete
andauthored
improve(doctor): avoid repeated plugin metadata scans (#119482)
* perf(doctor): reuse plugin metadata snapshot Punchcard-Session: coral-workshop-workshop-3f * test(doctor): update legacy issue mock Punchcard-Session: coral-workshop-workshop-3f * fix(doctor): refresh metadata after repairs * test(doctor): type legacy issue mock arguments Punchcard-Session: coral-workshop-workshop-3f * fix(doctor): invalidate scoped plugin metadata Punchcard-Session: coral-workshop-workshop-3f * fix(doctor): keep snapshot scope type private Punchcard-Session: coral-workshop-workshop-3f --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent f68ecec commit 80da616

41 files changed

Lines changed: 1940 additions & 454 deletions

Some content is hidden

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

‎src/commands/doctor-config-flow.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { expectDefined } from "@openclaw/normalization-core";
55
import { withTempHome } from "openclaw/plugin-sdk/test-env";
66
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
77
import { writeChannelPairingStateSnapshot } from "../pairing/pairing-store-sqlite.test-helpers.js";
8+
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
89
import { closeOpenClawStateDatabaseForTest } from "../state/openclaw-state-db.js";
910
import { loadAndMaybeMigrateDoctorConfig } from "./doctor-config-flow.js";
1011
import {
@@ -17,6 +18,7 @@ type TerminalNote = (message: string, title?: string) => void;
1718
const terminalNoteMock = vi.hoisted(() => vi.fn<TerminalNote>());
1819
const callGatewayMock = vi.hoisted(() => vi.fn());
1920
const runDoctorRepairSequenceMock = vi.hoisted(() => vi.fn());
21+
const createDoctorPluginMetadataSnapshotScopeParamsMock = vi.hoisted(() => vi.fn());
2022
const runDoctorConfigPreflightOptionsMock = vi.hoisted(() => vi.fn());
2123
const collectDoctorPreviewNotesParamsMock = vi.hoisted(() => vi.fn());
2224
const collectImplicitFallbackClobberWarningsMock = vi.hoisted(() =>
@@ -255,6 +257,21 @@ vi.mock("./doctor/repair-sequencing.js", async () => {
255257
};
256258
});
257259

260+
vi.mock("./doctor/shared/plugin-metadata-snapshot-scope.js", async () => {
261+
const actual = await vi.importActual<
262+
typeof import("./doctor/shared/plugin-metadata-snapshot-scope.js")
263+
>("./doctor/shared/plugin-metadata-snapshot-scope.js");
264+
return {
265+
...actual,
266+
createDoctorPluginMetadataSnapshotScope: (
267+
params: Parameters<typeof actual.createDoctorPluginMetadataSnapshotScope>[0],
268+
) => {
269+
createDoctorPluginMetadataSnapshotScopeParamsMock(params);
270+
return actual.createDoctorPluginMetadataSnapshotScope(params);
271+
},
272+
};
273+
});
274+
258275
vi.mock("../config/plugin-auto-enable.js", () => ({
259276
applyPluginAutoEnable: vi.fn(
260277
({
@@ -1595,6 +1612,7 @@ describe("doctor config flow", () => {
15951612
callGatewayMock.mockReset();
15961613
callGatewayMock.mockResolvedValue({});
15971614
runDoctorRepairSequenceMock.mockReset();
1615+
createDoctorPluginMetadataSnapshotScopeParamsMock.mockClear();
15981616
collectDoctorPreviewNotesParamsMock.mockClear();
15991617
collectImplicitFallbackClobberWarningsMock.mockClear();
16001618
collectImplicitFallbackClobberWarningsMock.mockReturnValue([]);
@@ -1901,6 +1919,53 @@ describe("doctor config flow", () => {
19011919
);
19021920
});
19031921

1922+
it("prepares plugin metadata for the complete Doctor lifecycle", async () => {
1923+
const result = await runDoctorConfigWithInput({
1924+
config: {},
1925+
run: loadAndMaybeMigrateDoctorConfig,
1926+
});
1927+
1928+
expect(runDoctorConfigPreflightOptionsMock).toHaveBeenLastCalledWith(
1929+
expect.objectContaining({ preparePluginMetadataSnapshot: true }),
1930+
);
1931+
expect(result.runWithPluginMetadataSnapshot).toEqual(expect.any(Function));
1932+
expect(result.invalidatePluginMetadataSnapshot).toEqual(expect.any(Function));
1933+
expect(collectDoctorPreviewNotesParamsMock).toHaveBeenLastCalledWith(
1934+
expect.objectContaining({
1935+
runWithPluginMetadataSnapshot: result.runWithPluginMetadataSnapshot,
1936+
}),
1937+
);
1938+
});
1939+
1940+
it("exposes cleanup-refreshed plugin metadata to later Doctor scopes", async () => {
1941+
const refreshedSnapshot = {
1942+
plugins: [],
1943+
index: { installRecords: {} },
1944+
} as unknown as PluginMetadataSnapshot;
1945+
runDoctorRepairSequenceMock.mockImplementation(async (params: { state: unknown }) => ({
1946+
state: params.state,
1947+
changeNotes: ['Removed stale managed install record for bundled plugin "google-meet".'],
1948+
warningNotes: [],
1949+
authProfilesRepaired: false,
1950+
pluginMetadataSnapshot: refreshedSnapshot,
1951+
}));
1952+
1953+
const result = await runDoctorConfigWithInput({
1954+
config: {},
1955+
repair: true,
1956+
run: loadAndMaybeMigrateDoctorConfig,
1957+
});
1958+
1959+
expect(result.pluginMetadataSnapshot).toBe(refreshedSnapshot);
1960+
const scopeParams = createDoctorPluginMetadataSnapshotScopeParamsMock.mock.lastCall?.[0] as {
1961+
getBaseSnapshot: () => PluginMetadataSnapshot | undefined;
1962+
};
1963+
expect(scopeParams.getBaseSnapshot()).toBe(refreshedSnapshot);
1964+
expect(scopeParams.getBaseSnapshot()?.index.installRecords).not.toHaveProperty("google-meet");
1965+
result.invalidatePluginMetadataSnapshot();
1966+
expect(scopeParams.getBaseSnapshot()).toBeUndefined();
1967+
});
1968+
19041969
it("collects plugin blocker previews from the pre-auto-enable config", async () => {
19051970
await runDoctorConfigWithInput({
19061971
config: {

‎src/commands/doctor-config-flow.ts‎

Lines changed: 111 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import path from "node:path";
33
import { note } from "../../packages/terminal-core/src/note.js";
44
import { readAgentRosterProperty } from "../agents/agent-scope-config.js";
5+
import { resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../agents/agent-scope.js";
56
import { formatCliCommand } from "../cli/command-format.js";
67
import { configIncludeOwnsAgentRoster } from "../config/agent-roster-provenance.js";
78
import { migratePersistedImplicitMainRoster } from "../config/legacy.roster.js";
@@ -31,6 +32,7 @@ import {
3132
import { materializeDefaultAgentRoles } from "./doctor/shared/default-agent-role-materialization.js";
3233
import { isSingleTopLevelIncludeMigration } from "./doctor/shared/include-migration-ownership.js";
3334
import { normalizeCompatibilityConfigValues } from "./doctor/shared/legacy-config-core-migrate.js";
35+
import type { DoctorPluginMetadataSnapshotState } from "./doctor/shared/plugin-metadata-snapshot-scope.js";
3436

3537
function hasLegacyInternalHookHandlers(raw: unknown): boolean {
3638
const handlers = (raw as { hooks?: { internal?: { handlers?: unknown } } })?.hooks?.internal
@@ -153,9 +155,33 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
153155
repairPrefixedConfig: shouldRepair,
154156
recoverCorruptTargetStore: shouldRepair,
155157
doctorOnlyStateMigrations: shouldRepair,
158+
preparePluginMetadataSnapshot: true,
156159
});
157160
const snapshot = preflight.snapshot;
158161
const baseCfg = preflight.baseConfig;
162+
const pluginMetadataSnapshotState: DoctorPluginMetadataSnapshotState = {
163+
current: preflight.pluginMetadataSnapshot,
164+
};
165+
const { createDoctorPluginMetadataSnapshotScope } =
166+
await import("./doctor/shared/plugin-metadata-snapshot-scope.js");
167+
const pluginMetadataSnapshotScope = createDoctorPluginMetadataSnapshotScope({
168+
getBaseSnapshot: () => pluginMetadataSnapshotState.current,
169+
env: process.env,
170+
});
171+
const runWithPluginMetadataSnapshot = pluginMetadataSnapshotScope.run;
172+
const invalidatePluginMetadataSnapshot = () => {
173+
// Filesystem/install repairs replace the authoritative plugin generation.
174+
pluginMetadataSnapshotState.current = undefined;
175+
pluginMetadataSnapshotScope.invalidate();
176+
};
177+
const runWithCurrentPluginMetadata = <T>(config: OpenClawConfig, run: () => T): T =>
178+
runWithPluginMetadataSnapshot(
179+
{
180+
config,
181+
workspaceDir: resolveAgentWorkspaceDir(config, resolveDefaultAgentId(config)),
182+
},
183+
run,
184+
);
159185
let state: DoctorConfigMutationState = {
160186
cfg: baseCfg,
161187
candidate: structuredClone(baseCfg),
@@ -189,12 +215,14 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
189215
const sourceLastTouchedVersion =
190216
typeof sourceMeta?.lastTouchedVersion === "string" ? sourceMeta.lastTouchedVersion : undefined;
191217

192-
const legacyStep = applyLegacyCompatibilityStep({
193-
snapshot,
194-
state,
195-
shouldRepair,
196-
doctorFixCommand,
197-
});
218+
const legacyStep = runWithCurrentPluginMetadata(state.candidate, () =>
219+
applyLegacyCompatibilityStep({
220+
snapshot,
221+
state,
222+
shouldRepair,
223+
doctorFixCommand,
224+
}),
225+
);
198226
state = legacyStep.state;
199227
const legacyMigrationPartiallyValid = legacyStep.partiallyValid === true;
200228
const legacyMigrationBlocksWrite = legacyStep.blocksWrite === true;
@@ -257,7 +285,9 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
257285
}
258286
const { findDoctorLegacyConfigIssues } =
259287
await import("./doctor/shared/legacy-config-issues.js");
260-
return findDoctorLegacyConfigIssues(snapshot.parsed, snapshot.parsed);
288+
return runWithCurrentPluginMetadata(state.candidate, () =>
289+
findDoctorLegacyConfigIssues(snapshot.parsed, snapshot.parsed),
290+
);
261291
})();
262292
const seenLegacyIssues = new Set(
263293
snapshot.legacyIssues.map((issue) => `${issue.path}:${issue.message}`),
@@ -310,10 +340,12 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
310340

311341
// Parsed config supplies invalid-key evidence only; migrations still mutate the
312342
// include/env-resolved candidate so doctor never writes unresolved source values.
313-
const normalized = normalizeCompatibilityConfigValues(state.candidate, {
314-
blockedModelIdentities: blockedCodexModelIdentities,
315-
sourceRaw: snapshot.parsed,
316-
});
343+
const normalized = runWithCurrentPluginMetadata(state.candidate, () =>
344+
normalizeCompatibilityConfigValues(state.candidate, {
345+
blockedModelIdentities: blockedCodexModelIdentities,
346+
sourceRaw: snapshot.parsed,
347+
}),
348+
);
317349
applyConfigMutation(normalized, {
318350
fixHint: `Run "${doctorFixCommand}" to apply these changes.`,
319351
});
@@ -343,14 +375,24 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
343375

344376
const pluginActivationSourceConfig = state.candidate;
345377
const { applyPluginAutoEnable } = await import("../config/plugin-auto-enable.js");
346-
applyConfigMutation(applyPluginAutoEnable({ config: state.candidate, env: process.env }), {
347-
fixHint: `Run "${doctorFixCommand}" to apply these changes.`,
348-
});
378+
applyConfigMutation(
379+
runWithCurrentPluginMetadata(state.candidate, () =>
380+
applyPluginAutoEnable({
381+
config: state.candidate,
382+
env: process.env,
383+
}),
384+
),
385+
{
386+
fixHint: `Run "${doctorFixCommand}" to apply these changes.`,
387+
},
388+
);
349389

350390
if (!shouldRepair) {
351391
const { repairStaleAgentModelRefs } =
352392
await import("./doctor/shared/stale-agent-model-ref-repair.js");
353-
const staleAgentModelRepair = repairStaleAgentModelRefs(state.candidate, { env: process.env });
393+
const staleAgentModelRepair = runWithCurrentPluginMetadata(state.candidate, () =>
394+
repairStaleAgentModelRefs(state.candidate, { env: process.env }),
395+
);
354396
applyConfigMutation(staleAgentModelRepair, {
355397
fixHint: `Run "${doctorFixCommand}" to remove stale agent model references.`,
356398
sanitize: true,
@@ -360,10 +402,12 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
360402

361403
const { collectPluginToolAllowlistWarnings } =
362404
await import("./doctor/shared/plugin-tool-allowlist-warnings.js");
363-
const pluginToolAllowlistWarnings = collectPluginToolAllowlistWarnings({
364-
cfg: state.candidate,
365-
env: process.env,
366-
});
405+
const pluginToolAllowlistWarnings = runWithCurrentPluginMetadata(state.candidate, () =>
406+
collectPluginToolAllowlistWarnings({
407+
cfg: state.candidate,
408+
env: process.env,
409+
}),
410+
);
367411
if (pluginToolAllowlistWarnings.length > 0) {
368412
note(sanitizeDoctorNote(pluginToolAllowlistWarnings.join("\n")), "Doctor warnings");
369413
}
@@ -375,21 +419,25 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
375419
if (hasConfiguredChannels) {
376420
const channelDoctor = await import("./doctor/shared/channel-doctor.js");
377421
collectMutableAllowlistWarnings = channelDoctor.collectChannelDoctorMutableAllowlistWarnings;
378-
const channelDoctorSequence = await channelDoctor.runChannelDoctorConfigSequences({
379-
cfg: state.candidate,
380-
env: process.env,
381-
shouldRepair,
382-
});
422+
const channelDoctorSequence = await runWithCurrentPluginMetadata(state.candidate, () =>
423+
channelDoctor.runChannelDoctorConfigSequences({
424+
cfg: state.candidate,
425+
env: process.env,
426+
shouldRepair,
427+
}),
428+
);
383429
emitDoctorNotes({
384430
note,
385431
changeNotes: channelDoctorSequence.changeNotes,
386432
warningNotes: channelDoctorSequence.warningNotes,
387433
});
388434

389-
for (const staleCleanup of await channelDoctor.collectChannelDoctorStaleConfigMutations(
390-
state.candidate,
391-
{ env: process.env },
392-
)) {
435+
const staleChannelCleanups = await runWithCurrentPluginMetadata(state.candidate, () =>
436+
channelDoctor.collectChannelDoctorStaleConfigMutations(state.candidate, {
437+
env: process.env,
438+
}),
439+
);
440+
for (const staleCleanup of staleChannelCleanups) {
393441
applyConfigMutation(staleCleanup, {
394442
fixHint: `Run "${doctorFixCommand}" to remove stale channel plugin references.`,
395443
sanitize: true,
@@ -410,8 +458,11 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
410458
doctorFixCommand,
411459
env: process.env,
412460
blockedCodexProviderPlan,
461+
pluginMetadataSnapshotState,
462+
runWithPluginMetadataSnapshot,
413463
});
414464
state = repairSequence.state;
465+
pluginMetadataSnapshotState.current = repairSequence.pluginMetadataSnapshot;
415466
openAICodexAuthProfileIdMap = repairSequence.openAICodexAuthProfileIdMap;
416467
if (repairSequence.authProfilesRepaired) {
417468
await refreshGatewayAuthStateAfterAuthProfileRepair();
@@ -423,14 +474,17 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
423474
});
424475
} else {
425476
const { collectDoctorPreviewNotes } = await import("./doctor/shared/preview-warnings.js");
426-
const previewNotes = await collectDoctorPreviewNotes({
427-
cfg: state.candidate,
428-
activationSourceConfig: pluginActivationSourceConfig,
429-
doctorFixCommand,
430-
env: process.env,
431-
allowExec: params.options.allowExec === true,
432-
blockedCodexProviderPlan,
433-
});
477+
const collectPreviewNotes = async () =>
478+
await collectDoctorPreviewNotes({
479+
cfg: state.candidate,
480+
activationSourceConfig: pluginActivationSourceConfig,
481+
doctorFixCommand,
482+
env: process.env,
483+
allowExec: params.options.allowExec === true,
484+
blockedCodexProviderPlan,
485+
runWithPluginMetadataSnapshot,
486+
});
487+
const previewNotes = await runWithCurrentPluginMetadata(state.candidate, collectPreviewNotes);
434488
emitDoctorNotes({
435489
note,
436490
infoNotes: previewNotes.infoNotes,
@@ -439,10 +493,12 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
439493
}
440494

441495
const mutableAllowlistWarnings = collectMutableAllowlistWarnings
442-
? await collectMutableAllowlistWarnings({
443-
cfg: state.candidate,
444-
env: process.env,
445-
})
496+
? await runWithCurrentPluginMetadata(state.candidate, () =>
497+
collectMutableAllowlistWarnings({
498+
cfg: state.candidate,
499+
env: process.env,
500+
}),
501+
)
446502
: [];
447503
if (mutableAllowlistWarnings.length > 0) {
448504
note(sanitizeDoctorNote(mutableAllowlistWarnings.join("\n")), "Doctor warnings");
@@ -490,13 +546,16 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
490546
: undefined,
491547
cfg.models?.providers?.["opencode-go"] ? "opencode-go" : undefined,
492548
].filter((pluginId): pluginId is string => pluginId !== undefined);
493-
const activeOpencodePluginIds =
494-
configuredOpencodePluginIds.length > 0
495-
? (await import("../plugins/providers.js")).resolveEnabledProviderPluginIds({
496-
config: cfg,
497-
onlyPluginIds: configuredOpencodePluginIds,
498-
})
499-
: [];
549+
let activeOpencodePluginIds: string[] = [];
550+
if (configuredOpencodePluginIds.length > 0) {
551+
const { resolveEnabledProviderPluginIds } = await import("../plugins/providers.js");
552+
activeOpencodePluginIds = runWithCurrentPluginMetadata(cfg, () =>
553+
resolveEnabledProviderPluginIds({
554+
config: cfg,
555+
onlyPluginIds: configuredOpencodePluginIds,
556+
}),
557+
);
558+
}
500559
noteOpencodeProviderOverrides(cfg, {
501560
opencodePluginActive: activeOpencodePluginIds.includes("opencode"),
502561
opencodeGoPluginActive: activeOpencodePluginIds.includes("opencode-go"),
@@ -525,5 +584,10 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
525584
? { blockedCodexModelIdentities: blockedCodexProviderPlan.blockedModelIdentities }
526585
: {}),
527586
...(openAICodexAuthProfileIdMap?.size ? { openAICodexAuthProfileIdMap } : {}),
587+
...(pluginMetadataSnapshotState.current
588+
? { pluginMetadataSnapshot: pluginMetadataSnapshotState.current }
589+
: {}),
590+
runWithPluginMetadataSnapshot,
591+
invalidatePluginMetadataSnapshot,
528592
};
529593
}

0 commit comments

Comments
 (0)