Skip to content

Commit c87ceec

Browse files
committed
fix(gateway): resolve archived-session narrative race (#87182)
Two changes that together fix the race where the gateway archives a session transcript before the host plugin (memory-core dreaming) can read it: 1. Preserve session store entries for keep-mode subagent runs. completeCleanupBookkeeping now skips removeInternalSessionEffectsSession when cleanup=keep, so the host's getSessionMessages call still resolves the entry. The host's explicit deleteSession handles full cleanup. 2. Include .jsonl.deleted.<ISO> archives in transcript history fallback. listResetArchiveCandidatesForTranscriptAsync previously only matched .jsonl.reset.<ISO> files. Now it also resolves .jsonl.deleted.<ISO> so sessions.get can read archived transcripts when the live file is gone. Keeps readSettledNarrativeText (settled retry with 50/150/300/750 ms delays) instead of the trajectory-based recovery removed from the prior approach, since the lifecycle fix removes the race at the source.
1 parent e27e2d0 commit c87ceec

3 files changed

Lines changed: 61 additions & 5 deletions

File tree

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,6 +1064,39 @@ describe("generateAndAppendDreamNarrative", () => {
10641064
expect(deleteKeys.filter((key: string) => key === firstSessionKey)).toHaveLength(2);
10651065
expect(deleteKeys.filter((key: string) => key === secondSessionKey)).toHaveLength(2);
10661066
});
1067+
1068+
it("recovers narrative text when getSessionMessages initially returns empty (archive race, #87182)", async () => {
1069+
const workspaceDir = await createTempWorkspace("openclaw-dreaming-narrative-");
1070+
const narrativeText = "The endpoints glowed faintly in the twilight of the codebase.";
1071+
const subagent = createMockSubagent("");
1072+
let getSessionCallCount = 0;
1073+
subagent.getSessionMessages.mockImplementation(async () => {
1074+
getSessionCallCount += 1;
1075+
if (getSessionCallCount === 1) {
1076+
return { messages: [] };
1077+
}
1078+
return {
1079+
messages: [
1080+
{ role: "user", content: "prompt" },
1081+
{ role: "assistant", content: narrativeText },
1082+
],
1083+
};
1084+
});
1085+
const logger = createMockLogger();
1086+
1087+
await generateAndAppendDreamNarrative({
1088+
subagent,
1089+
workspaceDir,
1090+
data: { phase: "rem", snippets: ["a distant endpoint"] },
1091+
nowMs: Date.parse("2026-04-05T03:00:00Z"),
1092+
timezone: "UTC",
1093+
logger,
1094+
});
1095+
1096+
expect(subagent.getSessionMessages).toHaveBeenCalledTimes(2);
1097+
const content = await fs.readFile(path.join(workspaceDir, "DREAMS.md"), "utf-8");
1098+
expect(content).toContain(narrativeText);
1099+
});
10671100
});
10681101

10691102
describe("runDetachedDreamNarrative", () => {

‎src/agents/subagent-registry-lifecycle.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,7 +1230,13 @@ export function createSubagentRegistryLifecycleController(params: {
12301230
);
12311231
});
12321232
};
1233-
if (!cleanupParams.preserveTranscript) {
1233+
// Keep-mode runs (plugin subagents) must retain their session store entry
1234+
// until the host plugin calls deleteSession explicitly. Removing the entry
1235+
// in the bookkeeping tail races with the host's getSessionMessages call,
1236+
// silently returning empty messages (#87182).
1237+
const shouldPreserveTranscript =
1238+
cleanupParams.preserveTranscript === true || cleanupParams.cleanup === "keep";
1239+
if (!shouldPreserveTranscript) {
12341240
runCleanupTail("session cleanup", async () => {
12351241
await removeInternalSessionEffectsSession(cleanupParams.entry.execution?.transcriptTarget);
12361242
});

‎src/gateway/session-transcript-files.fs.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,8 @@ async function resetArchiveHeaderMatchesSessionId(
237237
}
238238
}
239239

240+
const ARCHIVE_CANDIDATE_REASONS = ["reset", "deleted"] as const;
241+
240242
async function listResetArchiveCandidatesForTranscriptAsync(
241243
transcriptPath: string,
242244
): Promise<ResetArchiveCandidate[] | undefined> {
@@ -260,14 +262,29 @@ async function listResetArchiveCandidatesForTranscriptAsync(
260262
const archives: ResetArchiveCandidate[] = [];
261263
try {
262264
for (const entry of await fs.promises.readdir(dir, { withFileTypes: true })) {
263-
if (!entry.isFile() || !entry.name.startsWith(`${base}.reset.`)) {
265+
if (!entry.isFile()) {
264266
continue;
265267
}
266-
const timestamp = parseSessionArchiveTimestamp(entry.name, "reset");
267-
if (timestamp == null) {
268+
let matched = false;
269+
let timestamp: number | null = null;
270+
for (const reason of ARCHIVE_CANDIDATE_REASONS) {
271+
if (!entry.name.startsWith(`${base}.${reason}.`)) {
272+
continue;
273+
}
274+
timestamp = parseSessionArchiveTimestamp(entry.name, reason);
275+
if (timestamp != null) {
276+
matched = true;
277+
break;
278+
}
279+
}
280+
if (!matched) {
268281
continue;
269282
}
270-
archives.push({ archivePath: path.join(dir, entry.name), name: entry.name, timestamp });
283+
archives.push({
284+
archivePath: path.join(dir, entry.name),
285+
name: entry.name,
286+
timestamp: timestamp!,
287+
});
271288
}
272289
} catch {
273290
return undefined;

0 commit comments

Comments
 (0)