Now I'm starting to understand the issue. Let me think about this more carefully.
The issue is: "Isolated cron runs leak context when they reuse a stable session key."
When a cron job runs with a stable session key (e.g., agent:main:cron:nightly), and the runtime generates a new sessionId for each run, but the same sessionKey is used:
- The first cron run creates a conversation with sessionId1 and sessionKey
agent:main:cron:nightly.
- When the cron run ends, the session_end handler archives the conversation (if the session isn't stateless).
- The next cron run uses the same sessionKey but a new sessionId.
- If the session isn't properly marked as stateless/isolated, the new run might find the archived conversation and... actually wait.
Let me re-read the handleSessionEnd method:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
And it checks reason !== "deleted" to determine whether to create a replacement.
But the issue is that cron runs that should be isolated (stateless) are NOT being treated as such. When a cron run completes and the next one starts with the same stable session key, the context from the previous run might still be in an active conversation that leaks into the new run.
Wait, let me re-read the issue: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context. Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged."
So the fix should ensure:
- Isolated cron sessions with stable session keys should archive their conversation at the end of each run.
- The next run should start with a fresh conversation.
- Compaction within the current run should still work.
- Non-cron sessions should be unaffected.
Let me look at how cron sessions are currently handled. Looking at the test, I see that cron sessions matching agent:*:cron:** are in ignoreSessionPatterns, not statelessSessionPatterns. But wait, let me look more carefully...
Actually, let me look at what happens when a session has a stable session key but changes its sessionId between runs. This is typical for cron jobs - they might have a fixed session key but a different session ID each time.
The key issue seems to be in how handleSessionEnd and bootstrap handle this case. When a cron job:
- Runs with sessionId1 and sessionKey "agent:main:cron:nightly"
- After the run, session_end is called with sessionId1
- The conversation is archived... but wait, what happens?
Let me look at handleSessionEnd again:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
...
const createReplacement = reason !== "deleted";
await this.withSessionQueue(
this.resolveSessionQueueKey(params.nextSessionId ?? params.sessionId, params.sessionKey ?? params.nextSessionKey),
async () =>
this.conversationStore.withTransaction(async () => {
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
}),
);
}
And applySessionReplacement:
private async applySessionReplacement(params: {
reason: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
createReplacement: boolean;
createReplacementWhenMissing?: boolean;
}): Promise<void> {
const current = await this.conversationStore.getConversationForSession({
sessionId: params.sessionId,
sessionKey: params.sessionKey,
});
...
So when session_end is called:
- It looks up the conversation for the current sessionId
- It archives that conversation
- If createReplacement is true, it creates a new conversation with nextSessionId/nextSessionKey
Now let me think about what happens for cron sessions that reuse a stable session key:
Run 1:
- sessionId = "cron-uuid-1", sessionKey = "agent:main:cron:nightly"
- bootstrap() creates/gets conversation, archives nothing
- After turns, conversation is active with sessionKey "agent:main:cron:nightly"
- session_end() is called
- It finds the conversation for sessionId "cron-uuid-1", archives it
- If createReplacement=true, it creates a new conversation with the same sessionKey
Run 2:
- sessionId = "cron-uuid-2", sessionKey = "agent:main:cron:nightly"
- bootstrap() is called
- getConversationForSession looks up by sessionKey "agent:main:cron:nightly"
- It finds the active conversation created during Run 1's session_end
- This is the LEAK! The new run is using the conversation from the previous run's session_end.
Wait, but that's not exactly right either. Let me look at this more carefully.
Actually, looking at the flow:
In Run 1's bootstrap:
getOrCreateConversation(sessionId, { sessionKey: "agent:main:cron:nightly" }) is called
- Since there's no existing conversation with that sessionKey, a new conversation is created with sessionKey "agent:main:cron:nightly" and sessionId "cron-uuid-1"
In Run 1's session_end:
handleSessionEnd is called with sessionId="cron-uuid-1", sessionKey="agent:main:cron:nightly"
applySessionReplacement is called
- It finds the conversation with sessionId "cron-uuid-1" (which has sessionKey "agent:main:cron:nightly")
- It archives that conversation
- Then it creates a replacement with nextSessionId=undefined (so it falls back to sessionId="cron-uuid-1") and nextSessionKey="agent:main:cron:nightly"
- So a new conversation is created with sessionId "cron-uuid-1" and sessionKey "agent:main:cron:nightly"
In Run 2's bootstrap:
getOrCreateConversation(sessionId, { sessionKey: "agent:main:cron:nightly" }) is called with sessionId="cron-uuid-2"
getOrCreateConversation first checks getConversationBySessionKey("agent:main:cron:nightly") which finds the active conversation created during Run 1's session_end (with sessionId "cron-uuid-1")
- Since a conversation is found, it returns that conversation (updating its sessionId to "cron-uuid-2")
- This means Run 2 picks up the context from Run 1!
This is the leak! The session_end handler creates a replacement conversation that has the same sessionKey, so the next bootstrap picks it up.
For isolated cron sessions, we should NOT create a replacement conversation after the session ends. Instead, the session should start completely fresh each time.
But wait - the issue says "Prior runs remain archived, compaction within the current run still works". This means:
- Previous runs should be archived (they are)
- The current run should get a fresh conversation (this is the fix needed)
- Compaction within the current run should work (this needs to continue working)
So the fix should be: For cron sessions (sessions matching cron patterns), when session_end is called, we should archive the conversation but NOT create a replacement. This way, the next bootstrap for the same sessionKey will create a completely fresh conversation.
But wait, looking at handleSessionEnd:
const createReplacement = reason !== "deleted";
For cron sessions, the reason would be something like "completed" or "idle" (not "deleted"), so createReplacement would be true. We need to make it false for cron sessions.
Actually, let me re-read the code more carefully. Let me look at what happens in handleSessionEnd when createReplacement is true but the current session ends:
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
And in applySessionReplacement:
const nextSessionId = params.nextSessionId?.trim() || params.sessionId?.trim() || current?.sessionId;
const nextSessionKey = params.nextSessionKey?.trim() || params.sessionKey?.trim() || current?.sessionKey;
const freshConversation = await this.conversationStore.createConversation({
sessionId: nextSessionId,
...(nextSessionKey ? { sessionKey: nextSessionKey } : {}),
});
So a new conversation is created with the same sessionKey but the old sessionId (since nextSessionId isn't set for cron).
Now I understand the leak. The fix should be: for cron sessions, don't create a replacement in session_end.
But there's another angle - maybe the fix should be in the bootstrap? Like, when bootstrapping a cron session with a stable session key, check if the session file has changed (indicating a new run) and if so, create a new conversation instead of reusing the existing one.
Actually, let me look at the existing mechanism for handling session file changes:
await this.rotateStaleSessionKeyConversationIfTrackedTranscriptMissing({
phase: "bootstrap",
sessionId: params.sessionId,
sessionKey: params.sessionKey,
sessionFile: params.sessionFile,
});
This checks if the tracked session file has changed and rotates the conversation if needed. But for cron sessions with a stable session key, the session file IS the same (cron sessions typically reuse the same file). So this check won't help.
Wait, but the issue says "isolated cron runtime sessions" - let me think about what "isolated" means here. Looking at the prepareSubagentSpawn method:
contextMode?: "isolated" | "fork";
This is about subagent context modes, not about cron sessions. Let me think about what "isolated" means for cron sessions.
Actually, I think "isolated" here means sessions that should not share context between runs. For cron sessions, each run should be independent.
The key insight is: For cron sessions (sessions matching cron patterns like agent:*:cron:**), the session_end handler should NOT create a replacement conversation. This way, the next run starts completely fresh.
But wait, I also need to consider the handleSessionEnd method. Let me look at the reason values it excludes:
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
So session_end is skipped for "new", "unknown", "restart", "shutdown". For other reasons like "completed", "idle", "deleted", it proceeds.
Now, the fix could be in handleSessionEnd. When the sessionKey matches cron patterns, we should NOT create a replacement. This means:
- Archive the current conversation (so it's preserved)
- Don't create a new conversation (so the next run starts fresh)
But there's a complication: handleSessionEnd is called for all session types, not just cron. We need to check if the session matches cron patterns.
Let me look at how to detect if a session is a cron session. Looking at isStatelessSession:
isStatelessSession(sessionKey: string | undefined): boolean {
const trimmedKey = typeof sessionKey === "string" ? sessionKey.trim() : "";
if (
!this.config.skipStatelessSessions
|| !trimmedKey
|| this.statelessSessionPatterns.length === 0
) {
return false;
}
return matchesSessionPattern(trimmedKey, this.statelessSessionPatterns);
}
And looking at shouldIgnoreSession:
private shouldIgnoreSession(params: { sessionId?: string; sessionKey?: string }): boolean {
...
const normalizedSessionKey =
typeof params.sessionKey === "string" && params.sessionKey.trim()
? params.sessionKey.trim()
: undefined;
return (
this.ignoredSessionPatterns.length > 0
&& typeof normalizedSessionKey === "string"
&& matchesSessionPattern(normalizedSessionKey, this.ignoredSessionPatterns)
);
}
So ignoredSessionPatterns includes agent:*:cron:** for cron sessions. And shouldIgnoreSession checks if the session matches the ignored patterns.
But handleSessionEnd already checks shouldIgnoreSession:
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
So if a session matches the ignored patterns (including cron), handleSessionEnd should return early and NOT archive the conversation. But that's the opposite of what we want! We want to archive the conversation but not create a replacement.
Wait, let me re-read the issue: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
So the issue is that cron sessions ARE sharing context because:
- The
handleSessionEnd handler creates a replacement conversation with the same sessionKey
- The next bootstrap picks up that replacement conversation
So the fix should be: For cron sessions, handleSessionEnd should archive the current conversation but NOT create a replacement.
But currently, handleSessionEnd returns early for cron sessions (due to shouldIgnoreSession), so neither the current conversation nor a replacement is created. This means:
- Run 1's conversation stays active
- Run 2 finds and reuses Run 1's conversation
- This is the leak!
So the fix is: For cron sessions, handleSessionEnd should still proceed (remove the shouldIgnoreSession check or make it conditional), but it should NOT create a replacement.
Actually wait, let me re-read handleSessionEnd more carefully:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
...
So for cron sessions, shouldIgnoreSession returns true, and handleSessionEnd returns early. This means:
- The conversation from Run 1 stays active (not archived)
- Run 2 finds the active conversation from Run 1 and reuses it
- This is the leak!
The fix should be: For cron sessions, handleSessionEnd should archive the current conversation but NOT create a replacement.
So we need to:
- Remove the
shouldIgnoreSession check for cron sessions in handleSessionEnd (or make it conditional)
- For cron sessions, set
createReplacement = false
But wait, shouldIgnoreSession also checks for cron patterns, and we need to know which sessions are cron sessions. Let me think about this...
Actually, looking more carefully at handleSessionEnd:
- It checks
shouldIgnoreSession - if true, return early
- It checks
isStatelessSession - if true, return early
- Otherwise, it archives and potentially creates replacement
The issue is that cron sessions are in ignoredSessionPatterns, so shouldIgnoreSession returns true for them. But we still need to handle them in handleSessionEnd to archive the conversation.
So the fix could be:
- For cron sessions (ignored sessions),
handleSessionEnd should still proceed but only archive without creating a replacement.
OR:
- Move cron sessions from
ignoredSessionPatterns to statelessSessionPatterns. But this would change other behaviors (like in bootstrap, afterTurn, etc.).
Actually, let me re-read the test:
const ignoredSessionKey = "agent:main:cron:nightly:run:run-123";
...
ignoreSessionPatterns: ["agent:*:cron:**"],
So cron sessions are currently in ignoredSessionPatterns, not statelessSessionPatterns. The test expects them to be ignored.
But the issue is that cron sessions ARE leaking context. So we need a different approach.
Let me think about this differently. The issue says "isolated cron runtime sessions". What makes a cron session "isolated"? I think it's the fact that cron sessions have a stable session key but different session IDs between runs.
Actually, let me re-read the issue: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
So the issue is about cron sessions that:
- Reuse a stable session key across runs
- Have different session IDs (runtime sessions) between runs
- Should NOT share LCM context
The fix should ensure that when a cron session ends, the active conversation is archived and NOT replaced with a new one. This way, the next run will create a fresh conversation.
Let me think about the cleanest fix:
Option 1: In handleSessionEnd, for sessions that match cron patterns (ignoredSessionPatterns), archive the conversation but don't create a replacement.
Option 2: In handleSessionEnd, remove the shouldIgnoreSession check for sessions that have a stable session key (meaning they need to be archived on each run).
Option 3: In getOrCreateConversation, check if the active conversation's sessionId is the same as the new sessionId. If not, create a new conversation instead of reusing the old one.
I think Option 1 is the cleanest. We need to:
- For cron sessions, still proceed in
handleSessionEnd (remove the early return for ignored sessions)
- For cron sessions, set
createReplacement = false
But actually, I need to think about this more carefully. The issue is about "isolated cron sessions" specifically. How do we identify an "isolated" cron session?
Looking at the session patterns:
ignoredSessionPatterns: sessions that should be completely ignored (no context management at all)
statelessSessionPatterns: sessions that have no persistent context
For cron sessions, they're in ignoredSessionPatterns which means they're completely ignored. But the issue is that they still need context management to prevent leaking between runs.
Wait, let me re-read the issue more carefully: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
So "isolated cron sessions" are sessions that:
- Are part of the cron pattern
- Reuse a stable session key
The fix should ensure that each isolated cron run gets a fresh conversation.
Let me look at the handleSessionEnd method again:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
...
For cron sessions, shouldIgnoreSession returns true, so we return early without archiving. This is the problem!
The fix should be: For cron sessions, still proceed in handleSessionEnd but only archive without creating a replacement.
Let me think about the implementation:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
const normalizedSessionKey = params.sessionKey?.trim();
const isCronSession =
this.ignoredSessionPatterns.length > 0
&& typeof normalizedSessionKey === "string"
&& matchesSessionPattern(normalizedSessionKey, this.ignoredSessionPatterns);
if (!isCronSession && this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
const createReplacement = reason !== "deleted" && !isCronSession;
this.ensureMigrated();
await this.withSessionQueue(
this.resolveSessionQueueKey(params.nextSessionId ?? params.sessionId, params.sessionKey ?? params.nextSessionKey),
async () =>
this.conversationStore.withTransaction(async () => {
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
}),
);
}
Wait, but this changes the behavior for non-cron ignored sessions too. Let me think about this...
Actually, the issue specifically mentions "cron" sessions. So I think the fix should be:
- For cron sessions (those matching cron patterns in
ignoredSessionPatterns), handleSessionEnd should still proceed
- For cron sessions, set
createReplacement = false
But I need to be careful not to break other ignored sessions. Let me think...
Actually, I think the fix should be more targeted. The issue is about cron sessions specifically. Let me look at how to detect cron sessions.
Looking at the default config:
ignoredSessionPatterns: ["agent:*:cron:**"],
So cron sessions are those that match agent:*:cron:**.
But the fix should be generic. The issue says "isolated cron runtime sessions that reuse a stable session key". The key characteristic is that they:
- Are in
ignoredSessionPatterns
- Reuse a stable session key
So the fix should be: For sessions in ignoredSessionPatterns that have a stable session key, handleSessionEnd should archive the conversation but not create a replacement.
Let me implement this fix.
Actually wait, I realize I need to understand the issue better. Let me re-read the issue:
"Isolated cron runs leak context when they reuse a stable session key"
"Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context. Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged."
So the issue is:
- Cron runs reuse a stable session key (e.g.,
agent:main:cron:nightly)
- Each run has a different session ID (runtime-generated)
- The context from one run leaks into the next run
- We need to ensure:
- Prior runs remain archived (they are, if we archive them)
- Compaction within the current run works (it does, since the current run has a fresh conversation)
- Non-cron sessions are unchanged
The fix should be in handleSessionEnd. For cron sessions:
- Archive the current conversation
- Don't create a replacement
This way, the next run will find no active conversation for the cron session key and will create a fresh one.
Let me look at how to detect cron sessions specifically. I think the cleanest approach is to check if the session matches ignoredSessionPatterns in handleSessionEnd.
Actually, let me reconsider. The current behavior is:
- Cron sessions are in
ignoredSessionPatterns
handleSessionEnd returns early for ignored sessions
- This means cron sessions never get archived
But the issue says "Prior runs remain archived". So currently, cron runs are NOT being archived. This is the leak.
The fix should be: For cron sessions, archive the conversation at the end of each run but don't create a replacement.
Let me implement this fix now.
Wait, let me reconsider again. The shouldIgnoreSession check in handleSessionEnd is there for a reason - to skip ignored sessions entirely. But the issue is that cron sessions need partial handling (archive but don't create replacement).
I think the cleanest fix is:
- Check if the session is a cron session (matches
ignoredSessionPatterns)
- If it's a cron session, proceed with archiving but don't create a replacement
- Otherwise, use the existing logic
Let me implement this.
Actually, I just realized something. The issue says "ordinary non-cron session continuity is unchanged." This suggests that for non-cron sessions, the current behavior should remain the same. So the fix should only affect cron sessions.
OK let me now implement the fix:
In handleSessionEnd:
- Before the
shouldIgnoreSession check, detect if the session is a cron session
- If it's a cron session, proceed with archiving but don't create a replacement
- Otherwise, use the existing logic
Here's the plan:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
const normalizedSessionKey = params.sessionKey?.trim();
const isCronSession =
this.ignoredSessionPatterns.length > 0
&& typeof normalizedSessionKey === "string"
&& matchesSessionPattern(normalizedSessionKey, this.ignoredSessionPatterns);
if (!isCronSession && this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
const createReplacement = reason !== "deleted" && !isCronSession;
this.ensureMigrated();
await this.withSessionQueue(
this.resolveSessionQueueKey(params.nextSessionId ?? params.sessionId, params.sessionKey ?? params.nextSessionKey),
async () =>
this.conversationStore.withTransaction(async () => {
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
}),
);
}
Wait, but I also need to make sure applySessionReplacement handles the case where current is null but createReplacementWhenMissing is true. Let me look at applySessionReplacement again:
private async applySessionReplacement(params: {
reason: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
createReplacement: boolean;
createReplacementWhenMissing?: boolean;
}): Promise<void> {
const current = await this.conversationStore.getConversationForSession({
sessionId: params.sessionId,
sessionKey: params.sessionKey,
});
if (!current && !params.createReplacementWhenMissing) {
return;
}
So if there's no current conversation and createReplacementWhenMissing is false (default), it just returns. This is fine for our case - we don't need to create a replacement for cron sessions.
OK, let me also think about edge cases:
- What if a cron session has no active conversation? ->
applySessionReplacement returns early, no harm done.
- What if a cron session's conversation is already archived? ->
applySessionReplacement won't try to archive it again (it checks if (current?.active)).
- What if compaction happens during the cron run? -> It works on the current run's conversation, which is correct.
- What if a cron session is followed by a non-cron session with the same session key? -> The non-cron session would create a new conversation, which is correct.
Actually wait, there's an issue. If shouldIgnoreSession is true (cron session), we skip the early return and proceed to archive. But isStatelessSession also checks patterns. Let me make sure these don't conflict.
Looking at isStatelessSession:
isStatelessSession(sessionKey: string | undefined): boolean {
const trimmedKey = typeof sessionKey === "string" ? sessionKey.trim() : "";
if (
!this.config.skipStatelessSessions
|| !trimmedKey
|| this.statelessSessionPatterns.length === 0
) {
return false;
}
return matchesSessionPattern(trimmedKey, this.statelessSessionPatterns);
}
This checks statelessSessionPatterns, not ignoredSessionPatterns. So a session can be in ignoredSessionPatterns but not in statelessSessionPatterns. That's the case for cron sessions.
So the logic is:
shouldIgnoreSession - checks ignoredSessionPatterns
isStatelessSession - checks statelessSessionPatterns
These are independent. A session can be in one, both, or neither.
For cron sessions:
- They're in
ignoredSessionPatterns
- They're NOT in
statelessSessionPatterns (usually)
shouldIgnoreSession returns true
isStatelessSession returns false (if skipStatelessSessions is false or patterns don't match)
So the current behavior for cron sessions in handleSessionEnd:
shouldIgnoreSession returns true
- We return early (no archiving)
The fix:
- Check if the session is a cron session (in
ignoredSessionPatterns)
- If so, don't return early; instead, archive without creating a replacement
Let me implement this now.
Actually, I realize there might be a subtlety. What if a session is in BOTH ignoredSessionPatterns and statelessSessionPatterns? In that case, isStatelessSession would return true and we'd still return early. That seems correct - stateless sessions shouldn't create replacements.
OK, let me now implement the fix. I'll modify handleSessionEnd to handle cron sessions specially.
Wait, I also need to think about the shouldIgnoreSession return. Currently:
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
This returns early for ignored sessions. But we need to handle cron sessions specially. So I need to split this check:
const normalizedSessionKey = params.sessionKey?.trim();
const isIgnoredSession =
this.ignoredSessionPatterns.length > 0
&& typeof normalizedSessionKey === "string"
&& matchesSessionPattern(normalizedSessionKey, this.ignoredSessionPatterns);
if (!isIgnoredSession && this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
Wait, this is redundant. shouldIgnoreSession already checks ignoredSessionPatterns. The issue is that I want to distinguish between:
- Ignored sessions (cron) - should archive without replacement
- Non-ignored sessions - should use existing logic
But there's another case: what about non-cron ignored sessions? Should they also be archived without replacement?
Looking at the issue description: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
This specifically mentions "cron" sessions. So I think the fix should only apply to cron sessions, not all ignored sessions.
Let me check how to detect cron sessions specifically. Looking at the default patterns:
ignoreSessionPatterns: ["agent:*:cron:**"],
So cron sessions have "cron" in their session key. I could check for this pattern specifically, but that's too specific. A better approach is to check if the session is in ignoredSessionPatterns.
Actually, the fix is: for ALL ignored sessions, archive without creating a replacement. This makes sense because ignored sessions shouldn't maintain persistent context.
But wait, the issue says "ordinary non-cron session continuity is unchanged." This implies that non-cron sessions should continue to work as before. And cron sessions are "ordinary" in terms of being non-cron... no wait, "non-cron session" means sessions that are NOT cron sessions.
So the fix should be:
- For cron sessions: archive without replacement
- For other sessions: continue as before
But how do I distinguish cron sessions from other ignored sessions? Looking at the test:
const ignoredSessionKey = "agent:main:cron:nightly:run:run-123";
And the pattern:
ignoreSessionPatterns: ["agent:*:cron:**"],
So cron sessions match the cron pattern. But there might be other ignored sessions that are not cron sessions.
I think the cleanest approach is: for ALL ignored sessions, archive without replacement. This ensures that ignored sessions (including cron) don't leak context between runs.
But the issue specifically says "cron" sessions. Let me re-read:
"Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
OK so "cron runtime sessions" are sessions that run as part of cron. The "isolated" qualifier means each run should be independent.
I think the fix should be: for sessions in ignoredSessionPatterns, archive without replacement in handleSessionEnd. This ensures:
- Cron sessions don't leak context
- Other ignored sessions also don't leak context (which is correct behavior)
Let me implement this.
Wait, but there's another consideration. The shouldIgnoreSession check in handleSessionEnd is there for a reason - to skip ignored sessions entirely. If we change this behavior, we might affect other parts of the code that rely on this behavior.
Let me check if there are other places where shouldIgnoreSession is used in handleSessionEnd:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
There's only one shouldIgnoreSession check in handleSessionEnd. So it's safe to modify.
Now, let me think about the fix more carefully:
For ignored sessions (cron and others):
- We should still archive the current conversation (so prior runs are preserved)
- We should NOT create a replacement (so each run gets a fresh start)
For non-ignored sessions:
- Continue as before (archive and potentially create replacement)
The fix:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
const normalizedSessionKey = params.sessionKey?.trim();
const isIgnoredSession =
this.ignoredSessionPatterns.length > 0
&& typeof normalizedSessionKey === "string"
&& matchesSessionPattern(normalizedSessionKey, this.ignoredSessionPatterns);
// For ignored sessions, only archive without creating a replacement
// to prevent context leaking between isolated runs.
const createReplacement =
reason !== "deleted" && !isIgnoredSession;
this.ensureMigrated();
await this.withSessionQueue(
this.resolveSessionQueueKey(params.nextSessionId ?? params.sessionId, params.sessionKey ?? params.nextSessionKey),
async () =>
this.conversationStore.withTransaction(async () => {
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
}),
);
}
Wait, but there's a subtle issue. If createReplacement is false, applySessionReplacement will only archive the current conversation. But what if there's no current conversation? Then applySessionReplacement returns early.
Let me check:
private async applySessionReplacement(params: {
...
}): Promise<void> {
const current = await this.conversationStore.getConversationForSession({
sessionId: params.sessionId,
sessionKey: params.sessionKey,
});
if (!current && !params.createReplacementWhenMissing) {
return;
}
So if there's no current conversation and createReplacementWhenMissing is false, it returns. This is fine for ignored sessions - we don't need to do anything if there's no current conversation.
But wait, there's another issue. For ignored sessions, we still want to archive the current conversation if it exists. Let me check if applySessionReplacement handles this:
if (current?.active) {
if (params.createReplacement && await this.isFreshLifecycleConversation(current)) {
this.deps.log.info(
`[lcm] ${params.reason} lifecycle no-op for already fresh conversation ${current.conversationId}`,
);
return;
}
await this.conversationStore.archiveConversation(current.conversationId);
}
if (!params.createReplacement) {
this.deps.log.info(
`[lcm] ${params.reason} lifecycle archived conversation ${current?.conversationId ?? "(none)"}`,
);
return;
}
Yes! If createReplacement is false:
- It archives the current conversation if it's active
- It returns without creating a replacement
This is exactly what we want for ignored sessions.
OK, let me also check the edge case where there's no current conversation:
if (!current && !params.createReplacementWhenMissing) {
return;
}
If there's no current conversation and createReplacementWhenMissing is false, it returns without doing anything. This is fine.
But wait, if there's no current conversation, we should probably still log something. Let me check what the log looks like:
if (!params.createReplacement) {
this.deps.log.info(
`[lcm] ${params.reason} lifecycle archived conversation ${current?.conversationId ?? "(none)"}`,
);
return;
}
So if there's no current conversation, it logs "archived conversation (none)". This is a bit misleading but acceptable.
Actually, I realize there's a problem. If createReplacement is true but there's no current conversation, we still try to create a replacement:
const nextSessionId = params.nextSessionId?.trim() || params.sessionId?.trim() || current?.sessionId;
...
const freshConversation = await this.conversationStore.createConversation({
sessionId: nextSessionId,
...
});
But if there's no current conversation, params.createReplacementWhenMissing needs to be true for this to work. Otherwise, the function returns early.
Let me check handleSessionEnd:
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
It doesn't set createReplacementWhenMissing, so it defaults to false. This means:
- If
createReplacement is true and there's no current conversation, nothing happens
- If
createReplacement is false and there's no current conversation, nothing happens
This is fine for our case.
Now, let me think about whether there are any other edge cases to consider:
- Ignored session with active conversation: Archive without replacement. Next run gets a fresh conversation. ✓
- Ignored session without active conversation: Nothing to archive. ✓
- Non-ignored session with active conversation: Archive and create replacement (if reason != "deleted"). ✓
- Non-ignored session without active conversation: Nothing happens. ✓
- Stateless session: Already returns early. ✓
- Ignored session that is also stateless: Already returns early (stateless check comes first). ✓
I think the fix is correct. Let me implement it now.
Wait, I also need to think about the logging. Currently, the log says "archived conversation (none)" when there's no conversation to archive. For ignored sessions, this might be confusing. Let me check if the logging is correct.
Actually, looking at the code again:
if (!current && !params.createReplacementWhenMissing) {
return;
}
if (current?.active) {
...
await this.conversationStore.archiveConversation(current.conversationId);
}
if (!params.createReplacement) {
this.deps.log.info(
`[lcm] ${params.reason} lifecycle archived conversation ${current?.conversationId ?? "(none)"}`,
);
return;
}
So if createReplacement is false and there's no current conversation:
- We return early at the first check (
!current && !params.createReplacementWhenMissing)
- We never reach the logging code
This is correct. If there's no current conversation and we're not creating a replacement, we just return.
OK, I'm confident the fix is correct. Let me implement it.
Actually, wait. Let me re-read the current handleSessionEnd code one more time:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
const createReplacement = reason !== "deleted";
this.ensureMigrated();
await this.withSessionQueue(
this.resolveSessionQueueKey(params.nextSessionId ?? params.sessionId, params.sessionKey ?? params.nextSessionKey),
async () =>
this.conversationStore.withTransaction(async () => {
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
}),
);
}
The fix should be:
- Move
isStatelessSession check before shouldIgnoreSession
- For ignored sessions, set
createReplacement = false
- Remove the early return for ignored sessions (but keep it for stateless sessions)
Here's the modified code:
async handleSessionEnd(params: {
reason?: string;
sessionId?: string;
sessionKey?: string;
nextSessionId?: string;
nextSessionKey?: string;
}): Promise<void> {
const reason = params.reason?.trim();
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
if (this.isStatelessSession(params.sessionKey ?? params.nextSessionKey)) {
return;
}
// For ignored (e.g., cron) sessions with a stable session key, we still
// need to archive the active conversation so prior runs do not leak into
// subsequent isolated runs, but we must NOT create a replacement row
// because a fresh conversation should be created at the next bootstrap.
const normalizedSessionKey = params.sessionKey?.trim();
const isIgnoredSession =
this.ignoredSessionPatterns.length > 0
&& typeof normalizedSessionKey === "string"
&& matchesSessionPattern(normalizedSessionKey, this.ignoredSessionPatterns);
const createReplacement = reason !== "deleted" && !isIgnoredSession;
this.ensureMigrated();
await this.withSessionQueue(
this.resolveSessionQueueKey(params.nextSessionId ?? params.sessionId, params.sessionKey ?? params.nextSessionKey),
async () =>
this.conversationStore.withTransaction(async () => {
await this.applySessionReplacement({
reason: `session_end:${reason}`,
sessionId: params.sessionId,
sessionKey: params.sessionKey ?? params.nextSessionKey,
nextSessionId: params.nextSessionId,
nextSessionKey: params.nextSessionKey,
createReplacement,
});
}),
);
}
This change:
- Removes the
shouldIgnoreSession early return
- Checks if the session is an ignored session (cron)
- Sets
createReplacement = false for ignored sessions
- Still returns early for stateless sessions
This ensures:
- Cron sessions are archived (no context leak)
- Cron sessions don't create replacements (next run gets a fresh conversation)
- Stateless sessions still return early (no change)
- Non-ignored sessions continue as before
Now let me implement this fix.
Actually, wait. I need to think about one more thing. The handleSessionEnd is called from api.on("session_end", ...). Let me check what reason values are passed for cron sessions:
Looking at the SessionEndLifecycleEvent type:
type SessionEndLifecycleEvent = {
sessionId?: string;
sessionKey?: string;
reason?: string;
nextSessionId?: string;
nextSessionKey?: string;
};
And the handler:
api.on("session_end", async (event) => {
const lifecycleEvent = event as SessionEndLifecycleEvent;
await (await shared.waitForEngine()).handleSessionEnd({
reason: lifecycleEvent.reason,
sessionId: lifecycleEvent.sessionId,
sessionKey: lifecycleEvent.sessionKey,
nextSessionId: lifecycleEvent.nextSessionId,
nextSessionKey: lifecycleEvent.nextSessionKey,
});
});
The reason comes from the host runtime. It could be "completed", "idle", "deleted", etc.
The handleSessionEnd method checks:
if (
!reason ||
reason === "new" ||
reason === "unknown" ||
reason === "restart" ||
reason === "shutdown"
) {
return;
}
So for cron sessions, the reason would typically be something like "completed" or "idle", which passes this check.
OK, I'm confident the fix is correct. Let me implement it.
Actually, let me also think about whether there are any other places in the codebase that need to be modified.
Looking at the issue: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
The fix should be in handleSessionEnd. But are there other places where context might leak?
Let me think about the flow:
- Cron Run 1: bootstrap() -> creates conversation -> afterTurn() -> session_end()
- Cron Run 2: bootstrap() -> should create fresh conversation
The leak happens in step 2. Let me check what happens in bootstrap() for a cron session:
const conversation = await this.conversationStore.getOrCreateConversation(params.sessionId, {
sessionKey: params.sessionKey,
});
And getOrCreateConversation:
async getOrCreateConversation(
sessionId: string,
titleOrOpts?: string | { title?: string; sessionKey?: string },
): Promise<ConversationRecord> {
...
const normalizedSessionKey = opts.sessionKey?.trim();
if (normalizedSessionKey) {
const byKey = await this.getConversationBySessionKey(normalizedSessionKey);
if (byKey) {
if (byKey.sessionId !== sessionId) {
this.db
.prepare(
`UPDATE conversations SET session_id = ?, updated_at = datetime('now') WHERE conversation_id = ?`,
)
.run(sessionId, byKey.conversationId);
byKey.sessionId = sessionId;
}
return byKey;
}
}
...
}
So getOrCreateConversation first checks if there's an existing conversation with the same sessionKey. If so, it updates the sessionId and returns the existing conversation. This is the leak!
For cron sessions, when Run 2 calls getOrCreateConversation with the new sessionId but the same sessionKey, it finds the conversation from Run 1 (if it wasn't archived) and reuses it.
But with our fix, handleSessionEnd will archive the conversation and not create a replacement. So in Run 2, getConversationBySessionKey will return null (since the conversation is archived), and a fresh conversation will be created.
This is correct!
But wait, there's a subtlety. getOrCreateConversation also checks by sessionId:
const existing = await this.getActiveConversationBySessionId(sessionId);
if (existing) {
...
}
So if the new sessionId has an existing conversation, it returns that. But for cron sessions, the new sessionId is different from the old one, so this check won't find anything.
And the sessionKey check is the one that finds the leaked conversation. But with our fix, the sessionKey's conversation is archived, so it won't be found.
OK, I'm confident the fix is correct. Let me implement it now.
Hmm, but I realize I should also check what happens when shouldIgnoreSession returns true in other methods like bootstrap():
async bootstrap(params: {
sessionId: string;
sessionFile: string;
sessionKey?: string;
}): Promise<BootstrapResult> {
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return {
bootstrapped: false,
importedMessages: 0,
reason: "session excluded by pattern",
};
}
So for cron sessions, bootstrap() returns early without doing anything. This means cron sessions are completely ignored during bootstrap.
But wait, this means cron sessions NEVER get their context managed! They're completely ignored in bootstrap, afterTurn, etc.
But the issue says "compaction within the current run still works". This means cron sessions DO have context during their run, but it shouldn't leak to the next run.
Hmm, I'm confused. Let me re-read the issue:
"Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context. Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged."
So:
- Prior runs remain archived - this means cron sessions ARE being archived (they should be)
- Compaction within the current run still works - this means cron sessions have context during their run
- Ordinary non-cron session continuity is unchanged - non-cron sessions should continue to work
But looking at the code, cron sessions are in ignoredSessionPatterns, which means they're completely ignored. So how does "compaction within the current run still work"?
Let me look at the test for cron sessions:
const ignoredSessionKey = "agent:main:cron:nightly:run:run-123";
...
ignoreSessionPatterns: ["agent:*:cron:**"],
And looking at the test at line 5105:
await engine.afterTurn({
sessionId: "auto-rotate-ignored-session",
sessionKey: "agent:main:cron:nightly",
...
});
And the expected log:
expect(autoRotateLogs).toEqual(
expect.arrayContaining([
expect.stringContaining("reason=session-excluded"),
...
]),
);
So the test expects cron sessions to be excluded from auto-rotate. But the issue says "compaction within the current run still works".
I think I'm misunderstanding the issue. Let me re-read:
"Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
I think "isolated" means that cron sessions should have their own isolated context, not that they're completely ignored.
Looking at the code more carefully, I see that cron sessions ARE ignored (skipped) in bootstrap and afterTurn. But they might still be affected by other mechanisms like handleSessionEnd.
Actually, wait. Let me re-read the handleSessionEnd code:
if (this.shouldIgnoreSession({ sessionId: params.sessionId, sessionKey: params.sessionKey })) {
return;
}
This means handleSessionEnd is also skipped for cron sessions. So cron sessions are completely ignored in handleSessionEnd too.
But the issue says "Prior runs remain archived". If cron sessions are completely ignored, they're never archived. So the issue must be about something else.
Let me re-think this. The issue is about "isolated cron sessions that reuse a stable session key". The key insight is "reuse a stable session key".
If a cron session has a stable session key and the session_end event is handled (not skipped), then:
- The conversation is archived
- A replacement conversation is created with the same session key
Then, when the next cron run starts:
- bootstrap() is called with the same session key
shouldIgnoreSession returns true, so bootstrap() returns early
- The replacement conversation from step 2 of the previous run is still active
- But since bootstrap() returns early, nothing happens
Wait, but if bootstrap() returns early, how does the cron session get its context? It doesn't. Cron sessions are completely ignored.
So the issue must be about something else. Let me look at the context more carefully.
Actually, I think I need to understand what "context" means in this context. The LCM context is the conversation stored in the database. When a cron session runs:
- bootstrap() is called, which is skipped (ignored)
- Messages are ingested (I assume this happens at the runtime level, not in LCM)
- afterTurn() is called, which is skipped (ignored)
- session_end() is called, which is skipped (ignored)
So cron sessions are completely ignored by LCM. Their context (stored in the conversation table) is never touched.
But the issue says "compaction within the current run still works". How does compaction work for cron sessions if they're ignored?
Actually, I think the issue might be about a different type of session. Let me look at the test cases again.
Looking at the test, cron sessions are ignored in ignoreSessionPatterns. But there might be other session patterns that are not cron sessions but still need isolation.
Actually, let me re-read the issue title: "Isolated cron runs leak context when they reuse a stable session key"
I think "cron runs" refers to a specific type of session. And "leak context" means that the context from one run is being reused by the next run.
Let me look at what happens when a session_end event is NOT skipped for cron sessions. If handleSessionEnd is called for cron sessions:
- The current conversation is archived
- A replacement conversation is created with the same session key
Then, when the next cron run starts:
- bootstrap() is called, which is skipped (ignored)
- The replacement conversation from step 2 of the previous run is still active
- But since bootstrap() returns early, nothing happens
So the leak is: the replacement conversation is created, but it's not used for anything. It just sits there, active, taking up space.
But the issue says "leak context". This implies that the context from the replacement conversation is somehow being used by the next cron run.
Hmm, but bootstrap() returns early for cron sessions. So the next cron run doesn't use the replacement conversation.
Unless... the context is accessed through a different mechanism, not through bootstrap().
Let me look at the tools (lcm_grep, lcm_describe, etc.) to see how they access context:
api.registerTool(
(ctx) => createLcmGrepTool({ deps, getLcm: shared.waitForEngine, sessionKey: ctx.sessionKey }),
{ name: "lcm_grep" },
);
The tools receive sessionKey. And they use the LCM engine to query context. Let me look at how the tools use the sessionKey:
<tool_call>
<function=bash_terminal>
<parameter=command>
grep -n "sessionKey" /lossless-claw/src/tools/lcm-grep-tool.ts | head -20
</tool_call>