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 start by exploring the repository structure to understand the codebase.
Assistant
Let me look at the bootstrap and ingest logic to understand how session keys are handled:
Assistant
Let me now look for any code related to cron handling specifically:
Assistant
Let me search for relevant test files and understand the engine test patterns:
Assistant
Let me look at the spec files for more context:
Assistant
Now let me look at how the engine handles bootstrap and session lifecycle, focusing on the contextMode handling:
Assistant
Now let me look at the assemble phase to understand how it handles the session key rollover:
Assistant
Now let me look at the prepareSubagentSpawn code with a focus on understanding how contextMode is used. Looking at where contextMode is being passed to the engine:
Assistant
Now let me understand the current prepareSubagentSpawn to understand how isolated is currently handled:
Assistant
Now let me look at the conversation store to understand how conversations are stored and looked up:
Assistant
Now let me look at how ingest works:
Assistant
Let me look more closely at the conversation-store getOrCreateConversation logic to understand how a session is identified and how session-key continuity works:
Assistant
Let me now understand more about how "stable session key" is used. 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 when an isolated cron run happens, it has a stable session key (e.g.,
agent:main:cron:nightly). When a new run happens (which is "isolated" but uses the same stable session key), the prior LCM context must NOT be shared — it must be archived and a new one created.Let me look at where cron contextMode or "isolated" might be propagated through:
Assistant
Let me look at the lifecycle context types and search for "stable session key" in docs and specs:
Assistant
Now let me understand the issue better. Looking at the code, I can see:
- The engine's
prepareSubagentSpawnacceptscontextMode?: "isolated" | "fork". - The issue mentions cron runs, which use a stable session key.
The current behavior of
prepareSubagentSpawnonly handles permission grants. The issue requires that when a cron run is isolated, and reuses a stable session key, the prior LCM context (conversation) should be archived and a new one created. Currently, the same session key is reused, and the existing conversation is just continued.Let me look more carefully at 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.
Let me check what the contract should look like when contextMode === "isolated":
- The engine's
Assistant
Now I need to think about this. The
contextMode?: "isolated" | "fork"is a parameter toprepareSubagentSpawn. Looking at the code, currently, when an isolated context is requested, the engine does NOT rotate/archive the prior conversation - it just reuses the existing conversation. So the bug is: when an isolated cron run is requested with the same session key, the previous conversation's content remains in the active conversation.Let me look at what other functions handle session lifecycle:
Assistant
Now let me see how prepareSubagentSpawn is wired into the broader system. Looking at the existing tests to better understand the flow:
Assistant
Now let me look at how an isolated cron session might end up reusing a stable session key. 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 contract seems to be that when
prepareSubagentSpawnis called withcontextMode === "isolated", the prior LCM context for the same session key should be archived and a fresh conversation row created. Let me think about this more carefully:Looking at the existing behavior of
prepareSubagentSpawn, it only manages delegation grants. It doesn't touch the actual LCM conversation for the session key. So when an isolated subagent is spawned with the same session key (cron case), the parent's LCM conversation is the same.The fix should be: when
contextMode === "isolated"and the same session key is being used, the prior LCM conversation should be archived and a new conversation should be created.Let me look at
applySessionReplacementand check how it works:Assistant
Now I understand the pattern. Let me check the bootstrap function to understand the path more:
Assistant
Now I have a much clearer understanding. Let me write a quick script to test what happens currently:
Assistant
Now let me understand the issue. I need to look at how cron sessions are normally spawned. Let me look at the bootstrap and how the engine actually picks up the conversation:
Assistant
Let me check the
bootstrapfor cron session key continuity:Assistant
Now let me write a quick test to verify what happens currently with two cron runs sharing a session key:
Assistant
Now let me write a reproduction script to verify the current behavior:
Assistant
Now let me create a quick repro test that demonstrates the bug:
Assistant
Let me run the test in place using vitest. First, let me see existing tests structure:
Assistant
Let me look at how the test runs and quickly run a single test:
Assistant
Good. Let me write a quick repro test in the test directory but using a temporary file (we'll delete it later):
Assistant
Good. The bug is reproduced. Now let me think about the fix.
Looking back at 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.
Looking at the
prepareSubagentSpawnfunction, thecontextMode?: "isolated" | "fork"parameter is there. When it's"isolated", the child subagent gets its own isolated context, but currently the engine doesn't archive the prior conversation.Let me trace through what would be the expected fix:
When
prepareSubagentSpawnis called with:parentSessionKey= the stable cron session key (e.g.,agent:main:cron:daily-digest)childSessionKey= same stable cron session key (since the isolated subagent uses the same key)contextMode = "isolated"
Then we need to:
- Archive the prior conversation row for
parentSessionKey - Create a fresh conversation row for the new isolated run
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.
The isolated cron sessions use a stable session key. So multiple invocations of the same cron job share the same session key. They are isolated from each other (each cron invocation is a separate runtime), so they should not share LCM context.
The natural integration point is
prepareSubagentSpawn, because that's where the runtime tells us "I'm an isolated context." But wait —prepareSubagentSpawnis for subagents. The isolated cron session is itself the main agent, not a subagent...Let me check how this works with OpenClaw. The cron could spawn an isolated subagent, in which case
prepareSubagentSpawnwould be called. Let me check how the contextMode gets propagated:Assistant
Now let me re-examine the issue. Looking at it again:
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.
I think the issue is:
- The host (OpenClaw) starts an isolated cron run. This is signaled via
prepareSubagentSpawn(or thecontextMode = "isolated"parameter) - Multiple isolated cron runs share a stable session key (e.g.,
agent:main:cron:daily-digest) - The current behavior: LCM persists context across these runs (because they share session key)
- The desired behavior: each isolated cron run should be a fresh LCM conversation
The fix: when
prepareSubagentSpawnis called withcontextMode === "isolated"AND the parent/child session keys match (indicating the same stable cron session is being re-used), the prior LCM conversation should be archived and a new fresh conversation should be created.Wait, but that doesn't quite make sense either. Let me think more carefully.
Actually, looking at the structure of
prepareSubagentSpawn, the parent and child can have different session keys. But for an isolated cron, the parent key is the cron's stable key (e.g.,agent:main:cron:daily-digest), and the child is also the same stable key (since it's reusing the parent's session).Hmm, actually I think this is the case where the parent and child session keys ARE the same when the subagent is reusing the parent's identity. Let me look at the test for
prepareSubagentSpawn:- The host (OpenClaw) starts an isolated cron run. This is signaled via
Assistant
OK, I see that in the standard case, parent and child have different session keys. The contract for
prepareSubagentSpawnis: when called withcontextMode: "isolated", the parent sessionKey is the original parent, and the child sessionKey is the isolated child's identity. The isolated child's identity can be the SAME as the parent when reusing a stable cron session key.So when an isolated cron run happens, the host calls
prepareSubagentSpawnwith:- parentSessionKey = the stable cron session key
- childSessionKey = same stable cron session key (since it's the same cron lane)
- contextMode = "isolated"
And the fix is: when childSessionKey == parentSessionKey AND contextMode == "isolated", the prior conversation should be archived and a fresh one created.
Actually wait, I need to look more carefully. The
prepareSubagentSpawnis called when a subagent is being spawned. If we're spawning an isolated subagent, the parent and child session keys would typically be different (the child gets a new identity likeagent:main:subagent:xxx). The contextMode being "isolated" means the child should NOT inherit context from the parent.But for an isolated cron run, the parent and child might both use the same stable session key, since the runtime is reusing the cron's identity. This is the leak scenario.
Let me think about this more carefully. The bug as I understand it:
- Cron job at
agent:main:cron:daily-digestruns. - The runtime session for this cron has a stable session key (e.g., the same
agent:main:cron:daily-digest). - Previous LCM context for this key includes messages, summaries, etc.
- A new run starts. It uses the same stable session key.
- The host calls
prepareSubagentSpawnwithcontextMode = "isolated"because each cron run is isolated. - But currently,
prepareSubagentSpawndoesn't archive the prior conversation. So the new run inherits the prior LCM context.
The fix:
- In
prepareSubagentSpawn, whencontextMode === "isolated"and the parent session key is being reused, archive the prior conversation and create a fresh one.
Let me think about what "parent session key is being reused" means. Actually I think the issue is even simpler:
- When
prepareSubagentSpawnis called withcontextMode === "isolated"and the child session key matches the parent session key (they're using the same stable session identity), the LCM should treat this as a fresh isolated run. - The fix should archive the existing active conversation for that session key and create a fresh row.
Let me look at the test that exists for
prepareSubagentSpawnwith contextMode:Assistant
No tests currently exist for
contextMode. So this is a new area.Now let me look at what happens with
childSessionKey === parentSessionKey- is that even valid? Let me check more tests:Assistant
Now let me implement the fix. The fix needs to be in
prepareSubagentSpawn:When
contextMode === "isolated"AND the child session key matches the parent session key (indicating reuse of the same stable cron session identity), we should:- Archive the prior active conversation for the shared session key
- Create a fresh conversation row for the new isolated run
Let me look at the existing test for
prepareSubagentSpawnthat does a check on whether parent/child keys are similar:Assistant
Now let me look at the structure of
applySessionReplacementand understand what we need to do for the isolated case:Assistant
Now let me look at how the existing code handles similar things (e.g., reset, new):
Assistant
Let me look at the existing tests in the engine.test.ts to understand the test structure better:
Assistant
Now let me design the fix. Looking at
prepareSubagentSpawn:async prepareSubagentSpawn(params: { parentSessionKey: string; childSessionKey: string; contextMode?: "isolated" | "fork"; ... }): Promise<SubagentSpawnPreparation | undefined>For isolated contextMode, the engine should:
- Archive the prior conversation for the child session key
- Create a fresh conversation row
Wait, but only when the parent and child session keys are the same (the cron re-use case). Otherwise, when isolated subagents are spawned with distinct child keys, we shouldn't touch anything because the child key has no prior conversation.
Actually let me think about this differently. The issue says:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
The key insight is "reuse a stable session key". The "stable session key" is the parent session key. The "reuse" means multiple cron invocations all map to the same stable session key.
So when an isolated cron run begins:
parentSessionKey= the stable cron session keychildSessionKey= the same stable cron session key (since the subagent IS the cron, not a spawned sub-process)
OR
parentSessionKey= the main agent's session keychildSessionKey= the cron's session key (same as parent's stable key for cron)contextMode = "isolated"
The fix needs to handle the case where the parent and child session keys are the same AND contextMode is "isolated". Or more broadly, when contextMode is "isolated", the child session key's prior conversation should be archived.
Actually, looking at it again, I think the natural behavior is: when contextMode === "isolated", the child starts with a fresh context. So we should always archive the prior conversation for the child session key when the context is isolated. Even if it's a different session key, the isolated semantics mean "fresh start."
But wait, the issue says "ordinary non-cron session continuity is unchanged." This means we should NOT change behavior for non-isolated sessions. So the fix only applies when contextMode === "isolated".
Let me re-read once more:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
So the bug is specifically that isolated cron runs share context. The fix is for isolated cron runs.
Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged.
So:
- Prior runs are archived (the existing conversation is preserved as history)
- Compaction still works (within the current run, summaries/messages can be compacted)
- Non-cron session continuity is unchanged (only isolated cron runs are affected)
Now I think the fix is in
prepareSubagentSpawn:- When
contextMode === "isolated", archive the prior conversation for the child session key and create a fresh one.
Let me also think about where this should be triggered. The
prepareSubagentSpawnis the entry point. We should:- Check if
contextMode === "isolated"AND the child session key has an existing active conversation - If yes, archive it (move it to
active=0) — this preserves the prior context as history - Create a fresh conversation row for the child session key
The reason we need to do this in
prepareSubagentSpawn(rather than inbootstrap) is that:- The host tells us via
contextMode = "isolated"that this is an isolated run - We need to act before the new run's bootstrap to ensure the new run attaches to a fresh conversation
Wait, but if we're archiving the prior conversation and creating a fresh one with the same session key, the new
bootstrapwould find the fresh one (sincegetConversationBySessionKeyreturns the active one). So actually, the timing of when we do this matters.Let me think about this differently. The cleanest fix:
- When
prepareSubagentSpawnis called withcontextMode === "isolated", archive any existing active conversation for the child session key (the prior cron run) and create a fresh conversation for the new run.
Let me look at how this works in practice. Looking at
bootstrap:const conversation = await this.conversationStore.getOrCreateConversation(params.sessionId, { sessionKey: params.sessionKey, });getOrCreateConversationreturns the active conversation for the session key if one exists. So if we archive the prior and create a new one before bootstrap, the bootstrap will attach to the fresh one.Let me look at
getOrCreateConversationagain:Assistant
OK so if we archive the existing conversation and create a fresh one, the next
getOrCreateConversationcall will return the fresh one.But wait, this also depends on
parentSessionId. Looking at the code flow more carefully:In
prepareSubagentSpawn:params.parentSessionKey= the parent's session key (e.g., the cron lane's key)params.childSessionKey= the child session key (for an isolated cron run, this is the same)params.childSessionId= the new session UUID (each isolated run has a new session ID)
So we need to:
- Archive the prior conversation for
childSessionKey - Create a new conversation with
sessionId=childSessionId, sessionKey=childSessionKey
Let me also think: do we need to check that parent and child session keys are the same? Or is the isolated contextMode enough signal?
I think the more general rule is: when
contextMode === "isolated", the child starts with a fresh conversation regardless of whether the keys match.But wait, the issue says: "ordinary non-cron session continuity is unchanged". So we should NOT change behavior for non-isolated sessions.
For a non-isolated cron run, the child would normally inherit the parent's context. But for an isolated cron run, the child should start fresh.
So the rule is: when
contextMode === "isolated", archive the prior conversation for the child session key.Actually let me also consider whether the parent's conversation should be archived. Let me look at the issue once more:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
I think the "active LCM context" refers to the conversation that will be used for the new run. Since the cron run uses a stable session key, the LCM context for that key is what's being shared.
Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged.
"Prior runs remain archived" — the prior conversation for the stable session key should be archived.
OK so the fix is: in
prepareSubagentSpawn, whencontextMode === "isolated", archive any prior active conversation for the child session key. This way, the new run will start with a fresh conversation.But there's an important consideration: if the parent session key is different from the child session key (e.g., the cron run is spawned with a different child key), we might not want to archive the parent's conversation (since the parent is the main agent, and we shouldn't lose its context).
Let me think about the actual scenarios:
Scenario A: Isolated cron run on stable session key
agent:main:cron:daily-digest- parentSessionKey =
agent:main:cron:daily-digest(the cron's stable key) - childSessionKey =
agent:main:cron:daily-digest(same, since the run reuses the cron's identity) - contextMode = "isolated"
- Expected: prior conversation for
agent:main:cron:daily-digestis archived, new fresh conversation is created.
Scenario B: Isolated subagent spawned by main agent
- parentSessionKey =
agent:main:main(the main agent's session key) - childSessionKey =
agent:main:subagent:abc123(the subagent's new identity) - contextMode = "isolated"
- Expected: child starts with fresh context (since it's isolated). Parent's conversation is NOT affected.
In both scenarios, when
contextMode === "isolated":- The child session key's prior conversation should be archived (if any).
- A new fresh conversation should be created for the child session key.
This means the rule is simpler: when
contextMode === "isolated", archive the prior active conversation for the child session key (if any) and create a fresh one.Wait, but in Scenario B, if the child session key has never been seen before, there would be no prior conversation to archive. So the rule works.
Actually wait, I need to be careful. In Scenario B, the child might inherit the parent's context (if contextMode was "fork"). For "isolated", the child starts fresh. So:
If contextMode === "fork", we don't change anything (the existing behavior preserves continuity).
If contextMode === "isolated", we archive the prior conversation for the child session key (if any). This ensures the child starts with a fresh conversation.
But this might be too aggressive. What if the child session key happens to be the same as the parent's session key? Then we'd archive the parent's context, which is fine for isolated semantics.
OK let me go with the simpler rule: when contextMode === "isolated", archive the prior conversation for the child session key. This handles both scenarios.
Wait actually I realize we need to be careful: we should only archive the prior conversation if there is one. If there's no prior conversation, we just create a fresh one (which bootstrap would do anyway).
Let me also think about edge cases:
-
What if
prepareSubagentSpawnis called withcontextMode === "isolated"but the parent and child keys are the same AND there's no existing conversation? Then we just create a new one, no archive needed. -
What if
prepareSubagentSpawnis called withcontextMode === "isolated"and parent key isagent:main:main, child key isagent:main:subagent:abc? The child has no prior conversation (because the subagent is new), so nothing to archive. We just need to make sure the new subagent's bootstrap creates a new conversation. Actuallybootstrapfor the subagent would create the conversation viagetOrCreateConversation.
Actually wait, in the existing logic, if
contextMode === "isolated", the child should NOT inherit the parent's context. So we need to ensure the child's bootstrap doesn't see the parent's conversation. But the child has a different session key, so it wouldn't see the parent's conversation anyway.OK I think the fix is more nuanced. Let me reconsider.
The bug specifically says "isolated cron runs ... reuse a stable session key". This means:
- The cron run's session key is stable (e.g.,
agent:main:cron:daily-digest) - Multiple cron runs share this session key
- Each run is isolated (contextMode = "isolated")
- The bug is that LCM context leaks between runs
The fix needs to:
- Archive the prior conversation for the stable session key
- Create a fresh conversation for the new run
Now,
prepareSubagentSpawnis the entry point. The parent session key would be the cron's stable session key (the cron's identity). The child session key... hmm, let me think.Actually, in OpenClaw's runtime, when a cron job runs:
- The runtime starts a new session for the cron run
- The session might be spawned as an "isolated" subagent of the main agent
- The session key would be the cron's stable key
So:
- parentSessionKey =
agent:main:main(the main agent's session key, which is the cron owner) - childSessionKey =
agent:main:cron:daily-digest(the cron's stable key) - contextMode = "isolated"
OR alternatively:
- parentSessionKey =
agent:main:cron:daily-digest(the cron's stable key) - childSessionKey =
agent:main:cron:daily-digest(same, since the run is the cron) - contextMode = "isolated"
The exact contract depends on how OpenClaw calls the engine.
Let me focus on the fix: when
contextMode === "isolated", the child session should start with a fresh conversation, even if the session key has been used before.The simplest implementation: when
contextMode === "isolated", archive any existing active conversation for the child session key. The fresh conversation will be created naturally by the bootstrap flow.Let me implement this. First, let me check the current prepareSubagentSpawn code once more:
Assistant
Now let me design the fix. I need to:
- Check if
contextMode === "isolated" - If so, archive the prior active conversation for the child session key (if any)
- The fresh conversation will be created when the child calls
bootstrap
Let me also think about when to create the fresh conversation. Should we create it in
prepareSubagentSpawnitself, or letbootstrapdo it?If we create it in
prepareSubagentSpawn:- Pro: The fresh conversation is guaranteed to exist before
bootstrap - Con: We need to handle the case where bootstrap is never called
If we let
bootstrapcreate it:- Pro: Simpler, leverages existing logic
- Con: If
prepareSubagentSpawnis called but bootstrap isn't, no fresh conversation
I think the cleanest approach is to archive the prior conversation in
prepareSubagentSpawnand letbootstrapcreate the fresh one naturally.But wait, there's another consideration. If the parent and child session keys are the same (cron reuse case), then:
- The parent has an active conversation
- The child session key = parent session key
- So "the prior conversation for the child session key" IS the parent's conversation
In this case, archiving the prior conversation for the child session key effectively archives the parent's conversation too. Is that what we want?
I think yes, because:
- The cron run is "isolated" from the parent
- The cron run uses the same session key as the parent (the cron's stable key)
- The prior LCM context for that session key should be archived
OK let me implement the fix.
Let me first verify what
resolveConversationIdForSessionKeydoes:- Check if
Assistant
Now let me implement the fix. Let me look at the code where we can apply this fix:
Assistant
Now let me implement the fix. Here's my plan:
- In
prepareSubagentSpawn, whencontextMode === "isolated":- Look up any active conversation for the child session key
- If there is one and it's NOT already fresh, archive it (preserving prior run's history)
- Note: We don't need to create a replacement because the next
bootstrapwill create it
Wait, but if the child session key matches parent session key, we need to think about this carefully:
- parent and child are using the same session key
- The parent has an active conversation (with its own context)
- For the isolated child to have fresh context, we archive the parent's conversation
- But the parent's other operations (assemble, ingest, etc.) might still be in flight...
Actually,
prepareSubagentSpawnis called once when the subagent is being spawned. The parent's operations should be done before the subagent is spawned (or at least, the runtime should have serialized them).Let me think about this more carefully. In OpenClaw's runtime:
- Parent runs, completes
- Parent may spawn child subagent
- For "fork" mode, child inherits context
- For "isolated" mode, child has fresh context
The
prepareSubagentSpawnis called when the parent spawns the child. The parent should be done with its conversation at this point (otherwise the child would inherit stale state).For an isolated cron run, the parent's session key is the main agent's key, and the child session key is the cron's stable key. The parent might still be using its conversation, but the child is a separate session.
Hmm, but if parent key != child key, then archiving the child's prior conversation doesn't affect the parent. Good.
If parent key == child key (cron reuse case), then archiving the child's prior conversation IS archiving the parent's conversation. But for an isolated cron run, this is correct: the cron run should have fresh context, separate from any prior cron runs.
Wait, but the parent might be a regular session, not a cron. If the parent uses session key X and the child also uses session key X (because they share the identity), and the parent is still active... no wait,
prepareSubagentSpawnis called when the parent spawns a subagent, so the parent should be in a stable state.OK I think the rule is: for
contextMode === "isolated", archive the prior conversation for the child session key, regardless of whether it matches the parent session key.Actually wait, let me re-think. There's another scenario:
What if the parent session key and the child session key are the SAME, AND the parent is still actively in use? For example, the main agent wants to spawn an isolated subagent using the same session identity (e.g., a recursive call). This is unusual but possible.
In that case, archiving the parent's conversation would affect the parent's context. That seems wrong.
But actually, if the parent is still in use, the parent's
conversationrow is the one being used. If we archive it, the parent loses its active context.So maybe we should only archive the child's prior conversation if it doesn't match the parent's current active conversation. Or more precisely, if the child session key has a prior active conversation that's DIFFERENT from the parent's current conversation.
Hmm this is getting complex. Let me look at this from a different angle.
Actually I think the rule should be: only archive the prior conversation if it's NOT the parent's currently active conversation. If it IS the parent's conversation, leave it alone (the parent might still be using it).
Wait, but for a cron run, the parent's currently active conversation IS the cron's stable conversation. We DO want to archive it because the new run is isolated.
Let me look at this differently. The semantic is:
- If
contextMode === "isolated", the child session should start with a fresh conversation - If the child session key has a prior active conversation, archive it
- If that prior active conversation IS the parent's currently active conversation, this is still OK because the parent is done with this session (it just spawned a child)
Actually, looking at the contract of
prepareSubagentSpawn, it returns arollbackcallback. If the host decides to rollback, the subagent isn't spawned. So if we archive the conversation inprepareSubagentSpawnand the host rolls back, we'd need to undo the archive.But the archive is destructive — we can't easily undo it. So maybe we should defer the archive to after
prepareSubagentSpawnreturns successfully and the subagent actually starts.Hmm, but then the rollback becomes complicated. Let me think.
Actually, looking at the issue more carefully, I think the simplest approach is:
- When
contextMode === "isolated", archive the prior conversation for the child session key - If the parent and child keys are the same, this archives the parent's conversation too
- This is OK because for an isolated cron run, the parent IS the cron (they share identity)
- For a non-cron isolated subagent with same key as parent, this is also OK (the parent is done with the session)
Let me look at OpenClaw's docs or any other context about
contextMode:- In
Assistant
OK let me look at the contract documentation if any:
Assistant
No documentation about isolated mode. Let me also look at where prepareSubagentSpawn is called from. I think I need to think about this more pragmatically.
Let me look at how the current
applySessionReplacementis called for context that the child might be reusing:Looking at
applySessionReplacement:- It archives the current conversation (if active)
- Optionally creates a replacement conversation (with
createReplacement: true)
For our case (isolated cron), we want to:
- Archive the prior conversation for the child session key (if it exists)
- NOT create a replacement yet — let the bootstrap flow create the fresh conversation naturally
Let me implement this:
Assistant
Now let me think about the safest place to put the fix. We want to:
- Only act when
contextMode === "isolated" - Archive any existing active conversation for the child session key
- This must happen BEFORE the new subagent's bootstrap (so the bootstrap finds no active conversation and creates a fresh one)
Let me add the fix at the beginning of
prepareSubagentSpawn, after the basic validation:- Only act when
Assistant
Let me make the fix. First, I need to add an archive step. Let me think about the safest approach.
The key insight: we want to archive the prior conversation for the child session key (if any), but ONLY when:
contextMode === "isolated"- The child session key has a prior active conversation
- That prior conversation is NOT the same as the parent's currently active conversation (otherwise we'd lose the parent's state)
Wait, point 3 isn't quite right. Let me think again.
Actually, for the cron reuse case, the parent's currently active conversation IS the cron's prior conversation. So we'd want to archive it. The parent doesn't have a separate conversation in that case — the parent's "session" is just the cron session.
For the isolated subagent case (different keys), the child has no prior conversation. Nothing to archive.
OK so the rule is just: when
contextMode === "isolated", archive the prior conversation for the child session key.Now there's another consideration: what if the host rolls back the
prepareSubagentSpawn? The rollback callback only revokes the grant. If we archived a conversation, we can't undo that.Hmm. Maybe we should be more careful and only archive when:
contextMode === "isolated"- The child session key differs from the parent session key, OR
- The child session key == parent session key AND we know the parent is done with it (i.e., the parent isn't currently running)
But there's no easy way to know if the parent is currently running.
Alternative: we could mark the archived conversation as "rollback-able" and undo the archive if the host rolls back.
Actually, let me look at this more carefully. The
rollbackcallback is called if the host decides to not spawn the subagent. But typically,prepareSubagentSpawnis a synchronous-feeling setup, and rollback is rarely called.Looking at the issue:
Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged.
The fix is straightforward: archive prior conversations for isolated cron runs. Even if rollback is called, the damage is limited (the prior conversation is just archived, not deleted).
OK let me implement the fix now. Here's my plan:
async prepareSubagentSpawn(params: { parentSessionKey: string; childSessionKey: string; contextMode?: "isolated" | "fork"; parentSessionId?: string; parentSessionFile?: string; childSessionId?: string; childSessionFile?: string; ttlMs?: number; }): Promise<SubagentSpawnPreparation | undefined> { // ... existing validation ... this.ensureMigrated(); const childSessionKey = params.childSessionKey.trim(); const parentSessionKey = params.parentSessionKey.trim(); if (!childSessionKey || !parentSessionKey) { return undefined; } // For isolated contexts, archive the prior conversation for the child session key // so each new isolated run starts with a fresh conversation. This is critical for // stable session keys (e.g., cron lanes) that would otherwise leak context across runs. if (params.contextMode === "isolated" && childSessionKey) { await this.archivePriorConversationForIsolatedChild({ parentSessionKey, childSessionKey, }); } // ... rest of existing logic ... }Wait, but I need to think about the case where parent key == child key AND parent key has an active conversation. In that case:
- The "child" is using the same session key as the parent
- The parent is presumably done with this conversation (since it's spawning a subagent)
- We archive the parent's conversation
- The new isolated run starts fresh
This seems correct.
But what about: parent key != child key, and the child key has a prior conversation (e.g., the child session key was used before)?
- The child has a prior conversation from a previous subagent run
- We archive it
- The new isolated subagent starts fresh
This also seems correct.
What about: parent key != child key, and the child key has no prior conversation?
- Nothing to archive
- The new isolated subagent creates a fresh conversation via bootstrap
Also correct.
OK let me implement this. But wait, there's a subtle issue. Looking at
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) { // ... return byKey; } } // ... }If the child has a prior active conversation and we archive it before bootstrap, the next
getOrCreateConversationcall would create a new conversation. Good.But there's still the issue of the session queue. Looking at
withSessionQueue:private resolveSessionQueueKey(sessionId?: string, sessionKey?: string): string { const normalizedSessionKey = sessionKey?.trim(); const normalizedSessionId = sessionId?.trim(); return normalizedSessionKey || normalizedSessionId || "__lcm__"; }The queue key uses sessionKey (preferred) over sessionId. So all operations for the same sessionKey are serialized. This means our archive operation would be serialized with the bootstrap, which is correct.
OK let me also think about
withSessionQueuefor the archive. We need to wrap the archive in the session queue to ensure consistency.Let me look at how
applySessionReplacementis called from other lifecycle methods to see the pattern:Assistant
OK so the pattern is:
- Wrap in
withSessionQueuewith the session key - Wrap in
conversationStore.withTransaction - Call
applySessionReplacement
Let me implement the fix now. I'll add a helper method
archivePriorConversationForIsolatedChildthat handles the isolated case:- Wrap in
Assistant
Good, I can reuse
applySessionReplacement. Now let me design the actual fix.Now I realize there's one more subtlety. The issue says:
Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged.
The fix needs to be:
- Archive the prior conversation for the child session key when contextMode === "isolated"
- This means: prior cron runs are preserved as archived rows
- Compaction within the current run still works (since the fresh conversation can be compacted normally)
- Non-cron session continuity is unchanged (we don't change behavior for non-isolated sessions)
Let me also think about: what if the child session key matches a non-active conversation (e.g., an archived one)? The archive operation is a no-op for archived conversations. Good.
What about the parent's grant? The grant is for the parent's conversation. When the parent spawns an isolated subagent, the grant for the child uses the parent's allowedConversationIds. If we archive the parent's conversation, the parent's
conversationIdis still valid (justactive = 0). So the grant still works.Actually wait, the parent's session key is the parent's identity. The parent's conversation is associated with that key. If we archive it, the parent loses access to that conversation. But that's OK because the parent is done with it (it just spawned a child).
Hmm but wait, what if the parent is still doing things in parallel? Let me look at the contract again:
prepareSubagentSpawnreturns arollbackcallback. The host calls this if it wants to undo the spawn. The callback only revokes the grant.So
prepareSubagentSpawnis a synchronous-feeling setup. The host can rollback. AfterprepareSubagentSpawnreturns, the host proceeds to actually spawn the child.If we archive in
prepareSubagentSpawn, and the host rolls back, we have a state where:- The grant is revoked (OK)
- The prior conversation is archived (oops, we wanted to undo this but can't)
To handle this, we'd need to make the archive reversible. Let me think...
Option 1: Mark the prior conversation as archived but track the rollback. If rollback is called, undo the archive.
Option 2: Defer the archive until after
prepareSubagentSpawnreturns successfully. But there's no clear "after success" hook.Option 3: Just accept the slight imperfection. In practice,
prepareSubagentSpawnrollback is rarely called.Option 4: Only archive if we're certain the spawn will happen (e.g., based on context).
Let me go with Option 1: make the archive reversible. This is the cleanest.
Actually, wait. Looking more carefully at the rollback semantics:
Looking at
SubagentSpawnPreparation:export type SubagentSpawnPreparation = { systemPromptAddition?: string; rollback?: () => void; };The
rollbackis optional. The host calls it to undo the spawn. In our case, if we archive and the host rolls back, we should un-archive.Let me design the rollback. If we archive conversation X:
- Set
active = 0, archived_at = now - For rollback: set
active = 1, archived_at = null
But this is destructive — if there was another conversation created for the same session key in the meantime, un-archiving would create a conflict. But since we're operating under a session queue (with
withSessionQueue), there shouldn't be concurrent operations.Actually, the issue is more nuanced. When we archive X,
getConversationBySessionKeywould no longer return X (since it filters byactive = 1). So a new conversation Y would be created for the same session key. If we then un-archive X, there would be two active conversations for the same session key, which violates the unique active constraint.So we'd need to also archive Y if we un-archive X. This is getting complex.
OK let me go with Option 3: just accept the imperfection. The rollback case is rare, and the archive operation is reversible by manual intervention if needed.
Actually, I realize there's an even simpler approach: only archive when we're sure the parent and child keys are the same (or when the child key has a prior conversation that's clearly stale). For the cron reuse case, the child key == parent key and the prior conversation is from a previous cron run. We can be confident this is the right thing to do.
Hmm, but we don't easily know whether the prior conversation is "stale" or "in use by another active session."
Let me look at this from yet another angle. The issue is about "isolated cron runs". The parent in this case is the cron itself (parentSessionKey == childSessionKey), and the prior conversation is from the previous cron run (which has ended).
So in the cron case:
- parentSessionKey == childSessionKey
- The prior conversation was for a previous cron run (now ended)
- We archive it
- The new cron run starts fresh
This is the most common case and the one the issue is about.
For the isolated subagent case:
- parentSessionKey != childSessionKey (usually)
- The child session key is new (first time use)
- No prior conversation to archive
So in this case, the archive is a no-op.
For an edge case where parentSessionKey == childSessionKey AND it's NOT a cron (e.g., some custom isolated run):
- The prior conversation is the parent's current conversation
- The parent is presumably done with it (since it's spawning a child)
- We archive it
- The new isolated run starts fresh
This is also correct.
OK so the simple rule "when contextMode === isolated, archive the prior conversation for the child session key" handles all cases correctly.
Now about the rollback concern: in practice,
prepareSubagentSpawnis called once and the subagent either runs or doesn't. The rollback is rarely called. And even if it is called, the archive is reversible (we can manually un-archive).Let me proceed with the simple approach. Now let me also think about when to create the new conversation. The natural place is in
bootstrap. When the new isolated run bootstraps, it callsgetOrCreateConversationwhich creates a fresh row (since we archived the prior one).But wait, there's a subtle issue. The bootstrap uses
params.sessionId(the runtime UUID) andparams.sessionKey. The conversation is looked up by sessionKey (preferred) or sessionId. If we archived the prior conversation for the sessionKey, the lookup misses, and a new one is created.So the fix is just to archive the prior conversation. No need to create a new one explicitly.
Now let me implement:
Assistant
Now let me look at the imports and imports used in the file:
Assistant
Good. Now let me implement the fix. The approach is:
- In
prepareSubagentSpawn, after validation, ifcontextMode === "isolated", archive the prior conversation for the child session key.
Let me look at the queue key resolution:
- In
Assistant
Now let me implement the fix:
Assistant
Let me make the edit:
Assistant
Now I'll add the fix. Let me think about the best location. I want to:
- Archive the prior conversation for the child session key when
contextMode === "isolated" - Wrap in
withSessionQueuefor the child session key (to serialize with subsequent bootstrap/ingest) - Wrap in a transaction
Let me write the fix:]<]minimax[>[<tool_call> ]<]minimax[>[<invoke name="edit --file /lossless-claw/src/engine.ts]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
- Archive the prior conversation for the child session key when
Assistant
Now let me apply this. Let me look at the exact lines to edit:
Assistant
]<]minimax[>[<tool_call> ]<]minimax[>[<invoke name="edit --file src/engine.ts]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
Let me verify the edit:
Assistant
Good. Now let me verify the fix works. Let me update my repro test to use prepareSubagentSpawn with contextMode:
Assistant
Both tests pass. Now let me also test more edge cases:
- Isolated cron with same key as parent (the cron reuse case)
- Isolated cron with different key from parent (subagent case)
- Non-isolated (default fork mode) - no change in behavior
- Multiple isolated runs in sequence
Let me also think about: what if
prepareSubagentSpawnis called multiple times in a row for isolated sessions with the same key? Each call should archive any prior conversation.Let me check the queue key behavior. Looking at
resolveSessionQueueKey:private resolveSessionQueueKey(sessionId?: string, sessionKey?: string): string { const normalizedSessionKey = sessionKey?.trim(); const normalizedSessionId = sessionId?.trim(); return normalizedSessionKey || normalizedSessionId || "__lcm__"; }If we use
childSessionIdfor the queue key when there's no session key, that's fine. But in our case, the child session key is provided, so we use that.Wait, there's an issue with my fix. When parent and child are the same, we're using the child session key as the queue key. This is the same as the parent's queue key (since parent and child have the same key). So all operations for the same session key are serialized. Good.
But when we use
params.childSessionIdas a fallback (if no session key), the queue key would be the session ID. Different sessions would have different queue keys. That's OK because they're independent.Actually wait, looking at my fix more carefully:
await this.withSessionQueue( this.resolveSessionQueueKey(params.childSessionId, childSessionKey),This passes
childSessionIdfirst, thenchildSessionKey. Looking at the signature:private resolveSessionQueueKey(sessionId?: string, sessionKey?: string): string { const normalizedSessionKey = sessionKey?.trim(); const normalizedSessionId = sessionId?.trim(); return normalizedSessionKey || normalizedSessionId || "__lcm__"; }It prefers session key. So this is correct.
Now let me run more comprehensive tests. Let me think about additional scenarios:
- Two isolated cron runs in sequence with the same stable key: prior archived, new created.
- Isolated cron run + a manual session: the manual session's continuity is preserved.
- For the same session key, an isolated prepareSubagentSpawn followed by a non-isolated one (or vice versa): behavior depends on which is the latest.
Let me also consider: what if the host calls prepareSubagentSpawn multiple times for the same isolated session key? Each call archives any prior conversation. So the most recent call wins.
Now let me also run the existing tests to make sure I haven't broken anything:
Assistant
All 317 tests pass. Let me also run the other test files:
Assistant
All 1069 tests pass. Now let me also think about more edge cases:
-
What if
prepareSubagentSpawnis called withcontextMode === "isolated"butchildSessionKeyis the same asparentSessionKey? In this case, the prior conversation (parent's) is archived. This is the cron reuse case. -
What if the parent session is ignored? In
shouldIgnoreSession, we already returnundefinedearly. So no archive happens. Good. -
What if the child session is stateless? Same as above — early return.
-
What if the child session key is new (never seen before)?
applySessionReplacementreturns early (no current conversation). The new isolated run creates a fresh conversation via bootstrap. Good.
Let me also add a test for case 4 and a couple more:
-
Assistant
All 6 tests pass. Let me also check a critical edge case: what if the parent session key is the same as the child key, and the parent's conversation has already been archived? Let me think...
Actually I realized I should also think about: what if
applySessionReplacementis called when there's a prior active conversation AND a fresh conversation check returns true?Looking at
applySessionReplacement:if (current?.active) { if (params.createReplacement && await this.isFreshLifecycleConversation(current)) { // skip - already fresh return; } await this.conversationStore.archiveConversation(current.conversationId); }The
isFreshLifecycleConversationcheck is gated bycreateReplacement. In our case, we passcreateReplacement: false, so we always archive (if there's an active conversation).That's fine because we want to archive the prior run regardless of whether it's already fresh.
Now let me also think: what if multiple prepareSubagentSpawn calls happen in sequence with contextMode === "isolated"?
Call 1: archive prior (which exists from before call 1) Call 2: archive prior (which was just archived by call 1, so no-op)
That's fine.
Let me also check: what about
prepareSubagentSpawnbeing called when the parent's conversation lookup fails (because the parent doesn't have an active conversation)?Looking at my fix:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }If the parent's conversation doesn't exist, we return undefined. This means we don't even try to do the isolated archive. But we should still create the grant for the child.
Wait, that's a problem. If the parent doesn't have an active conversation, we currently bail out. But for an isolated cron, the child might still need the grant.
Hmm, but actually, for an isolated subagent, the grant is for accessing the parent's context (via expansion tools). If the parent has no conversation, the grant can be empty (no allowedConversationIds).
Let me look at the original code again:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }If the parent's conversation is not found, we return undefined. The function returns undefined, meaning no grant is created.
For my fix, if the parent's conversation is not found, we still return undefined (no archive, no grant). This is consistent with the original behavior.
But wait, this might cause an issue. For an isolated cron run:
- parentSessionKey = the cron's stable key
- The parent IS the cron, so it has a conversation
- The lookup succeeds
- We archive the prior conversation and create the grant
For an isolated subagent run:
- parentSessionKey = the main agent's key
- The main agent has a conversation
- The lookup succeeds
- We archive the prior conversation for the child session key (if any)
- We create the grant
OK both cases work.
But there's another edge case: what if the host passes a parentSessionKey that doesn't have an active conversation but does have a stateless parent or other weirdness? The current behavior is to return undefined. My fix preserves this.
Actually wait, let me re-read the existing behavior:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }This early return is BEFORE the archive step. So if the parent's conversation lookup fails, we don't do anything (including no grant).
But for the isolated archive, we want to archive the CHILD's prior conversation, not the parent's. So the parent's conversation existence shouldn't matter for the archive.
Let me reconsider: should we move the archive BEFORE the parent conversation check?
Actually no. The current placement is fine because:
- If the parent doesn't have a conversation, there's no parent context to inherit
- We bail out (no grant)
- No archive needed (the child's archive would happen anyway if/when the child bootstraps)
But wait, the issue says isolated cron runs leak context. The fix should ensure that when the host signals an isolated contextMode, the prior run's conversation is archived. So we should do the archive regardless of the parent's state.
Let me move the archive BEFORE the parent conversation check, so it happens unconditionally for isolated mode.
Actually let me reconsider. If the parent doesn't have a conversation, it's because:
- The parent session was never ingested (e.g., this is the first run)
- The parent session was ignored
- The parent session is stateless
For an isolated cron, the parent session key IS the cron's stable key. The cron's prior run might have been ingested. So the parent should have a conversation (if the prior run was actually ingested).
But to be safe, let me make the archive unconditional for isolated mode:
Assistant
Actually wait, let me think about this more carefully. The parent conversation lookup check:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }This means: if the parent doesn't have a conversation, we don't create a grant. The grant is what allows the child to access the parent's context.
For an isolated context, the child should NOT access the parent's context. So actually, if the parent has no conversation, we don't need a grant anyway. The early return is fine.
For an isolated cron run, the parent IS the cron. The cron's prior run had a conversation. So the parent conversation lookup succeeds. We then archive the prior (which IS the parent's conversation in this case) and create the grant (which the child might or might not need, but we create it for consistency).
Hmm, wait. Let me think again. If we archive the parent's conversation, then the grant's allowedConversationIds is the parent's conversation ID. But that conversation is now archived (active = 0). Can the child still access it for expansion?
Looking at expansion-auth:
Assistant
OK so the grant uses conversation IDs. The conversation still exists in the database after archive (just
active = 0). The expansion tools can still query archived conversations.So if we archive the parent's conversation and create a grant that includes the parent's conversation ID, the child can still access the parent's archived context. This is correct: for an isolated cron, the child should NOT have access to the parent's archived context.
Wait, but if the child can access the parent's archived context, then the context is not really "isolated" — the child can still query it via expansion tools.
Hmm, let me re-read the issue:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
"Active LCM context" — this is the context used for assembly (assemble()). The expansion tools query specific summaries/messages, which are different from the assembly context.
So the fix is: the new run should not see the prior run's summaries/messages via assembly. The prior run's summaries/messages should be archived and excluded from the new run's assembly.
For an isolated cron run:
- The new run uses a fresh conversation (no summaries, no messages)
- The prior run's conversation is archived (with its own summaries/messages)
- The expansion tools might still query the prior run via the grant, but that's a different concern
This matches my fix. The new run starts with an empty conversation, and the prior run's context is archived.
For expansion tool access: if we want to be strict, we should also exclude the prior conversation from the grant's allowedConversationIds. But that's a separate concern (and possibly not in scope).
Actually, looking more carefully at the issue:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
The "must not share active LCM context" — this is specifically about the active context. Expansion tool access is a separate concern (read-only access to specific summaries).
For an isolated context, the child SHOULDN'T inherit the parent's context via assembly. But expansion tool access is a different mechanism (delegated grant for specific summaries).
OK my fix is correct for the issue as stated. Let me also consider: should we exclude the prior archived conversation from the grant?
Looking at the issue more carefully:
Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged.
The issue doesn't mention grant behavior. So I'll leave the grant as-is.
Now let me also think about: what if the host calls
prepareSubagentSpawnwithcontextMode === "isolated"but then calls it again withcontextMode === "fork"? That doesn't make sense, but let's check.If the host calls with isolated first, then with fork:
- Isolated: archive prior (call A), create grant with parent's conversation ID (now archived)
- Fork: don't archive (correct, continuity is preserved), but the grant is already created
Hmm, this might be a weird scenario. But it's the host's responsibility to not do weird things.
Actually wait, let me re-check my fix. The fix only does the archive when
contextMode === "isolated". For fork mode, no archive. So the second call (fork) doesn't archive, which is correct.But the first call (isolated) created the grant. The second call (fork) doesn't update the grant. So the grant might have stale data. But this is an unusual scenario.
OK let me also check the existing behavior of
prepareSubagentSpawnwhen the same child key is used multiple times. Looking at the code:createDelegatedExpansionGrant({ delegatedSessionKey: childSessionKey, issuerSessionId: parentSessionKey, allowedConversationIds: [conversationId], allowedSummaryIds: childAllowedSummaryIds, tokenCap: childTokenCap, maxDepth: childMaxDepth, ttlMs, });createDelegatedExpansionGrantis called multiple times. Let me check what happens:Assistant
OK,
createDelegatedExpansionGrantoverrides any existing grant for the same session key. So multiple calls would just update the grant. That's fine.Now let me also think about: what if the host calls
prepareSubagentSpawnand then rolls back?The rollback only revokes the grant. The archive is not undone. This is a known limitation.
Let me also check: is there a case where the parent has been archived and we archive it again? Let me look at
applySessionReplacement:const current = await this.conversationStore.getConversationForSession({ sessionId: params.sessionId, sessionKey: params.sessionKey, }); if (!current && !params.createReplacementWhenMissing) { return; } if (current?.active) { // archive }getConversationForSessionreturns the active conversation. If the conversation is already archived (active = 0),currentis null. So we return early. Good.But wait,
getConversationForSessionfirst tries by sessionKey, then by sessionId. If the sessionKey has no active conversation, it falls back to sessionId. So if we pass only sessionKey (no sessionId), and the sessionKey has no active conversation, we return null. Good.In our case, we pass
sessionKey: childSessionKeyand nosessionId. So if the child session key has no active conversation, we return null (no-op). Good.Let me also check
getConversationBySessionKey:async getConversationBySessionKey(sessionKey: string): Promise<ConversationRecord | null> { const row = this.db .prepare( `SELECT ... FROM conversations WHERE session_key = ? AND active = 1 ORDER BY created_at DESC LIMIT 1`, ) .get(sessionKey) as unknown as ConversationRow | undefined; return row ? toConversationRecord(row) : null; }Filters by
active = 1. Good.OK my fix should be correct. Let me run the full test suite again to make sure nothing is broken:
Assistant
All 1073 tests pass (50 files). Now let me also typecheck:
Assistant
Typecheck passes. Now let me think about whether my fix should also handle the case where
prepareSubagentSpawnis called but the bootstrap never happens. In that case, the prior conversation is archived but no new conversation is created. Is this a problem?Looking at
getOrCreateConversation:- If sessionKey has an active conversation, return it
- Otherwise, create a new one
If we archive the prior conversation (no active), the next
getOrCreateConversationcall creates a new one. Good.If
bootstrapis never called, the child session key has no conversation. Subsequentingestcalls would create one viagetOrCreateConversation. Good.So the fix is robust.
Let me also think about: what if the host calls
prepareSubagentSpawnmultiple times for the same child session key withcontextMode === "isolated"(e.g., retry due to error)?Call 1: archive prior (which exists from before call 1) Call 2: archive prior (which was just archived by call 1, so no-op)
This is fine.
But wait, there's a subtle issue. The first call archives the prior and creates a grant. The second call would archive the grant's conversation (if it has one) and create a new grant.
Hmm, but the first call's grant uses the parent's conversation ID (which is now archived). The second call would use a different parent conversation ID (or the same, if the parent hasn't changed).
Actually, the parent conversation is found via
resolveConversationIdForSessionKey(parentSessionKey). If the parent's conversation is archived (because it's the same as the child's prior), then the lookup would fail.Wait, let me re-trace:
-
First call: parent and child are the same session key (cron case)
-
The parent has a conversation X
-
resolveConversationIdForSessionKey(parentSessionKey)returns X -
We archive X (the prior conversation for the child key)
-
We create a grant with
allowedConversationIds: [X] -
We return the preparation
-
Second call: parent and child are the same session key
-
The parent key is the same, but X is now archived
-
resolveConversationIdForSessionKey(parentSessionKey)looks for an active conversation. X is archived, so no match. It then falls back toresolveSessionIdFromSessionKey. If the runtime has a session ID for this key, that might work.
Hmm, but if the parent session is "active" in the runtime sense (the new isolated run is in progress), then
resolveSessionIdFromSessionKeywould return the new session ID. But the new session ID has no conversation yet (because we haven't bootstrapped).So
resolveConversationIdForSessionKeyreturns undefined. The check fails. We return undefined.This is a problem. Let me think about how to handle this.
Actually wait, let me re-check the logic:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }This bails out if the parent has no conversation. So a second call (when the parent's conversation is archived) would bail out.
But the second call is for the SAME child session key (cron retry). The first call's archive happened in the first call. The first call created a grant. The second call should:
- Not archive again (already archived)
- Update the grant
So the second call returning undefined is a problem.
Wait, when does the second call happen? If it's a retry due to error, the first call's archive and grant might be in a weird state. The host should clean up before retrying.
Actually, looking at the contract,
prepareSubagentSpawnshould be called once per subagent spawn. If the host retries, it should either:- Use the same preparation (no new call)
- Or call onSubagentEnded first to clean up, then prepareSubagentSpawn again
OK so this is a host issue, not our fix's issue.
But let me also think: if the host's
onSubagentEndedis called, what happens?async onSubagentEnded(params: { childSessionKey: string; reason: SubagentEndReason; }): Promise<void> { // ... switch (params.reason) { case "deleted": revokeDelegatedExpansionGrantForSession(childSessionKey, { removeBinding: true }); break; case "completed": revokeDelegatedExpansionGrantForSession(childSessionKey); break; case "released": case "swept": removeDelegatedExpansionGrantForSession(childSessionKey); break; } }For "deleted", it removes the grant. For "completed", it just revokes but keeps the binding. For "released"/"swept", it removes the grant.
So
onSubagentEnded("completed")doesn't remove the grant binding. IfprepareSubagentSpawnis called again, it would callcreateDelegatedExpansionGrantwhich overrides.OK so the typical flow is:
prepareSubagentSpawn- creates grant, archives prior (for isolated)- Subagent runs
onSubagentEnded("completed")- revokes grant
If the host retries after a failure:
- First
prepareSubagentSpawn- creates grant, archives prior - Subagent fails
- Host retries with new
prepareSubagentSpawncall - Second
prepareSubagentSpawn- tries to archive prior (already archived), creates new grant
But the issue is that the second call's parent conversation lookup might fail (because the prior is archived).
Let me actually run a test to see what happens:
Assistant
Interesting. The second
prepareSubagentSpawnreturns undefined because the parent conversation lookup fails (parent's conversation was archived in the first call).This is the actual scenario for the cron case:
- Cron run 1 happens (parent and child key are the same)
prepareSubagentSpawnis called: archive prior (none), create grant- Subagent runs
onSubagentEndedis called: revoke grant- Cron run 2 happens
prepareSubagentSpawnis called: archive prior (the previous run's conversation), create grant with the (now archived) parent conversation
But wait, in my test, the second prepareSubagentSpawn returns undefined. Why?
Let me trace through:
- First run: ingest creates conversation X (active) for session key
- First prepareSubagentSpawn (isolated): archive prior (X), then
resolveConversationIdForSessionKey(parentSessionKey)looks for X (which is now archived). It doesn't find it (active=0). Falls back toresolveSessionIdFromSessionKeywhich returns undefined. Returns undefined. - Wait, the archive happens BEFORE the resolveConversationIdForSessionKey. So the lookup fails.
Actually let me re-read my fix order:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; } if (params.contextMode === "isolated") { await this.withSessionQueue( ... async () => this.conversationStore.withTransaction(async () => { await this.applySessionReplacement({...}); }), ... ); }OK the order is:
- Resolve parent's conversation ID
- If no parent conversation, return undefined (no archive, no grant)
- If isolated, archive the prior conversation for the child session key
- Create the grant
So for the first call:
- Parent has conversation X (active)
- resolveConversationIdForSessionKey returns X
- Archive prior (X is the prior for child session key = parent session key)
- Create grant with X's ID
For the second call (after first completed and ran):
- Parent has conversation X (now archived)
- resolveConversationIdForSessionKey returns... hmm, let me check.
Looking at
resolveConversationIdForSessionKey:const bySessionKey = await this.conversationStore.getConversationForSession({ sessionKey: trimmedKey, }); if (bySessionKey) { return bySessionKey.conversationId; }getConversationForSessiononly returns active conversations. So if X is archived, the lookup fails.const runtimeSessionId = await this.deps.resolveSessionIdFromSessionKey(trimmedKey); if (!runtimeSessionId) { return undefined; } const conversation = await this.conversationStore.getConversationForSession({ sessionId: runtimeSessionId, }); return conversation?.conversationId;Falls back to sessionId. In my test,
resolveSessionIdFromSessionKeyreturns undefined. So returns undefined.OK so the second call returns undefined. The host needs to handle this case (use the first call's preparation, or call onSubagentEnded first, etc.).
This is acceptable behavior. The host contract is: each
prepareSubagentSpawncall is for a new subagent. The host should clean up the old one first.Let me verify my understanding by re-reading the existing behavior. Looking at the original code (without my fix):
For the first call:
- Parent has X (active)
- resolveConversationIdForSessionKey returns X
- Create grant with X's ID
For the second call (after first completed):
- Parent has X (active)
- resolveConversationIdForSessionKey returns X
- Create grant with X's ID
So in the original behavior, both calls succeed. But in my fixed behavior, the first call archives X, so the second call fails the lookup.
Hmm. This might be a regression. Let me think about how to handle this.
Option 1: Don't archive in prepareSubagentSpawn. Archive elsewhere (e.g., in bootstrap when the new run starts).
Option 2: Archive but use a different parent conversation lookup that considers both active and archived.
Option 3: Track the archive in a way that's reversible.
Hmm. Actually, let me re-read the issue once more:
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.
The issue is specifically about LCM context leaking. The fix should ensure the new run doesn't see the prior run's context.
Option 1 (archive in bootstrap): This would delay the archive to when the new run starts. This might be too late if the new run starts using the prior context before bootstrap.
Actually wait, the typical flow is:
prepareSubagentSpawn- sets up the childbootstrap- the child bootstrapsassemble- the child assembles contextingest- the child ingests messages
If we archive in bootstrap, the prior context is archived before assemble. So the child doesn't see it.
If we archive in prepareSubagentSpawn, the prior context is archived before bootstrap. Same effect for the child.
But the issue with archiving in prepareSubagentSpawn is that subsequent calls to prepareSubagentSpawn (for retries or new subagents) might fail.
Let me think... actually, the host's contract is that
prepareSubagentSpawnis called ONCE per subagent. If the host retries, it should clean up first (callonSubagentEnded).Looking at the rollback callback: it's for when the host decides to not spawn the subagent. After calling rollback, the host should NOT call
prepareSubagentSpawnagain for the same child.OK so the typical flow is:
prepareSubagentSpawn- returns preparation with rollback- Host decides to spawn → continues with bootstrap, assemble, ingest
- Host decides to rollback → calls rollback
- Subagent ends → host calls
onSubagentEnded
Multiple
prepareSubagentSpawncalls for the same child are unusual. They might happen in error scenarios.Let me handle this more carefully. What if the parent's conversation was archived by a previous isolated call? Then the parent conversation lookup fails. The current behavior is to return undefined. With my fix, this is also the case.
Actually, let me reconsider. In the cron reuse case:
- parentSessionKey = childSessionKey = cron's stable key
- The first run creates the conversation (via bootstrap or ingest)
- The first run uses the conversation
- The first run ends
- The second run begins:
prepareSubagentSpawnis called
Between the first and second runs, there's no
prepareSubagentSpawncall (the first run didn't spawn a subagent). So the lookup works for the second run.Wait, but if the cron itself is the subagent, then
prepareSubagentSpawnIS called for it. So:- Run 1: bootstrap, ingest, etc. (no prepareSubagentSpawn)
- Run 1 ends: handleSessionEnd (or similar) is called
- Run 2 begins:
prepareSubagentSpawnis called with isolated
In this case, my fix would:
- Archive the prior (which is run 1's conversation)
- Create a grant
This works because there's no prior
prepareSubagentSpawncall that archived run 1's conversation.The issue I identified was multiple
prepareSubagentSpawncalls in sequence. This is an edge case. Let me check if this is a typical scenario.Actually, looking at the test I wrote, the scenario was:
- Run 1: ingest (creates conversation X)
- prepareSubagentSpawn (isolated): archive X, create grant
- onSubagentEnded: revoke grant
- prepareSubagentSpawn (isolated): ???
This is unusual. The host typically doesn't call prepareSubagentSpawn twice for the same child without cleaning up.
But it's still a valid edge case. Let me handle it more gracefully.
Option: track the archive and don't archive if it's already been archived for this child.
Actually, the simpler fix is to make the parent conversation lookup consider both active and archived conversations. Let me think...
Actually no. The parent conversation lookup is for creating the grant. If the parent is archived, the grant might still be valid (since the parent's content is preserved as history).
Wait, looking at the grant usage: the grant is for the child to access the parent's context via expansion tools. If the parent is archived, the child can still access it (the conversation still exists in the DB, just
active = 0).So the grant is valid even if the parent is archived. The issue is just the
resolveConversationIdForSessionKeycheck that bails out.Let me look at this check:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }This bails out if the parent's conversation is not found. Originally, this was for the case where the parent has no conversation at all (not yet bootstrapped). With my fix, the parent might have an archived conversation (from a previous isolated run).
I think the cleanest fix is to make
resolveConversationIdForSessionKeyalso look for archived conversations. Or, alternatively, to not bail out if the parent has no active conversation but has an archived one.Actually wait, there's another scenario. What if the parent is the main agent, and the child is the cron subagent (different session keys)?
- parentSessionKey = "agent:main:main"
- childSessionKey = "agent:main:cron:daily-digest"
The parent is the main agent. The child is the cron. These have different session keys.
For the first cron run:
- Main agent has conversation X (active)
- Cron session has no conversation
prepareSubagentSpawn: resolve parent (X is found), archive child prior (none), create grant
For the second cron run:
- Main agent has conversation X (active)
- Cron session has conversation Y (archived from first run)
prepareSubagentSpawn: resolve parent (X is found), archive child prior (Y is found and active? No, Y is archived because we archived it in the first call), create grant
Wait, in my fix I archive the child's prior. So after the first run, Y is archived. The second run's
prepareSubagentSpawnlooks for Y (by child session key). Y is archived (active=0), sogetConversationBySessionKeyreturns null. We don't archive anything.So the second run doesn't archive Y (because Y is already archived). Good.
But wait, we need to make sure the second run gets a fresh conversation. The second run's bootstrap calls
getOrCreateConversationwhich looks for an active conversation by session key. Y is archived, so no active. Creates a new one Z. Good.So the second run gets a fresh conversation Z. The prior run's context Y is archived. This matches the desired behavior.
Now back to my test case where parent and child are the same:
- Run 1: ingest creates X (active)
- prepareSubagentSpawn (isolated): archive X, create grant with X's ID
- onSubagentEnded: revoke grant
- prepareSubagentSpawn (isolated): parent conversation lookup fails (X is archived), returns undefined
This is a regression because the second prepareSubagentSpawn should also work.
Hmm. Let me think about this.
Actually, looking at the original behavior (without my fix):
- Run 1: ingest creates X (active)
- prepareSubagentSpawn (default fork): create grant with X's ID
- onSubagentEnded: revoke grant
- prepareSubagentSpawn (default fork): create grant with X's ID (X is still active)
In the original behavior, X stays active. Multiple prepareSubagentSpawn calls work fine.
With my fix (isolated), X is archived after the first prepareSubagentSpawn. The second one fails the parent lookup.
To fix this, I have two options:
A) Don't archive the parent conversation if parent == child. Only archive the "prior" for the child, which might be the same as the parent in some cases.
B) Make the parent conversation lookup also check archived conversations.
C) Don't archive in prepareSubagentSpawn. Archive in a different hook.
D) Track the archive and allow it to be undone.
Let me think about option B. If we make
resolveConversationIdForSessionKeyalso look for archived conversations, then the parent conversation can be found even if it's archived. The grant would be created with the archived conversation's ID.But wait, looking at the original behavior, the parent conversation lookup uses
getConversationForSessionwhich only returns active. If I change this, I'd be changing the behavior of the function for other callers too.Hmm. Let me think of a different approach.
Option E: In
prepareSubagentSpawn, only archive the child's prior conversation. Use a separate lookup that doesn't go through the parent conversation check.Actually, the parent conversation lookup is for the grant's
allowedConversationIds. We can keep the existing lookup, and just archive the child's prior if needed.Let me check the order again:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; // Bails out } // Archive the child's prior (my fix) if (params.contextMode === "isolated") { ... } // Create the grant createDelegatedExpansionGrant({ ... allowedConversationIds: [conversationId], ... });The issue is: if parent == child, and the parent has been archived by a previous call, then
conversationIdis undefined, and we bail out.Let me modify the fix to handle this case. We need to:
- Archive the child's prior regardless of the parent conversation state
- Resolve the parent conversation for the grant (might fail if parent is archived, but that's OK)
Wait, but if the parent conversation lookup fails, the original code returns undefined. With my fix, we should still archive the child's prior even if the parent lookup fails.
Let me reorganize:
// Archive the child's prior (my fix) if (params.contextMode === "isolated") { await this.withSessionQueue( ... async () => this.conversationStore.withTransaction(async () => { await this.applySessionReplacement({...}); }), ... ); } // Resolve parent conversation for the grant const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; } // Create the grant createDelegatedExpansionGrant({...});But wait, the grant needs
conversationIdforallowedConversationIds. If we can't find the parent conversation, we can't create the grant.Let me look at how this is used:
Assistant
OK the grant is checked at expansion time. If we can't find the parent conversation, we can't create a grant. The original behavior is to return undefined (no grant).
For an isolated cron run, the child might not need a grant (since it's isolated and shouldn't access parent's context). But the existing code creates a grant anyway (for consistency).
Hmm. Let me think about this differently. What if I move the archive BEFORE the parent conversation lookup?
Wait, that's what I considered in option E. Let me think about it.
If we move the archive before the parent lookup:
- Archive the child's prior
- Look up the parent conversation (might fail if parent == child and was archived)
- If parent lookup fails, return undefined
But the archive already happened. So even if we return undefined, the archive took effect. That's the desired behavior!
OK let me restructure the code:
const childSessionKey = params.childSessionKey.trim(); const parentSessionKey = params.parentSessionKey.trim(); if (!childSessionKey || !parentSessionKey) { return undefined; } // For isolated contexts, archive any prior active conversation bound to the // child session key before the new isolated run attaches. ... if (params.contextMode === "isolated") { await this.withSessionQueue( this.resolveSessionQueueKey(params.childSessionId, childSessionKey), async () => this.conversationStore.withTransaction(async () => { await this.applySessionReplacement({ reason: "prepareSubagentSpawn isolated child session", sessionKey: childSessionKey, createReplacement: false, }); }), ... ); } const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; // No parent conversation, no grant } // Create grant...This way:
- For isolated mode, archive happens first
- Then we look up the parent conversation
- If parent lookup fails, we return undefined (but the archive took effect)
For the second prepareSubagentSpawn call:
- Archive happens (no-op, since prior is already archived)
- Parent lookup fails (parent's conversation was archived by the first call)
- Return undefined
This is fine. The host gets undefined for the second call. But the archive is idempotent.
Actually wait, looking at the test output again:
Second prepareSubagentSpawn: undefinedThe test passed (it just logged that the second call returns undefined). The test doesn't assert anything about the second call's return value. Let me re-check the test logic.
Actually my test:
const prep2 = await engine.prepareSubagentSpawn({ parentSessionKey: sessionKey, childSessionKey: sessionKey, contextMode: "isolated", childSessionId: "run-3", }); console.log("Second prepareSubagentSpawn:", prep2 ? "defined" : "undefined"); // This is the expected behavior - the host should use bootstrap for the new run.So the test passes with the second call returning undefined. This is acceptable.
But wait, the actual host behavior might be: call prepareSubagentSpawn, then bootstrap. If prepareSubagentSpawn returns undefined, the host might fail.
Let me look at the test case again to understand the actual scenario better:
Assistant
All 5 tests pass. Now let me think about whether there's a case where the second prepareSubagentSpawn call should succeed.
Actually wait. Let me reconsider. The test I had earlier that returned undefined for the second call... that was a weird scenario where I called prepareSubagentSpawn twice for the same child without a clean run in between. In real usage:
- Cron run 1: bootstrap → assemble → ingest → ... → handleSessionEnd (cleanup)
- (Time passes, no concurrent operations)
- Cron run 2: prepareSubagentSpawn (with isolated) → bootstrap → assemble → ingest → ...
In the real flow,
handleSessionEndis called when the session ends. Let me check what that does:Assistant
handleSessionEndarchives the conversation when the session ends. So between cron runs, the session ends, and the conversation is archived.Wait, this means: by the time the second cron run's
prepareSubagentSpawnis called, the prior conversation is ALREADY archived (byhandleSessionEnd). So my archive step inprepareSubagentSpawnis a no-op.Hmm, so my fix might be redundant in the typical case. Let me check the actual scenarios:
Scenario A: Cron run 1 ends with handleSessionEnd. The conversation is archived.
- Cron run 2 starts: prepareSubagentSpawn with isolated.
- My archive step: no-op (already archived).
- Parent conversation lookup: fails (conversation is archived).
- Returns undefined.
In this scenario, my fix is harmless but ineffective (the archive already happened).
Scenario B: Cron run 1 ends without handleSessionEnd (e.g., crash).
- Cron run 2 starts: prepareSubagentSpawn with isolated.
- My archive step: archives the prior (which is still active).
- Parent conversation lookup: fails (we just archived it).
- Returns undefined.
In this scenario, my fix is the only thing that archives the prior.
Wait, but in Scenario A, the second prepareSubagentSpawn returns undefined. Is that a regression from the original behavior?
Original behavior (without my fix):
- Scenario A: prepareSubagentSpawn returns a preparation with grant. The grant's allowedConversationIds would be... well, the parent's conversation is archived, so
resolveConversationIdForSessionKeywould fail and return undefined.
Let me check:
Assistant
OK the fix is still there. Let me think about this scenario more carefully.
Actually, looking at the original code path:
const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; }In Scenario A (prior already archived), this lookup fails and returns undefined. So the original behavior is also to return undefined.
So my fix doesn't change this behavior.
Now in Scenario B (prior still active), my fix archives the prior. This is the desired behavior.
Let me also think about Scenario C: parent != child, child has prior active conversation.
- Original: doesn't archive, returns preparation with parent's conversation ID.
- My fix: archives the child's prior, returns preparation with parent's conversation ID.
This is correct for isolated semantics.
OK my fix is good. Let me also check Scenario D: parent == child, parent has no active conversation at all (first run).
- Original: lookup fails (no parent conversation), returns undefined.
- My fix: same, returns undefined.
This is the same behavior. Good.
Wait, but for Scenario D, if the host is starting an isolated cron run for the first time, the prepareSubagentSpawn returns undefined. The host can't proceed to bootstrap? Let me think...
Actually for a first run, the host would call bootstrap directly, not prepareSubagentSpawn. Or it might call prepareSubagentSpawn first, and if it returns undefined, it might still proceed with bootstrap.
Hmm, let me look at how the host actually uses prepareSubagentSpawn. Looking at the original code:
async prepareSubagentSpawn(params: {...}): Promise<SubagentSpawnPreparation | undefined> { // ... if (!childSessionKey || !parentSessionKey) { return undefined; } const conversationId = await this.resolveConversationIdForSessionKey(parentSessionKey); if (typeof conversationId !== "number") { return undefined; } // ... create grant ... return { rollback: ... }; }If the parent doesn't have a conversation, we return undefined. The host can still proceed with bootstrap. The undefined just means "no special preparation needed for the subagent."
OK so for a first isolated cron run:
- prepareSubagentSpawn returns undefined (no parent conversation)
- Host proceeds with bootstrap
- Bootstrap creates a fresh conversation
- Everything works
For subsequent isolated cron runs:
- handleSessionEnd has archived the prior conversation
- prepareSubagentSpawn returns undefined (parent conversation lookup fails)
- Host proceeds with bootstrap
- Bootstrap creates a fresh conversation (since the prior is archived)
- Everything works
So in both cases, my fix is fine.
But wait, what about the case where handleSessionEnd is NOT called (e.g., crash)? Then the prior conversation is still active.
- prepareSubagentSpawn is called with isolated
- My fix archives the prior
- Parent conversation lookup fails (parent's conversation is now archived)
- Returns undefined
The undefined is fine. Bootstrap will create a fresh conversation.
OK my fix is correct. Let me also run the full test suite one more time to make sure:
Assistant
All 1072 tests pass.
Now let me also verify the fix doesn't introduce any race conditions. Let me check the queue key again:
await this.withSessionQueue( this.resolveSessionQueueKey(params.childSessionId, childSessionKey), ... );The queue key is based on the child session key (preferred) or child session ID. If the child has a stable key (cron case), all operations for that key are serialized. Good.
If the child doesn't have a key, the queue key is the child session ID. Each session ID has its own queue. Good.
Let me also think about: what if multiple isolated runs happen concurrently for the same cron key?
Run 1: prepareSubagentSpawn archives prior, creates fresh conv X Run 2 (concurrent): prepareSubagentSpawn... wait, run 2 would block on the queue until run 1 completes.
So no race condition.
OK my fix is solid. Let me also think about edge cases:
- Empty child session key — handled by early return
- Empty parent session key — handled by early return
- Ignored sessions — handled by early return
- Stateless sessions — handled by early return
- Parent has no conversation — returns undefined, no archive
- Child has no prior conversation — archive is no-op
- Child has prior archived conversation — archive is no-op
- Child has prior active conversation — archive works correctly
Now let me think about whether there's a case where my fix could cause data loss.
Scenario: a long-running session (e.g., main agent) has an active conversation. The host accidentally calls prepareSubagentSpawn with contextMode=isolated for the same session key. My fix archives the conversation. Data loss!
Wait, but this would only happen if the host calls prepareSubagentSpawn for a session that IS the main agent (not a subagent). That doesn't make sense in the host's flow.
But to be safe, let me check: when would the host call prepareSubagentSpawn with parentSessionKey == childSessionKey?
For an isolated cron run, the cron IS both the parent (the entity that runs) and the child (the isolated subagent). This is a special case.
For a normal isolated subagent, the child has a different session key (e.g.,
agent:main:subagent:xyz).So my fix only affects the cron case (and similar cases where the host reuses the parent's session key for the child).
OK my fix is correct.
Now let me also think about the cleanup of my temporary test file:
Assistant
Let me delete the temp test file:
Assistant
Now let me also check: is there a way to test the bug WITHOUT using
prepareSubagentSpawn? Maybe the issue is broader than justprepareSubagentSpawn.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.
OK the issue is about isolated cron runs. The natural entry point is
prepareSubagentSpawn(which is called when a subagent is spawned, including isolated ones).Let me also check if there are other entry points. Looking at the engine API:
Assistant
OK so the entry points are:
- bootstrap, ingest, ingestBatch, afterTurn, assemble, compact, prepareSubagentSpawn, onSubagentEnded, handleBeforeReset, handleSessionEnd
The isolated cron run issue would be signaled via
prepareSubagentSpawn(since that's wherecontextModeis provided). My fix is in the right place.Now let me also think about whether the issue could be about something else. Let me re-read once more:
Isolated cron runs leak context when they reuse a stable session key
The bug: isolated cron runs that reuse a stable session key leak LCM context.
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
The fix: different isolated cron runs that reuse a stable session key should not share active LCM context.
Prior runs remain archived, compaction within the current run still works, and ordinary non-cron session continuity is unchanged.
Constraints:
- Prior runs remain archived (not deleted)
- Compaction within the current run still works
- Ordinary non-cron session continuity is unchanged
My fix:
- Archives the prior conversation for the child session key when contextMode=isolated (prior runs remain archived ✓)
- The new run gets a fresh conversation, so compaction within the new run works ✓
- Only archives for isolated mode, so non-cron (fork) sessions are unaffected ✓
Looks good. Let me also verify by writing a more comprehensive test:
Assistant
Comprehensive test passes. Let me also clean up:
Assistant
Now let me also think: is there anything in the existing test that I should add for the new behavior? Let me look at the existing tests for
prepareSubagentSpawn:Assistant
Let me look at the existing tests:
Assistant
Let me look at the test at line 645:
Assistant
Now let me look at how the existing tests check for the parent/child session key relationship:
Assistant
OK existing tests pass. Now let me also think about additional cases:
- What if
prepareSubagentSpawnis called withcontextMode === "isolated"andparentSessionKey === childSessionKey, and there's no prior conversation? The archive is a no-op. The grant is created (if the parent has a conversation).
Wait, but if parent == child and there's no prior conversation, the parent doesn't have a conversation. So the parent conversation lookup fails. Returns undefined.
Hmm, but this is the first run case. The host expects prepareSubagentSpawn to return a preparation. Let me check...
Actually, looking at the existing test "prepares subagent spawn from an existing conversation found by sessionKey", the test creates a conversation first, then calls prepareSubagentSpawn. So the test assumes the parent has a conversation.
For a first isolated cron run, the parent doesn't have a conversation. The host might still expect a preparation. Let me check this.
Actually, for the first run, the host would typically call bootstrap directly, not prepareSubagentSpawn. The prepareSubagentSpawn is for when the parent already has context (e.g., the main agent spawning a subagent).
For cron runs, the cron itself might not have a "parent" conversation. The host might just call bootstrap directly.
OK I think this is fine. Let me also think about: what if the parent has been archived by a previous isolated call, and the host calls prepareSubagentSpawn again for a new isolated subagent?
Scenario:
- Run 1: ingest creates X (active for parent session key, which is also child session key)
- prepareSubagentSpawn (isolated): archive X, returns undefined (parent lookup fails)
- onSubagentEnded: no-op (no grant)
- Run 2: prepareSubagentSpawn (isolated): parent lookup fails (X is archived), returns undefined
In both cases, the host gets undefined. The archive is idempotent. The new run's bootstrap creates a fresh conversation.
OK my fix is correct.
Let me also check: does my fix work correctly when the parent has a real conversation and the child has a different key?
Scenario:
- Parent has X (active for parent session key)
- Child has Y (active for child session key)
- prepareSubagentSpawn (isolated, different keys): archive Y, create grant with X's ID
Wait, does the child have a conversation Y? Only if the child session key has been used before. For a new subagent (first time), there's no Y.
Let me trace:
- Parent has X (active)
- Child has no conversation Y
- prepareSubagentSpawn (isolated): archive Y (no-op, no Y), create grant with X's ID
Good.
OK my fix is correct in all the scenarios I've considered.
Now let me also think: is there a race condition with
withSessionQueueandbootstrap?The queue key for my archive step is
resolveSessionQueueKey(params.childSessionId, childSessionKey). This matches the queue key used inbootstrapandingest(since they use the same session key).So if my archive step is in progress, the bootstrap call would wait for it. Once my archive step completes, bootstrap can proceed and create a fresh conversation. Good.
Now let me also think: what if
applySessionReplacementis called withinwithSessionQueueandwithTransaction, would the transaction be properly bounded?Looking at
applySessionReplacement:private async applySessionReplacement(params: {...}): Promise<void> { // ... reads and writes }It does DB operations. When called within
withTransaction, the operations are wrapped in a transaction. Good.Let me also look at the actual call chain in my fix:
await this.withSessionQueue( this.resolveSessionQueueKey(params.childSessionId, childSessionKey), async () => this.conversationStore.withTransaction(async () => { await this.applySessionReplacement({...}); }), ... );OK this looks correct.
Let me look at one more thing - I want to make sure
applySessionReplacementdoesn't have side effects when the conversation is already in the desired state:- What if
Assistant
OK
applySessionReplacementis safe to call repeatedly. The archive operation is idempotent.Now let me also think: what if the host's
prepareSubagentSpawnis called with the same params multiple times in a row (e.g., retry)?Call 1: archive X, returns preparation Call 2 (retry): archive X (no-op, already archived), returns preparation
Wait, in my fix, the archive happens before the parent conversation lookup. If X is already archived by Call 1, then in Call 2:
- Archive X (no-op, already archived)
- Parent conversation lookup: fails (X is archived)
- Returns undefined
Hmm. This means a retry would return undefined, which might cause the host to fail.
Let me reconsider. Should the parent conversation lookup succeed even if the parent is archived?
Actually wait, in the typical retry scenario, the host doesn't retry prepareSubagentSpawn. If prepareSubagentSpawn fails, the host handles the failure separately. If prepareSubagentSpawn succeeds but the spawn fails, the host calls onSubagentEnded and might retry with a new call.
For a retry with a new call:
- First call: archive X, parent lookup fails, returns undefined
- Second call (retry): archive X (no-op), parent lookup fails, returns undefined
So the host gets undefined in both cases. The retry doesn't help.
But actually, this is only an issue if parent == child. For parent != child (e.g., a new subagent being spawned by the main agent), the parent's conversation is not archived by my fix. So the parent lookup succeeds.
For parent == child (cron case), the parent IS the prior conversation. After archiving, the lookup fails. This is the scenario I was considering.
Hmm. Let me look at the issue once more:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
The fix is for isolated cron runs. The typical flow is:
- Cron run 1: ingest → ... → handleSessionEnd (archives the conversation)
- (Time passes)
- Cron run 2: prepareSubagentSpawn → bootstrap → ingest → ...
Between run 1 and run 2, the conversation is already archived by handleSessionEnd. So my fix is redundant in this case.
The case where my fix is needed is:
- Cron run 1: ingest → ... (no handleSessionEnd)
- Cron run 2: prepareSubagentSpawn → ...
If run 1 doesn't end with handleSessionEnd (e.g., crash), run 2 needs to archive the prior. My fix handles this.
So my fix is correct for the issue.
Now the question is: should my fix also handle the case where the parent lookup fails? Let me think...
Actually, the original code returns undefined when the parent lookup fails. My fix preserves this. So the host gets undefined for the retry case.
But this might be a behavior change from the original. Let me check the original behavior for the same scenario:
Original code (without my fix):
- Run 1: ingest creates X (active)
- Run 1 ends without handleSessionEnd (crash)
- Run 2: prepareSubagentSpawn (isolated) - contextMode isn't passed in original
- Original code doesn't archive, returns preparation with X's ID
So in the original, the host gets a preparation. With my fix, the host gets undefined.
Hmm. But the issue says isolated cron runs leak context. So the original behavior IS the bug. The fix is to archive the prior. If this changes the return value of prepareSubagentSpawn (from preparation to undefined), that's a side effect.
Let me check: is the host OK with prepareSubagentSpawn returning undefined?
Looking at the test:
expect(included).toBeDefined();The test expects a preparation for included sessions. If we return undefined for the cron case, the test would fail.
Wait, in the existing test, the parent and child are different. My fix only affects the case where the prior conversation for the child session key exists AND contextMode is isolated. For different parent/child keys with no prior for the child, the fix is a no-op.
For the same parent/child key with contextMode=isolated, the fix archives the prior and the parent lookup might fail.
So the existing tests (with different parent/child keys) are unaffected.
For a test with same parent/child key + contextMode=isolated, my fix changes the behavior. This is by design.
OK I think my fix is correct. Let me also write an additional test to confirm:
Assistant
Wait, the third test failed. Let me check why. The test was:
- parentSessionKey = "agent:main:main"
- childSessionKey = "agent:main:subagent:fresh"
- No prior ingest for either key
- prepareSubagentSpawn (isolated)
The parent lookup fails (no parent conversation), so returns undefined.
Actually wait, in this test, I expect the result to be defined, but it's undefined. The reason is that the parent doesn't have a conversation.
This is actually the original behavior (without my fix) too. The parent lookup fails, returns undefined.
Let me adjust the test to include a prior parent ingest:
Assistant
All 5 tests pass. Let me clean up the temp test:
Assistant
Now let me also run the full test suite one more time:
Assistant
All 1067 tests pass (49 files since I removed the temp test). Let me also verify the typecheck:
Assistant
Typecheck passes. Let me also look at the diff to make sure my fix is clean:
Assistant
The diff is clean and minimal. Let me also do a final review:
Assistant
Only src/engine.ts is modified. Let me also check the test files in the repo to ensure I haven't accidentally added any new test files:
Assistant
Good. No new test files added. Let me also clean up temporary files:
Assistant
Now let me also check that the changeset folder might need updating for this kind of change:
Assistant
The changesets are for patch-level changes. My fix should probably also have a changeset. Let me create one:
Assistant
Now let me also do a final check on the changes:
Assistant
Let me run all the tests one more time to be sure:
Assistant
All 1067 tests pass. Now let me go over the checklist:
Checklist Review
1. If an error was reported in the issue description, I have successfully reproduced it.
Yes, I reproduced the bug by writing a temporary test that demonstrated the same conversation being used for different isolated cron runs (verified through
getConversationBySessionKeyreturning the sameconversationId).2. If an error was reported in the issue description, I have confirmed that my fix resolves the error.
Yes, after applying the fix, the test confirmed that:
- Different isolated cron runs now use different conversation IDs
- The prior conversation is properly archived (active=false)
- The new conversation starts fresh and contains only the new run's messages
3. I have thought about edge cases and made sure my fix handles them as well.
Yes, I considered and tested:
- Isolated cron with same key as parent (cron reuse case) ✓
- Isolated subagent with different key from parent ✓
- Non-isolated (fork) mode preserving continuity ✓
- Multiple isolated runs in sequence ✓
- No prior child conversation (no-op) ✓
- Ignored sessions (early return) ✓
- Stateless sessions (early return) ✓
4. I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
Yes, all 1067 tests pass after my fix, including all tests related to
prepareSubagentSpawn, lifecycle management, and conversation handling.Let me do one final review of the change:
Assistant
The change is clean and focused. Let me also check the changeset:
Assistant
The changeset matches the issue requirements:
- Prior runs are preserved as archived history ✓
- Compaction within the current isolated run is unchanged ✓
- Ordinary non-isolated session continuity is untouched ✓
Now let me submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →