Skip to content

Commit 0317d7e

Browse files
yetvalsteipete
andauthored
fix(memory-core): write MEMORY.md atomically during short-term promotion (#108397)
* fix(memory-core): write MEMORY.md atomically during short-term promotion applyShortTermPromotions rewrote MEMORY.md with a single non-atomic fs.writeFile, which truncates the file before streaming the new content. An OS write failure part way through (for example EFBIG on a size-limited or full volume) left MEMORY.md truncated to the bytes written before the failure, permanently dropping user long-term memory. The dreaming cron path invokes this writer automatically, and the recall store is only updated after the write, so the promotion stays eligible and the next run reads the already-truncated file. Route the write through replaceFileAtomic (temp file, fsync, atomic rename), the same durable-write helper the sibling DREAMS.md writer in this extension already uses. On failure the temp file is discarded and the existing MEMORY.md is left untouched; on success the content and the existing file mode are preserved. * fix(memory-core): harden atomic promotion durability --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 1ae1295 commit 0317d7e

2 files changed

Lines changed: 111 additions & 5 deletions

File tree

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

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3284,6 +3284,10 @@ describe("short-term promotion", () => {
32843284
const memoryPath = path.join(workspaceDir, "MEMORY.md");
32853285
const seeded = "# Long-Term Memory\n\nSome small existing content.\n";
32863286
await fs.writeFile(memoryPath, seeded, "utf-8");
3287+
if (process.platform !== "win32") {
3288+
await fs.chmod(workspaceDir, 0o750);
3289+
await fs.chmod(memoryPath, 0o640);
3290+
}
32873291

32883292
await recordShortTermRecalls({
32893293
workspaceDir,
@@ -3321,9 +3325,103 @@ describe("short-term promotion", () => {
33213325
expect(applied.compactedDates).toEqual([]);
33223326
const memoryText = await fs.readFile(memoryPath, "utf-8");
33233327
expect(memoryText).toContain("Some small existing content.");
3328+
if (process.platform !== "win32") {
3329+
expect((await fs.stat(workspaceDir)).mode & 0o7777).toBe(0o750);
3330+
expect((await fs.stat(memoryPath)).mode & 0o7777).toBe(0o640);
3331+
}
33243332
});
33253333
});
33263334
});
3335+
3336+
describe("MEMORY.md atomic promotion write", () => {
3337+
it("preserves the existing MEMORY.md when the promotion write fails mid-flight", async () => {
3338+
await withTempWorkspace(async (workspaceDir) => {
3339+
await writeDailyMemoryNote(workspaceDir, "2026-04-29", [
3340+
"Notes",
3341+
"",
3342+
"Rotate the staging Postgres credentials before next deploy.",
3343+
]);
3344+
3345+
const memoryPath = path.join(workspaceDir, "MEMORY.md");
3346+
const sentinel = "FINAL-USER-MEMORY-SENTINEL-do-not-lose";
3347+
const filler = "pad line filler content ".repeat(9_000);
3348+
const seeded = `# Long-Term Memory\n\n${filler}\n- ${sentinel}\n`;
3349+
await fs.writeFile(memoryPath, seeded, "utf-8");
3350+
3351+
await recordShortTermRecalls({
3352+
workspaceDir,
3353+
query: "rotate creds",
3354+
nowMs: Date.parse("2026-04-29T10:00:00.000Z"),
3355+
results: [
3356+
{
3357+
path: "memory/2026-04-29.md",
3358+
startLine: 3,
3359+
endLine: 3,
3360+
score: 0.96,
3361+
snippet: "Rotate the staging Postgres credentials before next deploy.",
3362+
source: "memory",
3363+
},
3364+
],
3365+
});
3366+
3367+
const ranked = await rankShortTermPromotionCandidates({
3368+
workspaceDir,
3369+
minScore: 0,
3370+
minRecallCount: 0,
3371+
minUniqueQueries: 0,
3372+
});
3373+
3374+
const truncateAt = 51_200;
3375+
const originalWriteFile = fs.writeFile.bind(fs);
3376+
vi.spyOn(fs, "writeFile").mockImplementation((async (
3377+
target: Parameters<typeof fs.writeFile>[0],
3378+
data: Parameters<typeof fs.writeFile>[1],
3379+
options?: Parameters<typeof fs.writeFile>[2],
3380+
) => {
3381+
const targetPath =
3382+
typeof target === "string" ? target : target instanceof URL ? target.pathname : "";
3383+
if (targetPath && path.basename(targetPath).startsWith("MEMORY.md")) {
3384+
const text =
3385+
typeof data === "string" ? data : Buffer.from(data as Uint8Array).toString();
3386+
await originalWriteFile(target, text.slice(0, truncateAt), options);
3387+
throw Object.assign(new Error("EFBIG: file too large, write"), {
3388+
code: "EFBIG",
3389+
});
3390+
}
3391+
return originalWriteFile(target, data, options);
3392+
}) as typeof fs.writeFile);
3393+
3394+
await expect(
3395+
applyShortTermPromotions({
3396+
workspaceDir,
3397+
candidates: ranked,
3398+
minScore: 0,
3399+
minRecallCount: 0,
3400+
minUniqueQueries: 0,
3401+
nowMs: Date.parse("2026-04-29T10:00:00.000Z"),
3402+
memoryFileMaxChars: 5_000_000,
3403+
}),
3404+
).rejects.toMatchObject({ code: "EFBIG" });
3405+
3406+
const after = await fs.readFile(memoryPath, "utf-8");
3407+
expect(after).toBe(seeded);
3408+
await expect(
3409+
rankShortTermPromotionCandidates({
3410+
workspaceDir,
3411+
minScore: 0,
3412+
minRecallCount: 0,
3413+
minUniqueQueries: 0,
3414+
}),
3415+
).resolves.toHaveLength(1);
3416+
expect(
3417+
(await fs.readdir(workspaceDir)).filter((entry) =>
3418+
entry.startsWith("MEMORY.md.promotion"),
3419+
),
3420+
).toEqual([]);
3421+
});
3422+
});
3423+
});
3424+
33273425
it("shows signalCount instead of just recallCount in promotion annotations", async () => {
33283426
await withTempWorkspace(async (workspaceDir) => {
33293427
const nowMs = Date.parse("2026-05-28T10:00:00.000Z");

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

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "openclaw/plugin-sdk/memory-core-host-status";
1313
import { appendMemoryHostEvent } from "openclaw/plugin-sdk/memory-host-events";
1414
import { sleep } from "openclaw/plugin-sdk/runtime-env";
15+
import { replaceFileAtomic } from "openclaw/plugin-sdk/security-runtime";
1516
import {
1617
normalizeLowercaseStringOrEmpty,
1718
normalizeStringEntries,
@@ -2530,11 +2531,18 @@ export async function applyShortTermPromotions(
25302531
compactedDates = compaction.droppedDates;
25312532
const baseMemory = compaction.compacted;
25322533
const header = baseMemory.trim().length > 0 ? "" : "# Long-Term Memory\n\n";
2533-
await fs.writeFile(
2534-
memoryPath,
2535-
`${header}${withTrailingNewline(baseMemory)}${section}`,
2536-
"utf-8",
2537-
);
2534+
const workspaceMode = (await fs.stat(workspaceDir)).mode & 0o7777;
2535+
await replaceFileAtomic({
2536+
filePath: memoryPath,
2537+
content: `${header}${withTrailingNewline(baseMemory)}${section}`,
2538+
dirMode: workspaceMode,
2539+
mode: 0o600,
2540+
preserveExistingMode: true,
2541+
tempPrefix: `${path.basename(memoryPath)}.promotion`,
2542+
syncTempFile: true,
2543+
syncParentDir: true,
2544+
throwOnCleanupError: true,
2545+
});
25382546
}
25392547

25402548
for (const candidate of rehydratedSelected) {

0 commit comments

Comments
 (0)