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.
Interface
No new public interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /lossless-claw, current file: none) bash-$
Assistant
Let me start by understanding the repository structure and the issue at hand. The issue is about isolated cron runs leaking context when they reuse a stable session key. This seems to be about a session/context management system where different isolated cron runtime sessions shouldn't share active LCM (Lossless Context Management?) context.
Let me explore the repository first.
Assistant
Let me look at the repository more carefully.
Assistant
This appears to be a TypeScript/JavaScript project. Let me explore the source code structure.
Assistant
This appears to be an LCM (Lossless Context Management) project. Let me explore more of the structure and find relevant files about sessions and cron.
Assistant
Let me explore the repository structure one command at a time.
Assistant
Let me now look at the AGENTS.md for guidance and search for files related to sessions, cron, and context.
Assistant
Let me look at the session-pattern.ts file, the engine.ts file, and also search for anything related to "cron", "session key", and "isolated".
Assistant
Let me search for more context about cron and sessions.
Assistant
Let me look at the engine.ts file to understand how sessions and context work.
Assistant
Let me search for more specific terms related to the issue.
Assistant
The file is large. Let me search for cron-related code and the "isolated" concept, and how the session key is used. The issue is about "isolated cron runs leak context when they reuse a stable session key."
Let me look at the cron-related files.
Assistant
Let me look at the cron-related files and the concept of "isolated" sessions:
Assistant
Now let me search for "isolated" and "stable" in the codebase:
Assistant
Let me look at the openclaw-bridge.ts file to understand the "contextMode" concept.
Assistant
Now I see that there's a contextMode?: "isolated" | "fork" concept in the prepareSubagentSpawn method. Let me look at the engine.ts file for how isolated sessions are handled, especially around prepareSubagentSpawn and the bootstrap/assemble methods.
Let me search for how "isolated" mode is handled in the engine.ts.
Assistant
Let me look at how contextMode is used in the engine, especially in the prepareSubagentSpawn and also how bootstrap handles it.
Assistant
Let me search for how conversations are managed by session keys, especially the "active" conversation concept:
Assistant
Let me look at the conversation store more closely:
Assistant
Now I need to look at the engine.ts file to understand how bootstrap and session management works. Specifically, I need to understand how context is managed when different sessions with the same session key are used. Let me search for more context around the bootstrap and assemble methods:
Assistant
Let me look at the bootstrap method and prepareSubagentSpawn in detail.
Assistant
Let me look at the bootstrap method to understand how sessions and context are managed:
Assistant
Let me look at the getOrCreateConversation logic and the lifecycle rollover mechanisms:
Assistant
Let me look at the getOrCreateConversation method:
Assistant
Now let me search for how handleSessionEnd works and how cron sessions are specifically handled:
Assistant
Let me look at the handleSessionEnd method:
Assistant
Now let me look at the plugin/index.ts where cron sessions are mentioned:
Assistant
Let me search the test files for references to cron sessions:
Assistant
Let me look at the engine test to understand how cron sessions work:
Assistant
Let me look at the engine test for how cron sessions work:
Assistant
Let me search for how the bootstrap handles the case where a stable session key is reused but the session is different (i.e., different runtime sessions). Let me look at how the bootstrap handles the case where a stable session key is reused but the session is different (i.e., different runtime sessions).
Assistant
Let me look at the specific area where the bootstrap deals with session file changes and session key rollovers:
Assistant
Now let me search for how "isolated" cron runs work specifically in the tests:
Assistant
Let me search for "isolated" in the tests:
Assistant
Let me look at the plugin index to understand how lifecycle hooks are registered:
Assistant
Let me look at the session end lifecycle event to understand when session_end fires:
Assistant
Let me look at the SessionEndLifecycleEvent:
Assistant
Let me now look at the assemble method and how it handles session key lookup:
Assistant
Let me look at the getConversationForSession method to understand how it handles session key lookups:
Assistant
Let me look at the test files for engine tests related to this:
Assistant
Let me look at the "ConversationStore session reuse" test:
Assistant
Let me look at the test around line 5090 for the cron-related test:
Assistant
Let me look at how session_end works and when it's called, and what happens in different scenarios. Let me also look at the spec/test files:
Assistant
Let me look at the session_end lifecycle tests:
Assistant
Let me look at the git history to understand recent changes related to this issue:
Assistant
Let me look at commit 9cd6630 which mentions "fail closed on ambiguous session rollover":
Assistant
Let me look at the full diff for that commit:
Assistant
Assistant
Let me look at line 6418:
Assistant
Let me look at the afterTurn method to see the full flow:
Assistant
Let me look at the afterTurn method.
Assistant
Let me look at the reconcileSessionTail method to understand the full context:
Assistant
Let me look at the reconcileTranscriptTailForAfterTurn method:
Assistant
Let me look at reconcileTranscriptTailForAfterTurnInSessionQueue:
Assistant
Now let me understand the full picture by looking at where rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is called and the bootstrap flow:
Assistant
Now I have a clear understanding of the issue. Let me trace through the key scenario:
Cron run 1: sessionKey="cron", sessionId="run-1", sessionFile="file1.jsonl" → bootstrap creates conversation
Cron run 2: sessionKey="cron", sessionId="run-2", sessionFile="file2.jsonl"
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing finds old conversation, different sessionId, different file, but old file still exists → returns false (no rotation)
If no tail anchor → fails closed (returns early, no bootstrap)
If tail anchor exists → falls through and the old conversation gets reused
The issue is when the old file exists and there IS a tail anchor match (or the same file path is reused) - the old context leaks. And even when it fails closed, the old conversation stays active (not archived), so it persists across runs.
Let me look at the exact bootstrap flow for the ambiguous rollover case:
Assistant
Now let me look at the afterTurn path for the same check:
Assistant
Now let me look at the assemble path:
Assistant
Now I have a complete understanding of the issue. Let me run the existing tests first to establish a baseline:
Assistant
Now I have a complete understanding of the issue and all tests pass. Let me plan the fix.
The issue: When cron runs reuse a stable session key, the rotateStaleSessionKeyConversationIfTrackedTranscriptMissing method correctly detects that the session ID is different and the session file path is different, but then fails to rotate because the old tracked transcript file still exists on disk. Then findAmbiguousSessionKeyRuntimeRollover detects the ambiguity and "fails closed" (returns early without archiving), but crucially the old conversation is NOT archived - it stays active. This means:
The old conversation stays active (not archived)
The new cron run can't use LCM at all (bootstrap/assemble/afterTurn all fail closed)
Prior runs are never archived
The fix should be: in rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, when the session file path is different AND the session ID is different, always rotate (archive old conversation, create replacement), regardless of whether the old file exists on disk. This matches the pattern of what already happens when the old file is missing.
Let me now implement the fix:
Assistant
Now I'll implement the fix. The key change is in rotateStaleSessionKeyConversationIfTrackedTranscriptMissing - removing the stat check that prevents rotation when the old file still exists on disk:
Assistant
Now I'll make the fix - removing the stat check that prevents rotation when the old file still exists on disk:
Assistant
Let me use the edit command instead:
Assistant
Now I can see the full code. Let me remove the stat check that prevents rotation when the old file exists.
Assistant
I see there's a duplicate this.deps.log.warn( line. Let me fix that:
Assistant
I see there's still a duplicate line. Let me fix it properly:
Assistant
Good, the code now looks correct. Let me verify the full method:
Assistant
Good, the method looks correct. Now let me check if the imports are still needed (stat and isMissingFileError are still used elsewhere):
Assistant
Good, isMissingFileError is still used elsewhere. Let me also check if stat is still used:
Assistant
Good, stat is still used elsewhere. Now let me run the tests to make sure the fix doesn't break anything:
Assistant
Assistant
Let me look at the full test output to understand all 6 failures:
Assistant
Let me look at the first 3 failing tests more carefully:
Assistant
Let me look at the first 3 failing tests to understand if my fix broke something important:
Assistant
Now I see the problem! The first test shows that when the old file EXISTS and the new file contains the OLD content (tail anchor), the conversation should be PRESERVED. My fix is too aggressive - it archives even when the old file still exists.
The correct approach is: keep the stat check (preserve existing behavior when old file exists), but modify the findAmbiguousSessionKeyRuntimeRollover handling to archive instead of fail closed when no tail anchor is found.
Let me revert my change and implement the correct fix:
Assistant
Good, I've reverted the change. Now let me implement the correct fix. The key insight is: when the old file exists and no tail anchor is found, archive the old conversation instead of failing closed. Let me look at the bootstrap ambiguous rollover handling:
Assistant
Now let me look at the applySessionReplacement method to understand how to call it:
Assistant
Now I understand the full picture. The fix should: when findAmbiguousSessionKeyRuntimeRollover detects ambiguity and no tail anchor is found, archive the old conversation and create a replacement instead of failing closed. Let me implement this:
Assistant
Now I'll implement the fix. Instead of returning early when no tail anchor is found, archive the old conversation and create a fresh replacement:
Assistant
Good, the bootstrap fix is in place. Now let me apply the same fix to the afterTurn path:
Assistant
Now let me modify the afterTurn path. Let me see the full return block:
Assistant
Now let me modify the afterTurn path:
Assistant
I see there's an extra closing brace. Let me fix it:
Assistant
Good. Now let me fix the assemble path. Let me look at it:
Assistant
Let me look at the full assemble ambiguous rollover handling:
Assistant
Let me modify the assemble path to archive the old conversation:
Assistant
I see there's a duplicate if (ambiguousRollover) { line. Let me fix that:
Assistant
Now let me run the tests to see if the fix works:
Assistant
Good progress! We're down to3 failing tests - all3 are the "ambiguous rollover" tests that expected "fail closed" behavior. Let me check what they expect:
Assistant
Good! The remaining 3 failures are the "fail closed on ambiguous runtime rollover" tests that my fix intentionally changes. According to the instructions: "If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account."
Let me verify all other tests pass:
Assistant
Only 3 tests fail - all are the "fail closed on ambiguous runtime rollover" tests that my fix intentionally changes. Let me create a test script to verify the fix works correctly:
Assistant
Let me now verify the changes I made by looking at the diff:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Now I understand the issue better. Let me look at the test in the engine.test.ts to understand how the "fail closed" logic works and what the problem is.
The issue is about "isolated cron runs" that reuse a stable session key. Looking at the code:
When a cron run is in ignoreSessionPatterns, it's completely ignored.
When a cron run is NOT in ignoreSessionPatterns, LCM processes it like any other session.
The problem: If cron runs are NOT in ignore patterns, and each cron run has a DIFFERENT session ID but the SAME session key, then:
The first cron run creates a conversation for that session key
The second cron run (with a different session ID) tries to bootstrap
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing checks if the old transcript is missing
If the old transcript IS missing (because cron runs create different files), it archives and creates a replacement
If the old transcript is NOT missing, findAmbiguousSessionKeyRuntimeRollover checks for ambiguity- If ambiguous, it "fails closed" (doesn't bootstrap/assemble)
But the issue says context is "leaking". Let me look more carefully at the code path where context could leak.
Wait, let me re-read the issue more carefully: "Isolated cron runs leak context when they reuse a stable session key"
The key word is "isolated" - this means the cron sessions are configured to be isolated (maybe through ignoreSessionPatterns), but there's still a leak somehow.
Actually, wait. Let me reconsider. The issue says "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:
Isolated cron runtime sessions should NOT share active LCM context
Prior runs should remain archived
Compaction within the current run should still work
Ordinary non-cron session continuity is unchanged
This sounds like the cron sessions are being tracked by LCM (not ignored), but they should be isolated from each other. The problem is that when they reuse the same session key, they share context.
Looking at the code:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing - rotates only when the old file is missing
findAmbiguousSessionKeyRuntimeRollover - detects and fails closed when old file exists
The issue could be: what if the cron session key is the same but the session file is the same path? Then neither guard would fire, and the new cron run would attach to the old conversation.
Wait, let me check findAmbiguousSessionKeyRuntimeRollover:
So if the session file is the same path, it's NOT considered ambiguous. This makes sense for normal sessions where the file path is stable, but for cron runs where each run should be isolated, this could cause a leak.
Let me think about the cron scenario:
Cron run 1: sessionId="run1", sessionKey="agent:main:cron:nightly", sessionFile="/path/to/cron.jsonl"
Cron run 2: sessionId="run2", sessionKey="agent:main:cron:nightly", sessionFile="/path/to/cron.jsonl" (same path)
In this case:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing: trackedSessionFile === params.sessionFile, so transcriptRotated=false → returns false
Then getOrCreateConversation finds the existing conversation by session key, updates the sessionId, and the new cron run attaches to the old conversation!
This is the leak! When cron runs reuse the same session key AND the same session file path, they share the active conversation.
But wait, there's also the checkpointIsPastTranscriptEof check that handles "same-path-shrink". If the file is truncated between runs, this would detect it. But if the file is overwritten with similar-size content, it might not be detected.
Actually, let me look at the bootstrap flow more carefully. After rotateStaleSessionKeyConversationIfTrackedTranscriptMissing and findAmbiguousSessionKeyRuntimeRollover:
This uses getOrCreateConversation, which looks up by session key first:
code
if (normalizedSessionKey) {
const byKey = await this.getConversationBySessionKey(normalizedSessionKey);
if (byKey) {
if (byKey.sessionId !== sessionId) {
// Update sessionId }
return byKey;
}
}
So it returns the existing conversation, which means the new cron run is using the same conversation.
Then the bootstrap proceeds to reconcile the session tail, potentially importing messages from the new session file into the existing conversation.
The problem is clear: getOrCreateConversation reuses the conversation by session key, which causes the leak.
Now, the fix should ensure that for "isolated" cron sessions, the old conversation is archived and a fresh one is created. But we need a way to identify which sessions are "isolated cron" sessions.
Looking at the issue description: "Different isolated cron runtime sessions" - this suggests that cron sessions are inherently isolated.
Looking at the ignore pattern configuration: ["agent:*:cron:**"] - cron sessions are typically in the ignore patterns. But the issue says they're "isolated", not "ignored".
Wait, I think "isolated" means the session is configured in some way to be treated as isolated. Let me look for any "isolated" flag in the session configuration.
Actually, I think the issue might be about how the rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function works. Let me re-read the code:
If the file shrank, it sets transcriptEpochRotated = true. But then it continues with the same conversation. The reconcile logic with allowNoAnchorImport: true would import the new messages.
So the fix should be: when the session key is stable but the session ID changes (indicating a new cron run), and the conversation is active, we should archive the old conversation and create a fresh one.
But this would break normal session continuity! The key difference between normal sessions and cron runs is that cron runs should be isolated.
How do we know if a session is a "cron" session? By the session key pattern. But the ignore patterns are already used for that.
Wait, I think the issue might be more subtle. Let me re-read the issue again: "Isolated cron runs leak context when they reuse a stable session key"
"Isolated cron runs" - these are cron runs that are supposed to be isolated. The issue is that they're NOT isolated when they reuse a stable session key.
Looking at the test in the engine.test.ts at line 434:
This suggests that cron sessions are typically ignored. But the issue is about when they're NOT ignored (or when they should be isolated but aren't).
Actually, I think I need to understand the full scenario better. Let me look at how cron sessions are typically configured.
From the test config:
code
ignoreSessionPatterns: ["agent:*:cron:**"]
This means sessions matching agent:*:cron:** are ignored. But the issue is about "isolated" cron runs, which might be different from "ignored" ones.
Wait, I think I finally understand. The issue is about the scenario where:
A cron session key (like agent:main:cron:nightly) is NOT in the ignore patterns
The cron runtime creates multiple runs with the same session key but different session IDs
Each run should be isolated (new conversation)
But the engine reuses the conversation by session key, causing context leakage
The fix should be: when a new session starts with a different session ID but the same session key, and the tracked session file has changed (or the session ID is different), the engine should archive the old conversation and create a fresh one for the new session.
But this needs to be done carefully to not break normal session continuity. The key insight is that for normal sessions, the session_end event fires before a new session starts with the same key. For cron runs, the session_end event might not fire.
Actually, I think the simplest fix is to modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to also handle the case where the session file is the same but the session ID is different AND the file has changed (different size/mtime).
Or better yet, the fix should be: when a new session starts with a different session ID and the same session key, and the old session file still exists (or is the same), we should check if the session file has changed significantly. If it has, rotate the conversation.
But I think the real issue is simpler than I'm making it. Let me look at the scenario more carefully:
For cron runs, each run has:
Different session ID (e.g., "run1", "run2")
Same session key (e.g., "agent:main:cron:nightly")
Different session file (e.g., "/tmp/cron-run1.jsonl", "/tmp/cron-run2.jsonl")
The session files are different, so rotateStaleSessionKeyConversationIfTrackedTranscriptMissing should detect the rotation. But it only rotates when the old file is MISSING. If the old file exists, it doesn't rotate.
For findAmbiguousSessionKeyRuntimeRollover, it detects the ambiguity and "fails closed" (refuses to bootstrap/assemble). This prevents the leak but also prevents the new cron run from using LCM at all.
The issue says: "Prior runs remain archived, compaction within the current run still works"
This suggests that the fix should:
Archive the prior conversation (so it's not active)
Create a fresh conversation for the new cron run
Allow compaction to work within the new run
Currently, when the old file exists and there's ambiguity, the engine fails closed (refuses to process). The fix should instead archive the old conversation and create a fresh one.
Let me look at the findAmbiguousSessionKeyRuntimeRollover function again. When it detects ambiguity (new session ID, same key, different file that exists), it should archive the old conversation and create a replacement, similar to what rotateStaleSessionKeyConversationIfTrackedTranscriptMissing does when the old file is missing.
Actually, I think the fix should be in rotateStaleSessionKeyConversationIfTrackedTranscriptMissing. Instead of bailing when the old file still exists, it should also rotate in that case.
Wait, but the function is called "IfTrackedTranscriptMissing" - it's specifically designed to only act when the file is missing. If we change its behavior, we should rename it or create a new function.
Let me think about the cleanest fix:
In rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, add a new case: when the session ID is different and the session file is different, archive the old conversation and create a replacement, regardless of whether the old file exists.
OR
In the bootstrap flow, after rotateStaleSessionKeyConversationIfTrackedTranscriptMissing and before findAmbiguousSessionKeyRuntimeRollover, add logic to detect the cron scenario and handle it.
I think option 1 is cleaner. Let me modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to also rotate when:
The session ID is different (new runtime)
The session file is different (new transcript)
The old conversation is active
This would cover both:
Old file missing (existing behavior)
Old file exists but new session is different (new behavior for cron runs)
The key concern is: will this break normal session continuity?
For normal sessions:
When the host fires session_end, the conversation is already archived- When the host doesn't fire session_end (e.g., restart), the session ID might be different
But the session file is typically the same path for normal sessions
Wait, the session file path is typically the same for normal sessions! So if we check trackedSessionFile !== params.sessionFile, we won't trigger for normal sessions (same file path) but will trigger for cron runs (different file path).
That's the key insight! The fix should be: when the session file path is different AND the old file still exists, rotate the conversation. This handles the cron case (different files) without breaking normal sessions (same file).
But wait, the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing already checks trackedSessionFile !== params.sessionFile and returns false when they're equal. The issue is that when they're different AND the old file exists, it doesn't rotate.
So the fix is: remove the check await stat(trackedSessionFile); return false; (or change the logic) so that when the session file is different, we always rotate regardless of whether the old file exists.
Let me code this fix now.
Actually, looking at the test for the "fail closed" behavior, the expected behavior when the old file exists is to refuse. But the issue says we should archive and replace. So we need to change the behavior.
Let me also think about the findAmbiguousSessionKeyRuntimeRollover function. If we fix rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to always rotate when the file is different, then findAmbiguousSessionKeyRuntimeRollover would never be reached in the bootstrap flow (because the rotation would have already happened).
But findAmbiguousSessionKeyRuntimeRollover is also used in assemble and afterTurn. So we need to ensure consistency.
Actually, I think the cleanest fix is:
Modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to also rotate when the session file is different and the old file exists (not just when it's missing)
This way, the conversation is always archived and replaced when the session key is reused with a different file
findAmbiguousSessionKeyRuntimeRollover would then never trigger (because the rotation already happened)
But I need to be careful about the createReplacement parameter. In assemble, it's called with createReplacement: false. So the rotation would archive but not create a replacement. This means assemble would find no active conversation and fall back to safeFallback. That's correct for assemble.
For bootstrap, it's called with the default createReplacement: true. So it would archive and create a replacement. Then getOrCreateConversation would find the new replacement conversation. That's correct for bootstrap.
Wait, but in the current flow for bootstrap, rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is called before getOrCreateConversation. If it archives and creates a replacement, then getOrCreateConversation would find the new replacement. But the replacement has the same session key, so it would be returned. The bootstrap would then import messages into the new conversation. That's correct.
Let me also think about afterTurn. After the fix, when afterTurn runs for the new cron run:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing would find no active conversation (because it was already archived and replaced during bootstrap)
It would return false (no rotation needed)
afterTurn would proceed normally with the new conversation
OK, I think the fix is:
In rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, remove the stat(trackedSessionFile) check. When the session file is different, always rotate.
Wait, but the function is designed to only rotate when the file is missing. If we remove the stat check, it would rotate even when the file exists. But the purpose of the stat check is to distinguish between:
File was deleted (definitely a rotation) → archive and replace
File still exists (might be the same session) → don't rotate
The issue is that for cron runs, the file still exists but it's a different session. So we need to handle this case.
Actually, I think the real issue is that the function name and design are too narrow. It only handles the case where the file is missing, but we need to handle the case where the file is different AND the session ID is different.
Let me think about what conditions should trigger a rotation:
Session key matches an existing active conversation
Session ID is different (new runtime)
Session file is different (new transcript)
Either: old file is missing, OR old file exists (doesn't matter)
Condition 3 is the key. When the session file is different, it's a new transcript, so the old conversation should be archived.
But wait, what about the case where the session file is the same path? For normal sessions, the session file is typically the same path. In that case, we DON'T want to rotate.
So the conditions should be:
Session key matches an existing active conversation
Session ID is different (new runtime)
Session file is different (new transcript path)
The old conversation has a tracked session file
These conditions are already checked in rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, except for the stat check that prevents rotation when the old file exists.
So the fix is: remove the stat check. When conditions 1-4 are met, always rotate.
But this might have side effects. Let me think...
If we always rotate when conditions 1-4 are met:
Normal sessions with the same session file path → condition 3 fails → no rotation (correct)
Cron runs with different session file paths → all conditions met → rotation (correct)
Sessions where the old file was deleted → all conditions met → rotation (existing behavior)
Sessions where the old file was moved → all conditions met → rotation (correct)
This seems right. The only concern is: what if a normal session changes its file path? In that case, we would rotate, which might not be desired. But the issue says "ordinary non-cron session continuity is unchanged", and normal sessions typically don't change their file path.
Wait, there's also the case where the session file is rotated (e.g., when it gets too large). In that case, the file path changes but it's still the same session. Would this trigger a rotation?
Looking at the auto-rotate logic, when a file is rotated:
The old file is renamed/removed
A new file is created at the same path
Or a new file is created at a different path
If the new file is at the same path, condition 3 fails → no rotation. If it's at a different path, condition 3 is met → rotation.
But for auto-rotated sessions, the session ID doesn't change (condition 2 fails). So the rotation wouldn't trigger.
Actually wait, let me re-read the condition:
code
if (!activeByKey || activeByKey.sessionId === params.sessionId) {
return false;
}
If the session ID is the same, we return false (no rotation). So for auto-rotated sessions where the session ID doesn't change, we wouldn't rotate.
For cron runs where the session ID changes, we would rotate. That's correct.
OK, I'm now confident the fix is: remove the stat check in rotateStaleSessionKeyConversationIfTrackedTranscriptMissing (or rather, don't bail when the file exists).
But wait, there's another consideration. The findAmbiguousSessionKeyRuntimeRollover function is also used in assemble and afterTurn. If we fix rotateStaleSessionKeyConversationIfTrackedTranscriptMissing but not findAmbiguousSessionKeyRuntimeRollover, there might be inconsistency.
Actually, findAmbiguousSessionKeyRuntimeRollover is only reached if rotateStaleSessionKeyConversationIfTrackedTranscriptMissing doesn't handle the case. With the fix, rotateStaleSessionKeyConversationIfTrackedTranscriptMissing would handle the case (rotate), so findAmbiguousSessionKeyRuntimeRollover would never be reached for this scenario.
But to be safe, I should also update findAmbiguousSessionKeyRuntimeRollover to be consistent.
Actually, I think the simplest and cleanest fix is:
In rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, remove the stat(trackedSessionFile) check
When the session file is different and the old conversation has a tracked file, always rotate3. The findAmbiguousSessionKeyRuntimeRollover function becomes unnecessary for this case (but we should keep it for other cases)
Wait, but I need to also think about what happens when the old file exists and we try to rotate. The rotation archives the old conversation and creates a replacement. This is fine regardless of whether the old file exists or not.
Let me also consider: what if the old file exists AND the new file contains the tail anchor? In that case, the new session is a continuation of the old one. But we're rotating anyway, which means we lose the continuity.
Hmm, but the issue says "isolated cron runs" - they SHOULD be isolated. So even if the new file contains the tail anchor, we should rotate.
Actually, I think there's a subtlety I'm missing. The findAmbiguousSessionKeyRuntimeRollover function has a transcriptContainsCurrentConversationTailAnchor check. If the new file contains the tail anchor, it's treated as a continuation. If not, it's treated as ambiguity.
For cron runs, the new file would NOT contain the tail anchor (because it's a fresh run). So findAmbiguousSessionKeyRuntimeRollover would detect ambiguity and fail closed.
But the issue says context is "leaking", not that it's "failing closed". So there must be a case where context leaks despite the fail-closed logic.
Let me think about this more carefully. When does the fail-closed logic NOT trigger?
When rotateStaleSessionKeyConversationIfTrackedTranscriptMissing successfully rotates (old file missing)
When findAmbiguousSessionKeyRuntimeRollover returns null (no ambiguity detected)
When does findAmbiguousSessionKeyRuntimeRollover return null?
No session key
No active conversation by session key
Same session ID
No tracked session file
Same session file path
Old file missing (stat fails)
The case where the session file path is the same is the key. If the cron runs use the same session file path, findAmbiguousSessionKeyRuntimeRollover returns null, and the engine proceeds to use the old conversation.
But wait, if the session file path is the same and the session ID is different, what happens?
getOrCreateConversation: finds existing conversation by session key → returns it
Bootstrap proceeds with the old conversation
But the file content has changed (it's a new cron run). The bootstrap checkpoint logic would detect:
If the file shrank: checkpointIsPastTranscriptEof → transcriptEpochRotated = true
If the file grew: append-only fast path might succeed (if the tail anchor matches)
If the file is completely different: reconcile would try to import new messages
In the case where the file shrank:
transcriptEpochRotated = true with reason "same-path-shrink"
allowNoAnchorImport: true in reconcile
New messages are imported into the old conversation
Old messages are still in the conversation
CONTEXT LEAK!
In the case where the file grew:
Append-only fast path might succeed
New messages are appended to the old conversation
Old messages are still in the conversation
CONTEXT LEAK!
In the case where the file is completely different:
Reconcile might fail to find anchors
If allowNoAnchorImport is true (due to transcriptEpochRotated), new messages are imported
Old messages are still in the conversation
CONTEXT LEAK!
So the context leak happens when:
The session file path is the same (or the old file exists)
The session ID is different (new cron run)
The old conversation is still active
The engine uses the old conversation for the new run
The fix should be: when the session ID is different and the session key matches an existing active conversation, rotate the conversation, regardless of whether the session file is the same or different.
But wait, this would break normal sessions where the session ID changes (e.g., after a restart). The issue says "ordinary non-cron session continuity is unchanged".
The key difference is: for normal sessions, the host fires session_end before starting a new session. For cron runs, the host might not fire session_end.
But the engine can't distinguish between these cases. It just sees a new session ID with the same session key.
Hmm, I think the fix needs to be more nuanced. Let me re-read the issue one more time: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
"Isolated cron runtime sessions" - these are sessions that are configured to be isolated. The configuration might be through the session key pattern (e.g., agent:*:cron:*).
Wait, but the issue says they should NOT share context. If they're in the ignore patterns, they're completely ignored (no LCM processing). The issue seems to be about sessions that ARE processed by LCM but should be isolated.
Actually, I think the issue is about a specific scenario:
Cron sessions are NOT in the ignore patterns
Each cron run creates a new session with a stable session key
The engine should treat each cron run as a fresh session (archive old, create new)
But currently, the engine reuses the old conversation
The fix should be: when a new session starts with a different session ID and the same session key, and the old conversation is still active, archive the old conversation and create a fresh one.
But this would break normal session continuity where the session ID changes but the conversation should continue.
Hmm, I think the issue is specifically about the rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function not handling the case where the old file exists. Let me look at the function signature again:
The name says "IfTrackedTranscriptMissing" - it only handles the case where the file is missing. The issue is that we need to also handle the case where the file exists but the session is different.
I think the fix should be to rename the function and extend its behavior to also handle the case where the old file exists. Or create a new function that handles the "file exists" case.
Let me look at the code one more time to understand the full picture.
Actually, I just realized something. The findAmbiguousSessionKeyRuntimeRollover function is specifically designed to handle the case where the old file exists. It "fails closed" to prevent context leakage. The issue is that this fail-closed behavior also prevents the new cron run from using LCM at all.
The desired behavior (according to the issue) is:
Archive the old conversation
Create a fresh conversation for the new cron run
Allow the new cron run to use LCM normally
So the fix should be: instead of "failing closed" when ambiguity is detected, we should "archive and replace" (similar to what rotateStaleSessionKeyConversationIfTrackedTranscriptMissing does when the file is missing).
This means: in findAmbiguousSessionKeyRuntimeRollover (or in the code that handles its result), when ambiguity is detected, archive the old conversation and create a replacement.
But wait, the findAmbiguousSessionKeyRuntimeRollover function is used in three places:
Bootstrap - after rotateStaleSessionKeyConversationIfTrackedTranscriptMissing
Assemble - after rotateStaleSessionKeyConversationIfTrackedTranscriptMissing3. AfterTurn - inside reconcileSessionTail
For all three, if the function detects ambiguity, the current behavior is to fail closed. The fix should change this to archive and replace.
But the function returns a record, and the callers decide what to do. So the fix should be in the callers, not in the function itself.
The fix: instead of failing closed, call applySessionReplacement to archive and create a replacement.
Assemble:
code
if (ambiguousRollover) {
this.logAmbiguousSessionKeyRuntimeRollover({...});
return safeFallback();
}
The fix: instead of returning safeFallback, call rotateStaleSessionKeyConversationIfTrackedTranscriptMissing with createReplacement: false (archive only).
Actually, wait. In assemble, rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is already called before findAmbiguousSessionKeyRuntimeRollover. If we fix rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to handle the "file exists" case, then findAmbiguousSessionKeyRuntimeRollover would never be reached in assemble.
But in bootstrap, rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is also called before findAmbiguousSessionKeyRuntimeRollover. Same logic applies.
So the simplest fix is: modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to also handle the case where the old file exists. This means removing the stat check.
Let me code this fix.
Wait, I also need to think about the afterTurn case. In afterTurn, the ambiguous rollover check is inside reconcileSessionTail. Let me look at that code.
Actually, looking at the diff from the commit 9cd6630, the afterTurn code was added:
This is inside reconcileSessionTail, which is called from bootstrap. So if we fix rotateStaleSessionKeyConversationIfTrackedTranscriptMissing in bootstrap, the reconcile would not reach this code path (because the conversation would have been rotated already).
OK, I think the fix is clear now:
Modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to remove the stat(trackedSessionFile) check
When conditions 1-4 are met (session key matches, different session ID, different session file, tracked file exists), always rotate
This handles both the "old file missing" and "old file exists" cases
The findAmbiguousSessionKeyRuntimeRollover function would still be there for safety, but it would rarely be reached
Let me also think about edge cases:
What if the session file path is the same but the content is different? Conditions 1-3 are met but condition 3 (different session file) is not met. In this case, we don't rotate. But the checkpointIsPastTranscriptEof check would detect the shrink.
What if the session ID is the same? Condition 2 fails, so we don't rotate. This is correct for normal sessions.
Wait, there's still the case where the session file path is the same. In that case, we don't rotate. But for cron runs with the same session file path, we should rotate.
Hmm, but the issue says "reuse a stable session key" - not "reuse a stable session file path". The session file path is typically different for each cron run (because each run has a unique file).
OK, I think the fix is sufficient for the described scenario. Let me also think about whether we need to change findAmbiguousSessionKeyRuntimeRollover.
If we fix rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, then:
In bootstrap: rotation happens before findAmbiguousSessionKeyRuntimeRollover is called
In assemble: rotation happens before findAmbiguousSessionKeyRuntimeRollover is called
In afterTurn (inside reconcileSessionTail): rotation doesn't happen hereWait, in afterTurn, rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is called separately. Let me check.
Looking at the afterTurn flow, I don't see a direct call to rotateStaleSessionKeyConversationIfTrackedTranscriptMissing in the afterTurn method. Let me search for it.
Actually, looking at the code, rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is called in:
Bootstrap (line ~7140)
Assemble (line ~8770)
AfterTurn - inside reconcileSessionTail (line ~6690 from the diff)
Wait, looking at the diff more carefully, the afterTurn code is inside reconcileSessionTail, which is called from bootstrap. So it's not directly in afterTurn.
Let me look at the afterTurn method to see if it calls rotateStaleSessionKeyConversationIfTrackedTranscriptMissing directly.
Actually, let me just search for all calls to rotateStaleSessionKeyConversationIfTrackedTranscriptMissing:
Actually, let me just focus on the fix. The fix is to modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to remove the stat check. Let me also check if we need to update the findAmbiguousSessionKeyRuntimeRollover function.
Since the fix in rotateStaleSessionKeyConversationIfTrackedTranscriptMissing would handle the case before findAmbiguousSessionKeyRuntimeRollover is reached, we might not need to change findAmbiguousSessionKeyRuntimeRollover. But for consistency and safety, I should consider whether findAmbiguousSessionKeyRuntimeRollover should also be updated.
Actually, I realize there's a simpler way to think about this. The rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function is designed to detect and handle "stale" conversations. A conversation is "stale" when:
The session key matches- The session ID is different (new runtime)
The tracked session file is different (new transcript)
The current implementation only handles the case where the old file is missing. The fix should also handle the case where the old file exists.
The findAmbiguousSessionKeyRuntimeRollover function was added as a safety net to catch the case where the old file exists. With the fix, this safety net is no longer needed (but we should keep it for other potential cases).
OK, let me implement the fix now. I'll modify rotateStaleSessionKeyConversationIfTrackedTranscriptMissing to remove the stat check and always rotate when conditions 1-4 are met.
Now let me understand the full context. Let me look at how the rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function works and search for all references to it:
I see there are 6 test failures. Let me look at the failing tests:
"bootstrap fails closed on ambiguous runtime rollover while the old transcript still exists"
"afterTurn fails closed on ambiguous runtime rollover while the old transcript still exists"
"assemble falls back to live messages on ambiguous runtime rollover while the old transcript still exists"
And there are 3 more failures. Let me look at all of them.
The first failure shows that bootstrap now returns {bootstrapped: true, importedMessages: 2} instead of {bootstrapped: false, importedMessages: 0, reason: "ambiguous session-key runtime rollover"}. This is expected! With the fix, bootstrap now archives the old conversation and creates a fresh one, then imports messages. So the test needs to be updated.
But wait, the issue says "UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository". So I can't modify the tests.
Hmm, but the tests are testing the OLD behavior (fail closed). The NEW behavior (archive and create fresh) is the correct behavior according to the issue. So the tests should be updated.
But the instructions say not to modify tests. Let me re-read the instructions:
"UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository. This will lead to an error in the system that evaluates your performance."
Hmm, but the issue says the current behavior is wrong (context leaks). The fix changes the behavior. The tests test the old (wrong) behavior. So the tests need to be updated.
Wait, let me re-read the instructions more carefully:
"If existing tests break because they need to be updated to reflect the changes you made, just ignore it. Evaluation system will not take it into account."
OK, so I should NOT modify the tests. If they break because of my fix, that's expected and the evaluation system will handle it.
But wait, there are also other failures. Let me look at all 6 failures to make sure my fix is correct.
Looking at the test output:
"bootstrap fails closed on ambiguous runtime rollover while the old transcript still exists" - expected fail closed, got successful bootstrap
"afterTurn fails closed on ambiguous runtime rollover while the old transcript still exists" - expected fail closed, got different behavior
"assemble falls back to live messages on ambiguous runtime rollover while the old transcript still exists" - expected fail closed, got different behavior
And 3 more failures. Let me see the full output.
Actually, let me re-read the test output more carefully. It says: