Skip to content

Commit 6269be7

Browse files
authored
refactor(memory): consolidate sync and dreaming helpers (#119633)
* refactor(memory): consolidate sync and dreaming helpers * test(memory): track descriptor-backed promotion writes
1 parent 0b68f8e commit 6269be7

6 files changed

Lines changed: 92 additions & 196 deletions

File tree

‎extensions/memory-core/src/dreaming-consolidation.ts‎

Lines changed: 1 addition & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
88
import type { MemoryConsolidationResult } from "./dreaming-consolidation-artifacts.js";
99
import { filterConsolidationCandidates } from "./dreaming-consolidation-candidates.js";
1010
import type { SubagentSurface } from "./dreaming-narrative.js";
11+
import { extractAssistantText } from "./dreaming-shared.js";
1112
import { DEFAULT_MEMORY_FILE_MAX_CHARS } from "./memory-budget.js";
1213
import {
1314
buildPromotionRecallAnnotations,
@@ -92,41 +93,6 @@ function buildConsolidationPrompt(
9293
});
9394
}
9495

95-
function extractAssistantText(messages: unknown[]): string | null {
96-
for (let index = messages.length - 1; index >= 0; index -= 1) {
97-
const message = messages[index];
98-
if (!message || typeof message !== "object" || Array.isArray(message)) {
99-
continue;
100-
}
101-
const record = message as { role?: unknown; content?: unknown };
102-
if (record.role !== "assistant") {
103-
continue;
104-
}
105-
if (typeof record.content === "string" && record.content.trim()) {
106-
return record.content.trim();
107-
}
108-
if (Array.isArray(record.content)) {
109-
const text = record.content
110-
.flatMap((part) => {
111-
if (!part || typeof part !== "object" || Array.isArray(part)) {
112-
return [];
113-
}
114-
const item = part as { type?: unknown; text?: unknown };
115-
return (item.type === "text" || item.type === "output_text") &&
116-
typeof item.text === "string"
117-
? [item.text]
118-
: [];
119-
})
120-
.join("\n")
121-
.trim();
122-
if (text) {
123-
return text;
124-
}
125-
}
126-
}
127-
return null;
128-
}
129-
13096
function parseConsolidatedMemory(raw: string): ConsolidationOutput | null {
13197
try {
13298
const parsed = JSON.parse(raw) as { memory?: unknown; operations?: unknown };

‎extensions/memory-core/src/dreaming-narrative.ts‎

Lines changed: 2 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
DREAMING_SESSION_KEY_PREFIX,
1818
scrubDreamingNarrativeArtifacts,
1919
} from "./dreaming-session-cleanup.js";
20+
import { extractAssistantText } from "./dreaming-shared.js";
2021

2122
// ── Types ──────────────────────────────────────────────────────────────
2223

@@ -349,44 +350,6 @@ function buildNarrativePrompt(data: NarrativePhaseData): string {
349350
return lines.join("\n");
350351
}
351352

352-
// ── Message extraction ─────────────────────────────────────────────────
353-
354-
function extractNarrativeText(messages: unknown[]): string | null {
355-
for (let i = messages.length - 1; i >= 0; i--) {
356-
const msg = messages[i];
357-
if (!msg || typeof msg !== "object" || Array.isArray(msg)) {
358-
continue;
359-
}
360-
const record = msg as Record<string, unknown>;
361-
if (record.role !== "assistant") {
362-
continue;
363-
}
364-
const content = record.content;
365-
if (typeof content === "string" && content.trim().length > 0) {
366-
return content.trim();
367-
}
368-
if (Array.isArray(content)) {
369-
const text = content
370-
.filter(
371-
(part: unknown) =>
372-
part &&
373-
typeof part === "object" &&
374-
!Array.isArray(part) &&
375-
((part as Record<string, unknown>).type === "text" ||
376-
(part as Record<string, unknown>).type === "output_text") &&
377-
typeof (part as Record<string, unknown>).text === "string",
378-
)
379-
.map((part) => (part as { text: string }).text)
380-
.join("\n")
381-
.trim();
382-
if (text.length > 0) {
383-
return text;
384-
}
385-
}
386-
}
387-
return null;
388-
}
389-
390353
function waitForNarrativeMessagesToSettle(delayMs: number): Promise<void> {
391354
return new Promise((resolve) => {
392355
setTimeout(resolve, delayMs);
@@ -401,7 +364,7 @@ async function readNarrativeText(params: {
401364
sessionKey: params.sessionKey,
402365
limit: NARRATIVE_MESSAGE_FETCH_LIMIT,
403366
});
404-
return extractNarrativeText(messages);
367+
return extractAssistantText(messages);
405368
}
406369

407370
async function readSettledNarrativeText(params: {

‎extensions/memory-core/src/dreaming-shared.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,43 @@
11
// Memory Core plugin module implements dreaming shared behavior.
2-
export { asNullableRecord as asRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
2+
import {
3+
asNullableRecord,
4+
normalizeOptionalString,
5+
} from "openclaw/plugin-sdk/string-coerce-runtime";
6+
7+
export { asNullableRecord as asRecord, normalizeOptionalString as normalizeTrimmedString };
38
export { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
49

5-
export function normalizeTrimmedString(value: unknown): string | undefined {
6-
if (typeof value !== "string") {
7-
return undefined;
10+
export function extractAssistantText(messages: unknown[]): string | null {
11+
for (let index = messages.length - 1; index >= 0; index -= 1) {
12+
const message = asNullableRecord(messages[index]);
13+
if (message?.role !== "assistant") {
14+
continue;
15+
}
16+
if (typeof message.content === "string" && message.content.trim()) {
17+
return message.content.trim();
18+
}
19+
if (Array.isArray(message.content)) {
20+
const text = message.content
21+
.flatMap((part) => {
22+
const item = asNullableRecord(part);
23+
return (item?.type === "text" || item?.type === "output_text") &&
24+
typeof item.text === "string"
25+
? [item.text]
26+
: [];
27+
})
28+
.join("\n")
29+
.trim();
30+
if (text) {
31+
return text;
32+
}
33+
}
834
}
9-
const trimmed = value.trim();
10-
return trimmed.length > 0 ? trimmed : undefined;
35+
return null;
1136
}
1237

1338
export function includesSystemEventToken(cleanedBody: string, eventText: string): boolean {
14-
const normalizedBody = normalizeTrimmedString(cleanedBody);
15-
const normalizedEventText = normalizeTrimmedString(eventText);
39+
const normalizedBody = normalizeOptionalString(cleanedBody);
40+
const normalizedEventText = normalizeOptionalString(eventText);
1641
if (!normalizedBody || !normalizedEventText) {
1742
return false;
1843
}

‎extensions/memory-core/src/memory/manager-source-sync-ops.ts‎

Lines changed: 31 additions & 106 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,7 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
114114
const dirtyEntries: MemoryIndexEntry[] = [];
115115
for (const entry of fileEntries) {
116116
if (!params.needsFullReindex && existingHashes.get(entry.path) === entry.hash) {
117-
if (params.progress) {
118-
params.progress.completed += 1;
119-
params.progress.report({
120-
completed: params.progress.completed,
121-
total: params.progress.total,
122-
});
123-
}
117+
this.advanceSyncProgress(params.progress);
124118
continue;
125119
}
126120
dirtyEntries.push(entry);
@@ -135,23 +129,11 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
135129
} else {
136130
const tasks = fileEntries.map((entry) => async () => {
137131
if (!params.needsFullReindex && existingHashes.get(entry.path) === entry.hash) {
138-
if (params.progress) {
139-
params.progress.completed += 1;
140-
params.progress.report({
141-
completed: params.progress.completed,
142-
total: params.progress.total,
143-
});
144-
}
132+
this.advanceSyncProgress(params.progress);
145133
return;
146134
}
147135
await this.indexFile(entry, { source: "memory" });
148-
if (params.progress) {
149-
params.progress.completed += 1;
150-
params.progress.report({
151-
completed: params.progress.completed,
152-
total: params.progress.total,
153-
});
154-
}
136+
this.advanceSyncProgress(params.progress);
155137
});
156138
await runWithConcurrency(tasks, this.getIndexConcurrency());
157139
}
@@ -309,6 +291,31 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
309291
}
310292
}
311293
};
294+
const resolveSessionIndexEntry = async (absPath: string): Promise<MemoryIndexEntry | null> => {
295+
if (!indexAll && !this.sessionsDirtyFiles.has(absPath)) {
296+
this.advanceSyncProgress(params.progress);
297+
return null;
298+
}
299+
const entry = await buildSessionEntry(
300+
absPath,
301+
this.buildSessionEntryOptions(corpusEntryForPath(absPath)),
302+
);
303+
if (!entry) {
304+
this.advanceSyncProgress(params.progress);
305+
return null;
306+
}
307+
const existingHash = resolveMemorySourceExistingHash({
308+
db: this.db,
309+
source: "sessions",
310+
path: entry.path,
311+
existingHashes,
312+
});
313+
if (canSkipUnchangedSessionEntry(entry, absPath, existingHash)) {
314+
this.advanceSyncProgress(params.progress);
315+
return null;
316+
}
317+
return entry;
318+
};
312319

313320
if (params.deferIndex) {
314321
const pendingIndexItems = [...(params.prefixIndexItems ?? [])];
@@ -333,47 +340,7 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
333340
await runWithConcurrency(
334341
fileBatch.map((absPath) => async (): Promise<MemoryIndexEntry | null> => {
335342
try {
336-
if (!indexAll && !this.sessionsDirtyFiles.has(absPath)) {
337-
if (params.progress) {
338-
params.progress.completed += 1;
339-
params.progress.report({
340-
completed: params.progress.completed,
341-
total: params.progress.total,
342-
});
343-
}
344-
return null;
345-
}
346-
const entry = await buildSessionEntry(
347-
absPath,
348-
this.buildSessionEntryOptions(corpusEntryForPath(absPath)),
349-
);
350-
if (!entry) {
351-
if (params.progress) {
352-
params.progress.completed += 1;
353-
params.progress.report({
354-
completed: params.progress.completed,
355-
total: params.progress.total,
356-
});
357-
}
358-
return null;
359-
}
360-
const existingHash = resolveMemorySourceExistingHash({
361-
db: this.db,
362-
source: "sessions",
363-
path: entry.path,
364-
existingHashes,
365-
});
366-
if (canSkipUnchangedSessionEntry(entry, absPath, existingHash)) {
367-
if (params.progress) {
368-
params.progress.completed += 1;
369-
params.progress.report({
370-
completed: params.progress.completed,
371-
total: params.progress.total,
372-
});
373-
}
374-
return null;
375-
}
376-
return entry;
343+
return await resolveSessionIndexEntry(absPath);
377344
} finally {
378345
await yieldAfterSessionFile();
379346
}
@@ -405,54 +372,12 @@ export abstract class MemoryManagerSourceSyncOps extends MemoryManagerSessionSyn
405372

406373
const tasks = files.map((absPath) => async () => {
407374
try {
408-
if (!indexAll && !this.sessionsDirtyFiles.has(absPath)) {
409-
if (params.progress) {
410-
params.progress.completed += 1;
411-
params.progress.report({
412-
completed: params.progress.completed,
413-
total: params.progress.total,
414-
});
415-
}
416-
return;
417-
}
418-
const entry = await buildSessionEntry(
419-
absPath,
420-
this.buildSessionEntryOptions(corpusEntryForPath(absPath)),
421-
);
375+
const entry = await resolveSessionIndexEntry(absPath);
422376
if (!entry) {
423-
if (params.progress) {
424-
params.progress.completed += 1;
425-
params.progress.report({
426-
completed: params.progress.completed,
427-
total: params.progress.total,
428-
});
429-
}
430-
return;
431-
}
432-
const existingHash = resolveMemorySourceExistingHash({
433-
db: this.db,
434-
source: "sessions",
435-
path: entry.path,
436-
existingHashes,
437-
});
438-
if (canSkipUnchangedSessionEntry(entry, absPath, existingHash)) {
439-
if (params.progress) {
440-
params.progress.completed += 1;
441-
params.progress.report({
442-
completed: params.progress.completed,
443-
total: params.progress.total,
444-
});
445-
}
446377
return;
447378
}
448379
await this.indexFile(entry, { source: "sessions", content: entry.content });
449-
if (params.progress) {
450-
params.progress.completed += 1;
451-
params.progress.report({
452-
completed: params.progress.completed,
453-
total: params.progress.total,
454-
});
455-
}
380+
this.advanceSyncProgress(params.progress);
456381
} finally {
457382
await yieldAfterSessionFile();
458383
}

‎extensions/memory-core/src/memory/manager-sync-base.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,14 @@ export abstract class MemoryManagerSyncBase {
257257
);
258258
}
259259

260+
protected advanceSyncProgress(progress: MemorySyncProgressState | undefined, count = 1): void {
261+
if (!progress) {
262+
return;
263+
}
264+
progress.completed += count;
265+
progress.report({ completed: progress.completed, total: progress.total });
266+
}
267+
260268
protected async indexQueuedFiles(
261269
items: MemoryIndexWorkItem[],
262270
progress?: MemorySyncProgressState,
@@ -276,13 +284,7 @@ export abstract class MemoryManagerSyncBase {
276284
for (const item of items) {
277285
item.afterIndex?.();
278286
}
279-
if (progress) {
280-
progress.completed += items.length;
281-
progress.report({
282-
completed: progress.completed,
283-
total: progress.total,
284-
});
285-
}
287+
this.advanceSyncProgress(progress, items.length);
286288
}
287289

288290
protected async executeSourceSyncPlans(

0 commit comments

Comments
 (0)