Skip to content

Commit 743556f

Browse files
Chris Zhangclaude
authored andcommitted
fix(memory-core): index cron runId so mirror transcripts skip dreaming corpus
cron runs sometimes leave a second transcript whose basename equals the runId embedded in the sessionKey, distinct from `entry.sessionId`. With classification only indexing `entry.sessionId`, that mirror file looks like an unowned orphan: `lookupSessionKeyForTranscriptPath` returns null, `isCronRunTranscriptPath` returns false, and the file's content slips into the dreaming session corpus despite the operator's `agent:<id>:cron:` prefix exclusion. Add `extractCronRunIdFromSessionKey` in `src/sessions/session-key-utils.ts` and let `loadSessionTranscriptClassificationForSessionsDir` register the extracted runId in both `cronRunSessionIds` and (when not already taken) `sessionIdToSessionKey`. This makes the existing sessionId-fallback in `extractSessionIdFromTranscriptFileName` recognize mirror files — including their `.deleted.<ts>` / `.reset.<ts>` rotated variants — as cron-owned, so dreaming auto-skips them via `generatedByCronRun` even without operator-supplied `excludeSessionKeyPrefixes`. Tests: `session-key-utils.test.ts` covers the extractor's accept/reject boundary and asserts agreement with `isCronRunSessionKey`. `session-files.test.ts` adds two regression cases: - a mirror transcript named after the runId (live + rotated) resolves back to the cron sessionKey and is reported as cron-owned; - a registered explicit-session entry whose sessionId collides with some cron's runId is not overwritten by the runId fallback. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent b885a67 commit 743556f

6 files changed

Lines changed: 154 additions & 1 deletion

File tree

‎packages/memory-host-sdk/src/host/openclaw-runtime-session.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ export {
22
HEARTBEAT_PROMPT,
33
HEARTBEAT_TOKEN,
44
SILENT_REPLY_TOKEN,
5+
extractCronRunIdFromSessionKey,
56
hasInternalSystemUserProvenance,
67
hasInterSessionUserProvenance,
78
isCompactionCheckpointTranscriptFileName,

‎packages/memory-host-sdk/src/host/openclaw-runtime.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,10 @@ export {
142142
hasInterSessionUserProvenance,
143143
hasInternalSystemUserProvenance,
144144
} from "../../../../src/sessions/input-provenance.js";
145-
export { isCronRunSessionKey } from "../../../../src/sessions/session-key-utils.js";
145+
export {
146+
extractCronRunIdFromSessionKey,
147+
isCronRunSessionKey,
148+
} from "../../../../src/sessions/session-key-utils.js";
146149
export { onSessionTranscriptUpdate } from "../../../../src/sessions/transcript-events.js";
147150
export { formatDocsLink } from "../../../../src/terminal/links.js";
148151
export { colorize, isRich, theme } from "../../../../src/terminal/theme.js";

‎packages/memory-host-sdk/src/host/session-files.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,4 +340,75 @@ describe("transcript classification helpers", () => {
340340
"sessions/bad_name.jsonl",
341341
);
342342
});
343+
344+
it("attributes cron mirror transcripts named after runId back to the cron sessionKey", () => {
345+
// Reproduces the leak scenario: cron runs sometimes leave a second
346+
// transcript whose basename equals the runId embedded in the sessionKey,
347+
// distinct from entry.sessionId. Without runId reverse lookup the mirror
348+
// file looks like an unowned orphan and slips into the dreaming corpus.
349+
const sessionsDir = path.join(tmpDir, "sessions-mirror");
350+
fsSync.mkdirSync(sessionsDir, { recursive: true });
351+
const cronSessionId = "cron-primary-id";
352+
const cronRunId = "cron-mirror-run-id";
353+
const primaryPath = path.join(sessionsDir, `${cronSessionId}.jsonl`);
354+
const mirrorPath = path.join(sessionsDir, `${cronRunId}.jsonl`);
355+
const mirrorRotatedPath = path.join(
356+
sessionsDir,
357+
`${cronRunId}.jsonl.deleted.2026-04-25T06-33-10.801Z`,
358+
);
359+
fsSync.writeFileSync(primaryPath, "");
360+
fsSync.writeFileSync(mirrorPath, "");
361+
fsSync.writeFileSync(mirrorRotatedPath, "");
362+
fsSync.writeFileSync(
363+
path.join(sessionsDir, "sessions.json"),
364+
JSON.stringify({
365+
[`agent:main:cron:job-x:run:${cronRunId}`]: {
366+
sessionId: cronSessionId,
367+
sessionFile: primaryPath,
368+
},
369+
}),
370+
"utf-8",
371+
);
372+
373+
const classification = loadSessionTranscriptClassificationForSessionsDir(sessionsDir);
374+
const expectedKey = `agent:main:cron:job-x:run:${cronRunId}`;
375+
376+
expect(lookupSessionKeyForTranscriptPath(classification, primaryPath)).toBe(expectedKey);
377+
expect(lookupSessionKeyForTranscriptPath(classification, mirrorPath)).toBe(expectedKey);
378+
expect(lookupSessionKeyForTranscriptPath(classification, mirrorRotatedPath)).toBe(expectedKey);
379+
expect(isCronRunTranscriptPath(classification, primaryPath)).toBe(true);
380+
expect(isCronRunTranscriptPath(classification, mirrorPath)).toBe(true);
381+
expect(isCronRunTranscriptPath(classification, mirrorRotatedPath)).toBe(true);
382+
});
383+
384+
it("does not let runId reverse lookup overwrite a registered sessionId mapping", () => {
385+
// Defensive: if some other entry happens to register the same id as its
386+
// sessionId, that direct registration must win over the cron-runId fallback.
387+
const sessionsDir = path.join(tmpDir, "sessions-mirror-collision");
388+
fsSync.mkdirSync(sessionsDir, { recursive: true });
389+
const collisionId = "shared-id";
390+
const explicitFile = path.join(sessionsDir, `${collisionId}.jsonl`);
391+
const cronPrimaryFile = path.join(sessionsDir, "cron-primary.jsonl");
392+
fsSync.writeFileSync(explicitFile, "");
393+
fsSync.writeFileSync(cronPrimaryFile, "");
394+
fsSync.writeFileSync(
395+
path.join(sessionsDir, "sessions.json"),
396+
JSON.stringify({
397+
[`agent:main:explicit:${collisionId}`]: {
398+
sessionId: collisionId,
399+
sessionFile: explicitFile,
400+
},
401+
[`agent:main:cron:job-y:run:${collisionId}`]: {
402+
sessionId: "cron-primary",
403+
sessionFile: cronPrimaryFile,
404+
},
405+
}),
406+
"utf-8",
407+
);
408+
409+
const classification = loadSessionTranscriptClassificationForSessionsDir(sessionsDir);
410+
expect(lookupSessionKeyForTranscriptPath(classification, explicitFile)).toBe(
411+
`agent:main:explicit:${collisionId}`,
412+
);
413+
});
343414
});

‎packages/memory-host-sdk/src/host/session-files.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { createSubsystemLogger, redactSensitiveText } from "./openclaw-runtime-i
66
import {
77
HEARTBEAT_PROMPT,
88
HEARTBEAT_TOKEN,
9+
extractCronRunIdFromSessionKey,
910
hasInternalSystemUserProvenance,
1011
hasInterSessionUserProvenance,
1112
isCompactionCheckpointTranscriptFileName,
@@ -212,6 +213,18 @@ export function loadSessionTranscriptClassificationForSessionsDir(
212213
if (sessionId) {
213214
cronRunSessionIds.add(sessionId);
214215
}
216+
// Cron runs may produce a "mirror" transcript whose basename equals the
217+
// runId embedded in the sessionKey rather than entry.sessionId. Index that
218+
// runId so reverse lookups (`isCronRunTranscriptPath`,
219+
// `lookupSessionKeyForTranscriptPath`) attribute the mirror file back to
220+
// this cron sessionKey instead of treating it as an unowned orphan.
221+
const runIdFromKey = extractCronRunIdFromSessionKey(sessionKey);
222+
if (runIdFromKey && runIdFromKey !== sessionId) {
223+
cronRunSessionIds.add(runIdFromKey);
224+
if (!sessionIdToSessionKey.has(runIdFromKey)) {
225+
sessionIdToSessionKey.set(runIdFromKey, sessionKey);
226+
}
227+
}
215228
}
216229
}
217230
return {
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { describe, expect, it } from "vitest";
2+
import { extractCronRunIdFromSessionKey, isCronRunSessionKey } from "./session-key-utils.js";
3+
4+
describe("extractCronRunIdFromSessionKey", () => {
5+
it("extracts the runId from a canonical cron-run sessionKey", () => {
6+
expect(extractCronRunIdFromSessionKey("agent:main:cron:job-1:run:run-1")).toBe("run-1");
7+
expect(
8+
extractCronRunIdFromSessionKey(
9+
"agent:email:cron:" +
10+
"ad576449-51d3-40ad-8a36-504dc6e933d4" +
11+
":run:9463050f-1f77-4fa6-a02b-4222a5857462",
12+
),
13+
).toBe("9463050f-1f77-4fa6-a02b-4222a5857462");
14+
});
15+
16+
it("returns null for non-cron-run keys", () => {
17+
expect(extractCronRunIdFromSessionKey("agent:main:main")).toBeNull();
18+
expect(extractCronRunIdFromSessionKey("agent:main:cron:job-1")).toBeNull();
19+
expect(extractCronRunIdFromSessionKey("agent:main:dreaming-narrative-light-abc")).toBeNull();
20+
expect(extractCronRunIdFromSessionKey("agent:main:healthcheck")).toBeNull();
21+
expect(extractCronRunIdFromSessionKey(undefined)).toBeNull();
22+
expect(extractCronRunIdFromSessionKey(null)).toBeNull();
23+
expect(extractCronRunIdFromSessionKey("")).toBeNull();
24+
});
25+
26+
it("agrees with isCronRunSessionKey on accept/reject boundary", () => {
27+
const samples = [
28+
"agent:main:cron:job-1:run:run-1",
29+
"agent:main:cron:job-1",
30+
"agent:main:main",
31+
"agent:main:cron:job-1:run:",
32+
"not-an-agent-key",
33+
];
34+
for (const sk of samples) {
35+
const isRun = isCronRunSessionKey(sk);
36+
const runId = extractCronRunIdFromSessionKey(sk);
37+
expect(runId === null).toBe(!isRun);
38+
}
39+
});
40+
});

‎src/sessions/session-key-utils.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,31 @@ export function isCronRunSessionKey(sessionKey: string | undefined | null): bool
5555
return /^cron:[^:]+:run:[^:]+$/.test(parsed.rest);
5656
}
5757

58+
const CRON_RUN_ID_RE = /^cron:[^:]+:run:([^:]+)$/;
59+
60+
/**
61+
* Extract the runId from a cron-run sessionKey (`agent:<id>:cron:<jobId>:run:<runId>`).
62+
* Returns null when the key is not a cron-run key.
63+
*
64+
* cron runs may produce a transcript file whose basename equals this runId rather
65+
* than the entry's sessionId field; reverse lookups need this id to attribute
66+
* those mirror transcripts back to the cron sessionKey.
67+
*/
68+
export function extractCronRunIdFromSessionKey(
69+
sessionKey: string | undefined | null,
70+
): string | null {
71+
const parsed = parseAgentSessionKey(sessionKey);
72+
if (!parsed) {
73+
return null;
74+
}
75+
const match = CRON_RUN_ID_RE.exec(parsed.rest);
76+
if (!match) {
77+
return null;
78+
}
79+
const runId = match[1].trim();
80+
return runId.length > 0 ? runId : null;
81+
}
82+
5883
export function isCronSessionKey(sessionKey: string | undefined | null): boolean {
5984
const parsed = parseAgentSessionKey(sessionKey);
6085
if (!parsed) {

0 commit comments

Comments
 (0)