Skip to content

Commit 0e2e6c3

Browse files
authored
fix(memory-wiki): publish dashboard snapshots (#132296)
Publish bounded Memory Wiki dashboard projections with the compiled cache so Control UI reads do not scan the full vault. Keep recovery explicit, preserve disabled automatic compilation, disclose bounded results, and fence all compilation work at plugin service shutdown. Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 9e86e08 commit 0e2e6c3

33 files changed

Lines changed: 1594 additions & 440 deletions

‎docs/plugins/memory-wiki.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,15 @@ gateway methods (`wiki.overview`, `wiki.get`, `wiki.importInsights`); inline
313313
page previews use `wiki.get`, the same lookup agents reach through the
314314
`wiki_get` tool.
315315

316+
Each dashboard keeps at most the newest 2,500 cards in its compiled snapshot.
317+
When a vault exceeds that bound, the UI shows the returned and total item counts.
318+
319+
Dashboard requests never scan raw vault pages or wait for a full vault compile.
320+
During automatic recovery, the UI reports that the dashboards are rebuilding;
321+
reload the tab shortly. When
322+
`ingest.autoCompile` is `false`, a source change or older cache reports that a
323+
compile is required instead. Run `openclaw wiki compile`, then reload the tab.
324+
316325
## Prompt and context behavior
317326

318327
When `context.includeCompiledDigestPrompt` is enabled, memory prompt sections
@@ -393,6 +402,7 @@ Key toggles:
393402
| `bridge.followMemoryEvents` | default `true` | include event logs in bridge mode |
394403
| `unsafeLocal.allowPrivateMemoryCoreAccess` | default `false` | required to run `unsafe-local` imports |
395404
| `unsafeLocal.paths` | default `[]` | explicit local paths to import in `unsafe-local` mode |
405+
| `ingest.autoCompile` | default `true` | rebuild compiled output after imported sources change |
396406
| `search.backend` | `shared` (default), `local` | |
397407
| `search.corpus` | `wiki` (default), `memory`, `all` | |
398408
| `context.includeCompiledDigestPrompt` | default `false` | append the selected agent's compact digest snapshot to memory prompt sections |

‎extensions/memory-wiki/index.test.ts‎

Lines changed: 138 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import {
1919
loadMemoryWikiVaultIdentity,
2020
resolveMemoryWikiVaultSourceGeneration,
2121
} from "./src/log.js";
22+
import { withMemoryWikiVaultMutation } from "./src/mutation-coordinator.js";
23+
import { waitForMemoryWikiImportedSourceSyncs } from "./src/source-sync.js";
2224
import { createMemoryWikiTestHarness } from "./src/test-helpers.js";
2325

2426
const toolMocks = vi.hoisted(() => {
@@ -41,6 +43,40 @@ vi.mock("./src/tool.js", () => toolMocks);
4143

4244
const { createPluginApi, createTempDir } = createMemoryWikiTestHarness();
4345

46+
function emptyCompiledSnapshot(): MemoryWikiCompiledCacheSnapshot {
47+
return {
48+
digest: { claimCount: 0, contradictionCount: 0, pages: [] },
49+
claims: [],
50+
dashboards: {
51+
importInsights: {
52+
sourceType: "chatgpt",
53+
totalItems: 0,
54+
totalClusters: 0,
55+
clusters: [],
56+
truncated: false,
57+
},
58+
overview: {
59+
totalItems: 0,
60+
totalPages: 0,
61+
pageCounts: { synthesis: 0, entity: 0, concept: 0, source: 0, report: 0 },
62+
totalClaims: 0,
63+
totalQuestions: 0,
64+
totalContradictions: 0,
65+
clusters: [],
66+
truncated: false,
67+
},
68+
},
69+
};
70+
}
71+
72+
function deferred() {
73+
let resolve!: () => void;
74+
const promise = new Promise<void>((done) => {
75+
resolve = done;
76+
});
77+
return { promise, resolve };
78+
}
79+
4480
describe("memory-wiki plugin", () => {
4581
it("registers prompt supplement, gateway methods, tools, and wiki cli surface", () => {
4682
const {
@@ -217,6 +253,107 @@ describe("memory-wiki plugin", () => {
217253
});
218254
});
219255

256+
it("fences cache publication when the plugin service stops", async () => {
257+
const rootDir = await createTempDir("memory-wiki-index-stop-fence-");
258+
await fs.mkdir(path.join(rootDir, ".openclaw-wiki"), { recursive: true });
259+
await fs.writeFile(path.join(rootDir, ".openclaw-wiki", "log.jsonl"), "", "utf8");
260+
const { api, registerService } = createPluginApi();
261+
api.pluginConfig = { vault: { path: rootDir } };
262+
plugin.register(api);
263+
const config = resolveMemoryWikiConfig(api.pluginConfig);
264+
const service = registerService.mock.calls[0]?.[0];
265+
await service?.start?.();
266+
const identity = await loadMemoryWikiVaultIdentity(rootDir);
267+
if (!identity.vaultGeneration) {
268+
throw new Error("Expected an active Memory Wiki vault generation");
269+
}
270+
const snapshot = emptyCompiledSnapshot();
271+
const validationEntered = deferred();
272+
const releaseValidation = deferred();
273+
const commitPublication = vi.fn();
274+
const publicationId = createMemoryWikiCompiledCachePublicationId();
275+
const publication = writeMemoryWikiCompiledCache(
276+
config,
277+
snapshot,
278+
resolveMemoryWikiCompiledCacheGeneration(snapshot),
279+
publicationId,
280+
null,
281+
async () => {
282+
validationEntered.resolve();
283+
await releaseValidation.promise;
284+
},
285+
commitPublication,
286+
async () => ({
287+
vaultGeneration: identity.vaultGeneration,
288+
compiledCachePublicationId: publicationId,
289+
}),
290+
);
291+
await validationEntered.promise;
292+
293+
await service?.stop?.();
294+
releaseValidation.resolve();
295+
296+
await expect(publication).rejects.toThrow("cache owner retired before publication");
297+
expect(commitPublication).not.toHaveBeenCalled();
298+
await expect(loadMemoryWikiCompiledCache(config)).resolves.toBeNull();
299+
});
300+
301+
it.each(["wiki.importInsights", "wiki.compile"])(
302+
"closes queued %s source sync before it can activate a vault",
303+
async (method) => {
304+
const rootDir = await createTempDir("memory-wiki-index-stop-sync-");
305+
const { api, registerGatewayMethod, registerService } = createPluginApi();
306+
api.pluginConfig = { vault: { path: rootDir } };
307+
plugin.register(api);
308+
const config = resolveMemoryWikiConfig(api.pluginConfig);
309+
const service = registerService.mock.calls[0]?.[0];
310+
await service?.start?.();
311+
312+
const mutationEntered = deferred();
313+
const releaseMutation = deferred();
314+
const mutation = withMemoryWikiVaultMutation(rootDir, async () => {
315+
mutationEntered.resolve();
316+
await releaseMutation.promise;
317+
});
318+
await mutationEntered.promise;
319+
const handler = registerGatewayMethod.mock.calls.find(([name]) => name === method)?.[1];
320+
if (!handler) {
321+
throw new Error(`Expected ${method} gateway handler`);
322+
}
323+
const request = handler({ params: {}, respond: vi.fn() });
324+
await vi.waitFor(async () => {
325+
const drainState = await Promise.race([
326+
waitForMemoryWikiImportedSourceSyncs().then(() => "settled" as const),
327+
new Promise<"pending">((resolve) => {
328+
setImmediate(() => resolve("pending"));
329+
}),
330+
]);
331+
expect(drainState).toBe("pending");
332+
});
333+
334+
const stop = service?.stop?.();
335+
releaseMutation.resolve();
336+
await mutation;
337+
await request;
338+
await stop;
339+
340+
const snapshot = emptyCompiledSnapshot();
341+
await expect(
342+
writeMemoryWikiCompiledCache(
343+
config,
344+
snapshot,
345+
resolveMemoryWikiCompiledCacheGeneration(snapshot),
346+
createMemoryWikiCompiledCachePublicationId(),
347+
null,
348+
async () => {},
349+
async () => {},
350+
() => loadMemoryWikiValidatedVaultIdentity(rootDir),
351+
),
352+
).rejects.toThrow("vault is not active");
353+
await expect(loadMemoryWikiCompiledCache(config)).resolves.toBeNull();
354+
},
355+
);
356+
220357
it("clears active owners before a fallible lifecycle identity refresh", async () => {
221358
const rootDir = await createTempDir("memory-wiki-index-refresh-failure-");
222359
const { api, registerService } = createPluginApi();
@@ -228,10 +365,7 @@ describe("memory-wiki plugin", () => {
228365
const service = registerService.mock.calls[0]?.[0];
229366
await service?.start?.();
230367

231-
const snapshot: MemoryWikiCompiledCacheSnapshot = {
232-
digest: { claimCount: 0, contradictionCount: 0, pages: [] },
233-
claims: [],
234-
};
368+
const snapshot = emptyCompiledSnapshot();
235369
const publicationId = createMemoryWikiCompiledCachePublicationId();
236370
const reservationId = createMemoryWikiCompiledCachePublicationId();
237371
const parentPublicationId = (await loadMemoryWikiVaultIdentity(rootDir))

‎extensions/memory-wiki/index.ts‎

Lines changed: 57 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
configureMemoryWikiSourceSyncStateStore,
3737
createMemoryWikiSourceSyncStateStore,
3838
} from "./src/source-sync-state.js";
39+
import { waitForMemoryWikiImportedSourceSyncs } from "./src/source-sync.js";
3940
import {
4041
createWikiApplyTool,
4142
createWikiGetTool,
@@ -95,7 +96,11 @@ export default definePluginEntry({
9596
// Context-free tool discovery cannot safely choose one agent's vault.
9697
return null;
9798
}
98-
return { appConfig, config: resolveConfig(agentId, appConfig) };
99+
return {
100+
appConfig,
101+
config: resolveConfig(agentId, appConfig),
102+
...(sourceSyncAbortController ? { signal: sourceSyncAbortController.signal } : {}),
103+
};
99104
};
100105
configureMemoryWikiSourceSyncStateStore(
101106
createMemoryWikiSourceSyncStateStore(api.runtime.state.openKeyedStore),
@@ -109,34 +114,38 @@ export default definePluginEntry({
109114
},
110115
});
111116
configureMemoryWikiCompiledCacheStore(compiledCacheStore);
117+
let sourceSyncAbortController: AbortController | undefined;
112118
api.registerService({
113119
id: "memory-wiki-compiled-cache-owner-cleanup",
114120
async start() {
115-
const appConfig = getAppConfig();
116-
const activeConfigs =
117-
config.vault.scope === "global"
118-
? [resolveConfig(undefined, appConfig)]
119-
: resolveMemoryWikiConfiguredAgentIds(appConfig).map((agentId) =>
120-
resolveConfig(agentId, appConfig),
121-
);
122-
// Clear every previously trusted owner before fallible vault reads. A failed
123-
// lifecycle refresh must leave prompt preparation closed, not stale-but-active.
124-
deactivateMemoryWikiCompiledCacheOwnersExcept(new Set());
125-
const preparedOwners: Array<{
126-
config: ReturnType<MemoryWikiConfigResolver>;
127-
identity: {
128-
vaultGeneration: string;
129-
compiledCachePublicationId: string | null;
130-
};
131-
}> = [];
132-
for (const activeConfig of activeConfigs) {
133-
const identity = await loadConfiguredVaultIdentity(activeConfig.vault.path);
134-
if (identity) {
135-
preparedOwners.push({ config: activeConfig, identity });
136-
}
137-
}
138-
const activeOwnerIds = new Set<string>();
121+
sourceSyncAbortController?.abort();
122+
const abortController = new AbortController();
123+
sourceSyncAbortController = abortController;
139124
try {
125+
const appConfig = getAppConfig();
126+
const activeConfigs =
127+
config.vault.scope === "global"
128+
? [resolveConfig(undefined, appConfig)]
129+
: resolveMemoryWikiConfiguredAgentIds(appConfig).map((agentId) =>
130+
resolveConfig(agentId, appConfig),
131+
);
132+
// Clear every previously trusted owner before fallible vault reads. A failed
133+
// lifecycle refresh must leave prompt preparation closed, not stale-but-active.
134+
deactivateMemoryWikiCompiledCacheOwnersExcept(new Set());
135+
const preparedOwners: Array<{
136+
config: ReturnType<MemoryWikiConfigResolver>;
137+
identity: {
138+
vaultGeneration: string;
139+
compiledCachePublicationId: string | null;
140+
};
141+
}> = [];
142+
for (const activeConfig of activeConfigs) {
143+
const identity = await loadConfiguredVaultIdentity(activeConfig.vault.path);
144+
if (identity) {
145+
preparedOwners.push({ config: activeConfig, identity });
146+
}
147+
}
148+
const activeOwnerIds = new Set<string>();
140149
for (const { config: activeConfig, identity } of preparedOwners) {
141150
activateMemoryWikiCompiledCacheOwner(
142151
activeConfig,
@@ -148,12 +157,23 @@ export default definePluginEntry({
148157
);
149158
activeOwnerIds.add(resolveMemoryWikiCompiledCacheOwnerId(activeConfig));
150159
}
160+
deactivateMemoryWikiCompiledCacheOwnersExcept(activeOwnerIds);
161+
await compiledCacheStore.deleteOwnersExcept(activeOwnerIds);
151162
} catch (error) {
163+
abortController.abort();
164+
if (sourceSyncAbortController === abortController) {
165+
sourceSyncAbortController = undefined;
166+
}
152167
deactivateMemoryWikiCompiledCacheOwnersExcept(new Set());
153168
throw error;
154169
}
155-
deactivateMemoryWikiCompiledCacheOwnersExcept(activeOwnerIds);
156-
await compiledCacheStore.deleteOwnersExcept(activeOwnerIds);
170+
},
171+
async stop() {
172+
sourceSyncAbortController?.abort();
173+
sourceSyncAbortController = undefined;
174+
deactivateMemoryWikiCompiledCacheOwnersExcept(new Set());
175+
await waitForMemoryWikiImportedSourceSyncs();
176+
deactivateMemoryWikiCompiledCacheOwnersExcept(new Set());
157177
},
158178
});
159179

@@ -166,13 +186,15 @@ export default definePluginEntry({
166186
appConfig: api.config,
167187
getAppConfig,
168188
resolveConfig,
189+
resolveSourceSyncSignal: () => sourceSyncAbortController?.signal,
169190
});
170191
api.registerTool(
171192
(ctx) => {
172193
const resolved = resolveToolContext(ctx.agentId);
173194
return resolved
174195
? createWikiStatusTool(resolved.config, resolved.appConfig, {
175196
agentId: resolved.config.agentId ?? ctx.agentId,
197+
...(resolved.signal ? { signal: resolved.signal } : {}),
176198
})
177199
: null;
178200
},
@@ -181,14 +203,18 @@ export default definePluginEntry({
181203
api.registerTool(
182204
(ctx) => {
183205
const resolved = resolveToolContext(ctx.agentId);
184-
return resolved ? createWikiLintTool(resolved.config, resolved.appConfig) : null;
206+
return resolved
207+
? createWikiLintTool(resolved.config, resolved.appConfig, resolved.signal)
208+
: null;
185209
},
186210
{ name: "wiki_lint" },
187211
);
188212
api.registerTool(
189213
(ctx) => {
190214
const resolved = resolveToolContext(ctx.agentId);
191-
return resolved ? createWikiApplyTool(resolved.config, resolved.appConfig) : null;
215+
return resolved
216+
? createWikiApplyTool(resolved.config, resolved.appConfig, resolved.signal)
217+
: null;
192218
},
193219
{ name: "wiki_apply" },
194220
);
@@ -203,6 +229,7 @@ export default definePluginEntry({
203229
agentSessionKey: ctx.sessionKey,
204230
sandboxed: ctx.sandboxed,
205231
conversationRecall: ctx.conversationRecall,
232+
...(resolved.signal ? { signal: resolved.signal } : {}),
206233
});
207234
},
208235
{ name: "wiki_search" },
@@ -218,6 +245,7 @@ export default definePluginEntry({
218245
agentSessionKey: ctx.sessionKey,
219246
sandboxed: ctx.sandboxed,
220247
conversationRecall: ctx.conversationRecall,
248+
...(resolved.signal ? { signal: resolved.signal } : {}),
221249
});
222250
},
223251
{ name: "wiki_get" },

‎extensions/memory-wiki/src/apply.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,8 +365,13 @@ async function applyUpdateMetadataMutation(params: {
365365
async function applyMemoryWikiMutationUnlocked(params: {
366366
config: ResolvedMemoryWikiConfig;
367367
mutation: ApplyMemoryWikiMutation;
368+
signal?: AbortSignal;
368369
}): Promise<ApplyMemoryWikiMutationResult> {
369-
await initializeMemoryWikiVault(params.config);
370+
await initializeMemoryWikiVault(
371+
params.config,
372+
params.signal ? { signal: params.signal } : undefined,
373+
);
374+
params.signal?.throwIfAborted();
370375
const result =
371376
params.mutation.op === "create_synthesis"
372377
? await applyCreateSynthesisMutation({
@@ -377,7 +382,11 @@ async function applyMemoryWikiMutationUnlocked(params: {
377382
config: params.config,
378383
mutation: params.mutation,
379384
});
380-
const compile = await compileMemoryWikiVault(params.config);
385+
params.signal?.throwIfAborted();
386+
const compile = await compileMemoryWikiVault(
387+
params.config,
388+
params.signal ? { signal: params.signal } : undefined,
389+
);
381390
return {
382391
changed: result.changed,
383392
operation: params.mutation.op,
@@ -390,6 +399,7 @@ async function applyMemoryWikiMutationUnlocked(params: {
390399
export async function applyMemoryWikiMutation(params: {
391400
config: ResolvedMemoryWikiConfig;
392401
mutation: ApplyMemoryWikiMutation;
402+
signal?: AbortSignal;
393403
}): Promise<ApplyMemoryWikiMutationResult> {
394404
return await withMemoryWikiVaultMutation(params.config.vault.path, () =>
395405
applyMemoryWikiMutationUnlocked(params),

0 commit comments

Comments
 (0)