Skip to content

Commit 79348f7

Browse files
mbelinkyvignesh07
andauthored
feat(memory-core): add REM preview and safe promotion replay (#61540)
* memory: add REM preview and safe promotion replay thanks @mbelinky * changelog: note REM preview and promotion replay --------- Co-authored-by: Vignesh <[email protected]>
1 parent cef64f0 commit 79348f7

8 files changed

Lines changed: 554 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ Docs: https://docs.openclaw.ai
1212

1313
- Memory/dreaming (experimental): add weighted short-term recall promotion, a `/dreaming` command, Dreams UI, multilingual conceptual tagging, and doctor/status repair support, while refactoring dreaming from competing modes into three cooperative phases (light, deep, REM) with independent schedules and recovery behavior so durable memory promotion can run in the background with less manual setup. (#60569, #60697) Thanks @vignesh07.
1414
- Memory/dreaming: add configurable aging controls (`recencyHalfLifeDays`, `maxAgeDays`) plus optional verbose logging so operators can tune recall decay and inspect promotion decisions more easily.
15+
- Memory/dreaming: add REM preview tooling (`openclaw memory rem-harness`, `promote-explain`), surface possible lasting truths during REM staging, and make deep promotion replay-safe so reruns reconcile instead of duplicating `MEMORY.md` entries.
1516
- Agents/video generation: add the built-in `video_generate` tool so agents can create videos through configured providers and return the generated media directly in the reply.
1617
- Control UI/multilingual: add localized control UI support for Simplified Chinese, Traditional Chinese, Brazilian Portuguese, German, Spanish, Japanese, Korean, French, Turkish, Indonesian, Polish, and Ukrainian. Thanks @vincentkoc.
1718
- iOS/exec approvals: add generic APNs approval notifications that open an in-app exec approval modal, fetch command details only after authenticated operator reconnect, and clear stale notification state when the approval resolves. (#60239) Thanks @ngutman.

‎extensions/memory-core/src/cli.runtime.ts‎

Lines changed: 238 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import fsSync from "node:fs";
22
import fs from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
5+
import { resolveMemoryRemDreamingConfig } from "openclaw/plugin-sdk/memory-core-host-status";
56
import { buildAgentSessionKey } from "openclaw/plugin-sdk/routing";
67
import {
78
colorize,
@@ -28,13 +29,17 @@ import {
2829
import type {
2930
MemoryCommandOptions,
3031
MemoryPromoteCommandOptions,
32+
MemoryPromoteExplainOptions,
33+
MemoryRemHarnessOptions,
3134
MemorySearchCommandOptions,
3235
} from "./cli.types.js";
36+
import { previewRemDreaming } from "./dreaming-phases.js";
3337
import { resolveShortTermPromotionDreamingConfig } from "./dreaming.js";
3438
import {
3539
applyShortTermPromotions,
3640
auditShortTermPromotionArtifacts,
3741
repairShortTermPromotionArtifacts,
42+
readShortTermRecallEntries,
3843
recordShortTermRecalls,
3944
rankShortTermPromotionCandidates,
4045
resolveShortTermRecallLockPath,
@@ -208,6 +213,26 @@ function formatExtraPaths(workspaceDir: string, extraPaths: string[]): string[]
208213
return normalizeExtraMemoryPaths(workspaceDir, extraPaths).map((entry) => shortenHomePath(entry));
209214
}
210215

216+
function matchesPromotionSelector(
217+
candidate: {
218+
key: string;
219+
path: string;
220+
snippet: string;
221+
},
222+
selector: string,
223+
): boolean {
224+
const trimmed = selector.trim().toLowerCase();
225+
if (!trimmed) {
226+
return false;
227+
}
228+
return (
229+
candidate.key.toLowerCase() === trimmed ||
230+
candidate.key.toLowerCase().includes(trimmed) ||
231+
candidate.path.toLowerCase().includes(trimmed) ||
232+
candidate.snippet.toLowerCase().includes(trimmed)
233+
);
234+
}
235+
211236
async function withMemoryManagerForAgent(params: {
212237
cfg: OpenClawConfig;
213238
agentId: string;
@@ -1000,6 +1025,8 @@ export async function runMemoryPromote(opts: MemoryPromoteCommandOptions) {
10001025
apply: applyResult
10011026
? {
10021027
applied: applyResult.applied,
1028+
appended: applyResult.appended,
1029+
reconciledExisting: applyResult.reconciledExisting,
10031030
memoryPath: applyResult.memoryPath,
10041031
appliedCandidates: applyResult.appliedCandidates,
10051032
}
@@ -1068,7 +1095,14 @@ export async function runMemoryPromote(opts: MemoryPromoteCommandOptions) {
10681095
colorize(
10691096
rich,
10701097
theme.success,
1071-
`Promoted ${applyResult.applied} candidate(s) to ${shortenHomePath(applyResult.memoryPath)}.`,
1098+
`Processed ${applyResult.applied} candidate(s) for ${shortenHomePath(applyResult.memoryPath)}.`,
1099+
),
1100+
);
1101+
lines.push(
1102+
colorize(
1103+
rich,
1104+
theme.muted,
1105+
`appended=${applyResult.appended} reconciledExisting=${applyResult.reconciledExisting}`,
10721106
),
10731107
);
10741108
} else {
@@ -1079,3 +1113,206 @@ export async function runMemoryPromote(opts: MemoryPromoteCommandOptions) {
10791113
},
10801114
});
10811115
}
1116+
1117+
export async function runMemoryPromoteExplain(
1118+
selectorArg: string | undefined,
1119+
opts: MemoryPromoteExplainOptions,
1120+
) {
1121+
const selector = selectorArg?.trim();
1122+
if (!selector) {
1123+
defaultRuntime.error("Memory promote-explain requires a non-empty selector.");
1124+
process.exitCode = 1;
1125+
return;
1126+
}
1127+
1128+
const { config: cfg, diagnostics } = await loadMemoryCommandConfig("memory promote-explain");
1129+
emitMemorySecretResolveDiagnostics(diagnostics, { json: Boolean(opts.json) });
1130+
const agentId = resolveAgent(cfg, opts.agent);
1131+
1132+
await withMemoryManagerForAgent({
1133+
cfg,
1134+
agentId,
1135+
purpose: "status",
1136+
run: async (manager) => {
1137+
const status = manager.status();
1138+
const workspaceDir = status.workspaceDir?.trim();
1139+
const dreaming = resolveShortTermPromotionDreamingConfig({
1140+
pluginConfig: resolveMemoryPluginConfig(cfg),
1141+
cfg,
1142+
});
1143+
if (!workspaceDir) {
1144+
defaultRuntime.error("Memory promote-explain requires a resolvable workspace directory.");
1145+
process.exitCode = 1;
1146+
return;
1147+
}
1148+
1149+
let candidates: Awaited<ReturnType<typeof rankShortTermPromotionCandidates>>;
1150+
try {
1151+
candidates = await rankShortTermPromotionCandidates({
1152+
workspaceDir,
1153+
minScore: 0,
1154+
minRecallCount: 0,
1155+
minUniqueQueries: 0,
1156+
includePromoted: Boolean(opts.includePromoted),
1157+
recencyHalfLifeDays: dreaming.recencyHalfLifeDays,
1158+
maxAgeDays: dreaming.maxAgeDays,
1159+
});
1160+
} catch (err) {
1161+
defaultRuntime.error(`Memory promote-explain failed: ${formatErrorMessage(err)}`);
1162+
process.exitCode = 1;
1163+
return;
1164+
}
1165+
1166+
const candidate = candidates.find((entry) => matchesPromotionSelector(entry, selector));
1167+
if (!candidate) {
1168+
defaultRuntime.error(`No promotion candidate matched "${selector}".`);
1169+
process.exitCode = 1;
1170+
return;
1171+
}
1172+
1173+
const thresholds = {
1174+
minScore: dreaming.minScore,
1175+
minRecallCount: dreaming.minRecallCount,
1176+
minUniqueQueries: dreaming.minUniqueQueries,
1177+
maxAgeDays: dreaming.maxAgeDays ?? null,
1178+
};
1179+
1180+
if (opts.json) {
1181+
defaultRuntime.writeJson({
1182+
workspaceDir,
1183+
thresholds,
1184+
candidate,
1185+
passes: {
1186+
score: candidate.score >= thresholds.minScore,
1187+
recallCount: candidate.recallCount >= thresholds.minRecallCount,
1188+
uniqueQueries: candidate.uniqueQueries >= thresholds.minUniqueQueries,
1189+
maxAge:
1190+
thresholds.maxAgeDays === null ? true : candidate.ageDays <= thresholds.maxAgeDays,
1191+
},
1192+
});
1193+
return;
1194+
}
1195+
1196+
const rich = isRich();
1197+
const lines = [
1198+
`${colorize(rich, theme.heading, "Promotion Explain")} ${colorize(rich, theme.muted, `(${agentId})`)}`,
1199+
`${colorize(rich, theme.accent, candidate.key)}`,
1200+
`${colorize(rich, theme.muted, `${shortenHomePath(candidate.path)}:${candidate.startLine}-${candidate.endLine}`)}`,
1201+
candidate.snippet,
1202+
colorize(
1203+
rich,
1204+
theme.muted,
1205+
`score=${candidate.score.toFixed(3)} recallCount=${candidate.recallCount} uniqueQueries=${candidate.uniqueQueries} ageDays=${candidate.ageDays.toFixed(1)}`,
1206+
),
1207+
colorize(
1208+
rich,
1209+
theme.muted,
1210+
`components: frequency=${candidate.components.frequency.toFixed(2)} relevance=${candidate.components.relevance.toFixed(2)} diversity=${candidate.components.diversity.toFixed(2)} recency=${candidate.components.recency.toFixed(2)} consolidation=${candidate.components.consolidation.toFixed(2)} conceptual=${candidate.components.conceptual.toFixed(2)}`,
1211+
),
1212+
colorize(
1213+
rich,
1214+
theme.muted,
1215+
`thresholds: minScore=${thresholds.minScore} minRecallCount=${thresholds.minRecallCount} minUniqueQueries=${thresholds.minUniqueQueries} maxAgeDays=${thresholds.maxAgeDays ?? "none"}`,
1216+
),
1217+
];
1218+
if (candidate.conceptTags.length > 0) {
1219+
lines.push(colorize(rich, theme.muted, `concepts=${candidate.conceptTags.join(", ")}`));
1220+
}
1221+
defaultRuntime.log(lines.join("\n"));
1222+
},
1223+
});
1224+
}
1225+
1226+
export async function runMemoryRemHarness(opts: MemoryRemHarnessOptions) {
1227+
const { config: cfg, diagnostics } = await loadMemoryCommandConfig("memory rem-harness");
1228+
emitMemorySecretResolveDiagnostics(diagnostics, { json: Boolean(opts.json) });
1229+
const agentId = resolveAgent(cfg, opts.agent);
1230+
1231+
await withMemoryManagerForAgent({
1232+
cfg,
1233+
agentId,
1234+
purpose: "status",
1235+
run: async (manager) => {
1236+
const status = manager.status();
1237+
const workspaceDir = status.workspaceDir?.trim();
1238+
const pluginConfig = resolveMemoryPluginConfig(cfg);
1239+
const deep = resolveShortTermPromotionDreamingConfig({
1240+
pluginConfig,
1241+
cfg,
1242+
});
1243+
if (!workspaceDir) {
1244+
defaultRuntime.error("Memory rem-harness requires a resolvable workspace directory.");
1245+
process.exitCode = 1;
1246+
return;
1247+
}
1248+
const remConfig = resolveMemoryRemDreamingConfig({
1249+
pluginConfig,
1250+
cfg,
1251+
});
1252+
const nowMs = Date.now();
1253+
const cutoffMs = nowMs - Math.max(0, remConfig.lookbackDays) * 24 * 60 * 60 * 1000;
1254+
const recallEntries = (await readShortTermRecallEntries({ workspaceDir, nowMs })).filter(
1255+
(entry) => Date.parse(entry.lastRecalledAt) >= cutoffMs,
1256+
);
1257+
const remPreview = previewRemDreaming({
1258+
entries: recallEntries,
1259+
limit: remConfig.limit,
1260+
minPatternStrength: remConfig.minPatternStrength,
1261+
});
1262+
const deepCandidates = await rankShortTermPromotionCandidates({
1263+
workspaceDir,
1264+
minScore: 0,
1265+
minRecallCount: 0,
1266+
minUniqueQueries: 0,
1267+
includePromoted: Boolean(opts.includePromoted),
1268+
recencyHalfLifeDays: deep.recencyHalfLifeDays,
1269+
maxAgeDays: deep.maxAgeDays,
1270+
});
1271+
1272+
if (opts.json) {
1273+
defaultRuntime.writeJson({
1274+
workspaceDir,
1275+
remConfig,
1276+
deepConfig: {
1277+
minScore: deep.minScore,
1278+
minRecallCount: deep.minRecallCount,
1279+
minUniqueQueries: deep.minUniqueQueries,
1280+
recencyHalfLifeDays: deep.recencyHalfLifeDays,
1281+
maxAgeDays: deep.maxAgeDays ?? null,
1282+
},
1283+
rem: remPreview,
1284+
deep: {
1285+
candidateCount: deepCandidates.length,
1286+
candidates: deepCandidates,
1287+
},
1288+
});
1289+
return;
1290+
}
1291+
1292+
const rich = isRich();
1293+
const lines = [
1294+
`${colorize(rich, theme.heading, "REM Harness")} ${colorize(rich, theme.muted, `(${agentId})`)}`,
1295+
colorize(rich, theme.muted, `workspace=${shortenHomePath(workspaceDir)}`),
1296+
colorize(
1297+
rich,
1298+
theme.muted,
1299+
`recentRecallEntries=${recallEntries.length} deepCandidates=${deepCandidates.length}`,
1300+
),
1301+
"",
1302+
colorize(rich, theme.heading, "REM Preview"),
1303+
...remPreview.bodyLines,
1304+
"",
1305+
colorize(rich, theme.heading, "Deep Candidates"),
1306+
...(deepCandidates.length > 0
1307+
? deepCandidates
1308+
.slice(0, 10)
1309+
.map(
1310+
(candidate) =>
1311+
`${candidate.score.toFixed(3)} ${candidate.snippet} [${shortenHomePath(candidate.path)}:${candidate.startLine}-${candidate.endLine}]`,
1312+
)
1313+
: ["- No deep candidates."]),
1314+
];
1315+
defaultRuntime.log(lines.join("\n"));
1316+
},
1317+
});
1318+
}

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

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,12 @@ describe("memory cli", () => {
295295
expect(helpText).toContain("Limit results for focused troubleshooting.");
296296
expect(helpText).toContain("openclaw memory promote --apply");
297297
expect(helpText).toContain("Append top-ranked short-term candidates into MEMORY.md.");
298+
expect(helpText).toContain('openclaw memory promote-explain "router vlan"');
299+
expect(helpText).toContain("Explain why a specific candidate would or would not promote.");
300+
expect(helpText).toContain("openclaw memory rem-harness --json");
301+
expect(helpText).toContain(
302+
"Preview REM reflections, candidate truths, and deep promotion output.",
303+
);
298304
});
299305

300306
it("prints vector error when unavailable", async () => {
@@ -881,6 +887,75 @@ describe("memory cli", () => {
881887
});
882888
});
883889

890+
it("explains a specific promote candidate as json", async () => {
891+
await withTempWorkspace(async (workspaceDir) => {
892+
await recordShortTermRecalls({
893+
workspaceDir,
894+
query: "router notes",
895+
results: [
896+
{
897+
path: "memory/2026-04-03.md",
898+
startLine: 4,
899+
endLine: 8,
900+
score: 0.86,
901+
snippet: "Configured VLAN 10 for IoT on router",
902+
source: "memory",
903+
},
904+
],
905+
});
906+
907+
const close = vi.fn(async () => {});
908+
mockManager({
909+
status: () => makeMemoryStatus({ workspaceDir }),
910+
close,
911+
});
912+
913+
const writeJson = spyRuntimeJson(defaultRuntime);
914+
await runMemoryCli(["promote-explain", "router", "--json", "--include-promoted"]);
915+
916+
const payload = firstWrittenJsonArg<{ candidate?: { snippet?: string } }>(writeJson);
917+
expect(payload?.candidate?.snippet).toContain("Configured VLAN 10");
918+
expect(close).toHaveBeenCalled();
919+
});
920+
});
921+
922+
it("previews rem harness output as json", async () => {
923+
await withTempWorkspace(async (workspaceDir) => {
924+
await recordShortTermRecalls({
925+
workspaceDir,
926+
query: "weather plans",
927+
nowMs: Date.parse("2026-04-03T10:00:00.000Z"),
928+
results: [
929+
{
930+
path: "memory/2026-04-03.md",
931+
startLine: 2,
932+
endLine: 3,
933+
score: 0.92,
934+
snippet: "Always check weather before suggesting outdoor plans.",
935+
source: "memory",
936+
},
937+
],
938+
});
939+
940+
const close = vi.fn(async () => {});
941+
mockManager({
942+
status: () => makeMemoryStatus({ workspaceDir }),
943+
close,
944+
});
945+
946+
const writeJson = spyRuntimeJson(defaultRuntime);
947+
await runMemoryCli(["rem-harness", "--json"]);
948+
949+
const payload = firstWrittenJsonArg<{
950+
rem?: { candidateTruths?: Array<{ snippet?: string }> };
951+
deep?: { candidates?: Array<{ snippet?: string }> };
952+
}>(writeJson);
953+
expect(payload?.rem?.candidateTruths?.[0]?.snippet).toContain("Always check weather");
954+
expect(payload?.deep?.candidates?.[0]?.snippet).toContain("Always check weather");
955+
expect(close).toHaveBeenCalled();
956+
});
957+
});
958+
884959
it("applies top promote candidates into MEMORY.md", async () => {
885960
await withTempWorkspace(async (workspaceDir) => {
886961
await writeDailyMemoryNote(workspaceDir, "2026-04-01", [
@@ -935,8 +1010,10 @@ describe("memory cli", () => {
9351010
const memoryPath = path.join(workspaceDir, "MEMORY.md");
9361011
const memoryText = await fs.readFile(memoryPath, "utf-8");
9371012
expect(memoryText).toContain("Promoted From Short-Term Memory");
1013+
expect(memoryText).toContain("openclaw-memory-promotion:");
9381014
expect(memoryText).toContain("memory/2026-04-01.md:10-10");
939-
expect(log).toHaveBeenCalledWith(expect.stringContaining("Promoted 1 candidate(s) to"));
1015+
expect(log).toHaveBeenCalledWith(expect.stringContaining("Processed 1 candidate(s) for"));
1016+
expect(log).toHaveBeenCalledWith(expect.stringContaining("appended=1 reconciledExisting=0"));
9401017
expect(close).toHaveBeenCalled();
9411018
});
9421019
});

0 commit comments

Comments
 (0)