Skip to content

Commit e3b435d

Browse files
vincentkocyetval
andcommitted
fix(memory-core): preserve mixed promotion blocks
Validate the complete marker-and-entry grammar before treating a promotion-shaped block as writer-owned. Preserve marker-only and mixed blocks so unheaded operator notes cannot be deleted during budget compaction. Co-authored-by: yetval <[email protected]>
1 parent 8a3521b commit e3b435d

3 files changed

Lines changed: 167 additions & 37 deletions

File tree

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

Lines changed: 61 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,11 @@ const PROMOTION_MARKER_LINE = "<!-- openclaw-memory-promotion:memory/short-term.
77
function promotionSection(date: string, sizeChars: number): string {
88
const heading = `## Promoted From Short-Term Memory (${date})\n`;
99
const marker = `${PROMOTION_MARKER_LINE}\n`;
10-
const padding = "x".repeat(Math.max(0, sizeChars - heading.length - marker.length));
11-
return `${heading}${marker}${padding}`;
10+
const entryPrefix = "- ";
11+
const padding = "x".repeat(
12+
Math.max(0, sizeChars - heading.length - marker.length - entryPrefix.length),
13+
);
14+
return `${heading}${marker}${entryPrefix}${padding}`;
1215
}
1316

1417
function markerFreeSection(date: string, body: string): string {
@@ -214,20 +217,20 @@ describe("compactMemoryForBudget — bounded MEMORY.md compaction (regression fo
214217
},
215218
);
216219

217-
it("does not treat a four-space-indented hash line as an ATX heading", () => {
220+
it("preserves a generated-looking block with ambiguous indented content", () => {
218221
const existing =
219222
`${promotionSection("2026-04-10", 400)}\n` +
220-
" ### Indented code\n keep this inside the generated block\n\n" +
223+
" ### Indented user note\n keep this durable content\n\n" +
221224
promotionSection("2026-04-20", 400);
222225
const newSection = `\n${promotionSection("2026-04-29", 400)}`;
223226
const result = compactMemoryForBudget({
224227
existingMemory: existing,
225228
newSection,
226229
budgetChars: 900,
227230
});
228-
expect(result.droppedDates).toContain("2026-04-10");
229-
expect(result.compacted).not.toContain("### Indented code");
230-
expect(result.compacted).not.toContain("keep this inside the generated block");
231+
expect(result.droppedDates).not.toContain("2026-04-10");
232+
expect(result.compacted).toContain("### Indented user note");
233+
expect(result.compacted).toContain("keep this durable content");
231234
});
232235

233236
it("preserves a user `#` section written after the only promotion section", () => {
@@ -342,7 +345,7 @@ describe("compactMemoryForBudget — bounded MEMORY.md compaction (regression fo
342345
},
343346
);
344347

345-
it("preserves a marker-free section whose heading matches the generated promotion pattern", () => {
348+
it("preserves a marker-free section whose heading matches the promotion pattern", () => {
346349
const existing = `# Long-Term Memory\n\n${markerFreeSection(
347350
"2026-04-10",
348351
"USER-AUTHORED: recovery key is paper-copy-17",
@@ -355,42 +358,75 @@ describe("compactMemoryForBudget — bounded MEMORY.md compaction (regression fo
355358
});
356359
expect(result.droppedDates).toEqual([]);
357360
expect(result.compacted).toBe(existing);
358-
expect(result.compacted).toContain("USER-AUTHORED: recovery key is paper-copy-17");
359361
});
360362

361-
it("drops only the marker-backed section when a marker-free lookalike sits beside it", () => {
363+
it("drops only a clean generated section beside a marker-free lookalike", () => {
362364
const userSection = markerFreeSection(
363365
"2026-04-10",
364366
"USER-AUTHORED: recovery key is paper-copy-17",
365367
);
366368
const existing = `# Long-Term Memory\n\n${userSection}\n${promotionSection("2026-04-20", 600)}`;
367-
const newSection = `\n${promotionSection("2026-04-29", 600)}`;
368369
const result = compactMemoryForBudget({
369370
existingMemory: existing,
370-
newSection,
371+
newSection: `\n${promotionSection("2026-04-29", 600)}`,
371372
budgetChars: 700,
372373
});
373374
expect(result.droppedDates).toEqual(["2026-04-20"]);
374-
expect(result.compacted).not.toContain("(2026-04-20)");
375-
expect(result.compacted).toContain("## Promoted From Short-Term Memory (2026-04-10)");
376375
expect(result.compacted).toContain("USER-AUTHORED: recovery key is paper-copy-17");
376+
expect(result.compacted).not.toContain("(2026-04-20)");
377377
});
378378

379-
it("still drops a marker-backed multi-project section that a user heading follows", () => {
380-
const existing =
381-
`${projectGroupedSection("2026-04-10")}\n` +
382-
"### Global\n\nMy own global rule, not a promoted entry.\n\n" +
383-
projectGroupedSection("2026-04-20");
384-
const newSection = `\n${projectGroupedSection("2026-04-29")}`;
379+
it("preserves a marker-only promotion-shaped block", () => {
380+
const existing = [
381+
"## Promoted From Short-Term Memory (2026-04-10)",
382+
PROMOTION_MARKER_LINE,
383+
"",
384+
].join("\n");
385385
const result = compactMemoryForBudget({
386386
existingMemory: existing,
387-
newSection,
387+
newSection: `\n${promotionSection("2026-04-29", 600)}`,
388+
budgetChars: 400,
389+
});
390+
expect(result.droppedDates).toEqual([]);
391+
expect(result.compacted).toBe(existing);
392+
});
393+
394+
it("preserves an entire mixed block when user text follows a generated entry", () => {
395+
const existing = [
396+
promotionSection("2026-04-10", 400),
397+
"",
398+
"USER-AUTHORED: keep this unheaded durable note.",
399+
"",
400+
promotionSection("2026-04-20", 400),
401+
].join("\n");
402+
const result = compactMemoryForBudget({
403+
existingMemory: existing,
404+
newSection: `\n${promotionSection("2026-04-29", 400)}`,
388405
budgetChars: 900,
389406
});
390-
expect(result.droppedDates).toContain("2026-04-10");
391-
expect(result.compacted).not.toContain("### Project: alpha");
392-
expect(result.compacted).toContain("### Global");
393-
expect(result.compacted).toContain("My own global rule, not a promoted entry.");
407+
expect(result.droppedDates).toEqual(["2026-04-20"]);
408+
expect(result.compacted).toContain("(2026-04-10)");
409+
expect(result.compacted).toContain("USER-AUTHORED: keep this unheaded durable note.");
410+
expect(result.compacted).not.toContain("(2026-04-20)");
411+
});
412+
413+
it("preserves a block with user text between generated entries", () => {
414+
const existing = [
415+
"## Promoted From Short-Term Memory (2026-04-10)",
416+
PROMOTION_MARKER_LINE,
417+
"- first generated entry",
418+
"USER-AUTHORED: this line is not owned by either marker.",
419+
"<!-- openclaw-memory-promotion:memory/short-term.md#second -->",
420+
"- second generated entry",
421+
"",
422+
].join("\n");
423+
const result = compactMemoryForBudget({
424+
existingMemory: existing,
425+
newSection: `\n${promotionSection("2026-04-29", 600)}`,
426+
budgetChars: 400,
427+
});
428+
expect(result.droppedDates).toEqual([]);
429+
expect(result.compacted).toBe(existing);
394430
});
395431

396432
it("exposes a sane default budget below the bootstrap injection cap", () => {

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

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,9 @@
99
*
1010
* Strategy: drop the OLDEST auto-promoted sections (date-ordered) until
1111
* the file plus the new section fit within the budget. A section counts as
12-
* dreaming-owned only when a `## Promoted From Short-Term Memory (DATE)`
13-
* heading is backed by at least one authoritative
14-
* `<!-- openclaw-memory-promotion:... -->` marker, which every generated
15-
* section carries (see `buildPromotionSection`). Everything else, including
16-
* user-authored content under a heading that merely looks generated, is
17-
* preserved unconditionally.
12+
* dreaming-owned only when its complete body matches the marker + entry
13+
* structure emitted by `buildPromotionSection`. Ambiguous or mixed content
14+
* is preserved unconditionally.
1815
*/
1916

2017
const PROMOTION_SECTION_HEADING_RE = /^## Promoted From Short-Term Memory \(([^)]+)\)\s*$/;
@@ -49,8 +46,37 @@ type MemoryBlock =
4946
| { kind: "preserved"; text: string }
5047
| { kind: "promotion"; date: string; text: string };
5148

52-
function hasPromotionEntryMarker(lines: string[]): boolean {
53-
return lines.some((line) => PROMOTION_ENTRY_MARKER_RE.test(line));
49+
function isGeneratedPromotionBlock(lines: string[]): boolean {
50+
let sawEntry = false;
51+
let index = 1;
52+
53+
while (index < lines.length) {
54+
const line = lines[index] ?? "";
55+
if (line.trim().length === 0) {
56+
index += 1;
57+
continue;
58+
}
59+
60+
if (PROMOTION_SUBSECTION_HEADING_RE.test(line)) {
61+
index += 1;
62+
while (index < lines.length && (lines[index] ?? "").trim().length === 0) {
63+
index += 1;
64+
}
65+
}
66+
67+
if (!PROMOTION_ENTRY_MARKER_RE.test(lines[index] ?? "")) {
68+
return false;
69+
}
70+
// A marker owns only the single bullet emitted with it. Treat any other
71+
// body shape as mixed user content so compaction cannot delete it.
72+
if (!(lines[index + 1] ?? "").startsWith("- ")) {
73+
return false;
74+
}
75+
sawEntry = true;
76+
index += 2;
77+
}
78+
79+
return sawEntry;
5480
}
5581

5682
function startsGeneratedPromotionSubsection(lines: string[], index: number): boolean {
@@ -76,7 +102,7 @@ function takeSetextHeadingLines(lines: string[]): string[] | undefined {
76102
return undefined;
77103
}
78104
const headingLines = lines.slice(start);
79-
if (hasPromotionEntryMarker(headingLines)) {
105+
if (headingLines.some((line) => PROMOTION_ENTRY_MARKER_RE.test(line))) {
80106
return undefined;
81107
}
82108
lines.splice(start);
@@ -98,7 +124,7 @@ function parseMemoryBlocks(content: string): MemoryBlock[] {
98124
return;
99125
}
100126
const text = currentLines.join("\n");
101-
if (currentKind === "promotion" && currentDate && hasPromotionEntryMarker(currentLines)) {
127+
if (currentKind === "promotion" && currentDate && isGeneratedPromotionBlock(currentLines)) {
102128
blocks.push({ kind: "promotion", date: currentDate, text });
103129
} else {
104130
blocks.push({ kind: "preserved", text });
@@ -159,8 +185,8 @@ type CompactMemoryResult = {
159185
*
160186
* Guarantees:
161187
* - Non-promotion content (user-authored markdown, the file header, any
162-
* heading of any level not matching the promotion pattern, and any
163-
* matching heading whose section carries no promotion marker) is preserved.
188+
* heading of any level not matching the promotion pattern, and any mixed
189+
* or malformed promotion-shaped block) is preserved.
164190
* - Promotion sections are dropped in ascending date order (oldest first).
165191
* - If `existingMemory + newSection` already fits the budget, the existing
166192
* memory is returned unchanged.

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

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

37143714
describe("MEMORY.md budget compaction (#73691)", () => {
3715+
it("preserves mixed marker-backed user text during a real promotion write", 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-mixed -->",
3730+
`- ${filler}`,
3731+
"",
3732+
"USER-AUTHORED: recovery key is paper-copy-17",
3733+
"",
3734+
"## Promoted From Short-Term Memory (2026-04-20)",
3735+
"<!-- openclaw-memory-promotion:legacy-generated -->",
3736+
`- ${filler}`,
3737+
"",
3738+
].join("\n");
3739+
await fs.writeFile(memoryPath, seeded, "utf-8");
3740+
3741+
await recordShortTermRecalls({
3742+
workspaceDir,
3743+
query: "rotate creds",
3744+
nowMs: Date.parse("2026-04-29T10:00:00.000Z"),
3745+
results: [
3746+
{
3747+
path: "memory/2026-04-29.md",
3748+
startLine: 3,
3749+
endLine: 3,
3750+
score: 0.96,
3751+
snippet: "Rotate the staging Postgres credentials before next deploy.",
3752+
source: "memory",
3753+
},
3754+
],
3755+
});
3756+
3757+
const ranked = await rankShortTermPromotionCandidates({
3758+
workspaceDir,
3759+
minScore: 0,
3760+
minRecallCount: 0,
3761+
minUniqueQueries: 0,
3762+
});
3763+
const applied = await applyShortTermPromotions({
3764+
workspaceDir,
3765+
candidates: ranked,
3766+
minScore: 0,
3767+
minRecallCount: 0,
3768+
minUniqueQueries: 0,
3769+
nowMs: Date.parse("2026-04-29T10:00:00.000Z"),
3770+
memoryFileMaxChars: 1_400,
3771+
});
3772+
3773+
expect(applied.applied).toBe(1);
3774+
expect(applied.compactedDates).toEqual(["2026-04-20"]);
3775+
const memoryText = await fs.readFile(memoryPath, "utf-8");
3776+
expect(memoryText).toContain("legacy-mixed");
3777+
expect(memoryText).toContain("USER-AUTHORED: recovery key is paper-copy-17");
3778+
expect(memoryText).not.toContain("legacy-generated");
3779+
expect(memoryText).toContain("Rotate the staging Postgres credentials");
3780+
});
3781+
});
3782+
37153783
it("preserves an indented user ATX heading when compaction writes MEMORY.md", async () => {
37163784
await withTempWorkspace(async (workspaceDir) => {
37173785
await writeDailyMemoryNote(workspaceDir, "2026-04-29", [

0 commit comments

Comments
 (0)