Skip to content

Commit 0fdae63

Browse files
authored
fix(memory): forgotten facts survive in consolidation history (#131248)
* fix(memory): forgotten facts survive in consolidation history * refactor(memory): share purge planning and consolidation fixtures
1 parent 0a20dc9 commit 0fdae63

11 files changed

Lines changed: 294 additions & 217 deletions

‎docs/cli/memory.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ and remain selected.
156156
| `untargetableEntryKeys` | Promotion markers found without origin rows in this agent's store. This does not enumerate unmarked prose. |
157157
| `curatedWrites` | Files to review, with `relativePath` and `observedAt` (Unix milliseconds). Includes supported recorded write attempts, which may not have succeeded. |
158158
| `artifacts` | Counts of matching files, entries, lines, and store rows described below. |
159-
| `refusals` | Reserved report list; currently empty. An empty list does not establish complete deletion coverage. |
159+
| `refusals` | Historical consolidation highlights needing manual review. An empty list does not establish complete deletion coverage. |
160160

161161
Preview and apply use the same matching logic, but each reads current state;
162162
a preview is not an immutable plan or a lock on subsequent writes. Apply
@@ -188,7 +188,10 @@ backups, rather than deleting every backup.
188188

189189
Consolidation preserves origins for replaced promotion markers while retained
190190
rewrite preimages reference them. Those origins are pruned only after live
191-
entries, retained preimages, and indexed snapshots stop referencing the keys.
191+
entries, retained preimages, diary excerpts, and indexed snapshots stop referencing the keys.
192+
New consolidation-history excerpts carry the replacement entry's lineage and
193+
are removed with it. Their origins remain while the excerpts remain, even
194+
after backup rotation; diary history has no automatic expiry.
192195
In a shared workspace, a later purge for another agent also checks its indexed
193196
snapshots, even when the first purge already removed the shared file content.
194197

‎docs/concepts/memory-provenance.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,12 @@ share a workspace; the model does not own the origin rows.
8787

8888
Origins for replaced entries remain while retained rewrite preimages still
8989
reference their promotion markers. Backup rotation prunes those origins only
90-
when live entries, retained preimages, and indexed snapshots no longer reference them.
90+
when live entries, retained preimages, diary excerpts, and indexed snapshots no longer reference them.
91+
92+
New consolidation-history excerpts retain the replacement entry's lineage,
93+
including its merged or superseded parents. Their origin rows remain while
94+
those excerpts remain, even after backup rotation. Diary history has no
95+
automatic expiry; long revision histories can retain growing origin sets.
9196

9297
When backfill coalesces the same claim from several sessions, it retains every
9398
source origin without counting the repeated claim as extra evidence.
@@ -200,7 +205,11 @@ reason `forgotten`.
200205
The memory plugin coordinates purges with its staging and file mutations.
201206
A pending dream narrative is skipped if its tracked source entries or prior
202207
diary context were removed before publication. This does not retroactively
203-
identify untracked paraphrases in older diary entries.
208+
identify untracked paraphrases in older diary entries. Historical consolidation
209+
highlights with quoted markers also lack reliable deletion boundaries. The
210+
report warns in `refusals` when it recognizes remaining highlights in that
211+
format; review them manually. The warning is not an inventory of all untracked
212+
history, and missing historical lineage is not reconstructed.
204213

205214
Indexing checks again before publishing chunks or cached embeddings, so a
206215
result prepared before the purge cannot restore forgotten session data or a

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

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ export async function storeMemoryPreimage(params: {
5959
const retainedKeys = new Set(entries.flatMap(({ value }) => extractPromotionKeys(value.content)));
6060
// Rotation releases only expired backup references. The current preimage and
6161
// staged keys still protect live content if the following MEMORY write fails.
62-
pruneMemoryEntryOrigins({
62+
await pruneMemoryEntryOrigins({
63+
workspaceDir: params.workspaceDir,
6364
agentIds: params.agentIds,
6465
entryKeys: current.flatMap(({ value }) => extractPromotionKeys(value.content)),
6566
retainedEntryKeys: new Set([...retainedKeys, ...params.retainedEntryKeys]),
@@ -79,12 +80,7 @@ export async function appendConsolidationSummary(params: {
7980
`- Added: ${params.result.added}`,
8081
`- Merged: ${params.result.merged}`,
8182
`- Superseded: ${params.result.superseded}`,
82-
...(params.result.highlights.length > 0
83-
? [
84-
"- Highlights:",
85-
...params.result.highlights.map((line) => ` - \`${line.replaceAll("`", "'")}\``),
86-
]
87-
: []),
83+
...params.result.highlights,
8884
"",
8985
];
9086
await updateDreamsFile({

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

Lines changed: 55 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,32 @@ function createSubagent(output: string, status = "ok", onWait?: () => Promise<vo
7979
};
8080
}
8181

82+
async function recordConsolidationRecall(workspaceDir: string) {
83+
await recordShortTermRecalls({
84+
workspaceDir,
85+
query: "tea preference",
86+
results: [
87+
{
88+
path: "memory/2026-07-01.md",
89+
startLine: 1,
90+
endLine: 1,
91+
score: 0.9,
92+
snippet: "User prefers green tea.",
93+
source: "memory",
94+
provenance: candidate("agent").provenance,
95+
},
96+
],
97+
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
98+
});
99+
return rankShortTermPromotionCandidates({
100+
workspaceDir,
101+
minScore: 0,
102+
minRecallCount: 0,
103+
minUniqueQueries: 0,
104+
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
105+
});
106+
}
107+
82108
const logger = { info: vi.fn(), warn: vi.fn() };
83109

84110
describe("memory consolidation", () => {
@@ -164,6 +190,30 @@ describe("memory consolidation", () => {
164190
expect(subagent.deleteSession).toHaveBeenCalledTimes(2);
165191
});
166192

193+
it("keeps consolidation history bounded and attached to each operation's lineage", () => {
194+
const operations = Array.from({ length: 5 }, (_, index) => ({
195+
candidateKey: `revision-${index}`,
196+
action: "merged" as const,
197+
resultEntry: `- Result ${index} ${"🦞".repeat(110)}`,
198+
priorEntries: [`- Prior ${index} ${"🦞".repeat(110)}`],
199+
}));
200+
const existingMemory = operations.flatMap((operation) => operation.priorEntries).join("\n");
201+
const result = applyMemoryConsolidationPlan({
202+
existingMemory,
203+
plan: { memory: "", operations },
204+
nowMs: 1_000,
205+
maxPriorEntryLossFraction: 1,
206+
});
207+
expect(result).not.toBeNull();
208+
expect(result!.highlights).toHaveLength(8);
209+
for (const [index, highlight] of result!.highlights.entries()) {
210+
const [marker, entry] = highlight.split("\n");
211+
expect(marker).toBe(`<!-- openclaw-memory-promotion:revision-${Math.floor(index / 2)} -->`);
212+
expect(entry!.length).toBeLessThanOrEqual(184); // 180 excerpt characters plus the Markdown bullet/quotes.
213+
expect(entry).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/u);
214+
}
215+
});
216+
167217
it("rejects a rewrite that loses too many prior entries", async () => {
168218
const workspaceDir = await createTempWorkspace("memory-consolidation-reject-");
169219
const promoted = candidate("owner");
@@ -582,29 +632,7 @@ describe("memory consolidation", () => {
582632
const notePath = path.join(workspaceDir, "memory", "2026-07-01.md");
583633
await fs.mkdir(path.dirname(notePath), { recursive: true });
584634
await fs.writeFile(notePath, "User prefers green tea.\n", "utf8");
585-
await recordShortTermRecalls({
586-
workspaceDir,
587-
query: "tea preference",
588-
results: [
589-
{
590-
path: "memory/2026-07-01.md",
591-
startLine: 1,
592-
endLine: 1,
593-
score: 0.9,
594-
snippet: "User prefers green tea.",
595-
source: "memory",
596-
provenance: candidate("agent").provenance,
597-
},
598-
],
599-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
600-
});
601-
const candidates = await rankShortTermPromotionCandidates({
602-
workspaceDir,
603-
minScore: 0,
604-
minRecallCount: 0,
605-
minUniqueQueries: 0,
606-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
607-
});
635+
const candidates = await recordConsolidationRecall(workspaceDir);
608636
const subagent = createSubagent("", "error");
609637
const applied = await applyShortTermPromotions({
610638
workspaceDir,
@@ -629,29 +657,7 @@ describe("memory consolidation", () => {
629657
await fs.mkdir(path.dirname(notePath), { recursive: true });
630658
await fs.writeFile(notePath, "User prefers green tea.\n", "utf8");
631659
await fs.writeFile(memoryPath, "# Memory\n\n- Original fact.\n", "utf8");
632-
await recordShortTermRecalls({
633-
workspaceDir,
634-
query: "tea preference",
635-
results: [
636-
{
637-
path: "memory/2026-07-01.md",
638-
startLine: 1,
639-
endLine: 1,
640-
score: 0.9,
641-
snippet: "User prefers green tea.",
642-
source: "memory",
643-
provenance: candidate("agent").provenance,
644-
},
645-
],
646-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
647-
});
648-
const candidates = await rankShortTermPromotionCandidates({
649-
workspaceDir,
650-
minScore: 0,
651-
minRecallCount: 0,
652-
minUniqueQueries: 0,
653-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
654-
});
660+
const candidates = await recordConsolidationRecall(workspaceDir);
655661
const promoted = candidates[0];
656662
if (!promoted) {
657663
throw new Error("expected ranked candidate");
@@ -698,29 +704,7 @@ describe("memory consolidation", () => {
698704
await fs.mkdir(path.dirname(notePath), { recursive: true });
699705
await fs.writeFile(notePath, "User prefers green tea.\n", "utf8");
700706
await fs.writeFile(memoryPath, "# Memory\n\n- Original fact.\n", "utf8");
701-
await recordShortTermRecalls({
702-
workspaceDir,
703-
query: "tea preference",
704-
results: [
705-
{
706-
path: "memory/2026-07-01.md",
707-
startLine: 1,
708-
endLine: 1,
709-
score: 0.9,
710-
snippet: "User prefers green tea.",
711-
source: "memory",
712-
provenance: candidate("agent").provenance,
713-
},
714-
],
715-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
716-
});
717-
const candidates = await rankShortTermPromotionCandidates({
718-
workspaceDir,
719-
minScore: 0,
720-
minRecallCount: 0,
721-
minUniqueQueries: 0,
722-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
723-
});
707+
const candidates = await recordConsolidationRecall(workspaceDir);
724708
const promoted = candidates[0];
725709
if (!promoted) {
726710
throw new Error("expected ranked candidate");
@@ -765,29 +749,7 @@ describe("memory consolidation", () => {
765749
await fs.mkdir(path.dirname(notePath), { recursive: true });
766750
await fs.writeFile(notePath, "User prefers green tea.\n", "utf8");
767751
await fs.writeFile(memoryPath, "# Memory\n\n- Original fact.\n", "utf8");
768-
await recordShortTermRecalls({
769-
workspaceDir,
770-
query: "tea preference",
771-
results: [
772-
{
773-
path: "memory/2026-07-01.md",
774-
startLine: 1,
775-
endLine: 1,
776-
score: 0.9,
777-
snippet: "User prefers green tea.",
778-
source: "memory",
779-
provenance: candidate("agent").provenance,
780-
},
781-
],
782-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
783-
});
784-
const candidates = await rankShortTermPromotionCandidates({
785-
workspaceDir,
786-
minScore: 0,
787-
minRecallCount: 0,
788-
minUniqueQueries: 0,
789-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
790-
});
752+
const candidates = await recordConsolidationRecall(workspaceDir);
791753
const promoted = candidates[0];
792754
if (!promoted) {
793755
throw new Error("expected ranked candidate");
@@ -854,29 +816,7 @@ describe("memory consolidation", () => {
854816
const memoryPath = path.join(workspaceDir, "MEMORY.md");
855817
await fs.mkdir(path.dirname(notePath), { recursive: true });
856818
await fs.writeFile(notePath, "User prefers green tea.\n", "utf8");
857-
await recordShortTermRecalls({
858-
workspaceDir,
859-
query: "tea preference",
860-
results: [
861-
{
862-
path: "memory/2026-07-01.md",
863-
startLine: 1,
864-
endLine: 1,
865-
score: 0.9,
866-
snippet: "User prefers green tea.",
867-
source: "memory",
868-
provenance: candidate("agent").provenance,
869-
},
870-
],
871-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
872-
});
873-
const candidates = await rankShortTermPromotionCandidates({
874-
workspaceDir,
875-
minScore: 0,
876-
minRecallCount: 0,
877-
minUniqueQueries: 0,
878-
nowMs: Date.parse("2026-07-02T10:00:00.000Z"),
879-
});
819+
const candidates = await recordConsolidationRecall(workspaceDir);
880820
const promoted = candidates[0];
881821
if (!promoted) {
882822
throw new Error("expected ranked candidate");

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

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -369,30 +369,6 @@ function validateConsolidatedMemory(params: {
369369
return null;
370370
}
371371

372-
function diffHighlights(previous: string, next: string): string[] {
373-
const previousLines = new Set(
374-
previous
375-
.split(/\r?\n/)
376-
.map((line) => line.trim())
377-
.filter(Boolean),
378-
);
379-
const nextLines = new Set(
380-
next
381-
.split(/\r?\n/)
382-
.map((line) => line.trim())
383-
.filter(Boolean),
384-
);
385-
const highlights = [
386-
...[...nextLines]
387-
.filter((line) => !previousLines.has(line))
388-
.map((line) => `+ ${truncateUtf16Safe(line, 180)}`),
389-
...[...previousLines]
390-
.filter((line) => !nextLines.has(line))
391-
.map((line) => `- ${truncateUtf16Safe(line, 180)}`),
392-
];
393-
return highlights.slice(0, 8);
394-
}
395-
396372
export function applyMemoryConsolidationPlan(params: {
397373
existingMemory: string;
398374
plan: MemoryConsolidationPlan;
@@ -492,7 +468,15 @@ export function applyMemoryConsolidationPlan(params: {
492468
merged: params.plan.operations.filter((operation) => operation.action === "merged").length,
493469
superseded: params.plan.operations.filter((operation) => operation.action === "superseded")
494470
.length,
495-
highlights: diffHighlights(params.existingMemory, content),
471+
// Each excerpt uses its replacement's unioned origins so the ordinary scrubber can erase it.
472+
highlights: params.plan.operations
473+
.flatMap(({ candidateKey, resultEntry, priorEntries }) =>
474+
[`+ ${resultEntry}`, ...priorEntries.map((entry) => `- ${entry}`)].map(
475+
(line) =>
476+
`${buildPromotionMarker(candidateKey)}\n- \`${truncateUtf16Safe(line, 180).replaceAll("`", "'")}\``,
477+
),
478+
)
479+
.slice(0, 8),
496480
};
497481
}
498482

‎extensions/memory-core/src/dreaming-dreams-file.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { replaceManagedMarkdownBlock } from "openclaw/plugin-sdk/memory-host-mar
66
import { readRegularFile, replaceFileAtomic } from "openclaw/plugin-sdk/security-runtime";
77
import { withMemoryWorkspaceLock } from "./memory-workspace-lock.js";
88

9-
const DREAMS_FILENAMES = ["DREAMS.md", "dreams.md"] as const;
9+
export const DREAMS_FILENAMES = ["DREAMS.md", "dreams.md"] as const;
1010
const DEEP_START_MARKER = "<!-- openclaw:dreaming:deep:start -->";
1111
const DEEP_END_MARKER = "<!-- openclaw:dreaming:deep:end -->";
1212

0 commit comments

Comments
 (0)