ISSUE DESCRIPTION Isolated cron runs leak context when they reuse a stable session key…
- User
ISSUE DESCRIPTION
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 usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto 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
I'll analyze the repository structure and understand the issue before making changes.
Assistant
Now I have a better understanding. Let me look at the engine and how cron/isolated runs are handled:
Assistant
Let me check the area for handling cron sessions specifically. The issue mentions "isolated cron runs" that share session keys. Let me find where session keys are involved with cron and isolated mode:
Assistant
Let me look at the engine.ts to understand how cron sessions are handled, specifically around lifecycle and how sessions are managed:
Assistant
Let me find where
contextMode: "isolated"is handled. The key thing is when an isolated run uses the same session key as a prior run, we should treat them separately:Assistant
Now let me look at the area around
applySessionReplacementand how it handlessessionKeyrotation, particularly when contextMode is "isolated":Assistant
Let me look at the conversation store's
createConversationmethod andgetConversationForSession:Assistant
Now let me check the engine.ts assemble to see if contextMode "isolated" handling is involved:
Assistant
So
contextModeis defined in the bridge interface but is not actually used by the engine inprepareSubagentSpawn. The issue says "isolated cron runs leak context when they reuse a stable session key". Let me look at the host runner and how it calls into LCM. The host callsprepareSubagentSpawnwithcontextMode: "isolated", which suggests isolated runs come in as subagents. Let me look at the full bridge and how it's called:Assistant
Now I understand the structure better. The
contextMode"isolated" flag is passed toprepareSubagentSpawn, but the engine doesn't actually use that parameter. Let me check the full implementation ofprepareSubagentSpawnto understand what's missing:Assistant
Now I understand the issue better. The
contextModeparameter is declared but not used. WhencontextMode === "isolated", the engine should isolate the LCM context for the child. The key insight from 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"
- "ordinary non-cron session continuity is unchanged"
So when an isolated run starts, the engine should archive any existing active conversation for that session key, then start fresh.
Let me look at the actual call paths and see what the structure for contextMode usage is:
Assistant
Let me look at the structure of conversations and how they are isolated when
contextMode === "isolated":Assistant
Now let me look at how compaction and assembly currently find an "active" conversation for a sessionKey. The key part is
getConversationBySessionKey:Assistant
Now let me look at the relevant tests to see how contextMode "isolated" might be tested, or to see how this issue might be tested:
Assistant
Now let me look at the createEngineWithConfig and createEngineWithDeps helpers to understand:
Assistant
Now I have enough understanding. Let me think about the fix. The issue is:
contextMode"isolated" is passed toprepareSubagentSpawn, but the engine doesn't use it.- When an isolated cron run starts with a stable session key (e.g.,
agent:main:cron:nightly), it inherits the active conversation context from the prior run. - The fix should be: when
contextMode === "isolated", archive any existing active conversation for that session key and start fresh — but only for the child session key.
Let me check the engine to understand the flow:
Assistant
Now let me think about the approach. The issue specifically says "isolated cron runtime sessions that reuse a stable session key must not share active LCM context". This is in the
prepareSubagentSpawn(called when an isolated cron run is about to start) — whencontextMode === "isolated":- We must archive any active conversation tied to the child session key
- This way, the next bootstrap/assemble for that child session key starts fresh
But wait, the existing code already creates a NEW conversation for
childSessionKeybecause the child key is randomized (agent:main:cron:nightly:run:run-123). Let me check:Assistant
Hmm — let me think again. The cron keys
agent:main:cron:nightlycould be a stable session key that hosts use for ALL runs. The cron "run" suffix is added by the host as the run ID (e.g.,agent:main:cron:nightly:run:run-123).But wait, looking at the issue title again: "Isolated cron runs leak context when they reuse a stable session key" — so the key is stable across runs. This means there IS a stable session key (e.g.
agent:main:cron:nightly) that gets reused across cron runs. And each isolated run should start fresh.So in the
prepareSubagentSpawnfor an isolated run, we need to archive any existing active conversation for the child session key to prevent context leaking. This makes sense: when a cron wakes up and runs isolated, prior accumulated context must NOT leak into the new run.Let me look at the bootstrap path to see if isolated runs already get a new conversation:
Assistant
I see — bootstrap calls
getOrCreateConversationwhich:- Returns existing active conversation for
sessionKeyif present - Otherwise returns existing active conversation for
sessionId - Otherwise creates new
So when an isolated cron run comes in with a stable session key (e.g.,
agent:main:cron:nightly) that already has an active conversation from prior run, it inherits it. We need to break this.Now let me look at how
onSubagentEndedis currently used to understand the lifecycle hook semantics:- Returns existing active conversation for
Assistant
Now let me see how
prepareSubagentSpawnis called. It looks like a NEW call to LCM for each child. Let me check that the contract sayschildSessionKey: stringis required andparentSessionKey: string:Assistant
Now let me look at the issue and where it was discussed. Let me check git log:
Assistant
Now let me understand what the expected behavior should be:
- When
prepareSubagentSpawnis called withcontextMode === "isolated"and the child session key is stable (reused across runs):- Archive any active conversation tied to that session key
- Don't carry over context
- The new bootstrap for the child will create a fresh conversation.
- Compaction within the current run still works (compaction operates on the active conversation).
- Non-cron (e.g.,
fork) session continuity is unchanged.
Now let me look at the
applySessionReplacementmethod more carefully and understand what archive does:- When
Assistant
Now I understand the helper. Let me write a temporary test to reproduce the bug first:
Assistant
Let me look at how prepareSubagentSpawn is called in tests:
Assistant
Now let me check the conversation-store tests:
Assistant
Now let me write a temporary script to test my understanding:
Assistant
Now let me write a temporary reproduction script:
Assistant
Let me make sure the existing tests pass first:
Assistant
Good, vitest works. Now let me create a script that simulates the bug to confirm my understanding:
Assistant
Let me actually create a proper test inside the repo so I can run it:
Assistant
I need to add
configto the deps. Let me fix the test:Assistant
Let me look at how createMessage works:
Assistant
I don't need the createMessage. Let me simplify the test to just check if active conversation is archived:
Assistant
I've confirmed the bug:
- When
contextMode === "isolated", the prior active conversation leaks into the next run (becauseprepareSubagentSpawndoes NOT archive the prior conversation). - When
contextModeis missing or "fork", the conversation stays active.
Now let me fix the bug. Let me look at
prepareSubagentSpawnmore carefully:- When
Assistant
Now I'll implement the fix. The fix needs to:
- When
contextMode === "isolated", archive any existing active conversation for the child session key (to ensure prior context doesn't leak into the new run).
Let me also look at the rollback mechanism — since the contract provides rollback, we should probably also handle the case where the conversation was archived. Let me think:
- If we archive the active conversation and the spawn fails, we should restore it on rollback. But actually, since the spawn is happening BEFORE the new run starts, the issue is what state we leave the DB in. The intent is that the prior conversation is "stale" for the new run.
Let me check how the existing
applySessionReplacementworks:- When
Assistant
Now I'll look at the
conversationStore.withTransactionto understand:Assistant
Now I'll write the fix. The change should be:
- When
contextMode === "isolated", archive the active conversation for the child session key (if any), so the new run starts fresh. - We should preserve continuity for the fork case (current behavior).
- The fix should also handle a
rollbackif the spawn fails.
Let me look at the rollback mechanism more carefully:
- When
Assistant
Now let me implement the fix:
Assistant
Now let me implement the fix. I'll add logic to:
- Detect
contextMode === "isolated" - Find any active conversation for the child session key (and its session id if provided)
- Archive it (this preserves history but removes it as active)
- The rollback should restore the archived state if possible
- Detect
Assistant
There's no "unarchive" or "reactivate" method. But for the rollback case, we should be able to revert. Let me check how the existing code handles this. The applySessionReplacement uses a "fresh conversation" pattern - it archives the current one and creates a new one.
Actually, looking again at the issue:
- "Prior runs remain archived" — so archiving is the right semantic
- "compaction within the current run still works" — so we don't need to reactivate on rollback necessarily; the archived conversation still has its context items and they can be used for new compaction
Actually wait - if the host calls
prepareSubagentSpawnbut then rolls back (e.g., spawn fails), the host may retry. In that case the prior conversation should still be available. Let me think about this more carefully.Actually I think the cleanest semantic is:
- Archive the prior conversation (mark inactive)
- Provide rollback that re-activates it if it was active before
Assistant
There isn't a reactivate method. Let me think about this differently. Let me check what rollback currently does and what other places handle this:
Assistant
The rollback is currently just for the expansion grant. The convention is: rollback is best-effort cleanup. If the spawn fails and the host retries, the prior context may be gone.
For the isolated case, I think the right approach is:
- Archive the prior conversation (if any) to ensure context isolation
- Rollback just undoes the grant creation; the archive is the "committed" change since the new run started
Let me make sure I understand what the host does. Let me check the documentation:
Assistant
Good. Now I see — cron isolated sessions have session keys like
agent:main:cron:daily-digest:run:run-123. The:run:run-123part is the unique run ID. So normally the session key IS unique per run.But the issue title says "reuse a stable session key" — this is a separate case where the host may not always include
:run:run-123. Let me think about this more carefully. Maybe in some hosts, the cron reuses the same key likeagent:main:cron:nightlyacross multiple runs and thecontextMode: "isolated"is the cue that this is an isolated run that should NOT share context with prior runs.OK, now let me implement the fix. Here's my plan:
- In
prepareSubagentSpawn, whencontextMode === "isolated", find the active conversation for the child session key (and the child session id if provided), and archive it. - The rollback function for the isolated case should re-activate the archived conversation so the host can retry without losing prior state.
Let me implement this:
- In
Assistant
Now let me look at the existing tests for
prepareSubagentSpawn:Assistant
Now let me implement the fix. I'll modify
prepareSubagentSpawninsrc/engine.ts:Assistant
Now let me make the fix. I'll add the isolated handling:
Assistant
Now let me apply the fix using
edit:Assistant
Good, ConversationRecord is imported. Now let me apply the fix:
Assistant
Now I need to:
- Add the helper method
archiveActiveConversationForIsolatedSubagent - Update the rollback function to restore the archived conversation if present
Let me first add the helper method. Let me find a good location:
- Add the helper method
Assistant
Let me look at applySessionReplacement and find a good place to insert the new helper:
Assistant
Let me add the helper after
applySessionReplacement. I'll add it betweenapplySessionReplacementandhandleBeforeReset:Assistant
Now let me verify the change:
Assistant
Now let me update the rollback to restore the archived conversation if needed:
Assistant
Wait - I need to check that
describeLogErroris imported in engine.ts. Let me check:Assistant
Good. Now let me verify the type for ConversationRecord:
Assistant
Now let me check ConversationRecord's import in engine.ts:
Assistant
Good. Now let me run the typecheck to see if my code compiles:
Assistant
Only the test file has an error. Let me check the engine.ts changes compile:
Assistant
Only the test file has the issue. Let me run the tests now:
Assistant
Both tests pass. Now let me think about edge cases and run all the existing tests:
Assistant
All 317 engine tests pass. Now let me run the full test suite:
Assistant
All 1069 tests pass. Now let me think about edge cases:
- What if there's NO existing active conversation for the child key? - We should just no-op (don't archive anything).
- What if the active conversation belongs to a different session id but same session key? - We should NOT archive it because it might be in the middle of another run.
- What if the host's
childSessionIdis provided but matches an active conversation with that sessionId (not the session key)? - We should still archive if it's the matching identity. - What if both
childSessionIdis provided and an active conversation exists by key but with a DIFFERENT session id? - Be cautious and skip (this could be another concurrent run). - Compaction within the current run still works - We need to verify that after archiving the prior conversation, the new bootstrap creates a fresh conversation and compaction still works on it.
Let me add more comprehensive tests:
Assistant
Two failures. Let me debug:
- The rollback test fails — the conversation isn't being reactivated. Let me check why.
- The createMessage test fails — let me check what's happening.
Let me first investigate the rollback:
Assistant
I see — the rollback uses
currentBySessionIdbut since we've just archived the conversation,getConversationBySessionIdmight find nothing (it filters by session_id, not active). Let me check:Assistant
OK so
getConversationBySessionIdreturns the conversation ordered by active DESC. So even if archived, it should return the conversation. But in the test, after the archive, we have a conversation that hasactive=0and the same session_id. Then we callgetConversationBySessionId("run-1-uuid"). Since there's only one conversation for that session_id, it should return it. But our check requirescurrentBySessionId.active && currentBySessionId.conversationId !== params.conversationId. After archive, currentBySessionId would be the archived conversation (the same one). SocurrentBySessionId.conversationId !== params.conversationIdwould be false → skip the return → continue to update.Hmm, wait, the test reports
after?.conversationIdis undefined. Let me check more carefully. Let me add some logging:Assistant
Let me look at the rollback function call:
Assistant
I see - the rollback is using
.catchwhich catches errors silently. Let me check if the issue is the reactivate not actually updating. Let me add logging to understand:Assistant
Let me modify the test to use console.log to see what's happening:
Assistant
Let me add some debug to the test by changing the log function:
Assistant
I see — the rollback function was called but the reactivate didn't happen. Let me check why. Looking at the code, the rollback uses
.catch()which catches errors silently. Let me trace what's happening:The reactivate function:
- Check by key: gets
byKeywhich is null (because we just archived). Skip. - Check by sessionId: gets
currentBySessionIdwhich is the archived conversation (conversationId 1). SincecurrentBySessionId.activeis false, skip. - So we proceed to update.
Wait — but the
UPDATE conversations SET active = 1 WHERE conversation_id = ?should run. Let me check if it ran... but the conversation is stillactive: false.Hmm. Let me check if my rollback code actually executed:
- Check by key: gets
Assistant
I see the problem! The rollback function fires off
reactivateArchivedConversationForIsolatedSubagentwhich returns a Promise, but the test callsawait prep?.rollback?.()and then immediately checks the result. Since.catch()is attached but the function is called and returns a promise, the test may check before the promise resolves. Let me verify by removing.catch()and making it blocking:Actually wait,
await prep?.rollback?.()should await the promise returned by the rollback function. The rollback function is sync (() => { ... }). It callsthis.reactivateArchivedConversationForIsolatedSubagent(...)which returns a promise. The.catch(...)is chained on that promise. The rollback function itself doesn't return anything (returns undefined).So
await prep?.rollback?.()resolves immediately after the rollback function executes synchronously (the promise is fire-and-forget). That's why the test fails — the reactivate hasn't completed when we check.I should make the rollback return the promise. Let me fix this:
Assistant
Now let me run the tests again:
Assistant
Hmm —
warnLogis empty. That means no error was thrown. But the reactivate didn't happen either. Let me look at the code path again:Assistant
Let me add debug to see what's happening:
Assistant
The
[DBG] reactivate calledlog is missing! That means the rollback function isn't even calling reactivate. Let me check:Assistant
Let me look at the rollback function again:
Assistant
Wait — I see the issue. The debug test ran fine, but no DBG output. Let me check if test ran with cached code:
Assistant
Hmm. Let me search for the right place where the rollback function is — maybe there are multiple instances:
Assistant
Let me check if the rollback is even called:
Assistant
Hmm —
[DBG] rollback calledis not appearing either. So the rollback function isn't called. Let me check the test:Assistant
Wait, the test calls
prep?.rollback?.(). Maybeprepis undefined? Let me check:Assistant
Looking at
shouldIgnoreSession, whenignoreSessionPatternsis empty, it returns false. So we should be good.Looking at
isStatelessSession, whenstatelessSessionPatternsis empty, returns false.Let me add a debug to the prep return path:
Assistant
Good, all DBG cleaned up. Now let me check what's happening. Let me look at the prepareSubagentSpawn to see what could cause it to return undefined:
Assistant
I see! The bug is that
resolveConversationIdForSessionKey(parentSessionKey)returns undefined because the parent's session key is "agent:main:main" but there's no conversation in the DB for that key. So the function returns undefined, and there's no rollback function to call.Let me verify this theory by checking my test setup. The test creates a conversation for the CHILD session key, not the parent. So the parent lookup fails.
Let me update the test to also create a parent conversation:
Assistant
OK now I understand. The
createMessagerequires all fields. Let me update the test to provide them:Assistant
OK, the createMessage requires
seq. Let me fix my tests:Assistant
All 7 tests pass. Now let me delete my temporary test files and run the full test suite to make sure I didn't break anything:
Assistant
All 1067 tests pass. Now let me look at the engine.ts changes one more time to ensure the code is clean:
Assistant
Let me also check the helper method:
Assistant
Now let me think about additional edge cases:
-
What if
archivedIsolatedConversation.sessionKeyis null? My code handles that —params.sessionKey?.trim()returns undefined and the byKey check is skipped. -
What if the conversation is archived but the session key was cleared? Let me check what happens when we archive. The archiveConversation only sets
active = 0,archived_at = now. The session_key remains unchanged. SoarchivedIsolatedConversation.sessionKeywill still be the original session key. Good. -
What if the original session key was null? Then
params.sessionKey?.trim()returns undefined, and we only check by session_id. Good. -
What if there's a constraint that prevents reactivating (e.g., another active conversation was created in the meantime)? My code checks for that and skips.
Let me also think about a specific scenario: what if is provided AND there's an active conversation for the child session key with a different sessionId. My current code logs a warning and returns null (no archive). This is the right behavior for safety.
-
Assistant
The archive happens BEFORE the parent lookup. So if the parent is not found, we've already archived the child but the spawn is aborted. The host might re-call with a working parent setup, and on the second call we'd archive again (no-op since already archived).
But what about: the parent doesn't have a conversation, but the child does, and we archive. Now the host retries. On retry, we'd call archive again (no-op). The previous active conversation remains archived. The host's
bootstrapwould create a fresh conversation. So the rollback case wouldn't be triggered automatically — the host would have to callrollbackitself.Hmm, but there's a subtle issue: if
conversationId === undefined(parent has no conversation), we return undefined. The host can still callrollback()since we return an object with rollback. So this should be fine.But wait — actually, in the current code, if parent has no conversation, we return undefined. Let me re-check:
Assistant
Wait, there's an issue. The current code structure is:
- Should-ignore check → return undefined (no archive)
- Key check → return undefined (no archive)
- Archive isolated conversation (NEW)
- Resolve parent conversation → if undefined, return undefined (but archive already happened!)
This means: when parent has no conversation, we still archive the child's prior conversation and return undefined (no rollback). The host has no way to undo the archive.
This is a problem. Let me move the archive AFTER the parent resolution so we only archive when the spawn will succeed:
Assistant
Now let me re-run the full test suite to make sure nothing broke:
Assistant
All 1067 tests pass. Now let me create a temporary test to verify the edge cases:
Assistant
All 10 tests pass. Now let me clean up the temporary test:
Assistant
Let me look at the final state of the changes:
Assistant
The diff looks good. Let me also clean up unused variable in
reactivateArchivedConversationForIsolatedSubagent:Assistant
All 1067 tests pass. Now let me also check the typecheck passes:
Assistant
Typecheck passes. Let me also create a changeset:
Assistant
Now let me look at the final diff:
Assistant
Assistant
Assistant
All 4 edge case tests pass. Let me clean up:
Assistant
Let me also test the scenario where the same run is called multiple times in a row (cascading isolated runs):
Assistant
All tests pass. Let me clean up:
Assistant
Let me also verify the changeset file:
Assistant
Let me run the full test suite one more time to ensure nothing is broken:
Assistant
All 1067 tests pass. Let me also run the typecheck:
Assistant
Typecheck passes. Let me also run the build:
Assistant
Build succeeds. Let me also check the git status one more time:
Assistant
Let me also check the test file we removed and any other temporary scripts:
Assistant
No temporary files. Let me also verify the final state of the engine.ts changes:
Assistant
The diff looks clean. Let me also check that the resulting implementation matches the issue requirements:
-
"Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context" ✓
prepareSubagentSpawnwithcontextMode: "isolated"now archives any active conversation for the child session key.
-
Assistant
Let me also run the regression test that was added before:
Assistant
Let me also clean up the temp files I created in /tmp:
Assistant
These are temp DB files from previous test runs. They're not related to my work.
Let me also verify the final state of the engine.ts changes once more, paying attention to the entire flow:
Assistant
The code looks good. Let me also check the changeset folder content:
Assistant
Let me do one final test run to make sure everything is still passing:
Assistant
Assistant
Clean typecheck. Let me look at the final summary:
Assistant
Summary of Changes
-
src/engine.ts(107 line additions):- Added logic in
prepareSubagentSpawnto detect when a host requests an isolated subagent spawn (contextMode === "isolated"). - Added a new private method
archiveActiveConversationForIsolatedSubagentthat archives any active conversation bound to the child session key, with safety checks for sessionId conflicts and missing conversations. - Updated the rollback function to re-activate the archived conversation if the host aborts the spawn.
- Added a new private method
reactivateArchivedConversationForIsolatedSubagentthat re-activates the archived conversation only if no other conversation has since claimed the same identity.
- Added logic in
-
.changeset/isolated-cron-context-leak.md(new file):- Documents the fix in the package release notes.
-
Assistant
The changes are ready to submit. Let me do one final check to ensure my changes are clean and complete:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.