Skip to content

Commit 2373022

Browse files
authored
fix(memory-core): ignore managed dreaming blocks during daily ingestion (#61720) (thanks @MonkeyLeeT)
1 parent 1055464 commit 2373022

3 files changed

Lines changed: 214 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Docs: https://docs.openclaw.ai
1414
- Docs/i18n: remove the zh-CN homepage redirect override so Mintlify can resolve the localized Chinese homepage without self-redirecting `/zh-CN/index`.
1515
- Agents/heartbeat: stop truncating live session transcripts after no-op heartbeat acks, move heartbeat cleanup to prompt assembly and compaction, and keep post-filter context-engine ingestion aligned with the real session baseline. (#60998) Thanks @nxmxbbd.
1616
- macOS/gateway version: strip trailing commit metadata from CLI version output before semver parsing so the Mac app recognizes installed gateway versions like `OpenClaw 2026.4.2 (d74a122)` again. (#61111) Thanks @oliviareid-svg.
17+
- Memory/dreaming: strip managed Light Sleep and REM blocks before daily-note ingestion so dreaming summaries stop re-ingesting their own staged output into new candidates. (#61720) Thanks @MonkeyLeeT.
1718

1819
## 2026.4.5
1920

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

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,28 @@ import {
1111
import { createMemoryCoreTestHarness } from "./test-helpers.js";
1212

1313
const { createTempWorkspace } = createMemoryCoreTestHarness();
14+
const DREAMING_TEST_BASE_TIME = new Date("2026-04-05T10:00:00.000Z");
15+
const DREAMING_TEST_DAY = "2026-04-05";
16+
const LIGHT_DREAMING_TEST_CONFIG: OpenClawConfig = {
17+
plugins: {
18+
entries: {
19+
"memory-core": {
20+
config: {
21+
dreaming: {
22+
enabled: true,
23+
phases: {
24+
light: {
25+
enabled: true,
26+
limit: 20,
27+
lookbackDays: 2,
28+
},
29+
},
30+
},
31+
},
32+
},
33+
},
34+
},
35+
};
1436

1537
function createHarness(config: OpenClawConfig, workspaceDir?: string) {
1638
let beforeAgentReply:
@@ -55,7 +77,124 @@ function createHarness(config: OpenClawConfig, workspaceDir?: string) {
5577
return { beforeAgentReply, logger };
5678
}
5779

80+
function setDreamingTestTime(offsetMinutes = 0) {
81+
vi.setSystemTime(new Date(DREAMING_TEST_BASE_TIME.getTime() + offsetMinutes * 60_000));
82+
}
83+
84+
async function withDreamingTestClock(run: () => Promise<void>) {
85+
vi.useFakeTimers();
86+
try {
87+
await run();
88+
} finally {
89+
vi.useRealTimers();
90+
}
91+
}
92+
93+
async function writeDailyNote(workspaceDir: string, lines: string[]): Promise<void> {
94+
await fs.mkdir(path.join(workspaceDir, "memory"), { recursive: true });
95+
await fs.writeFile(
96+
path.join(workspaceDir, "memory", `${DREAMING_TEST_DAY}.md`),
97+
lines.join("\n"),
98+
"utf-8",
99+
);
100+
}
101+
102+
function createLightDreamingHarness(workspaceDir: string) {
103+
return createHarness(LIGHT_DREAMING_TEST_CONFIG, workspaceDir);
104+
}
105+
106+
async function triggerLightDreaming(
107+
beforeAgentReply: NonNullable<ReturnType<typeof createHarness>["beforeAgentReply"]>,
108+
workspaceDir: string,
109+
offsetMinutes: number,
110+
): Promise<void> {
111+
setDreamingTestTime(offsetMinutes);
112+
await beforeAgentReply(
113+
{ cleanedBody: "__openclaw_memory_core_light_sleep__" },
114+
{ trigger: "heartbeat", workspaceDir },
115+
);
116+
}
117+
118+
async function readCandidateSnippets(workspaceDir: string, nowIso: string): Promise<string[]> {
119+
const candidates = await rankShortTermPromotionCandidates({
120+
workspaceDir,
121+
minScore: 0,
122+
minRecallCount: 0,
123+
minUniqueQueries: 0,
124+
nowMs: Date.parse(nowIso),
125+
});
126+
return candidates.map((candidate) => candidate.snippet);
127+
}
128+
58129
describe("memory-core dreaming phases", () => {
130+
it("does not re-ingest managed light dreaming blocks from daily notes", async () => {
131+
const workspaceDir = await createTempWorkspace("openclaw-dreaming-phases-");
132+
await withDreamingTestClock(async () => {
133+
await writeDailyNote(workspaceDir, [
134+
`# ${DREAMING_TEST_DAY}`,
135+
"",
136+
"- Move backups to S3 Glacier.",
137+
"- Keep retention at 365 days.",
138+
]);
139+
140+
const { beforeAgentReply } = createLightDreamingHarness(workspaceDir);
141+
const candidateCounts: number[] = [];
142+
const candidateSnippets: string[][] = [];
143+
for (let run = 0; run < 3; run += 1) {
144+
await triggerLightDreaming(beforeAgentReply, workspaceDir, run + 1);
145+
candidateSnippets.push(
146+
await readCandidateSnippets(workspaceDir, `2026-04-05T10:0${run + 1}:00.000Z`),
147+
);
148+
candidateCounts.push(candidateSnippets.at(-1)?.length ?? 0);
149+
}
150+
151+
expect(candidateCounts).toEqual([1, 1, 1]);
152+
expect(candidateSnippets).toEqual([
153+
["Move backups to S3 Glacier.; Keep retention at 365 days."],
154+
["Move backups to S3 Glacier.; Keep retention at 365 days."],
155+
["Move backups to S3 Glacier.; Keep retention at 365 days."],
156+
]);
157+
158+
const dailyContent = await fs.readFile(
159+
path.join(workspaceDir, "memory", `${DREAMING_TEST_DAY}.md`),
160+
"utf-8",
161+
);
162+
expect(dailyContent).toContain("## Light Sleep");
163+
expect(dailyContent.match(/^- Candidate:/gm)).toHaveLength(1);
164+
expect(dailyContent).not.toContain("Light Sleep: Candidate:");
165+
});
166+
});
167+
168+
it("stops stripping a malformed managed block at the next section boundary", async () => {
169+
const workspaceDir = await createTempWorkspace("openclaw-dreaming-phases-");
170+
await withDreamingTestClock(async () => {
171+
await writeDailyNote(workspaceDir, [
172+
`# ${DREAMING_TEST_DAY}`,
173+
"",
174+
"- Move backups to S3 Glacier.",
175+
"",
176+
"## Light Sleep",
177+
"<!-- openclaw:dreaming:light:start -->",
178+
"- Candidate: Old staged summary.",
179+
"",
180+
"## Ops",
181+
"- Rotate access keys.",
182+
"",
183+
"## Light Sleep",
184+
"<!-- openclaw:dreaming:light:start -->",
185+
"- Candidate: Fresh staged summary.",
186+
"<!-- openclaw:dreaming:light:end -->",
187+
]);
188+
189+
const { beforeAgentReply } = createLightDreamingHarness(workspaceDir);
190+
await triggerLightDreaming(beforeAgentReply, workspaceDir, 1);
191+
192+
expect(await readCandidateSnippets(workspaceDir, "2026-04-05T10:01:00.000Z")).toContain(
193+
"Ops: Rotate access keys.",
194+
);
195+
});
196+
});
197+
59198
it("checkpoints daily ingestion and skips unchanged daily files", async () => {
60199
const workspaceDir = await createTempWorkspace("openclaw-dreaming-phases-");
61200
await fs.mkdir(path.join(workspaceDir, "memory"), { recursive: true });

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

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,18 @@ const DAILY_INGESTION_MIN_SNIPPET_CHARS = 8;
8686
const DAILY_INGESTION_MAX_CHUNK_LINES = 4;
8787
const GENERIC_DAY_HEADING_RE =
8888
/^(?:(?:mon|monday|tue|tues|tuesday|wed|wednesday|thu|thur|thurs|thursday|fri|friday|sat|saturday|sun|sunday)(?:,\s+)?)?(?:(?:jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+\d{1,2}(?:st|nd|rd|th)?(?:,\s*\d{4})?|\d{1,2}[/-]\d{1,2}(?:[/-]\d{2,4})?|\d{4}[/-]\d{2}[/-]\d{2})$/i;
89+
const MANAGED_DAILY_DREAMING_BLOCKS = [
90+
{
91+
heading: "## Light Sleep",
92+
startMarker: "<!-- openclaw:dreaming:light:start -->",
93+
endMarker: "<!-- openclaw:dreaming:light:end -->",
94+
},
95+
{
96+
heading: "## REM Sleep",
97+
startMarker: "<!-- openclaw:dreaming:rem:start -->",
98+
endMarker: "<!-- openclaw:dreaming:rem:end -->",
99+
},
100+
] as const;
89101

90102
function asRecord(value: unknown): Record<string, unknown> | null {
91103
if (!value || typeof value !== "object" || Array.isArray(value)) {
@@ -476,6 +488,67 @@ function buildDailySnippetChunks(lines: string[], limit: number): DailySnippetCh
476488
return chunks.slice(0, limit);
477489
}
478490

491+
function findManagedDailyDreamingHeadingIndex(
492+
lines: string[],
493+
startIndex: number,
494+
heading: string,
495+
): number | null {
496+
for (let index = startIndex - 1; index >= 0; index -= 1) {
497+
const trimmed = lines[index]?.trim() ?? "";
498+
if (!trimmed) {
499+
continue;
500+
}
501+
return trimmed === heading ? index : null;
502+
}
503+
return null;
504+
}
505+
506+
function isManagedDailyDreamingBoundary(
507+
line: string,
508+
blockByStartMarker: ReadonlyMap<string, (typeof MANAGED_DAILY_DREAMING_BLOCKS)[number]>,
509+
): boolean {
510+
const trimmed = line.trim();
511+
return /^#{1,6}\s+/.test(trimmed) || blockByStartMarker.has(trimmed);
512+
}
513+
514+
function stripManagedDailyDreamingLines(lines: string[]): string[] {
515+
const blockByStartMarker: ReadonlyMap<string, (typeof MANAGED_DAILY_DREAMING_BLOCKS)[number]> =
516+
new Map(MANAGED_DAILY_DREAMING_BLOCKS.map((block) => [block.startMarker, block]));
517+
const sanitized = [...lines];
518+
for (let index = 0; index < sanitized.length; index += 1) {
519+
const block = blockByStartMarker.get(sanitized[index]?.trim() ?? "");
520+
if (!block) {
521+
continue;
522+
}
523+
524+
let stripUntilIndex = -1;
525+
for (let cursor = index + 1; cursor < sanitized.length; cursor += 1) {
526+
const line = sanitized[cursor];
527+
const trimmed = line?.trim() ?? "";
528+
if (trimmed === block.endMarker) {
529+
stripUntilIndex = cursor;
530+
break;
531+
}
532+
if (line && isManagedDailyDreamingBoundary(line, blockByStartMarker)) {
533+
stripUntilIndex = cursor - 1;
534+
break;
535+
}
536+
}
537+
if (stripUntilIndex < index) {
538+
continue;
539+
}
540+
541+
const headingIndex = findManagedDailyDreamingHeadingIndex(lines, index, block.heading);
542+
const startIndex = headingIndex ?? index;
543+
for (let cursor = startIndex; cursor <= stripUntilIndex; cursor += 1) {
544+
sanitized[cursor] = "";
545+
}
546+
index = stripUntilIndex;
547+
}
548+
549+
return sanitized;
550+
}
551+
479552
function entryWithinLookback(entry: ShortTermRecallEntry, cutoffMs: number): boolean {
480553
const byDay = (entry.recallDays ?? []).some((day) => isDayWithinLookback(day, cutoffMs));
481554
if (byDay) {
@@ -640,7 +713,7 @@ async function collectDailyIngestionBatches(params: {
640713
if (!raw) {
641714
continue;
642715
}
643-
const lines = raw.split(/\r?\n/);
716+
const lines = stripManagedDailyDreamingLines(raw.split(/\r?\n/));
644717
const chunks = buildDailySnippetChunks(lines, perFileCap);
645718
const results: MemorySearchResult[] = [];
646719
for (const chunk of chunks) {

0 commit comments

Comments
 (0)