Skip to content

Commit bbe08c5

Browse files
committed
fix(memory): track complete backfill rewind baselines
1 parent f2835a0 commit bbe08c5

3 files changed

Lines changed: 155 additions & 21 deletions

File tree

‎extensions/memory-core/src/session-backfill-lifecycle.ts‎

Lines changed: 68 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createHash } from "node:crypto";
22
import { readSessionIngestionState, writeSessionIngestionState } from "./dreaming-phases.js";
33
import {
4-
clearMemoryCoreWorkspaceNamespace,
4+
deleteMemoryCoreWorkspaceEntry,
55
readMemoryCoreWorkspaceEntries,
66
SESSION_BACKFILL_REWIND_NAMESPACE,
77
writeMemoryCoreWorkspaceEntry,
@@ -13,6 +13,8 @@ import type {
1313

1414
const DEFAULT_SESSION_BACKFILL_LIMIT_DAYS = 92;
1515
const MEMORY_DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
16+
// Batch keys are SHA-256 hex digests, so this colon-delimited marker cannot collide.
17+
const SESSION_BACKFILL_BASELINE_KEY_PREFIX = "complete-baseline:";
1618

1719
type SessionBackfillRewindCandidate = {
1820
contentIndex: number;
@@ -26,6 +28,12 @@ type SessionBackfillRewindBatch = {
2628
candidates: SessionBackfillRewindCandidate[];
2729
};
2830

31+
type SessionBackfillBaseline = {
32+
version: 1;
33+
complete: true;
34+
agentId: string;
35+
};
36+
2937
function normalizeMemoryDay(value: string | undefined, flag: string): string | undefined {
3038
if (value === undefined) {
3139
return undefined;
@@ -81,6 +89,18 @@ export async function recordSessionBackfillRewindBatch(params: {
8189
});
8290
}
8391

92+
export async function markSessionBackfillRewindBaseline(params: {
93+
workspaceDir: string;
94+
agentId: string;
95+
}): Promise<void> {
96+
await writeMemoryCoreWorkspaceEntry<SessionBackfillBaseline>({
97+
namespace: SESSION_BACKFILL_REWIND_NAMESPACE,
98+
workspaceDir: params.workspaceDir,
99+
key: `${SESSION_BACKFILL_BASELINE_KEY_PREFIX}${params.agentId}`,
100+
value: { version: 1, complete: true, agentId: params.agentId },
101+
});
102+
}
103+
84104
function isSessionBackfillRewindCandidate(value: unknown): value is SessionBackfillRewindCandidate {
85105
if (value === null || typeof value !== "object" || Array.isArray(value)) {
86106
return false;
@@ -98,25 +118,43 @@ function isSessionBackfillRewindCandidate(value: unknown): value is SessionBackf
98118
);
99119
}
100120

101-
export async function rewindSessionBackfillIngestionState(workspaceDir: string): Promise<number> {
102-
const entries = await readMemoryCoreWorkspaceEntries<SessionBackfillRewindBatch>({
121+
function isSessionBackfillRewindBatch(
122+
value: SessionBackfillRewindBatch | SessionBackfillBaseline,
123+
): value is SessionBackfillRewindBatch {
124+
return value.version === 1 && "candidates" in value && Array.isArray(value.candidates);
125+
}
126+
127+
export async function rewindSessionBackfillIngestionState(params: {
128+
workspaceDir: string;
129+
agentId: string;
130+
}): Promise<{
131+
completeCoverage: boolean;
132+
rewoundCandidates: number;
133+
}> {
134+
const entries = await readMemoryCoreWorkspaceEntries<
135+
SessionBackfillRewindBatch | SessionBackfillBaseline
136+
>({
103137
namespace: SESSION_BACKFILL_REWIND_NAMESPACE,
104-
workspaceDir,
138+
workspaceDir: params.workspaceDir,
105139
});
106-
const candidates = entries.flatMap((entry) =>
107-
entry.value?.version === 1 && Array.isArray(entry.value.candidates)
140+
const completeCoverage = entries.some(
141+
(entry) =>
142+
entry.key === `${SESSION_BACKFILL_BASELINE_KEY_PREFIX}${params.agentId}` &&
143+
"complete" in entry.value &&
144+
entry.value.agentId === params.agentId,
145+
);
146+
const batchEntries = entries.filter((entry) => isSessionBackfillRewindBatch(entry.value));
147+
const candidates = batchEntries.flatMap((entry) =>
148+
isSessionBackfillRewindBatch(entry.value)
108149
? entry.value.candidates.filter(isSessionBackfillRewindCandidate)
109150
: [],
110151
);
111152
if (candidates.length === 0) {
112-
await clearMemoryCoreWorkspaceNamespace({
113-
namespace: SESSION_BACKFILL_REWIND_NAMESPACE,
114-
workspaceDir,
115-
});
116-
return 0;
153+
await deleteSessionBackfillRewindBatches(params.workspaceDir, batchEntries);
154+
return { completeCoverage, rewoundCandidates: 0 };
117155
}
118156

119-
const state = await readSessionIngestionState(workspaceDir);
157+
const state = await readSessionIngestionState(params.workspaceDir);
120158
const removedHashesByScope = new Map<string, Set<string>>();
121159
const rewindLineByStateKey = new Map<string, number>();
122160
for (const candidate of candidates) {
@@ -153,12 +191,24 @@ export async function rewindSessionBackfillIngestionState(workspaceDir: string):
153191
};
154192
}
155193
}
156-
await writeSessionIngestionState(workspaceDir, { ...state, files, seenMessages });
157-
await clearMemoryCoreWorkspaceNamespace({
158-
namespace: SESSION_BACKFILL_REWIND_NAMESPACE,
159-
workspaceDir,
160-
});
161-
return candidates.length;
194+
await writeSessionIngestionState(params.workspaceDir, { ...state, files, seenMessages });
195+
await deleteSessionBackfillRewindBatches(params.workspaceDir, batchEntries);
196+
return { completeCoverage, rewoundCandidates: candidates.length };
197+
}
198+
199+
async function deleteSessionBackfillRewindBatches(
200+
workspaceDir: string,
201+
entries: Array<{ key: string }>,
202+
): Promise<void> {
203+
await Promise.all(
204+
entries.map((entry) =>
205+
deleteMemoryCoreWorkspaceEntry({
206+
namespace: SESSION_BACKFILL_REWIND_NAMESPACE,
207+
workspaceDir,
208+
key: entry.key,
209+
}),
210+
),
211+
);
162212
}
163213

164214
function belongsToAgentFileState(key: string, agentId: string): boolean {

‎extensions/memory-core/src/session-backfill.test.ts‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ import {
1515
clearMemoryCoreWorkspaceNamespace,
1616
SESSION_BACKFILL_REWIND_NAMESPACE,
1717
} from "./dreaming-state.js";
18-
import { resetSessionBackfillIngestionState } from "./session-backfill-lifecycle.js";
18+
import {
19+
markSessionBackfillRewindBaseline,
20+
resetSessionBackfillIngestionState,
21+
rewindSessionBackfillIngestionState,
22+
} from "./session-backfill-lifecycle.js";
1923
import {
2024
executeSessionBackfill,
2125
executeSessionBackfillBatch,
@@ -605,6 +609,67 @@ describe("runSessionBackfill", () => {
605609
expect(preview.candidateCount).toBe(1);
606610
expect(reapplied.candidateCount).toBe(1);
607611
expect(hashStagedContent(afterReapply)).toBe(firstContentHash);
612+
613+
const stateAfterReapply = await dreamingTestState.readSessionIngestionState(workspaceDir);
614+
const scope = Object.keys(stateAfterReapply.seenMessages)[0];
615+
if (!scope) {
616+
throw new Error("Expected re-applied session ingestion scope");
617+
}
618+
await writeSessionIngestionState(workspaceDir, {
619+
...stateAfterReapply,
620+
seenMessages: {
621+
...stateAfterReapply.seenMessages,
622+
[scope]: [...(stateAfterReapply.seenMessages[scope] ?? []), "later-live"],
623+
},
624+
});
625+
await runSessionBackfill({ agentId: "main", workspaceDir, rollback: true });
626+
expect(
627+
(await dreamingTestState.readSessionIngestionState(workspaceDir)).seenMessages[scope],
628+
).toEqual(["later-live"]);
629+
});
630+
631+
it("resets mixed legacy state when later journal rows do not prove complete coverage", async () => {
632+
const workspaceDir = await createIsolatedWorkspace("mixed-legacy-rollback-");
633+
const applyParams = {
634+
agentId: "main",
635+
workspaceDir,
636+
apply: true,
637+
nowMs: Date.parse("2026-05-03T12:00:00.000Z"),
638+
timezone: "UTC",
639+
} as const;
640+
await seedCanonicalTranscript("legacy-mixed", [
641+
{
642+
role: "user",
643+
content: "The preferred shell is zsh",
644+
timestamp: "2026-05-01T10:00:00.000Z",
645+
owner: true,
646+
},
647+
]);
648+
await runSessionBackfill(applyParams);
649+
await clearMemoryCoreWorkspaceNamespace({
650+
namespace: SESSION_BACKFILL_REWIND_NAMESPACE,
651+
workspaceDir,
652+
});
653+
await seedCanonicalTranscript("journaled-mixed", [
654+
{
655+
role: "user",
656+
content: "The preferred pager is less",
657+
timestamp: "2026-05-02T10:00:00.000Z",
658+
owner: true,
659+
},
660+
]);
661+
await runSessionBackfill(applyParams);
662+
const firstContentHash = hashStagedContent(await readShortTermRecallEntries({ workspaceDir }));
663+
664+
await runSessionBackfill({ agentId: "main", workspaceDir, rollback: true });
665+
const preview = await runSessionBackfill({ agentId: "main", workspaceDir, timezone: "UTC" });
666+
const reapplied = await runSessionBackfill(applyParams);
667+
668+
expect(preview.candidateCount).toBe(2);
669+
expect(reapplied.candidateCount).toBe(2);
670+
expect(hashStagedContent(await readShortTermRecallEntries({ workspaceDir }))).toBe(
671+
firstContentHash,
672+
);
608673
});
609674

610675
it("keeps other agents' archived scopes when resetting an agent named archive", async () => {
@@ -641,4 +706,18 @@ describe("runSessionBackfill", () => {
641706
},
642707
});
643708
});
709+
710+
it("does not share a clean rewind baseline across agents", async () => {
711+
const workspaceDir = await createIsolatedWorkspace("agent-baseline-");
712+
await markSessionBackfillRewindBaseline({ workspaceDir, agentId: "main" });
713+
714+
expect(await rewindSessionBackfillIngestionState({ workspaceDir, agentId: "other" })).toEqual({
715+
completeCoverage: false,
716+
rewoundCandidates: 0,
717+
});
718+
expect(await rewindSessionBackfillIngestionState({ workspaceDir, agentId: "main" })).toEqual({
719+
completeCoverage: true,
720+
rewoundCandidates: 0,
721+
});
722+
});
644723
});

‎extensions/memory-core/src/session-backfill.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import type {
3838
} from "./session-backfill-contract.js";
3939
import {
4040
drainSessionBackfill,
41+
markSessionBackfillRewindBaseline,
4142
normalizeSessionBackfillSelection,
4243
recordSessionBackfillRewindBatch,
4344
resetSessionBackfillIngestionState,
@@ -538,12 +539,16 @@ async function executeSessionBackfillCore(
538539
removeBackfillDiaryEntries({ workspaceDir }),
539540
removeGroundedShortTermCandidates({ workspaceDir }),
540541
]);
541-
const rewoundCandidates = await rewindSessionBackfillIngestionState(workspaceDir);
542-
if (rewoundCandidates === 0 && (diary.removed > 0 || staged.removed > 0)) {
542+
const rewind = await rewindSessionBackfillIngestionState({
543+
workspaceDir,
544+
agentId: params.agentId,
545+
});
546+
if (!rewind.completeCoverage && (diary.removed > 0 || staged.removed > 0)) {
543547
// Applies from before the rewind journal shipped have no owned offsets to restore.
544548
// Without this agent-scoped reset, rollback deletes artifacts but re-apply finds nothing.
545549
await resetSessionBackfillIngestionState({ workspaceDir, agentId: params.agentId });
546550
}
551+
await markSessionBackfillRewindBaseline({ workspaceDir, agentId: params.agentId });
547552
return {
548553
result: {
549554
agentId: params.agentId,

0 commit comments

Comments
 (0)