Skip to content

Commit f0bf74b

Browse files
authored
feat(memory): backfill retained session transcripts (#115162)
* feat(memory): enumerate retained session transcripts * feat(memory): add session transcript backfill * test(memory): cover session backfill workflows * docs(memory): document session transcript backfill * fix(memory): preserve oldest session backfill ordering * fix(memory): harden session archive backfill * test(memory): prove owner-turn provenance gating * fix(memory): persist session backfill progress * fix(memory): preserve ranged backfill progress * fix(memory): order per-file backfill candidates * fix(memory): retain paged backfill diary entries * fix(memory): preserve rem backfill diary history * fix(memory): adapt backfill to retained session identity * fix(memory): keep rem backfill preview-only * fix(memory): satisfy backfill CI guards
1 parent 4fb3355 commit f0bf74b

17 files changed

Lines changed: 1569 additions & 18 deletions

‎docs/cli/memory.md‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
summary: "CLI reference for `openclaw memory` (status/index/search/promote/promote-explain/rem-harness/rem-backfill)"
2+
summary: "CLI reference for `openclaw memory` (status/index/search/promote/promote-explain/rem-harness/rem-backfill/session-backfill)"
33
read_when:
44
- You want to index or search semantic memory
55
- You're debugging memory availability or indexing
@@ -139,6 +139,50 @@ openclaw memory rem-backfill --rollback [--rollback-short-term] [--json]
139139
- `--rollback-short-term`: remove previously staged grounded short-term
140140
candidates.
141141

142+
## `memory session-backfill`
143+
144+
Distill retained session history through the same provenance and short-term
145+
staging pipeline used by dreaming. The default is a read-only preview, ordered
146+
from the oldest unprocessed day to the newest.
147+
148+
```bash
149+
openclaw memory session-backfill --agent <id> [--from YYYY-MM-DD] [--to YYYY-MM-DD] \
150+
[--limit-days <n>] [--archive-files <path...>] [--rem | --apply] [--json]
151+
openclaw memory session-backfill --agent <id> --rollback [--json]
152+
```
153+
154+
| Flag | Default | Effect |
155+
| --------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------- |
156+
| `--from YYYY-MM-DD` | | Include messages on or after this day in the dreaming timezone. |
157+
| `--to YYYY-MM-DD` | | Include messages on or before this day in the dreaming timezone. |
158+
| `--limit-days <n>` | `92` | Process at most this many hash-untracked days, oldest first. |
159+
| `--archive-files <path...>` | | Also inspect foreign transcript files as untrusted input; embedded owner metadata is not accepted. |
160+
| `--rem` | | Write deterministic grounded per-day previews to `DREAMS.md` only. |
161+
| `--apply` | preview only | Stage trusted candidates and write reversible `DREAMS.md` diary blocks. |
162+
| `--rollback` | | Remove all grounded backfill candidates and shared backfill diary blocks, including `rem-backfill` artifacts. |
163+
| `--json` | | Print machine-readable per-day counts and top candidates. |
164+
165+
The command reads the selected agent's canonical session store, including
166+
retained SQLite transcript identities from session rotation. It uses the same
167+
tracked message hashes and per-run caps as live session ingestion, so repeated
168+
`--apply` runs skip already ingested messages. Owner and agent lines from the
169+
canonical store are eligible; tool output, web or non-owner input, and turns
170+
without trustworthy owner provenance are excluded. Foreign archive files have
171+
no authenticated owner-provenance contract, so their embedded ownership fields
172+
remain untrusted and cannot be staged.
173+
174+
`--apply` writes only the session corpus under `memory/.dreams/`, short-term
175+
staging state, and reversible diary entries in `DREAMS.md`. It never writes
176+
`MEMORY.md` or `USER.md`; durable promotion remains a separate `memory promote`
177+
or dreaming decision. `--rem` and `--apply` are mutually exclusive.
178+
179+
Backfill rollback is intentionally shared with `memory rem-backfill`: both
180+
commands use the same grounded-only staging class and diary markers. Run
181+
`session-backfill --rollback` only when you intend to clear both commands'
182+
grounded backfill artifacts from that workspace. Rollback preserves transcript
183+
ingestion cursors and tracked message hashes, so removed messages are not
184+
automatically re-ingested.
185+
142186
## Dreaming
143187

144188
Dreaming is the background memory consolidation system with three cooperative

‎docs/concepts/dreaming.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,25 @@ There is also a grounded historical backfill lane for review and recovery work:
112112
- `memory rem-backfill --path ...` writes reversible grounded diary entries into `DREAMS.md`.
113113
- `memory rem-backfill --path ... --stage-short-term` stages grounded durable candidates into the same short-term evidence store the normal deep phase uses.
114114
- `memory rem-backfill --rollback` and `--rollback-short-term` remove those staged backfill artifacts without touching ordinary diary entries or live short-term recall.
115+
- `memory session-backfill --agent <id>` previews trusted candidates from the agent's retained session history, oldest unprocessed day first.
116+
- `memory session-backfill --agent <id> --apply` stages those candidates through the normal short-term store and writes reversible diary blocks without changing `MEMORY.md` or `USER.md`.
117+
- `memory session-backfill --agent <id> --rem` writes a deterministic grounded preview per day to `DREAMS.md` without staging candidates or calling a model.
118+
- `memory session-backfill --agent <id> --rollback` clears the shared grounded backfill candidates and diary blocks, including artifacts created by `rem-backfill`.
115119

116120
</Accordion>
117121
</AccordionGroup>
118122

123+
Session backfill uses canonical retained transcript identities, including
124+
sessions preserved across rotation. Messages are bucketed in the configured
125+
dreaming timezone and share live ingestion's tracked message hashes and signal
126+
caps, so bounded reruns continue forward without re-ingesting prior messages.
127+
Rollback removes generated artifacts but retains those ingestion checkpoints.
128+
Foreign files supplied with `--archive-files` are treated conservatively. Their
129+
embedded ownership fields are caller-controlled and therefore remain untrusted;
130+
without an authenticated provenance contract, they cannot enter short-term
131+
staging. Tool output, web content, and non-owner turns are excluded from the
132+
canonical session path as well.
133+
119134
The Control UI exposes the same diary backfill/reset flow on the agent's Memory tab (Agents page) so you can inspect results in the dream scene before deciding whether grounded candidates deserve promotion. A distinct grounded Scene lane shows which staged short-term entries came from historical replay, which promoted items were grounded-led, and lets you clear only grounded-only staged entries without touching live short-term state.
120135

121136
## Deep ranking signals

‎docs/docs_map.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1757,6 +1757,7 @@ Do not edit it by hand; run `pnpm docs:map:gen`.
17571757
- H2: memory promote-explain
17581758
- H2: memory rem-harness
17591759
- H2: memory rem-backfill
1760+
- H2: memory session-backfill
17601761
- H2: Dreaming
17611762
- H2: SecretRef gateway dependency
17621763
- H2: Related

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

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,103 @@ import { seedHistoricalDailyMemorySignals } from "./dreaming-phases.js";
1616
import type { MemoryCoreRuntimeHost } from "./memory/runtime-host.js";
1717
import { previewGroundedRemMarkdown } from "./rem-evidence.js";
1818
import { previewRemHarness } from "./rem-harness.js";
19+
import { runSessionBackfill, type MemorySessionBackfillOptions } from "./session-backfill.js";
1920
import {
2021
recordGroundedShortTermCandidates,
2122
removeGroundedShortTermCandidates,
2223
} from "./short-term-promotion.js";
2324
const { heading, muted, warn } = theme;
25+
26+
export async function runMemorySessionBackfill(
27+
opts: MemorySessionBackfillOptions,
28+
hostOptions?: MemoryCoreRuntimeHost,
29+
) {
30+
const { config: cfg, diagnostics } = await loadMemoryCommandConfig("memory session-backfill");
31+
emitMemorySecretResolveDiagnostics(diagnostics, { json: Boolean(opts.json) });
32+
const agentId = resolveAgent(cfg, opts.agent);
33+
await withMemoryManagerForAgent({
34+
cfg,
35+
agentId,
36+
purpose: "status",
37+
acquireLocalService: hostOptions?.acquireLocalService,
38+
withLease: hostOptions?.withLease,
39+
run: async (manager) => {
40+
const workspaceDir = manager.status().workspaceDir?.trim();
41+
if (!workspaceDir) {
42+
defaultRuntime.error("Memory session-backfill requires a resolvable workspace directory.");
43+
process.exitCode = 1;
44+
return;
45+
}
46+
if (
47+
opts.rollback &&
48+
(opts.apply || opts.rem || opts.from || opts.to || opts.archiveFiles?.length)
49+
) {
50+
defaultRuntime.error(
51+
"Memory session-backfill --rollback cannot be combined with input, range, --rem, or --apply options.",
52+
);
53+
process.exitCode = 1;
54+
return;
55+
}
56+
const remConfig = resolveMemoryRemDreamingConfig({
57+
pluginConfig: resolveMemoryPluginConfig(cfg),
58+
cfg,
59+
});
60+
let result;
61+
try {
62+
result = await runSessionBackfill({
63+
agentId,
64+
workspaceDir,
65+
...(opts.from !== undefined ? { from: opts.from } : {}),
66+
...(opts.to !== undefined ? { to: opts.to } : {}),
67+
...(opts.limitDays !== undefined ? { limitDays: opts.limitDays } : {}),
68+
...(opts.rem !== undefined ? { rem: opts.rem } : {}),
69+
...(opts.apply !== undefined ? { apply: opts.apply } : {}),
70+
...(opts.rollback !== undefined ? { rollback: opts.rollback } : {}),
71+
...(opts.archiveFiles !== undefined ? { archiveFiles: opts.archiveFiles } : {}),
72+
...(remConfig.timezone !== undefined ? { timezone: remConfig.timezone } : {}),
73+
});
74+
} catch (error) {
75+
defaultRuntime.error(error instanceof Error ? error.message : String(error));
76+
process.exitCode = 1;
77+
return;
78+
}
79+
if (opts.json) {
80+
defaultRuntime.writeJson(result);
81+
return;
82+
}
83+
if (result.rollback) {
84+
defaultRuntime.log(
85+
[
86+
`${heading("Session Backfill")} ${muted("(rollback)")}`,
87+
muted(`workspace=${shortenHomePath(workspaceDir)}`),
88+
muted(`removedDiaryEntries=${result.rollback.removedDiaryEntries}`),
89+
muted(`removedStagedEntries=${result.rollback.removedStagedEntries}`),
90+
].join("\n"),
91+
);
92+
return;
93+
}
94+
const lines = [
95+
`${heading("Session Backfill")} ${muted(`(${agentId})`)}`,
96+
muted(`workspace=${shortenHomePath(workspaceDir)}`),
97+
muted(
98+
`days=${result.days.length} candidates=${result.candidateCount} staged=${result.stagedEntries}`,
99+
),
100+
];
101+
for (const day of result.days) {
102+
lines.push("", heading(day.day), muted(`candidates=${day.candidateCount}`));
103+
lines.push(...day.topCandidates.map((candidate) => `- ${candidate}`));
104+
}
105+
if (result.days.length === 0) {
106+
lines.push("", "No new hash-untracked trusted session candidates.");
107+
}
108+
if (!result.applied && !result.rem) {
109+
lines.push("", muted("Dry run; use --apply to stage candidates."));
110+
}
111+
defaultRuntime.log(lines.join("\n"));
112+
},
113+
});
114+
}
115+
24116
export async function runMemoryRemHarness(
25117
opts: MemoryRemHarnessOptions,
26118
hostOptions?: MemoryCoreRuntimeHost,

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,9 @@ export {
44
runMemoryPromoteExplain,
55
runMemorySearch,
66
} from "./cli-index-search.runtime.js";
7-
export { runMemoryRemBackfill, runMemoryRemHarness } from "./cli-rem.runtime.js";
7+
export {
8+
runMemoryRemBackfill,
9+
runMemoryRemHarness,
10+
runMemorySessionBackfill,
11+
} from "./cli-rem.runtime.js";
812
export { runMemoryStatus } from "./cli-status.runtime.js";

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type {
1919
MemorySearchCommandOptions,
2020
} from "./cli.types.js";
2121
import type { MemoryCoreRuntimeHost } from "./memory/runtime-host.js";
22+
import type { MemorySessionBackfillOptions } from "./session-backfill.js";
2223
import {
2324
DEFAULT_PROMOTION_MIN_RECALL_COUNT,
2425
DEFAULT_PROMOTION_MIN_SCORE,
@@ -28,6 +29,7 @@ import {
2829
const loadMemoryCliRuntime = createLazyRuntimeModule(() => import("./cli.runtime.js"));
2930

3031
const DECIMAL_NUMBER_RE = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/;
32+
const DEFAULT_SESSION_BACKFILL_LIMIT_DAYS = 92;
3133

3234
async function runMemoryStatus(opts: MemoryCommandOptions, hostOptions?: MemoryCoreRuntimeHost) {
3335
const runtime = await loadMemoryCliRuntime();
@@ -81,6 +83,14 @@ async function runMemoryRemBackfill(
8183
await runtime.runMemoryRemBackfill(opts, hostOptions);
8284
}
8385

86+
async function runMemorySessionBackfill(
87+
opts: MemorySessionBackfillOptions,
88+
hostOptions?: MemoryCoreRuntimeHost,
89+
) {
90+
const runtime = await loadMemoryCliRuntime();
91+
await runtime.runMemorySessionBackfill(opts, hostOptions);
92+
}
93+
8494
function invalidCliArgument(message: string): Error & { code: string; exitCode: number } {
8595
const error = new Error(message) as Error & { code: string; exitCode: number };
8696
error.name = "InvalidArgumentError";
@@ -159,6 +169,10 @@ export function registerMemoryCli(program: Command, hostOptions?: MemoryCoreRunt
159169
"openclaw memory rem-backfill --path ./memory --stage-short-term",
160170
"Also seed durable grounded candidates into the live short-term promotion store.",
161171
],
172+
[
173+
"openclaw memory session-backfill --agent main --from 2026-01-01",
174+
"Preview trusted candidates from retained session history.",
175+
],
162176
["openclaw memory status --json", "Output machine-readable JSON (good for scripts)."],
163177
])}\n\n${theme.muted("Docs:")} ${formatDocsLink("/cli/memory", "docs.openclaw.ai/cli/memory")}\n`,
164178
);
@@ -276,6 +290,34 @@ export function registerMemoryCli(program: Command, hostOptions?: MemoryCoreRunt
276290
await runMemoryRemBackfill(opts, hostOptions);
277291
});
278292

293+
memory
294+
.command("session-backfill")
295+
.description("Distill retained session history into staged memory candidates")
296+
.option("--agent <id>", "Agent id (default: default agent)")
297+
.option("--from <YYYY-MM-DD>", "Oldest transcript day to include")
298+
.option("--to <YYYY-MM-DD>", "Newest transcript day to include")
299+
.option(
300+
"--limit-days <n>",
301+
`Maximum unprocessed days (default: ${DEFAULT_SESSION_BACKFILL_LIMIT_DAYS})`,
302+
(value: string) => parseMemoryCliPositiveIntegerOption(value, "--limit-days"),
303+
DEFAULT_SESSION_BACKFILL_LIMIT_DAYS,
304+
)
305+
.option("--rem", "Write grounded per-day REM previews to DREAMS.md", false)
306+
.option("--apply", "Stage candidates and write DREAMS.md diary entries", false)
307+
.option(
308+
"--rollback",
309+
"Remove all grounded backfill candidates and shared backfill diary entries",
310+
false,
311+
)
312+
.option(
313+
"--archive-files <path...>",
314+
"Also inspect foreign transcript archive files conservatively",
315+
)
316+
.option("--json", "Print JSON")
317+
.action(async (opts: MemorySessionBackfillOptions) => {
318+
await runMemorySessionBackfill(opts, hostOptions);
319+
});
320+
279321
memory.action(() => {
280322
memory.outputHelp();
281323
process.exitCode = 0;

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

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -635,35 +635,49 @@ export async function writeBackfillDiaryEntries(params: {
635635
bodyLines: string[];
636636
sourcePath?: string;
637637
}>;
638+
preserveExisting?: boolean;
638639
timezone?: string;
639640
}): Promise<{ dreamsPath: string; written: number; replaced: number }> {
640641
return await updateDreamsFile({
641642
workspaceDir: params.workspaceDir,
642643
updater: (existing, dreamsPath) => {
643-
const stripped = stripBackfillDiaryBlocks(existing);
644+
const stripped = params.preserveExisting
645+
? { updated: existing, removed: 0 }
646+
: stripBackfillDiaryBlocks(existing);
644647
const startIdx = stripped.updated.indexOf(DIARY_START_MARKER);
645648
const endIdx = stripped.updated.indexOf(DIARY_END_MARKER);
646649
const inner =
647650
startIdx >= 0 && endIdx > startIdx
648651
? stripped.updated.slice(startIdx + DIARY_START_MARKER.length, endIdx)
649652
: "";
650653
const preservedBlocks = splitDiaryBlocks(inner);
651-
const nextBlocks = [
652-
...preservedBlocks,
653-
...params.entries.map((entry) =>
654-
buildBackfillDiaryEntry({
655-
isoDay: entry.isoDay,
656-
bodyLines: entry.bodyLines,
657-
sourcePath: entry.sourcePath,
658-
timezone: params.timezone,
659-
}),
660-
),
661-
];
654+
const additions = params.entries.map((entry) =>
655+
buildBackfillDiaryEntry({
656+
isoDay: entry.isoDay,
657+
bodyLines: entry.bodyLines,
658+
sourcePath: entry.sourcePath,
659+
timezone: params.timezone,
660+
}),
661+
);
662+
const existingFingerprints = new Set(
663+
preservedBlocks.map((block) => normalizeDiaryBlockFingerprint(block)),
664+
);
665+
const appended = params.preserveExisting
666+
? additions.filter((block) => {
667+
const fingerprint = normalizeDiaryBlockFingerprint(block);
668+
if (existingFingerprints.has(fingerprint)) {
669+
return false;
670+
}
671+
existingFingerprints.add(fingerprint);
672+
return true;
673+
})
674+
: additions;
675+
const nextBlocks = [...preservedBlocks, ...appended];
662676
return {
663677
content: replaceDiaryContent(stripped.updated, joinDiaryBlocks(nextBlocks)),
664678
result: {
665679
dreamsPath,
666-
written: params.entries.length,
680+
written: appended.length,
667681
replaced: stripped.removed,
668682
},
669683
};

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2051,4 +2051,26 @@ export async function runDreamingSweepPhases(params: {
20512051
}
20522052
}
20532053
}
2054+
2055+
// Session backfill is a batch driver over the live-ingestion primitives. Keep
2056+
// these exports narrow so both paths share caps, hashing, state, and rendering.
2057+
export {
2058+
SESSION_INGESTION_MAX_MESSAGES_PER_FILE,
2059+
SESSION_INGESTION_MAX_MESSAGES_PER_SWEEP,
2060+
SESSION_INGESTION_MIN_MESSAGES_PER_FILE,
2061+
SESSION_INGESTION_MIN_SNIPPET_CHARS,
2062+
SESSION_INGESTION_SCORE,
2063+
appendSessionCorpusLines,
2064+
buildSessionFileScopeKey,
2065+
buildSessionRenderedLine,
2066+
buildSqliteDreamingSessionPath,
2067+
buildSessionStateKey,
2068+
hashSessionMessageId,
2069+
mergeTrackedMessageHashes,
2070+
normalizeSessionCorpusSnippet,
2071+
readSessionIngestionState,
2072+
trimTrackedSessionScopes,
2073+
writeSessionIngestionState,
2074+
};
2075+
export type { SessionIngestionMessage };
20542076
/* oxlint-disable max-lines -- TODO: split this grandfathered oversized file. */

0 commit comments

Comments
 (0)