Skip to content

Commit b4f8510

Browse files
PollyBot13obviyus
andauthored
fix(memory): preserve wiki sidecars in direct agent scopes (#133234)
Direct agent scopes now reuse eligible same-workspace memory sidecars from the active plugin runtime. This preserves wiki corpus search, prompt guidance, and prepared prompt context without rerunning plugin registration. Disabled, cross-workspace, and conflicting-source owners remain unavailable. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent f46f9b5 commit b4f8510

4 files changed

Lines changed: 234 additions & 2 deletions

File tree

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
// Verifies direct agent registry scopes retain root-owned memory corpus sidecars.
2+
import fs from "node:fs";
3+
import path from "node:path";
4+
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";
7+
import { loadAndActivateRootPluginRegistry } from "../plugins/loader.js";
8+
import {
9+
cleanupPluginLoaderFixturesForTest,
10+
makePluginLoaderTempDir,
11+
resetPluginLoaderTestStateForTest,
12+
useNoBundledPlugins,
13+
writePlugin,
14+
} from "../plugins/loader.test-fixtures.js";
15+
import {
16+
buildMemoryPromptSection,
17+
listMemoryCorpusSupplements,
18+
prepareMemoryPromptSection,
19+
} from "../plugins/memory-state.js";
20+
import { withAgentPluginRegistry } from "./runtime-plugins.js";
21+
22+
afterEach(() => {
23+
resetPluginLoaderTestStateForTest();
24+
});
25+
26+
afterAll(() => {
27+
cleanupPluginLoaderFixturesForTest();
28+
});
29+
30+
it("keeps root-owned memory sidecars in a direct agent registry", async () => {
31+
useNoBundledPlugins();
32+
const pluginId = "memory-corpus-sidecar";
33+
const configSchema = {
34+
type: "object",
35+
additionalProperties: false,
36+
properties: { source: { type: "string" } },
37+
};
38+
const plugin = writePlugin({
39+
id: pluginId,
40+
configSchema,
41+
body: `module.exports = {
42+
id: ${JSON.stringify(pluginId)},
43+
register(api) {
44+
api.registerMemoryPromptSupplement(() => ["runtime wiki guidance"]);
45+
api.registerMemoryPromptPreparation(async () => ["runtime wiki digest"]);
46+
api.registerMemoryCorpusSupplement({
47+
search: async () => [],
48+
get: async () => null,
49+
});
50+
},
51+
};\n`,
52+
});
53+
fs.writeFileSync(
54+
path.join(plugin.dir, "openclaw.plugin.json"),
55+
JSON.stringify({ id: pluginId, configSchema, contracts: { tools: ["corpus_probe"] } }),
56+
"utf8",
57+
);
58+
const config = {
59+
plugins: {
60+
entries: { [pluginId]: { config: { source: "runtime" } } },
61+
load: { paths: [plugin.dir] },
62+
},
63+
} satisfies OpenClawConfig;
64+
const workspaceDir = makePluginLoaderTempDir();
65+
const rootConfig = applyPluginAutoEnable({ config, env: process.env }).config;
66+
expect(rootConfig.plugins?.entries?.[pluginId]?.enabled).toBe(true);
67+
const root = loadAndActivateRootPluginRegistry({
68+
cache: false,
69+
config: rootConfig,
70+
onlyPluginIds: [pluginId],
71+
workspaceDir,
72+
});
73+
74+
expect(root.memoryCorpusSupplements.map((entry) => entry.pluginId)).toEqual([pluginId]);
75+
const rootSupplement = root.memoryCorpusSupplements[0]?.supplement;
76+
await withAgentPluginRegistry({
77+
config,
78+
workspaceDir,
79+
run: async () => {
80+
expect(listMemoryCorpusSupplements().map((entry) => entry.pluginId)).toEqual([pluginId]);
81+
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+
]);
88+
},
89+
});
90+
await withAgentPluginRegistry({
91+
config,
92+
workspaceDir: makePluginLoaderTempDir(),
93+
run: async () => {
94+
expect(listMemoryCorpusSupplements()).toEqual([]);
95+
},
96+
});
97+
await withAgentPluginRegistry({
98+
config: { plugins: { enabled: false } },
99+
workspaceDir,
100+
run: async () => {
101+
expect(listMemoryCorpusSupplements()).toEqual([]);
102+
},
103+
});
104+
});

‎src/agents/runtime-plugins.ts‎

Lines changed: 31 additions & 2 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,10 +9,14 @@ 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";
12+
import { adoptRuntimeMemoryRegistrations } from "../plugins/memory-state.js";
1113
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1214
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
1315
import type { PluginRegistry } from "../plugins/registry-types.js";
14-
import { getActivePluginRegistry } from "../plugins/runtime.js";
16+
import {
17+
getActivePluginRegistry,
18+
getActivePluginRegistryWorkspaceDir,
19+
} from "../plugins/runtime.js";
1520
import {
1621
getPluginRuntimeGatewayRequestScope,
1722
withPluginRuntimeRegistryScope,
@@ -146,10 +151,34 @@ export async function withAgentPluginRegistry<T>(params: {
146151
if (getPluginRuntimeGatewayRequestScope()?.pluginRegistry) {
147152
return await params.run();
148153
}
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;
149161
const pluginRegistry = loadAgentRuntimePluginRegistryHandle({
150162
basePluginIds: [],
151163
config: params.config,
164+
...(metadataSnapshot ? { metadataSnapshot } : {}),
152165
workspaceDir: params.workspaceDir,
153166
});
154-
return await withPluginRuntimeRegistryScope(pluginRegistry, params.run);
167+
const activeRegistry = getActivePluginRegistry();
168+
const scopedRegistry =
169+
activeRegistry &&
170+
metadataSnapshot &&
171+
getActivePluginRegistryWorkspaceDir() === resolveUserPath(params.workspaceDir)
172+
? adoptRuntimeMemoryRegistrations(
173+
pluginRegistry,
174+
activeRegistry,
175+
applyPluginAutoEnable({
176+
config: params.config,
177+
env: process.env,
178+
discovery: metadataSnapshot.discovery,
179+
manifestRegistry: metadataSnapshot.manifestRegistry,
180+
}).config,
181+
)
182+
: pluginRegistry;
183+
return await withPluginRuntimeRegistryScope(scopedRegistry, params.run);
155184
}

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Covers plugin-backed memory state registration and reset behavior.
22
import { afterEach, describe, expect, it, vi } from "vitest";
33
import {
4+
adoptRuntimeMemoryRegistrations,
45
buildMemoryPromptSection,
56
clearMemoryPluginState,
67
getMemoryCapabilityRegistration,
@@ -19,6 +20,7 @@ import {
1920
} from "./memory-state.test-fixtures.js";
2021
import { createEmptyPluginRegistry } from "./registry-empty.js";
2122
import { withPluginRegistrationContext } from "./runtime.js";
23+
import { createPluginRecord } from "./status.test-helpers.js";
2224

2325
function createMemoryRuntime() {
2426
return {
@@ -421,6 +423,28 @@ describe("memory plugin state", () => {
421423
).resolves.toEqual([{ corpus: "wiki", path: "sources/alpha.md", score: 1, snippet: "x" }]);
422424
});
423425

426+
it("does not adopt memory sidecars across conflicting plugin owners", () => {
427+
const supplement = { search: async () => [], get: async () => null };
428+
const prepare = async () => ["runtime wiki digest"];
429+
const builder = () => ["runtime wiki guidance"];
430+
const root = createEmptyPluginRegistry();
431+
root.plugins.push(createPluginRecord({ id: "memory-wiki", source: "/root/wiki.js" }));
432+
root.memoryCorpusSupplements.push({ pluginId: "memory-wiki", supplement });
433+
root.memoryPromptPreparations.push({ pluginId: "memory-wiki", prepare });
434+
root.memoryPromptSupplements.push({ pluginId: "memory-wiki", builder });
435+
const scoped = createEmptyPluginRegistry();
436+
scoped.plugins.push(createPluginRecord({ id: "memory-wiki", source: "/shadow/wiki.js" }));
437+
438+
expect(
439+
adoptRuntimeMemoryRegistrations(scoped, root, {
440+
plugins: { allow: ["memory-wiki"], entries: { "memory-wiki": { enabled: true } } },
441+
}),
442+
).toBe(scoped);
443+
expect(scoped.memoryCorpusSupplements).toEqual([]);
444+
expect(scoped.memoryPromptPreparations).toEqual([]);
445+
expect(scoped.memoryPromptSupplements).toEqual([]);
446+
});
447+
424448
it("clearMemoryPluginState resets both registries", () => {
425449
registerMemoryState({
426450
promptSection: ["stale section"],

‎src/plugins/memory-state.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
33
import { filterStringEntries } from "@openclaw/normalization-core/string-normalization";
44
import type { OpenClawConfig } from "../config/types.openclaw.js";
55
import { createSubsystemLogger } from "../logging/subsystem.js";
6+
import { normalizePluginsConfig, resolveEffectivePluginActivationState } from "./config-state.js";
67
import type {
78
MemoryCorpusSupplement,
89
MemoryCorpusSupplementRegistration,
@@ -18,6 +19,7 @@ import type {
1819
MemoryPromptSupplementRegistration,
1920
PreparedMemoryPromptSection,
2021
} from "./registry-contribution-types.js";
22+
import type { PluginRegistry } from "./registry-types.js";
2123
import { requireActivePluginRegistry, resolveDirectPluginRegistrationOwner } from "./runtime.js";
2224

2325
const log = createSubsystemLogger("plugins/memory-state");
@@ -100,6 +102,79 @@ export function getMemoryCapabilityRegistration(): MemoryPluginCapabilityRegistr
100102
export function listMemoryCorpusSupplements(): MemoryCorpusSupplementRegistration[] {
101103
return [...requireActivePluginRegistry().memoryCorpusSupplements];
102104
}
105+
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(
128+
targetRegistry: PluginRegistry,
129+
runtimeRegistry: PluginRegistry,
130+
config: OpenClawConfig,
131+
): PluginRegistry {
132+
const normalizedConfig = normalizePluginsConfig(config.plugins);
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);
136+
if (
137+
runtimeOwner?.status !== "loaded" ||
138+
!resolveEffectivePluginActivationState({
139+
id: runtimeOwner.id,
140+
origin: runtimeOwner.origin,
141+
config: normalizedConfig,
142+
rootConfig: config,
143+
enabledByDefault: runtimeOwner.activationSource === "default",
144+
}).enabled ||
145+
(targetOwner &&
146+
(targetOwner.status !== "loaded" || targetOwner.source !== runtimeOwner.source))
147+
) {
148+
return false;
149+
}
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+
};
177+
}
103178
export function registerMemoryPromptSupplement(
104179
requestedPluginId: string,
105180
builder: MemoryPromptSectionBuilder,

0 commit comments

Comments
 (0)