Skip to content

Commit cdb55b3

Browse files
authored
fix(memory-core): retry narrative message reads (#89091)
* fix(memory-core): retry narrative message reads * fix(memory-core): wait longer for narrative text
1 parent 8d72cb9 commit cdb55b3

2 files changed

Lines changed: 129 additions & 4 deletions

File tree

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

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,11 @@ function expectLogExcludes(source: MockCallSource, text: string): void {
7373
expect(logIncludes(source, text), `Expected log not to include ${text}`).toBe(false);
7474
}
7575

76+
async function flushNarrativeSettleTimers<T>(operation: Promise<T>): Promise<T> {
77+
await vi.runAllTimersAsync();
78+
return operation;
79+
}
80+
7681
async function expectPathMissing(targetPath: string): Promise<void> {
7782
const accessResult = await fs
7883
.access(targetPath)
@@ -683,6 +688,88 @@ describe("generateAndAppendDreamNarrative", () => {
683688
expect(logger.info).toHaveBeenCalled();
684689
});
685690

691+
it("waits for persisted assistant text before falling back", async () => {
692+
vi.useFakeTimers();
693+
try {
694+
const workspaceDir = await createTempWorkspace("openclaw-dreaming-narrative-");
695+
const subagent = createMockSubagent("");
696+
subagent.getSessionMessages
697+
.mockResolvedValueOnce({
698+
messages: [{ role: "user", content: "prompt" }],
699+
})
700+
.mockResolvedValueOnce({
701+
messages: [
702+
{ role: "user", content: "prompt" },
703+
{
704+
role: "assistant",
705+
content: [{ type: "text", text: "The delayed diary text finally settled." }],
706+
},
707+
],
708+
});
709+
const logger = createMockLogger();
710+
711+
const operation = generateAndAppendDreamNarrative({
712+
subagent,
713+
workspaceDir,
714+
data: {
715+
phase: "light",
716+
snippets: ["The narrative assistant persisted after the run completed."],
717+
},
718+
nowMs: Date.parse("2026-04-05T03:00:00Z"),
719+
timezone: "UTC",
720+
logger,
721+
});
722+
await flushNarrativeSettleTimers(operation);
723+
724+
expect(subagent.getSessionMessages).toHaveBeenCalledTimes(2);
725+
expect(subagent.getSessionMessages).toHaveBeenNthCalledWith(1, {
726+
sessionKey: expect.stringContaining("dreaming-narrative-light-"),
727+
limit: expect.any(Number),
728+
});
729+
expect(subagent.getSessionMessages).toHaveBeenNthCalledWith(2, {
730+
sessionKey: expect.stringContaining("dreaming-narrative-light-"),
731+
limit: expect.any(Number),
732+
});
733+
const content = await fs.readFile(path.join(workspaceDir, "DREAMS.md"), "utf-8");
734+
expect(content).toContain("The delayed diary text finally settled.");
735+
expect(content).not.toContain("A memory trace surfaced");
736+
expectLogExcludes(logger.warn, "produced no text");
737+
} finally {
738+
vi.useRealTimers();
739+
}
740+
});
741+
742+
it("falls back after settled assistant text never appears", async () => {
743+
vi.useFakeTimers();
744+
try {
745+
const workspaceDir = await createTempWorkspace("openclaw-dreaming-narrative-");
746+
const subagent = createMockSubagent("");
747+
const logger = createMockLogger();
748+
749+
const operation = generateAndAppendDreamNarrative({
750+
subagent,
751+
workspaceDir,
752+
data: {
753+
phase: "light",
754+
snippets: ["The narrative assistant never persisted text."],
755+
},
756+
nowMs: Date.parse("2026-04-05T03:00:00Z"),
757+
timezone: "UTC",
758+
logger,
759+
});
760+
await flushNarrativeSettleTimers(operation);
761+
762+
expect(subagent.getSessionMessages).toHaveBeenCalledTimes(5);
763+
const content = await fs.readFile(path.join(workspaceDir, "DREAMS.md"), "utf-8");
764+
expect(content).toContain(
765+
"A memory trace surfaced, but details were unavailable in this run.",
766+
);
767+
expectLogIncludes(logger.warn, "produced no text");
768+
} finally {
769+
vi.useRealTimers();
770+
}
771+
});
772+
686773
it("retries with the session default when the configured model cannot start", async () => {
687774
const workspaceDir = await createTempWorkspace("openclaw-dreaming-narrative-");
688775
const subagent = createMockSubagent("The default model carried the diary home.");

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

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ const NARRATIVE_SYSTEM_PROMPT = [
9999
// worst case at one minute, well below the multi-minute stall the original
100100
// comment warned against.
101101
const NARRATIVE_TIMEOUT_MS = 60_000;
102+
const NARRATIVE_MESSAGE_FETCH_LIMIT = 5;
103+
// A completed run can reach the session reader before the final assistant text
104+
// is visible, so retry briefly before falling back to synthetic diary text.
105+
const NARRATIVE_MESSAGE_SETTLE_DELAYS_MS = [50, 150, 300, 750] as const;
102106
const DREAMING_SESSION_KEY_PREFIX = "dreaming-narrative-";
103107
const DREAMING_TRANSCRIPT_RUN_MARKER = '"runId":"dreaming-narrative-';
104108
const DREAMING_ORPHAN_MIN_AGE_MS = 300_000;
@@ -342,6 +346,42 @@ export function extractNarrativeText(messages: unknown[]): string | null {
342346
return null;
343347
}
344348

349+
function waitForNarrativeMessagesToSettle(delayMs: number): Promise<void> {
350+
return new Promise((resolve) => {
351+
setTimeout(resolve, delayMs);
352+
});
353+
}
354+
355+
async function readNarrativeText(params: {
356+
subagent: SubagentSurface;
357+
sessionKey: string;
358+
}): Promise<string | null> {
359+
const { messages } = await params.subagent.getSessionMessages({
360+
sessionKey: params.sessionKey,
361+
limit: NARRATIVE_MESSAGE_FETCH_LIMIT,
362+
});
363+
return extractNarrativeText(messages);
364+
}
365+
366+
async function readSettledNarrativeText(params: {
367+
subagent: SubagentSurface;
368+
sessionKey: string;
369+
}): Promise<string | null> {
370+
const immediateNarrative = await readNarrativeText(params);
371+
if (immediateNarrative) {
372+
return immediateNarrative;
373+
}
374+
375+
for (const delayMs of NARRATIVE_MESSAGE_SETTLE_DELAYS_MS) {
376+
await waitForNarrativeMessagesToSettle(delayMs);
377+
const narrative = await readNarrativeText(params);
378+
if (narrative) {
379+
return narrative;
380+
}
381+
}
382+
return null;
383+
}
384+
345385
// ── Date formatting ────────────────────────────────────────────────────
346386

347387
export function formatNarrativeDate(epochMs: number, timezone?: string): string {
@@ -966,12 +1006,10 @@ export async function generateAndAppendDreamNarrative(params: {
9661006
return;
9671007
}
9681008

969-
const { messages } = await params.subagent.getSessionMessages({
1009+
const narrative = await readSettledNarrativeText({
1010+
subagent: params.subagent,
9701011
sessionKey: successfulSessionKey,
971-
limit: 5,
9721012
});
973-
974-
const narrative = extractNarrativeText(messages);
9751013
if (!narrative) {
9761014
params.logger.warn(
9771015
`memory-core: narrative generation produced no text for ${params.data.phase} phase; writing fallback diary entry.`,

0 commit comments

Comments
 (0)