Skip to content

Commit 335478f

Browse files
committed
fix(plugins): isolate registry refresh cache generations
1 parent 9a7de4d commit 335478f

11 files changed

Lines changed: 204 additions & 63 deletions

‎src/plugins/bundled-plugin-metadata.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { spawnSync } from "node:child_process";
33
import fs from "node:fs";
44
import path from "node:path";
55
import { toErrorObject as toLintErrorObject } from "@openclaw/normalization-core/error-coercion";
6-
import { assert, beforeAll, describe, expect, it } from "vitest";
6+
import { assert, beforeAll, beforeEach, describe, expect, it } from "vitest";
77
import { expectNoReaddirSyncDuring } from "../test-utils/fs-scan-assertions.js";
88
import { listGitTrackedFiles, toRepoRelativePath } from "../test-utils/repo-files.js";
99
import { collectBundledChannelConfigsCore } from "./bundled-channel-config-metadata.js";
@@ -28,6 +28,7 @@ import {
2828
loadPluginManifest,
2929
type PackageManifest,
3030
} from "./manifest.js";
31+
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
3132
import { writeBundledRuntimeSidecarPathBaseline } from "./runtime-sidecar-paths-baseline.js";
3233
import { BUNDLED_RUNTIME_SIDECAR_PATHS } from "./runtime-sidecar-paths.js";
3334

@@ -36,6 +37,10 @@ const EXPECTED_EMPTY_CONFIG_GATEWAY_STARTUP_EXTRAS = ["memory-core", "xai"] as c
3637

3738
installGeneratedPluginTempRootCleanup();
3839

40+
beforeEach(() => {
41+
clearPluginMetadataLifecycleCaches();
42+
});
43+
3944
function expectTestOnlyArtifactsExcluded(artifacts: readonly string[]) {
4045
artifacts.forEach((artifact) => {
4146
expect(artifact).not.toMatch(/^test-/);
@@ -767,7 +772,7 @@ describe("bundled plugin metadata", () => {
767772
).toBe(path.join(pluginRoot, "index.ts"));
768773
});
769774

770-
it("reflects bundled manifest edits on the next metadata read", () => {
775+
it("reflects bundled manifest edits in the next lifecycle generation", () => {
771776
const tempRoot = createGeneratedPluginTempRoot("openclaw-bundled-plugin-fresh-");
772777
const pluginRoot = path.join(tempRoot, "extensions", "alpha");
773778

@@ -792,6 +797,7 @@ describe("bundled plugin metadata", () => {
792797
name: "After",
793798
configSchema: { type: "object" },
794799
});
800+
clearPluginMetadataLifecycleCaches();
795801

796802
expect(listBundledPluginMetadata({ rootDir: tempRoot })[0]?.manifest.name).toBe("After");
797803
});

‎src/plugins/install-persistence.test.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import type { OpenClawConfig } from "../config/config.js";
2424
import { hasRetainedManagedNpmInstallMarker } from "./managed-npm-retention.js";
2525
import { recordPluginManifestInstallOwner } from "./manifest-install-owner.js";
2626
import type { PluginManifestRecord } from "./manifest-registry.js";
27+
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
2728

2829
function requireMockCallArg(
2930
mockFn: { mock: { calls: unknown[][] } },
@@ -73,6 +74,7 @@ const installWriteOptions = {
7374

7475
describe("persistPluginInstall", () => {
7576
beforeEach(() => {
77+
clearPluginMetadataLifecycleCaches();
7678
resetPluginsCliTestState();
7779
});
7880

@@ -724,10 +726,12 @@ describe("persistPluginInstall", () => {
724726
});
725727

726728
expect(buildPluginDiagnosticsReportMock).toHaveBeenCalledTimes(1);
727-
expect(buildPluginDiagnosticsReportMock).toHaveBeenCalledWith({
728-
config: enabledConfig,
729-
onlyPluginIds: ["legacy-memory"],
730-
});
729+
expect(buildPluginDiagnosticsReportMock).toHaveBeenCalledWith(
730+
expect.objectContaining({
731+
config: enabledConfig,
732+
onlyPluginIds: ["legacy-memory"],
733+
}),
734+
);
731735
expect(
732736
requireMockCallArg(loadPluginManifestRegistryMock, "loadPluginManifestRegistryMock", 1)
733737
.config,
@@ -850,10 +854,12 @@ describe("persistPluginInstall", () => {
850854
});
851855

852856
expect(buildPluginDiagnosticsReportMock).toHaveBeenCalledTimes(1);
853-
expect(buildPluginDiagnosticsReportMock).toHaveBeenCalledWith({
854-
config: enabledConfig,
855-
onlyPluginIds: ["plain"],
856-
});
857+
expect(buildPluginDiagnosticsReportMock).toHaveBeenCalledWith(
858+
expect.objectContaining({
859+
config: enabledConfig,
860+
onlyPluginIds: ["plain"],
861+
}),
862+
);
857863
expect(
858864
requireMockCallArg(loadPluginManifestRegistryMock, "loadPluginManifestRegistryMock", 1)
859865
.config,

‎src/plugins/management-service.inspect.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
hostedFeedDiffsEntry,
66
metadataSnapshot,
77
} from "./management-service.test-helpers.js";
8+
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
89

910
const mocks = vi.hoisted(() => ({ metadata: vi.fn(), officialCatalog: vi.fn() }));
1011

@@ -24,6 +25,7 @@ const { clearManagedPluginOfficialCatalogCache, inspectManagedPlugin } =
2425

2526
describe("managed plugin inspection", () => {
2627
beforeEach(() => {
28+
clearPluginMetadataLifecycleCaches();
2729
clearManagedPluginOfficialCatalogCache();
2830
mocks.metadata.mockReset();
2931
mocks.officialCatalog.mockReset();
@@ -34,7 +36,7 @@ describe("managed plugin inspection", () => {
3436
mocks.metadata.mockReturnValue(metadataSnapshot({ enabled: true }));
3537

3638
const inspection = await inspectManagedPlugin({
37-
config: {},
39+
config: { plugins: { entries: { workboard: { enabled: true } } } },
3840
env: {},
3941
pluginId: "workboard",
4042
});
@@ -93,6 +95,7 @@ describe("managed plugin inspection", () => {
9395
plugins: {
9496
entries: {
9597
"community-plugin": {
98+
enabled: false,
9699
hooks: { allowPromptInjection: false, allowConversationAccess: true },
97100
llm: { allowModelOverride: true },
98101
},
@@ -148,7 +151,7 @@ describe("managed plugin inspection", () => {
148151
);
149152

150153
const inspection = await inspectManagedPlugin({
151-
config: {},
154+
config: { plugins: { entries: { "community-plugin": { enabled: false } } } },
152155
env: {},
153156
pluginId: "community-plugin",
154157
});

‎src/plugins/management-service.workspace-inventory.test.ts‎

Lines changed: 84 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import fs from "node:fs";
12
import path from "node:path";
2-
import { afterEach, expect, it, vi } from "vitest";
3+
import { afterEach, beforeEach, expect, it, vi } from "vitest";
34
import { resolveConfigWidePluginMetadataSnapshot } from "../config/io.plugin-metadata.js";
45
import type { OpenClawConfig } from "../config/types.openclaw.js";
56
import {
@@ -8,9 +9,12 @@ import {
89
} from "../state/openclaw-state-db.js";
910
import { setGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot.js";
1011
import { getGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-state.js";
12+
import { resolvePluginInstallDir } from "./install-paths.js";
1113
import { writePersistedInstalledPluginIndex } from "./installed-plugin-index-store-write.js";
14+
import { readPersistedInstalledPluginIndex } from "./installed-plugin-index-store.js";
1215
import { loadInstalledPluginIndex } from "./installed-plugin-index.js";
1316
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
17+
import { loadPluginMetadataSnapshot } from "./plugin-metadata-snapshot.js";
1418
import { createColdPluginFixture } from "./test-helpers/cold-plugin-fixtures.js";
1519
import {
1620
cleanupTrackedTempDirs,
@@ -34,12 +38,19 @@ vi.mock("./official-external-plugin-catalog.js", async (importOriginal) => ({
3438
}),
3539
}));
3640

37-
const { listManagedPlugins, refreshManagedPluginMetadata, setManagedPluginEnabled } =
38-
await import("./management-service.js");
41+
const {
42+
listManagedPlugins,
43+
refreshManagedPluginMetadata,
44+
setManagedPluginEnabled,
45+
uninstallManagedPlugin,
46+
} = await import("./management-service.js");
3947
const roots: string[] = [];
4048

41-
afterEach(() => {
49+
beforeEach(() => {
4250
clearPluginMetadataLifecycleCaches();
51+
});
52+
53+
afterEach(() => {
4354
closeOpenClawStateDatabaseForTest();
4455
cleanupTrackedTempDirs(roots);
4556
vi.unstubAllEnvs();
@@ -89,6 +100,75 @@ it("refreshes an externally changed install ledger before publishing management
89100
expect(boot.byPluginId.has(fixture.pluginId)).toBe(false);
90101
});
91102

103+
it("removes an npm-pack plugin from management inventory without replacing Gateway metadata", async () => {
104+
const root = makeTrackedTempDir("managed-npm-pack-uninstall", roots);
105+
const stateDir = path.join(root, "state");
106+
const packageName = "@example/tgz-visible";
107+
const pluginRoot = resolvePluginInstallDir("tgz-visible", path.join(stateDir, "extensions"));
108+
mkdirSafeDir(pluginRoot);
109+
const fixture = createColdPluginFixture({
110+
rootDir: pluginRoot,
111+
pluginId: "tgz-visible",
112+
packageName,
113+
});
114+
vi.stubEnv("OPENCLAW_STATE_DIR", stateDir);
115+
vi.stubEnv("OPENCLAW_DISABLE_BUNDLED_PLUGINS", "1");
116+
let config: OpenClawConfig = {
117+
plugins: { entries: { [fixture.pluginId]: { enabled: true } } },
118+
};
119+
const installRecord = {
120+
source: "npm",
121+
spec: `${packageName}@1.0.0`,
122+
sourcePath: path.join(root, `${fixture.pluginId}.tgz`),
123+
installPath: pluginRoot,
124+
artifactKind: "npm-pack",
125+
artifactFormat: "tgz",
126+
} as const;
127+
configIo.read.mockImplementation(async () => ({
128+
snapshot: {
129+
valid: true,
130+
parsed: config,
131+
path: path.join(stateDir, "openclaw.json"),
132+
sourceConfig: config,
133+
hash: "base-hash",
134+
},
135+
writeOptions: { expectedConfigPath: path.join(stateDir, "openclaw.json") },
136+
}));
137+
configIo.write.mockImplementation(async ({ nextConfig }: { nextConfig: OpenClawConfig }) => {
138+
config = nextConfig;
139+
});
140+
await writePersistedInstalledPluginIndex(
141+
loadInstalledPluginIndex({
142+
config,
143+
env: process.env,
144+
installRecords: { [fixture.pluginId]: installRecord },
145+
}),
146+
);
147+
const boot = loadPluginMetadataSnapshot({
148+
config,
149+
env: process.env,
150+
preferPersisted: false,
151+
});
152+
setGatewayPluginMetadataSnapshot(boot, { config, env: process.env });
153+
expect((await listManagedPlugins({ config })).plugins).toContainEqual(
154+
expect.objectContaining({ id: fixture.pluginId, installed: true }),
155+
);
156+
157+
await uninstallManagedPlugin({ pluginId: fixture.pluginId });
158+
159+
expect(fs.existsSync(pluginRoot)).toBe(false);
160+
expect(
161+
(await readPersistedInstalledPluginIndex())?.plugins.some(
162+
(plugin) => plugin.pluginId === fixture.pluginId,
163+
),
164+
).toBe(false);
165+
expect((await listManagedPlugins({ config })).plugins).not.toContainEqual(
166+
expect.objectContaining({ id: fixture.pluginId }),
167+
);
168+
expect(getGatewayPluginMetadataSnapshot()).toBe(boot);
169+
expect(boot.byPluginId.has(fixture.pluginId)).toBe(true);
170+
});
171+
92172
it.each([undefined, "main"])(
93173
"toggles a listed secondary-workspace plugin with system owner %s",
94174
async (systemAgentId) => {

‎src/plugins/manifest.json5-tolerance.test.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
import fs from "node:fs";
33
import path from "node:path";
44
import JSON5 from "json5";
5-
import { afterEach, describe, expect, it, vi } from "vitest";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { resolveMemorySlotDecision } from "./config-state.js";
77
import { loadPluginManifest } from "./manifest.js";
8+
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
89
import { cleanupTrackedTempDirs, makeTrackedTempDir } from "./test-helpers/fs-fixtures.js";
910

1011
const tempDirs: string[] = [];
@@ -13,6 +14,10 @@ function makeTempDir() {
1314
return makeTrackedTempDir("openclaw-manifest-json5", tempDirs);
1415
}
1516

17+
beforeEach(() => {
18+
clearPluginMetadataLifecycleCaches();
19+
});
20+
1621
afterEach(() => {
1722
vi.restoreAllMocks();
1823
cleanupTrackedTempDirs(tempDirs);
@@ -93,7 +98,7 @@ describe("loadPluginManifest JSON5 tolerance", () => {
9398
expect(json5Parse).not.toHaveBeenCalled();
9499
});
95100

96-
it("reuses unchanged manifest loads by file signature", () => {
101+
it("reuses unchanged manifest loads within one lifecycle generation", () => {
97102
const dir = makeTempDir();
98103
fs.writeFileSync(
99104
path.join(dir, "openclaw.plugin.json"),
@@ -103,14 +108,11 @@ describe("loadPluginManifest JSON5 tolerance", () => {
103108
}),
104109
"utf-8",
105110
);
106-
const readFileSync = vi.spyOn(fs, "readFileSync");
107-
108111
const first = loadPluginManifest(dir, false);
109112
const second = loadPluginManifest(dir, false);
110113

111114
expect(first.ok).toBe(true);
112-
expect(second.ok).toBe(true);
113-
expect(readFileSync).toHaveBeenCalledTimes(1);
115+
expect(second).toBe(first);
114116
});
115117

116118
it("parses a manifest with trailing commas", () => {

‎src/plugins/migration-provider-runtime.test.ts‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Covers migration provider runtime hooks supplied by plugins.
22
import { beforeEach, describe, expect, it, vi } from "vitest";
33
import type { OpenClawConfig } from "../config/types.openclaw.js";
4+
import { clearPluginMetadataLifecycleCaches } from "./plugin-metadata-lifecycle.js";
45
import type { PluginRegistry } from "./registry-types.js";
56
import { createEmptyPluginRegistry } from "./registry.js";
67
import { getPluginRuntimeGatewayRequestScope } from "./runtime/gateway-request-scope.js";
@@ -20,6 +21,12 @@ type MockPluginIndex = {
2021
diagnostics: unknown[];
2122
};
2223

24+
type MockPluginSnapshotLoadParams = {
25+
index?: MockPluginIndex;
26+
config?: OpenClawConfig;
27+
env?: NodeJS.ProcessEnv;
28+
};
29+
2330
function createEmptyMockManifestRegistry(): MockManifestRegistry {
2431
return { plugins: [], diagnostics: [] };
2532
}
@@ -38,7 +45,7 @@ const mocks = vi.hoisted(() => ({
3845
loadPluginRegistrySnapshot: vi.fn<(_params?: unknown) => MockPluginIndex>(() =>
3946
createMockPluginIndex([]),
4047
),
41-
loadPluginRegistrySnapshotWithMetadata: vi.fn((params?: { index?: MockPluginIndex }) => ({
48+
loadPluginRegistrySnapshotWithMetadata: vi.fn((params?: MockPluginSnapshotLoadParams) => ({
4249
source: params?.index ? "provided" : "derived",
4350
snapshot: params?.index ?? createMockPluginIndex([]),
4451
diagnostics: [],
@@ -69,6 +76,22 @@ vi.mock("./plugin-registry-snapshot.js", () => ({
6976
loadPluginRegistrySnapshotWithMetadata: mocks.loadPluginRegistrySnapshotWithMetadata,
7077
}));
7178

79+
vi.mock("./plugin-metadata-snapshot.js", () => ({
80+
loadPluginMetadataSnapshot: (params: { config?: OpenClawConfig; env?: NodeJS.ProcessEnv }) => {
81+
const loaded = mocks.loadPluginRegistrySnapshotWithMetadata(params);
82+
const manifestRegistry = mocks.loadPluginManifestRegistry({
83+
index: loaded.snapshot,
84+
config: params.config,
85+
env: params.env,
86+
includeDisabled: true,
87+
});
88+
return {
89+
index: loaded.snapshot,
90+
plugins: manifestRegistry.plugins,
91+
};
92+
},
93+
}));
94+
7295
vi.mock("./manifest-registry-installed.js", () => ({
7396
loadPluginManifestRegistryForInstalledIndex: mocks.loadPluginManifestRegistry,
7497
resolveInstalledManifestRegistryIndexFingerprint: () => "test-installed-index",
@@ -105,6 +128,7 @@ function requireMockCallArg(
105128

106129
describe("migration provider runtime", () => {
107130
beforeEach(async () => {
131+
clearPluginMetadataLifecycleCaches();
108132
vi.resetModules();
109133
vi.clearAllMocks();
110134
mocks.resolveRuntimePluginRegistry.mockReturnValue(createEmptyPluginRegistry());
@@ -113,7 +137,7 @@ describe("migration provider runtime", () => {
113137
mocks.loadPluginRegistryHandle.mockReturnValue(createEmptyPluginRegistry());
114138
mocks.listBundledPluginMetadata.mockReturnValue([]);
115139
mocks.loadPluginRegistrySnapshotWithMetadata.mockImplementation(
116-
(params?: { index?: MockPluginIndex }) => ({
140+
(params?: MockPluginSnapshotLoadParams) => ({
117141
source: params?.index ? "provided" : "derived",
118142
snapshot: params?.index ?? mocks.loadPluginRegistrySnapshot(),
119143
diagnostics: [],
@@ -188,7 +212,12 @@ describe("migration provider runtime", () => {
188212

189213
it("loads configured external migration-provider plugins from manifest contracts", async () => {
190214
const cfg = {
191-
plugins: { entries: { "external-migration": { enabled: true } } },
215+
plugins: {
216+
entries: {
217+
"external-migration": { enabled: true },
218+
"disabled-external-migration": { enabled: false },
219+
},
220+
},
192221
} as OpenClawConfig;
193222
const provider = createMigrationProvider("external-import");
194223
const active = createEmptyPluginRegistry();

0 commit comments

Comments
 (0)