Skip to content

Commit 760e505

Browse files
committed
fix(memory): preserve direct-scope sidecars
1 parent 8aad0f8 commit 760e505

4 files changed

Lines changed: 116 additions & 32 deletions

File tree

‎src/agents/runtime-plugins.memory-corpus.integration.test.ts‎

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
// Verifies direct agent registry scopes retain root-owned memory corpus sidecars.
2+
import fs from "node:fs";
3+
import path from "node:path";
24
import { afterAll, afterEach, expect, it } from "vitest";
5+
import { applyPluginAutoEnable } from "../config/plugin-auto-enable.js";
6+
import type { OpenClawConfig } from "../config/types.openclaw.js";
37
import { loadAndActivateRootPluginRegistry } from "../plugins/loader.js";
48
import {
59
cleanupPluginLoaderFixturesForTest,
@@ -8,7 +12,11 @@ import {
812
useNoBundledPlugins,
913
writePlugin,
1014
} from "../plugins/loader.test-fixtures.js";
11-
import { listMemoryCorpusSupplements } from "../plugins/memory-state.js";
15+
import {
16+
buildMemoryPromptSection,
17+
listMemoryCorpusSupplements,
18+
prepareMemoryPromptSection,
19+
} from "../plugins/memory-state.js";
1220
import { withAgentPluginRegistry } from "./runtime-plugins.js";
1321

1422
afterEach(() => {
@@ -19,32 +27,46 @@ afterAll(() => {
1927
cleanupPluginLoaderFixturesForTest();
2028
});
2129

22-
it("keeps a root-owned memory corpus sidecar in a direct agent registry", async () => {
30+
it("keeps root-owned memory sidecars in a direct agent registry", async () => {
2331
useNoBundledPlugins();
2432
const pluginId = "memory-corpus-sidecar";
33+
const configSchema = {
34+
type: "object",
35+
additionalProperties: false,
36+
properties: { source: { type: "string" } },
37+
};
2538
const plugin = writePlugin({
2639
id: pluginId,
40+
configSchema,
2741
body: `module.exports = {
2842
id: ${JSON.stringify(pluginId)},
2943
register(api) {
44+
api.registerMemoryPromptSupplement(() => ["runtime wiki guidance"]);
45+
api.registerMemoryPromptPreparation(async () => ["runtime wiki digest"]);
3046
api.registerMemoryCorpusSupplement({
3147
search: async () => [],
3248
get: async () => null,
3349
});
3450
},
3551
};\n`,
3652
});
53+
fs.writeFileSync(
54+
path.join(plugin.dir, "openclaw.plugin.json"),
55+
JSON.stringify({ id: pluginId, configSchema, contracts: { tools: ["corpus_probe"] } }),
56+
"utf8",
57+
);
3758
const config = {
3859
plugins: {
39-
allow: [pluginId],
40-
entries: { [pluginId]: { enabled: true } },
60+
entries: { [pluginId]: { config: { source: "runtime" } } },
4161
load: { paths: [plugin.dir] },
4262
},
43-
};
63+
} satisfies OpenClawConfig;
4464
const workspaceDir = makePluginLoaderTempDir();
65+
const rootConfig = applyPluginAutoEnable({ config, env: process.env }).config;
66+
expect(rootConfig.plugins?.entries?.[pluginId]?.enabled).toBe(true);
4567
const root = loadAndActivateRootPluginRegistry({
4668
cache: false,
47-
config,
69+
config: rootConfig,
4870
onlyPluginIds: [pluginId],
4971
workspaceDir,
5072
});
@@ -57,6 +79,12 @@ it("keeps a root-owned memory corpus sidecar in a direct agent registry", async
5779
run: async () => {
5880
expect(listMemoryCorpusSupplements().map((entry) => entry.pluginId)).toEqual([pluginId]);
5981
expect(listMemoryCorpusSupplements()[0]?.supplement).toBe(rootSupplement);
82+
const promptParams = { availableTools: new Set(["memory_search"]) };
83+
const prepared = await prepareMemoryPromptSection(promptParams);
84+
expect(buildMemoryPromptSection(promptParams, prepared)).toEqual([
85+
"runtime wiki guidance",
86+
"runtime wiki digest",
87+
]);
6088
},
6189
});
6290
await withAgentPluginRegistry({

‎src/agents/runtime-plugins.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { applyPluginAutoEnable } from "../config/plugin-auto-enable.js";
12
import type { OpenClawConfig } from "../config/types.openclaw.js";
23
import { adoptRuntimeContextEngineRegistrations } from "../context-engine/registry.js";
34
import {
@@ -8,7 +9,7 @@ import {
89
import { normalizePluginsConfig } from "../plugins/config-state.js";
910
import { extractPluginInstallRecordsFromInstalledPluginIndex } from "../plugins/installed-plugin-index-install-records.js";
1011
import { loadPluginRegistryHandle } from "../plugins/loader.js";
11-
import { adoptRuntimeMemoryCorpusSupplementRegistrations } from "../plugins/memory-state.js";
12+
import { adoptRuntimeMemoryRegistrations } from "../plugins/memory-state.js";
1213
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1314
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
1415
import type { PluginRegistry } from "../plugins/registry-types.js";
@@ -150,18 +151,33 @@ export async function withAgentPluginRegistry<T>(params: {
150151
if (getPluginRuntimeGatewayRequestScope()?.pluginRegistry) {
151152
return await params.run();
152153
}
154+
const metadataSnapshot = normalizePluginsConfig(params.config.plugins).enabled
155+
? loadPluginMetadataSnapshot({
156+
config: params.config,
157+
env: process.env,
158+
workspaceDir: params.workspaceDir,
159+
})
160+
: undefined;
153161
const pluginRegistry = loadAgentRuntimePluginRegistryHandle({
154162
basePluginIds: [],
155163
config: params.config,
164+
...(metadataSnapshot ? { metadataSnapshot } : {}),
156165
workspaceDir: params.workspaceDir,
157166
});
158167
const activeRegistry = getActivePluginRegistry();
159168
const scopedRegistry =
160-
activeRegistry && getActivePluginRegistryWorkspaceDir() === resolveUserPath(params.workspaceDir)
161-
? adoptRuntimeMemoryCorpusSupplementRegistrations(
169+
activeRegistry &&
170+
metadataSnapshot &&
171+
getActivePluginRegistryWorkspaceDir() === resolveUserPath(params.workspaceDir)
172+
? adoptRuntimeMemoryRegistrations(
162173
pluginRegistry,
163174
activeRegistry,
164-
params.config,
175+
applyPluginAutoEnable({
176+
config: params.config,
177+
env: process.env,
178+
discovery: metadataSnapshot.discovery,
179+
manifestRegistry: metadataSnapshot.manifestRegistry,
180+
}).config,
165181
)
166182
: pluginRegistry;
167183
return await withPluginRuntimeRegistryScope(scopedRegistry, params.run);

‎src/plugins/memory-state.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Covers plugin-backed memory state registration and reset behavior.
22
import { afterEach, describe, expect, it, vi } from "vitest";
33
import {
4-
adoptRuntimeMemoryCorpusSupplementRegistrations,
4+
adoptRuntimeMemoryRegistrations,
55
buildMemoryPromptSection,
66
clearMemoryPluginState,
77
getMemoryCapabilityRegistration,
@@ -423,20 +423,26 @@ describe("memory plugin state", () => {
423423
).resolves.toEqual([{ corpus: "wiki", path: "sources/alpha.md", score: 1, snippet: "x" }]);
424424
});
425425

426-
it("does not adopt a corpus supplement across conflicting plugin owners", () => {
426+
it("does not adopt memory sidecars across conflicting plugin owners", () => {
427427
const supplement = { search: async () => [], get: async () => null };
428+
const prepare = async () => ["runtime wiki digest"];
429+
const builder = () => ["runtime wiki guidance"];
428430
const root = createEmptyPluginRegistry();
429431
root.plugins.push(createPluginRecord({ id: "memory-wiki", source: "/root/wiki.js" }));
430432
root.memoryCorpusSupplements.push({ pluginId: "memory-wiki", supplement });
433+
root.memoryPromptPreparations.push({ pluginId: "memory-wiki", prepare });
434+
root.memoryPromptSupplements.push({ pluginId: "memory-wiki", builder });
431435
const scoped = createEmptyPluginRegistry();
432436
scoped.plugins.push(createPluginRecord({ id: "memory-wiki", source: "/shadow/wiki.js" }));
433437

434438
expect(
435-
adoptRuntimeMemoryCorpusSupplementRegistrations(scoped, root, {
439+
adoptRuntimeMemoryRegistrations(scoped, root, {
436440
plugins: { allow: ["memory-wiki"], entries: { "memory-wiki": { enabled: true } } },
437441
}),
438442
).toBe(scoped);
439443
expect(scoped.memoryCorpusSupplements).toEqual([]);
444+
expect(scoped.memoryPromptPreparations).toEqual([]);
445+
expect(scoped.memoryPromptSupplements).toEqual([]);
440446
});
441447

442448
it("clearMemoryPluginState resets both registries", () => {

‎src/plugins/memory-state.ts‎

Lines changed: 53 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -103,25 +103,36 @@ export function listMemoryCorpusSupplements(): MemoryCorpusSupplementRegistratio
103103
return [...requireActivePluginRegistry().memoryCorpusSupplements];
104104
}
105105

106-
/** Copies root-owned corpus supplements into a same-workspace scoped registry. */
107-
export function adoptRuntimeMemoryCorpusSupplementRegistrations(
106+
function adoptEligibleRuntimeMemoryRegistrations<T extends { pluginId: string }>(
107+
target: T[],
108+
runtime: readonly T[],
109+
canAdopt: (pluginId: string) => boolean,
110+
): T[] {
111+
const pluginIds = new Set(target.map((registration) => registration.pluginId));
112+
let adopted: T[] | undefined;
113+
for (const registration of runtime) {
114+
if (pluginIds.has(registration.pluginId) || !canAdopt(registration.pluginId)) {
115+
continue;
116+
}
117+
(adopted ??= [...target]).push(registration);
118+
pluginIds.add(registration.pluginId);
119+
}
120+
return adopted ?? target;
121+
}
122+
123+
/**
124+
* Discovery scopes cannot safely rerun full memory plugin setup.
125+
* Reuse exact root sidecars only while activation and source ownership still match.
126+
*/
127+
export function adoptRuntimeMemoryRegistrations(
108128
targetRegistry: PluginRegistry,
109129
runtimeRegistry: PluginRegistry,
110130
config: OpenClawConfig,
111131
): PluginRegistry {
112132
const normalizedConfig = normalizePluginsConfig(config.plugins);
113-
const supplements = [...targetRegistry.memoryCorpusSupplements];
114-
let changed = false;
115-
for (const registration of runtimeRegistry.memoryCorpusSupplements) {
116-
if (supplements.some((candidate) => candidate.pluginId === registration.pluginId)) {
117-
continue;
118-
}
119-
const targetOwner = targetRegistry.plugins.find(
120-
(plugin) => plugin.id === registration.pluginId,
121-
);
122-
const runtimeOwner = runtimeRegistry.plugins.find(
123-
(plugin) => plugin.id === registration.pluginId,
124-
);
133+
const canAdopt = (pluginId: string) => {
134+
const targetOwner = targetRegistry.plugins.find((plugin) => plugin.id === pluginId);
135+
const runtimeOwner = runtimeRegistry.plugins.find((plugin) => plugin.id === pluginId);
125136
if (
126137
runtimeOwner?.status !== "loaded" ||
127138
!resolveEffectivePluginActivationState({
@@ -134,12 +145,35 @@ export function adoptRuntimeMemoryCorpusSupplementRegistrations(
134145
(targetOwner &&
135146
(targetOwner.status !== "loaded" || targetOwner.source !== runtimeOwner.source))
136147
) {
137-
continue;
148+
return false;
138149
}
139-
supplements.push(registration);
140-
changed = true;
141-
}
142-
return changed ? { ...targetRegistry, memoryCorpusSupplements: supplements } : targetRegistry;
150+
return true;
151+
};
152+
const memoryCorpusSupplements = adoptEligibleRuntimeMemoryRegistrations(
153+
targetRegistry.memoryCorpusSupplements,
154+
runtimeRegistry.memoryCorpusSupplements,
155+
canAdopt,
156+
);
157+
const memoryPromptPreparations = adoptEligibleRuntimeMemoryRegistrations(
158+
targetRegistry.memoryPromptPreparations,
159+
runtimeRegistry.memoryPromptPreparations,
160+
canAdopt,
161+
);
162+
const memoryPromptSupplements = adoptEligibleRuntimeMemoryRegistrations(
163+
targetRegistry.memoryPromptSupplements,
164+
runtimeRegistry.memoryPromptSupplements,
165+
canAdopt,
166+
);
167+
return memoryCorpusSupplements === targetRegistry.memoryCorpusSupplements &&
168+
memoryPromptPreparations === targetRegistry.memoryPromptPreparations &&
169+
memoryPromptSupplements === targetRegistry.memoryPromptSupplements
170+
? targetRegistry
171+
: {
172+
...targetRegistry,
173+
memoryCorpusSupplements,
174+
memoryPromptPreparations,
175+
memoryPromptSupplements,
176+
};
143177
}
144178
export function registerMemoryPromptSupplement(
145179
requestedPluginId: string,

0 commit comments

Comments
 (0)