Skip to content

Commit 772235c

Browse files
yetvalvincentkoc
andauthored
fix(memory-core): stop MEMORY.md compaction from deleting user headings (#116057)
* fix(memory-core): stop MEMORY.md compaction from deleting user headings parseMemoryBlocks segmented MEMORY.md only on "## ", so a user heading of any other level did not close the promotion section above it. The section ran on to the next "## " heading or EOF, and dropping it to fit the budget deleted the user text it had swallowed, with no backup and no diagnostic. Close the current block on any ATX heading, keeping the generator's own "### Global" and "### Project: <key>" subheadings inside the promotion body so multi-project sections stay droppable whole. * fix(memory-core): identify generated promotion subsections by their entry marker The first exception treated every "### Global" and "### Project: <key>" heading under a promotion block as dreaming-owned, so a user who wrote one of those headings themselves still lost it to compaction, which is the same data-loss class this change set out to fix. A generated subsection always leads with an openclaw-memory-promotion entry marker comment, so require that marker as the next non-blank line before treating the heading as part of the promotion body. User headings that collide with the generated names now terminate the block and survive. * fix(memory-core): recognize tab-delimited and empty ATX headings The heading detector required a literal ASCII space after the opening # sequence. CommonMark also allows a tab or end of line, so a user note starting with a tab-delimited heading stayed inside the promotion block above it and was deleted when compaction dropped that block. Accept a space, a tab, or end of line after the # sequence. The generated subsection pattern stays space-only because that is what buildPromotionSection emits, so a tab-delimited heading is user-authored and is preserved. * fix(memory-core): preserve Setext headings during compaction Setext headings were still absorbed into the generated promotion block above them, so dropping that block could silently delete durable user notes. Move the heading paragraph into a preserved block when its underline is encountered, while keeping marker-backed generated content compactable. * fix(memory-core): preserve indented ATX headings --------- Co-authored-by: Vincent Koc <[email protected]>
1 parent 87c71cf commit 772235c

3 files changed

Lines changed: 288 additions & 3 deletions

File tree

‎extensions/memory-core/src/memory-budget.test.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,25 @@ function promotionSection(date: string, sizeChars: number): string {
88
return `${heading}${padding}`;
99
}
1010

11+
function projectGroupedSection(date: string): string {
12+
return [
13+
"",
14+
`## Promoted From Short-Term Memory (${date})`,
15+
"",
16+
"### Global",
17+
"",
18+
"<!-- openclaw-memory-promotion:memory/short-term.md#global -->",
19+
`- ${"g".repeat(120)} [score=0.900 signals=4 recalls=4 avg=0.900 source=memory/short-term.md:1-2]`,
20+
"",
21+
"### Project: alpha",
22+
"",
23+
"<!-- openclaw-memory-promotion:memory/short-term.md#alpha -->",
24+
`- ${"a".repeat(120)} [score=0.900 signals=4 recalls=4 avg=0.900 source=memory/short-term.md:3-4]`,
25+
"",
26+
"",
27+
].join("\n");
28+
}
29+
1130
describe("compactMemoryForBudget — bounded MEMORY.md compaction (regression for #73691)", () => {
1231
it("returns existing memory unchanged when total fits the budget", () => {
1332
const existing = "# Long-Term Memory\n\nSome content.\n";
@@ -168,6 +187,154 @@ describe("compactMemoryForBudget — bounded MEMORY.md compaction (regression fo
168187
).toBeLessThanOrEqual(budget);
169188
});
170189

190+
it.each([0, 1, 2, 3])(
191+
"preserves a user `###` section with %i leading spaces under a promotion section",
192+
(leadingSpaces) => {
193+
const heading = `${" ".repeat(leadingSpaces)}### Correction (added by me)`;
194+
const existing =
195+
`${promotionSection("2026-04-10", 400)}\n` +
196+
`${heading}\nThe prod DB is db-2.corp.example, NOT db-1.\n\n` +
197+
promotionSection("2026-04-20", 400);
198+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
199+
const result = compactMemoryForBudget({
200+
existingMemory: existing,
201+
newSection,
202+
budgetChars: 900,
203+
});
204+
expect(result.droppedDates).toContain("2026-04-10");
205+
expect(result.compacted).toContain(heading);
206+
expect(result.compacted).toContain("The prod DB is db-2.corp.example, NOT db-1.");
207+
},
208+
);
209+
210+
it("does not treat a four-space-indented hash line as an ATX heading", () => {
211+
const existing =
212+
`${promotionSection("2026-04-10", 400)}\n` +
213+
" ### Indented code\n keep this inside the generated block\n\n" +
214+
promotionSection("2026-04-20", 400);
215+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
216+
const result = compactMemoryForBudget({
217+
existingMemory: existing,
218+
newSection,
219+
budgetChars: 900,
220+
});
221+
expect(result.droppedDates).toContain("2026-04-10");
222+
expect(result.compacted).not.toContain("### Indented code");
223+
expect(result.compacted).not.toContain("keep this inside the generated block");
224+
});
225+
226+
it("preserves a user `#` section written after the only promotion section", () => {
227+
const existing =
228+
`# Long-Term Memory\n\n${promotionSection("2026-04-10", 800)}\n` +
229+
"# My Notes\n\nKeep this paragraph.\n";
230+
const newSection = `\n${promotionSection("2026-04-29", 600)}`;
231+
const result = compactMemoryForBudget({
232+
existingMemory: existing,
233+
newSection,
234+
budgetChars: 800,
235+
});
236+
expect(result.droppedDates).toContain("2026-04-10");
237+
expect(result.compacted).toContain("# My Notes");
238+
expect(result.compacted).toContain("Keep this paragraph.");
239+
expect(result.compacted).toContain("# Long-Term Memory");
240+
});
241+
242+
it("drops a multi-project promotion section whole, including its `###` project subheadings", () => {
243+
const existing = `${projectGroupedSection("2026-04-10")}\n${projectGroupedSection("2026-04-20")}`;
244+
const newSection = `\n${projectGroupedSection("2026-04-29")}`;
245+
const result = compactMemoryForBudget({
246+
existingMemory: existing,
247+
newSection,
248+
budgetChars: 700,
249+
});
250+
expect(result.droppedDates).toEqual(["2026-04-10", "2026-04-20"]);
251+
expect(result.compacted).not.toContain("### Project: alpha");
252+
expect(result.compacted).not.toContain("### Global");
253+
expect(result.compacted).not.toContain("openclaw-memory-promotion");
254+
});
255+
256+
it("preserves a user-authored `### Global` heading written under a promotion section", () => {
257+
const existing =
258+
`${promotionSection("2026-04-10", 400)}\n` +
259+
"### Global\n\nMy own global rule, not a promoted entry.\n\n" +
260+
promotionSection("2026-04-20", 400);
261+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
262+
const result = compactMemoryForBudget({
263+
existingMemory: existing,
264+
newSection,
265+
budgetChars: 900,
266+
});
267+
expect(result.droppedDates).toContain("2026-04-10");
268+
expect(result.compacted).toContain("### Global");
269+
expect(result.compacted).toContain("My own global rule, not a promoted entry.");
270+
});
271+
272+
it("preserves a user-authored `### Project:` heading written under a promotion section", () => {
273+
const existing =
274+
`${promotionSection("2026-04-10", 400)}\n` +
275+
"### Project: alpha\n\nAlpha ships on Fridays.\n\n" +
276+
promotionSection("2026-04-20", 400);
277+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
278+
const result = compactMemoryForBudget({
279+
existingMemory: existing,
280+
newSection,
281+
budgetChars: 900,
282+
});
283+
expect(result.droppedDates).toContain("2026-04-10");
284+
expect(result.compacted).toContain("### Project: alpha");
285+
expect(result.compacted).toContain("Alpha ships on Fridays.");
286+
});
287+
288+
it("preserves a tab-delimited user heading written under a promotion section", () => {
289+
const existing =
290+
`${promotionSection("2026-04-10", 400)}\n` +
291+
"###\tCorrection\nThe prod DB is db-2.corp.example, NOT db-1.\n\n" +
292+
promotionSection("2026-04-20", 400);
293+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
294+
const result = compactMemoryForBudget({
295+
existingMemory: existing,
296+
newSection,
297+
budgetChars: 900,
298+
});
299+
expect(result.droppedDates).toContain("2026-04-10");
300+
expect(result.compacted).toContain("###\tCorrection");
301+
expect(result.compacted).toContain("The prod DB is db-2.corp.example, NOT db-1.");
302+
});
303+
304+
it("preserves an empty user heading line written under a promotion section", () => {
305+
const existing =
306+
`${promotionSection("2026-04-10", 400)}\n` +
307+
"###\nNotes I keep under a bare heading.\n\n" +
308+
promotionSection("2026-04-20", 400);
309+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
310+
const result = compactMemoryForBudget({
311+
existingMemory: existing,
312+
newSection,
313+
budgetChars: 900,
314+
});
315+
expect(result.droppedDates).toContain("2026-04-10");
316+
expect(result.compacted).toContain("Notes I keep under a bare heading.");
317+
});
318+
319+
it.each(["---", "==="])(
320+
"preserves a user Setext heading with a `%s` underline under a promotion section",
321+
(underline) => {
322+
const existing =
323+
`${promotionSection("2026-04-10", 400)}\n\n` +
324+
`My Durable Notes\n${underline}\nKeep this user-authored paragraph.\n\n` +
325+
promotionSection("2026-04-20", 400);
326+
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
327+
const result = compactMemoryForBudget({
328+
existingMemory: existing,
329+
newSection,
330+
budgetChars: 900,
331+
});
332+
expect(result.droppedDates).toContain("2026-04-10");
333+
expect(result.compacted).toContain(`My Durable Notes\n${underline}`);
334+
expect(result.compacted).toContain("Keep this user-authored paragraph.");
335+
},
336+
);
337+
171338
it("exposes a sane default budget below the bootstrap injection cap", () => {
172339
// Bootstrap injection is capped at 12_000 chars per file (see
173340
// src/agents/embedded-agent-helpers/bootstrap.ts). The MEMORY.md budget

‎extensions/memory-core/src/memory-budget.ts‎

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@
1616

1717
const PROMOTION_SECTION_HEADING_RE = /^## Promoted From Short-Term Memory \(([^)]+)\)\s*$/;
1818

19+
const PROMOTION_SUBSECTION_HEADING_RE = /^### (?:Global|Project: .+?)\s*$/;
20+
21+
const PROMOTION_ENTRY_MARKER_RE = /^<!--\s*openclaw-memory-promotion:.*-->\s*$/i;
22+
23+
const ATX_HEADING_RE = /^ {0,3}#{1,6}(?:[ \t]|$)/;
24+
25+
const SETEXT_HEADING_UNDERLINE_RE = /^ {0,3}(?:=+|-+)[ \t]*$/;
26+
1927
/**
2028
* Default budget for MEMORY.md content on disk, in characters. Chosen to
2129
* stay safely below the bootstrap injection cap (~12KB per file at the
@@ -38,6 +46,36 @@ type MemoryBlock =
3846
| { kind: "preserved"; text: string }
3947
| { kind: "promotion"; date: string; text: string };
4048

49+
function startsGeneratedPromotionSubsection(lines: string[], index: number): boolean {
50+
if (!PROMOTION_SUBSECTION_HEADING_RE.test(lines[index] ?? "")) {
51+
return false;
52+
}
53+
for (let next = index + 1; next < lines.length; next += 1) {
54+
const line = lines[next] ?? "";
55+
if (line.trim().length === 0) {
56+
continue;
57+
}
58+
return PROMOTION_ENTRY_MARKER_RE.test(line);
59+
}
60+
return false;
61+
}
62+
63+
function takeSetextHeadingLines(lines: string[]): string[] | undefined {
64+
let start = lines.length;
65+
while (start > 1 && lines[start - 1]?.trim().length !== 0) {
66+
start -= 1;
67+
}
68+
if (start === lines.length) {
69+
return undefined;
70+
}
71+
const headingLines = lines.slice(start);
72+
if (headingLines.some((line) => PROMOTION_ENTRY_MARKER_RE.test(line))) {
73+
return undefined;
74+
}
75+
lines.splice(start);
76+
return headingLines;
77+
}
78+
4179
function parseMemoryBlocks(content: string): MemoryBlock[] {
4280
if (content.length === 0) {
4381
return [];
@@ -63,8 +101,18 @@ function parseMemoryBlocks(content: string): MemoryBlock[] {
63101
currentDate = undefined;
64102
};
65103

66-
for (const line of lines) {
67-
if (line.startsWith("## ")) {
104+
for (const [index, line] of lines.entries()) {
105+
if (currentKind === "promotion" && SETEXT_HEADING_UNDERLINE_RE.test(line)) {
106+
const headingLines = takeSetextHeadingLines(currentLines);
107+
if (headingLines) {
108+
flush();
109+
currentLines = [...headingLines, line];
110+
continue;
111+
}
112+
}
113+
const continuesPromotionBody =
114+
currentKind === "promotion" && startsGeneratedPromotionSubsection(lines, index);
115+
if (ATX_HEADING_RE.test(line) && !continuesPromotionBody) {
68116
flush();
69117
const match = PROMOTION_SECTION_HEADING_RE.exec(line);
70118
if (match) {
@@ -104,7 +152,7 @@ type CompactMemoryResult = {
104152
*
105153
* Guarantees:
106154
* - Non-promotion content (user-authored markdown, the file header, any
107-
* `##` heading not matching the promotion pattern) is preserved.
155+
* heading of any level not matching the promotion pattern) is preserved.
108156
* - Promotion sections are dropped in ascending date order (oldest first).
109157
* - If `existingMemory + newSection` already fits the budget, the existing
110158
* memory is returned unchanged.

‎extensions/memory-core/src/short-term-promotion.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3712,6 +3712,76 @@ describe("short-term promotion", () => {
37123712
});
37133713

37143714
describe("MEMORY.md budget compaction (#73691)", () => {
3715+
it("preserves an indented user ATX heading when compaction writes MEMORY.md", async () => {
3716+
await withTempWorkspace(async (workspaceDir) => {
3717+
await writeDailyMemoryNote(workspaceDir, "2026-04-29", [
3718+
"Notes",
3719+
"",
3720+
"Rotate the staging Postgres credentials before next deploy.",
3721+
]);
3722+
3723+
const memoryPath = path.join(workspaceDir, "MEMORY.md");
3724+
const filler = "x".repeat(600);
3725+
const seeded = [
3726+
"# Long-Term Memory",
3727+
"",
3728+
"## Promoted From Short-Term Memory (2026-04-10)",
3729+
"<!-- openclaw-memory-promotion:legacy-old -->",
3730+
`- ${filler}`,
3731+
"",
3732+
" ### Correction (added by me)",
3733+
"The prod DB is db-2.corp.example, NOT db-1.",
3734+
"",
3735+
"## Promoted From Short-Term Memory (2026-04-20)",
3736+
"<!-- openclaw-memory-promotion:legacy-newer -->",
3737+
`- ${filler}`,
3738+
"",
3739+
].join("\n");
3740+
await fs.writeFile(memoryPath, seeded, "utf-8");
3741+
3742+
await recordShortTermRecalls({
3743+
workspaceDir,
3744+
query: "rotate creds",
3745+
nowMs: Date.parse("2026-04-29T10:00:00.000Z"),
3746+
results: [
3747+
{
3748+
path: "memory/2026-04-29.md",
3749+
startLine: 3,
3750+
endLine: 3,
3751+
score: 0.96,
3752+
snippet: "Rotate the staging Postgres credentials before next deploy.",
3753+
source: "memory",
3754+
},
3755+
],
3756+
});
3757+
3758+
const ranked = await rankShortTermPromotionCandidates({
3759+
workspaceDir,
3760+
minScore: 0,
3761+
minRecallCount: 0,
3762+
minUniqueQueries: 0,
3763+
});
3764+
3765+
const applied = await applyShortTermPromotions({
3766+
workspaceDir,
3767+
candidates: ranked,
3768+
minScore: 0,
3769+
minRecallCount: 0,
3770+
minUniqueQueries: 0,
3771+
nowMs: Date.parse("2026-04-29T10:00:00.000Z"),
3772+
memoryFileMaxChars: 1_400,
3773+
});
3774+
3775+
expect(applied.applied).toBe(1);
3776+
expect(applied.compactedDates).toContain("2026-04-10");
3777+
const memoryText = await fs.readFile(memoryPath, "utf-8");
3778+
expect(memoryText).not.toContain("legacy-old");
3779+
expect(memoryText).toContain(" ### Correction (added by me)");
3780+
expect(memoryText).toContain("The prod DB is db-2.corp.example, NOT db-1.");
3781+
expect(memoryText).toContain("Rotate the staging Postgres credentials");
3782+
});
3783+
});
3784+
37153785
it("drops the oldest promoted section before write when memoryFileMaxChars would be exceeded", async () => {
37163786
await withTempWorkspace(async (workspaceDir) => {
37173787
// Source daily note that the candidate references (rehydrate reads it).

0 commit comments

Comments
 (0)