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 what we're working with.
Assistant
Now let's look for "cron" or "isolated" in the codebase:
Assistant
Let me look at the engine code that handles
contextMode:Assistant
Let me search for how
cronis handled in the context of LCM context loading:Assistant
Now let's look at
wirePluginHandlersand how the engine gets called:Assistant
Let me look at how the engine handles session context loading:
Assistant
Now let me understand the issue more deeply. The issue is about "isolated cron runs" reusing a "stable session key" causing leaked LCM context. Let me search for tests and find any related issues:
Assistant
Now I understand more about the context. Let me check git log and recent commits to understand the project better:
Assistant
Now let me look at how the engine processes the before_agent_run hook to understand context loading:
Assistant
Let me look at how the context engine handles "isolated" mode and the bootstrap:
Assistant
Now let me search for
ingestand how it handles context loading for a session run:Assistant
Now let me understand: when an isolated cron run reuses a stable session key, what happens? Let's look at
getOrCreateConversationmore carefully:Assistant
Now I see the key behavior. When
getConversationBySessionKeyis called, it returns the ACTIVE conversation. So if a session key likeagent:main:cron:daily-digest:run:run-123is used, and it already has an active conversation from a prior isolated cron run, the new run will be appended to that existing active conversation - leading to leaked context.Let's look at the test cases to confirm understanding:
Assistant
Now let's check
contextModein engine:Assistant
Now I understand the contextMode is about a subagent spawn with contextMode="isolated" vs "fork". Let's look for how this is propagated through:
Assistant
Now let's see the existing tests for prepareSubagentSpawn:
Assistant
Now let me look for the existing engine tests around cron sessions:
Assistant
Now let me look at how
cronsessions are handled. The issue title mentions "Isolated cron runs leak context when they reuse a stable session key". Let me look at what the existing solution might be:Assistant
Now let me understand how the host OpenClaw differentiates isolated vs. non-isolated cron runs. Let me look for contextMode in tests:
Assistant
Now let me look at where the issue applies in the engine. Let's look at
bootstrapto see if there is any handling forcontextMode:Assistant
Now I understand the issue better. When a session key is reused,
getOrCreateConversationfinds the existing active conversation (because the session key matches), and the next run reuses it instead of starting fresh. The issue mentions "isolated cron runs" specifically.Let me look at how cron sessions are typically identified - look for
cron::Assistant
Now let me look at the README about cron sessions:
Assistant
Now I need to understand the issue. 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 the scenario is: OpenClaw runs an isolated cron task with a stable session key (like
agent:main:cron:daily-digest:run:run-123). After this run completes, a fresh isolated cron run reuses the same session key. The current behavior re-uses the active LCM conversation from the previous run, leaking context from the prior cron run.The fix should detect isolated cron sessions that share a stable session key across multiple runs, archive the previous conversation (so prior runs remain archived), and create a fresh active conversation.
Let me see how to identify these "isolated cron" sessions. Let me look at how context engine and
prepareSubagentSpawnwork withcontextMode:Assistant
Now let me understand what makes a cron session "isolated". The README mentions "isolated run sessions like
agent:main:cron:daily-digest:run:run-123" — these are stable session keys used by cron jobs that may run multiple times.Let me search for how this is detected in the codebase:
Assistant
Now let me check what
applySessionReplacementandhandleBeforeResetdoes:Assistant
Now let me look at where the cron session detection can happen. The issue says: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
So an "isolated cron run" is one where OpenClaw reuses the same stable session key. Looking at how
contextModeis involved:isolatedmeans no shared contextforkmeans forked context
Let me check how OpenClaw handles cron session runs to understand:
Assistant
Now let me look at the existing
handleSessionEndto see when it fires, to understand how to detect the start of a new isolated cron run:Assistant
Now let me look at how OpenClaw hosts isolated sessions:
Assistant
Now let me look at how
getConversationBySessionKeyand how it handles the situation. Let me trace the lifecycle:Assistant
Now I want to understand: for an isolated cron run that reuses a stable session key, what's the behavior today? Let me reproduce.
Let me look at
ingestSingle:Assistant
Now I see!
getOrCreateConversationwill find the existing active conversation by sessionKey. So if the session key is reused, the prior context is inherited.Let me think about the solution:
-
The host OpenClaw may provide a way to signal that this is an "isolated" cron run. The
contextMode: "isolated"is used for subagent spawns, but maybe cron sessions also need a similar signal. -
Looking at the issue title again: "Isolated cron runs leak context when they reuse a stable session key" - this is about isolated cron runs. The key is identifying isolated cron runs.
Let me look at the OpenClaw runtime model to find how this is signaled:
-
Assistant
Let me see the engine parameters for
bootstrap:Assistant
Let me look at the ContextEngine interface to see how it defines operations:
Assistant
Now let me understand the design. The
contextMode: "isolated"only exists forprepareSubagentSpawn. For cron jobs in OpenClaw, the host probably uses something different. Let me think about it from the perspective of the issue:The issue says: "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
So the host (OpenClaw) creates an isolated cron run with a stable session key. After the run completes (or even when starting a new one), a new isolated cron run might reuse the same session key.
The key insight: even though the session key is stable (same identifier), the current run is a fresh execution with no shared state from the previous run. So we shouldn't share active LCM context across these runs.
Now let me understand how the host signals this. Looking at the
assemble,bootstrap,ingest- none of them have an explicit "isolated" flag. So we need a way to detect this from the session key itself, OR from the session lifecycle.Let me look for "isolated" session key patterns:
Assistant
Let me now look for the recent fix that handles similar issues:
Assistant
Let me look at this prior fix to see how similar issues were addressed:
Assistant
Let me look at the existing changeset files to understand the changeset format:
Assistant
Now let me look at the
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingfunction:Assistant
Now I have a clearer picture. There's an existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingthat detects when a stable session key is reused with a different session file. But the case for "isolated cron runs" might not have a different session file - the host might use the same file each run.Let me look at how OpenClaw detects cron isolation. Perhaps the host passes an
isolatedflag:Assistant
Let me look for any references to
isolatedin CHANGELOG:Assistant
Let me check recent fixes to understand pattern:
Assistant
Now let me check the OpenClaw node_modules to see if there's any cron session info there:
Assistant
Now let me trace through the problem more carefully. Let me look at how OpenClaw models "isolated cron runs":
The key insight is that the
contextMode: "isolated"parameter is only used inprepareSubagentSpawnfor subagents. For cron runs in OpenClaw, there isn't an explicitisolatedflag.Looking at the issue carefully:
- "Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context."
- The phrase "isolated cron" suggests these are isolated cron jobs (with no shared state).
The way to detect this is via the session key pattern itself. Cron isolated run session keys are typically stable (don't change between runs of the same job) - they look like
agent:main:cron:daily-digest:run:run-123. They are detected by the patternagent:*:cron:**(oragent:*:cron:*:run:**).But more importantly, OpenClaw's
contextModemay also exist for cron jobs. Let me look at how the host providescontextMode:Assistant
Now, the question is how do we detect an isolated cron run? Let me check the existing
getConversationBySessionKeylogic again. The question is: in an isolated cron run, the prior run is already archived? Or does it remain active?Let me look at how the OpenClaw architecture works for cron sessions. From the README:
agent:*:cron:**excludes cron sessions, including "isolated run sessions likeagent:main:cron:daily-digest:run:run-123"
So when cron sessions are NOT excluded (default), they go through the engine. When an isolated cron run happens, it creates a stable session key. Then a new isolated cron run reuses the same session key.
Now the question is what makes the second run "isolated" - is it just the fact that it's a new cron run (with same session key), or is there an explicit signal?
Let me check how the OpenClaw architecture describes this. Let me look at the engine's behavior more carefully:
Assistant
Now let me check the
assembleandbootstrapflow once more to understand where the issue might arise:Assistant
Now I think I understand. The detection would happen via the
runtimeContextfield. Let me check:Assistant
Now let me check what code paths use
runtimeContext:Assistant
Now, let me think about this more carefully. The fix should be based on the runtime context, not the session key. Looking at the existing code, OpenClaw may set a runtime hint in
runtimeContextindicating isolation.Let me check what kinds of things are in runtimeContext:
Assistant
Now let me search how
runtimeContextcould signal isolation. Actually, given the issue says "isolated cron runs" specifically and given thecontextMode: "isolated"parameter exists, I think the most natural interpretation is:The host (OpenClaw) signals an isolated cron run through some means. Let me look for OpenClaw hooks like
before_agent_run:Assistant
Now I have a clearer picture. Let me approach this differently - the issue is general. The fix should be in the engine when it receives a bootstrap or first ingest for a session key that already has an active conversation.
But wait - the issue says "isolated cron runs". Let me see if there's an existing
isolatedflag in the engine or host contract.Let me think about this practically. The fix needs to be:
- Detect when a session is "isolated" (i.e., the host signals this in some way)
- When detected, archive the prior active conversation before bootstrap/ingest
- Create a fresh active conversation for the new run
The signal must come from somewhere. Let me check if maybe it's the session file path itself:
Assistant
Let me look at recent fix-related issues to understand what tests are expected:
Assistant
No existing tests. Let me look at how the openclaw bridge passes runtime info:
Assistant
Now, let me look at the test setup to see how the engine is being constructed and tested:
Assistant
Now let me think about this issue more thoroughly:
The fix needs to detect isolated cron runs. Looking at the runtime context, there's likely a flag like
isolated: trueorcontextMode: "isolated"set for cron jobs.Looking at the existing
prepareSubagentSpawnwithcontextMode: "isolated", this sets up an isolated subagent that doesn't share context. The issue says this same logic should apply to "isolated cron runs" that reuse a stable session key.Let me look at how this is likely signaled. Most likely the OpenClaw runtime sets a flag indicating that this is an isolated run. Let me check the
runtimeContext:Assistant
OK so
contextMode: "isolated"only exists inprepareSubagentSpawn. For cron jobs, the only signal we have is probably throughruntimeContext.Let me look more at the runtime context to see if we need to add isolation detection:
Assistant
Now let me look at the plugin's
before_prompt_buildhook more carefully:Assistant
Now let me think about the issue. The issue clearly says "Isolated cron runs" but the host doesn't seem to provide an explicit
isolatedflag for cron in the current bridge.Let me check more carefully the bootstrap path to find where I might need to detect this:
Assistant
Now I understand the bootstrap path. The issue is that when
getOrCreateConversationis called with a session key that already has an active conversation (from a prior isolated run), it returns the existing conversation - inheriting prior context.Now let me think about how to detect "isolated cron runs":
Looking at this more carefully:
- The host (OpenClaw) creates an isolated cron run session
- The session key is stable across runs
- The host likely indicates "isolated" via
runtimeContext(e.g.,runtimeContext.isolated === trueor similar)
OR
- The host may not pass an explicit isolation flag
- We may need to detect the case via some heuristic
Let me check what existing PRs in the codebase look like for similar fixes:
Assistant
Now let me approach this differently. Let me look at how the OpenClaw source actually identifies isolated cron sessions:
Assistant
Let me look at the broader context of the issue - the test setup
createEngineWithDeps:Assistant
OK now let me run existing tests to see the current state:
Assistant
Now let me write a small reproduction script to verify the bug exists:
Assistant
Let me write a vitest test instead:
Assistant
I've successfully reproduced the bug! Both messages end up in the same active conversation when the session key is reused. The fix needs to ensure that when an isolated cron run reuses a stable session key, the previous conversation gets archived and a fresh one is created.
Now let me clean up the test:
Assistant
Now, let me think about how to detect isolated cron runs. The host (OpenClaw) must signal this somehow. Looking at the openclaw-bridge, I notice there's
runtimeContextfield. Let me check how OpenClaw uses cron sessions. Since we don't have direct access to OpenClaw source, let me see if there's any signal already present in the engine:Assistant
Now, the question is: how do we know the run is "isolated"?
Looking again at the
runtimeContextmechanism - I believe the host OpenClaw sets anisolatedflag in the runtime context for cron jobs (since they're isolated by nature). Let me think more carefully.Actually, looking at the README: "isolated run sessions like
agent:main:cron:daily-digest:run:run-123" - therun:run-123part of the key is what makes it isolated. This means OpenClaw creates a stable session key likeagent:main:cron:daily-digest:run:run-123for each isolated run.So the detection mechanism might be the session key pattern
run:run-itself, or just any stable session key that has acron:segment but isn't actually being excluded.But looking at this more carefully - the issue title says "isolated cron runs" and the existing
contextMode: "isolated"parameter is used inprepareSubagentSpawn. The fact that the issue title uses "isolated" terminology (same ascontextMode) suggests OpenClaw might be signaling isolation throughcontextModefor these cron runs too.Let me look at what
runtimeContextactually contains in practice. Let me check the bridge for clues:Assistant
Now I understand. The runtimeContext has things like
allowDeferredCompactionExecution,currentTokenCount,rewriteTranscriptEntries,usage,promptCache, etc.For an isolated cron run, OpenClaw likely signals it via
runtimeContext.isolated === trueor similar.Let me think about this differently. The fix should:
- Accept a signal from the host indicating isolation
- When detected, archive the prior active conversation and start fresh
Let me look at what existing patterns there are for this kind of detection. Let me look at
bootstrapmore carefully to understand how I can add this logic:Assistant
Now I see the structure. There are functions like
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingandfindAmbiguousSessionKeyRuntimeRolloverthat handle similar cases.Let me think about the actual approach. Looking at the issue, "isolated cron runs" probably refers to OpenClaw's cron mechanism where each cron job is a separate, isolated execution. The host would signal this through... probably nothing in the current contract.
Wait - let me check what
runtimeContextwould naturally contain. Looking at theruntimeContextdocumentation in OpenClaw docs is not available to me, so let me check what fields the existing code expects:Assistant
Now let me look at the OpenClaw spec more carefully. Let me check the test for the
contextModerelated scenarios:Assistant
OK let me re-examine the 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.
So:
- There's no public interface change
- Prior runs should be archived (not deleted)
- Compaction within current run should still work
- Ordinary non-cron session continuity is unchanged
Let me see what the engine already has for similar detection. Let me look at
assemblefor how it handles the rotation:Assistant
Hmm. The
contextModeparameter only exists forprepareSubagentSpawn. For cron runs, the host doesn't provide a signal explicitly.Let me look at the OpenClaw docs to understand cron session management. Wait, I just realized - the issue is about runtime sessions. Let me think about this from a different angle:
The phrase "isolated cron runs" implies:
- Each cron run is its own isolated execution
- They reuse a stable session key (i.e.,
agent:main:cron:daily-digest:run:run-123) - The host (OpenClaw) creates the session with that stable key, but each run starts fresh
This means each new cron run is a "fresh start" in terms of context, but the session key is reused. The LCM engine needs to detect this and reset the active context.
Now, looking at the architecture - if the host creates a new session ID for each run, but reuses the session key, the LCM engine should archive the previous conversation and create a new one. This is exactly what
getOrCreateConversationdoes for sessionId - but it does NOT do this for sessionKey when there's already an active conversation.The fix should:
- In
bootstrap,ingest,assemble,afterTurn: when we detect that an active conversation exists for the same session key but with a different sessionId, AND this is an "isolated" run, archive the prior conversation.
But we need to know if it's "isolated". Looking at the OpenClaw contract, there must be a way to signal this. Let me check the bridge more carefully:
Assistant
OK so the only
isolatedflag in the current contract iscontextMode: "isolated"inprepareSubagentSpawn. But for cron runs, this doesn't apply.Let me look at this from yet another angle. Perhaps the design is:
- The host passes
runtimeContext: { isolated: true }or similar for cron runs - We need to add this detection
OR
- The host passes the session key itself in a specific format
- We detect it from the key pattern
Let me check the OpenClaw changelog/docs again:
- The host passes
Assistant
OK now let me think about this more carefully.
The issue says: "Isolated cron runs leak context when they reuse a stable session key"
I think the simplest interpretation is:
- A cron job in OpenClaw creates an isolated session for each execution
- Each isolated session uses a stable key like
agent:main:cron:daily-digest:run:run-123(which doesn't change between runs of the same cron job) - The sessionId for each run IS different (it's a fresh runtime UUID per execution)
The issue: when LCM receives the new run with the same sessionKey but different sessionId, it currently reuses the active conversation from the previous run - leaking context.
The fix: detect when this happens and archive the previous conversation, creating a fresh one.
The signal must come from somewhere. Let me look more carefully at the bootstrap path. 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) { if (byKey.sessionId !== sessionId) { // Update the session_id but KEEP the conversation! this.db.prepare(...).run(sessionId, byKey.conversationId); byKey.sessionId = sessionId; } return byKey; } } ... }When the session key is reused with a different sessionId, it just updates the sessionId but keeps the same conversation. This is the source of context leakage.
Now, the signal. I think the natural way for the host (OpenClaw) to signal isolation is through
runtimeContextsince that's the runtime context. Let me check whatruntimeContextis for the host.Actually wait. Let me look at how the runtime context flows. In
bootstrap, we don't get aruntimeContext. Iningest, we don't get one either. Inassemble, we don't. InafterTurn, we don't. Onlycompactandmaintainget aruntimeContext.So
runtimeContextis NOT the right place for an "isolated" flag for cron runs.Let me look at this from yet another angle. What if the OpenClaw host provides a way to indicate "isolated" through a different mechanism, like the sessionFile path itself? Or maybe the issue is simpler - the engine needs to ALWAYS treat cron sessions (by pattern) as isolated.
Let me look at what
shouldIgnoreSessiondoes withcron:**:Looking at
shouldIgnoreSession, it returns true for sessions matching theignoreSessionPatterns. By default,cronsessions are NOT ignored (only via config). So they go through normal processing.Hmm, let me look at this from another angle. Maybe the issue is to add the
isolatedhandling in thebootstrappath when:- Session key is reused
- Session ID is different
- The session file is different (or doesn't exist)
Actually, looking at
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing, this handles the case where the tracked transcript file is missing. So when an isolated cron run reuses a session key, the prior transcript file may not exist, and this function would rotate.But the issue says this is currently leaking context, so this mechanism isn't working for isolated cron runs.
Let me see if I can determine the actual signal. The README mentions "isolated run sessions like
agent:main:cron:daily-digest:run:run-123". The key part isrun:run-123. This is part of the session key pattern.Actually let me think about this: maybe the fix is to detect this specific pattern (cron with
run:segment) and treat these as isolated. Let me look at the existingcronsession handling:Assistant
OK now I have an idea. The issue says no new public interfaces. So the fix should be internal. Let me look at how to detect this scenario:
Scenario: A new run starts with a session key that already has an active conversation, but the run is isolated (i.e., it should not inherit context from previous runs).
The natural way OpenClaw signals isolation:
- Different session ID for each run (yes - because sessionId is the runtime UUID per execution)
- Possibly a different session file
- The session key is stable (yes)
Let me look at the prior logic for the "stale session key rollover" issue:
Assistant
Now let me look at this from a different angle. Let me trace what happens when an isolated cron run is started in OpenClaw. The OpenClaw host likely:
- Creates a new sessionId (a fresh runtime UUID)
- Sets the session key to the stable key
- Possibly creates a new session file
But how does it know it's "isolated"? Maybe the host calls
before_resetor something? Or maybe via runtime context.Let me check if there's any signal in
runtimeContext:Assistant
Now let me think about it. The fix needs to detect the case where:
- A sessionKey already has an active conversation
- The new run is "isolated" (must not share context)
For the engine, we have limited information from the host contract. But looking at the issue again:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
I think the most natural way to detect "isolated" runs is:
- The sessionKey matches the pattern
agent:*:cron:**(similar to how cron sessions are excluded) - OR there's a new runtime signal
Wait, let me re-read the README again:
Assistant
Now I need to design the fix. Looking at the issue:
- "Isolated cron runs" - this implies they have a specific pattern (cron session keys)
- Reuse stable session key
- Must not share active LCM context
The most reasonable interpretation:
- Cron jobs in OpenClaw have stable session keys but each invocation creates a fresh execution
- LCM should detect this case and not reuse prior conversation
Now, how does LCM know it's an isolated cron run? The most reliable way would be via the
runtimeContext. Let me add support for anisolatedflag in the appropriate place.Wait, let me check what makes a session "isolated" - perhaps it's that it's a cron run. Let me see if cron jobs get a specific signal:
Actually, the simplest interpretation: For "isolated cron runs" (which by their nature are isolated), each invocation starts fresh. So when we detect a cron session key being reused with a different session ID, we should treat it as isolated.
But what about ordinary non-cron sessions that reuse a session key (e.g.,
/resetsemantics)? The issue says "ordinary non-cron session continuity is unchanged" - meaning we should NOT touch these.So the heuristic might be:
- If sessionKey matches a cron pattern AND session ID is different AND there was a prior active conversation → it's an isolated cron run → archive and start fresh
OR
- The host signals isolation via runtimeContext
Let me look at what the host OpenClaw might signal. Since the issue says "isolated cron runs" and the existing
contextMode: "isolated"is for subagent spawns, the most natural design is to add anisolated(orcontextMode) signal to the bootstrap/ingest path too.Hmm, but the issue says "No new public interfaces are introduced". So we can't add a new param to the bridge. We have to use what's already there.
Let me look at what runtime context could be set. Actually wait - the bridge's
runtimeContextis oncompactandmaintain. We don't get one inbootstrap,ingest,assemble, orafterTurn. So we can't get isolation info from runtimeContext for cron runs.OK so the detection must come from sessionKey or sessionFile or sessionId. Let me think...
Looking at the README again, "isolated run sessions like
agent:main:cron:daily-digest:run:run-123" - this is a SPECIFIC pattern of session key. Therun:run-123segment identifies the run. The fact that this is stable across runs is what makes it "isolated".Wait - actually the natural interpretation may be:
- For cron jobs in OpenClaw, each isolated execution has a stable session key like
agent:main:cron:daily-digest:run:run-123 - The host creates this stable key ONCE and reuses it for each cron run
- For LCM to recognize "isolated" runs, we need to detect this pattern
Looking at the pattern
agent:main:cron:daily-digest:run:run-123, the structure is:agent- agent prefixmain- agent IDcron- cron segmentdaily-digest- cron job namerun- segmentrun-123- run ID
For LCM to detect "isolated cron runs", I think the right approach is:
- Detect session keys matching the pattern (e.g., having
cron:segment ANDrun:segment) - When such a session key is reused with a different sessionId → it's an isolated cron run → archive the prior conversation
But this approach is brittle (depends on session key naming convention).
Let me look at this once more. Maybe the host OpenClaw provides the isolation signal through some means I'm missing. Let me look at
bootstrapandingestagain:Assistant
OK so we have
sessionId,sessionFile, andsessionKey. The host doesn't pass anything else tobootstrap.Let me look at OpenClaw architecture docs/specs more carefully to find if there's any clue:
Assistant
No documentation on the isolation mechanism. Let me think about this differently:
Since the issue says "No new public interfaces are introduced", and the existing interface doesn't expose an
isolatedflag forbootstrap,ingest,assemble,afterTurn, the fix MUST work with what's already there.Let me look at this from a fresh angle:
The bug: When an isolated cron run with stable session key
Kis invoked, if there was a prior active conversation forKwith a different sessionId, the new run reuses that prior conversation → context leakage.The fix: When bootstrap/ingest/assemble/afterTurn detects that the session key has an active conversation with a different sessionId (and possibly a different session file), it should archive the prior conversation and create a fresh one for the new run.
But wait, this would break
/resetsemantics and other similar use cases where we WANT to reuse the conversation. The issue says "ordinary non-cron session continuity is unchanged" - so we need to distinguish.Looking at the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing- it already handles the case where the prior tracked transcript file is missing. So if a prior isolated cron run's transcript was deleted, this function would rotate.Let me re-read this function:
private async rotateStaleSessionKeyConversationIfTrackedTranscriptMissing(params: { phase: "bootstrap" | "assemble" | "afterTurn"; sessionId: string; sessionKey?: string; sessionFile?: string; createReplacement?: boolean; }): Promise<boolean> { // ... const activeByKey = await this.conversationStore.getConversationBySessionKey(normalizedSessionKey); if (!activeByKey || activeByKey.sessionId === params.sessionId) { return false; // Same sessionId, no rotation needed } const activeBootstrapState = await this.summaryStore.getConversationBootstrapState(activeByKey.conversationId); const trackedSessionFile = activeBootstrapState?.sessionFilePath; if (typeof trackedSessionFile !== "string" || trackedSessionFile.length === 0) { return false; // No tracked file, can't rotate } const transcriptRotated = params.sessionFile === undefined || trackedSessionFile !== params.sessionFile; if (!transcriptRotated) { return false; // Same file, no rotation } try { await stat(trackedSessionFile); return false; // File still exists, can't rotate } catch (err) { if (!isMissingFileError(err)) { return false; } } // Rotate! ... }This only rotates when:
- Session key has active conversation
- Session ID is different
- Tracked transcript file path is different from current session file
- The old transcript file is missing
So if the new isolated cron run uses a DIFFERENT transcript file AND the old transcript is missing, it rotates. Otherwise, it doesn't.
Now, for isolated cron runs, the session file might be the same path (because OpenClaw creates a fresh transcript at the same path for each isolated run). So
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingwouldn't trigger.Let me check what the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingdoes NOT handle:- Case: Same transcript file, different sessionId, same session key, same transcript file path
- This is the case where OpenClaw creates a fresh transcript file at the same path
In that case,
getOrCreateConversationfinds the active conversation by sessionKey and reuses it. The transcript reconcile may find overlap (because the new transcript file has been recreated).The fix needs to handle this specific case. Let me think about how to detect it:
Possible heuristic: If a session key has an active conversation with a different sessionId AND the session file path matches AND there's a stable identifier pattern (cron-like), treat as isolated cron run → rotate.
OR
Better: The host signals this via
runtimeContext.isolated === true. We need to thread this through.Actually, wait. Let me re-read the issue description one more time:
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.
The issue clearly says "isolated cron runs". The fix is for cron runs specifically. Let me check if there's a way to detect cron runs from session key patterns:
The README says:
agent:*:cron:**excludes cron sessions, "including isolated run sessions likeagent:main:cron:daily-digest:run:run-123".So if a user excludes
cron:**, both the parent cron session and the isolated run sessions are excluded.But by default, they're NOT excluded, and they go through the normal pipeline.
Hmm. The fix needs to detect cron-like patterns AND detect that the session is "isolated" (i.e., a fresh execution). Let me look at the structure:
agent:main:cron:nightly- parent cron sessionagent:main:cron:nightly:run:run-123- isolated run session (stable key)
For an isolated run session:
- It has a
run:run-NNNsegment - This segment is stable across multiple runs (it's part of the session key)
- Each run is a separate execution with a new sessionId
OK so here's my theory: the host creates an isolated run session with a stable key. The new run reuses the key. We can detect this by:
- The session key has a
run:run-Nsegment - The session key has an active conversation from a prior run
- The session ID is different
If all three are true, it's an isolated cron run that should not share context.
But wait, the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingalready checks sessionId differences and session file differences. The issue might be that:- The session file path is the same (OpenClaw recreates the file at the same path)
- So
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingdoesn't trigger - So
getOrCreateConversationreuses the prior active conversation
The fix should:
- Detect the case where sessionKey has an active conversation with different sessionId
- Detect that the session file at the tracked path is "fresh" (different content, different mtime, etc.)
- Or alternatively, use a heuristic that matches "isolated cron run" patterns
Actually, let me look at this from yet another angle. Maybe the fix is simpler - just check if the sessionId is different AND there's an existing active conversation for that sessionKey, then rotate it.
But the issue says "ordinary non-cron session continuity is unchanged". So we need to be careful NOT to rotate ordinary sessions.
Hmm, let me look at the OpenClaw architecture to understand how
/resetis handled. When/resetis issued, the existing logic callshandleBeforeResetwith reasonreset, which archives and creates a replacement. So/resetis handled separately.For subagent spawns with
contextMode: "isolated", the prepareSubagentSpawn creates a delegated expansion grant but doesn't touch the LCM conversation.For subagent spawns with
contextMode: "fork", the bootstrap creates a fork-bounded bootstrap that limits context to the parent.OK so the subagent case is handled differently - it creates a child session with a DIFFERENT session key.
For cron runs, the host creates an isolated session. If this isolated session uses a STABLE session key (i.e., the same key for multiple runs), then we have the issue.
Let me look at this once more. Perhaps the host signals this via:
runtimeContext(only available in compact/maintain)- Or via the bootstrap message contents
Wait - what if the host signals via
runtimeContextinassemble, and we just need to pass it through? Let me check the assemble flow:Assistant
OK no
runtimeContextinassemble. So the host can't signal isolation via runtimeContext.Let me think about this from the simplest possible angle. The natural way OpenClaw would handle isolated cron runs:
Looking at OpenClaw architecture again - the host calls
bootstrapwithsessionIdandsessionKey. The sessionId is the runtime UUID. For isolated cron runs, the host probably creates a new sessionId for each run. The sessionKey is stable (e.g.,agent:main:cron:daily-digest:run:run-123).The LCM engine receives this and currently does:
bootstrap({sessionId: 'new-uuid', sessionKey: 'agent:main:cron:daily-digest:run:run-123', sessionFile: '/path/to/file'})rotateStaleSessionKeyConversationIfTrackedTranscriptMissing- this only rotates if the prior transcript file is missing AND the new sessionFile is differentgetOrCreateConversation- this finds the active conversation by sessionKey (regardless of sessionId) and reuses it
The fix should detect this isolated run case. Given no new interfaces, we need to use existing data.
Wait, let me check if perhaps the
runtimeContextis part of bootstrap or some other path I'm missing:Assistant
OK. Let me think about the most reasonable approach: look at the existing detection of cron-like sessions, perhaps via the session key pattern itself.
Looking at the README, the cron run session keys look like:
agent:main:cron:nightly- parent cron sessionagent:main:cron:nightly:run:run-123- isolated run session
The
run:run-123part is what identifies it as an "isolated run". So we can detect this via the session key pattern.But this is brittle. Let me think if there's a more robust way.
Actually, looking at the README pattern:
agent:*:cron:**matches bothagent:main:cron:nightlyandagent:main:cron:nightly:run:run-123. So the cron pattern itself isagent:*:cron:**oragent:*:cron:*.Let me approach this with a clear plan:
- Detect "isolated cron runs" by session key pattern + session ID differs from active conversation's sessionId
- When detected, archive the prior active conversation and create a fresh one
- Do this in
bootstrap,ingest,assemble,afterTurn
Wait, actually let me look at this more carefully. The issue title says "isolated cron runs". Looking at the existing
contextMode: "isolated"for subagent spawns, this implies the host signals isolation explicitly. For cron, the host doesn't signal this in the current bridge.Hmm let me see if there's another way. Maybe we need to look at what OpenClaw provides via the lifecycle hooks. Looking at
before_resetandsession_end:Assistant
OK, so for cron runs, the host:
- May call
session_endto close the previous run's session - Creates a new session with stable key
If
session_endis called with the right reason (like "released" or "swept"), we could potentially handle this. But the issue says "leak context", which implies the issue happens even when the session_end is called.Let me think about this differently. Looking at
handleSessionEnd:async handleSessionEnd(params: { reason?: string; sessionId?: string; sessionKey?: string; nextSessionId?: string; nextSessionKey?: string; }): Promise<void> { const reason = params.reason?.trim(); if ( !reason || reason === "new" || reason === "unknown" || reason === "restart" || reason === "shutdown" ) { return; // <-- Skips these reasons } ... }For
reason === "new", it skips. But for "released" or "swept", it does the replacement.Let me check what happens for cron session_end reason. The reason codes are:
deleted- revoke grant, remove bindingcompleted- revoke grantreleased- remove grantswept- remove grant
Looking at this list, none of these are explicitly "isolated cron run end".
Let me approach this differently. Let me look at what
applySessionReplacementdoes:Actually, let me think about this issue more concretely. The simplest test case to write would be:
- First, do a bootstrap for a stable cron key
- Then, do a second bootstrap with a new sessionId but same sessionKey
- Verify the new run doesn't share context with the first run
Let me write that test now:
- May call
Assistant
The bug is confirmed. Two isolated cron runs with the same stable session key share the same conversation (the conversation's sessionId is just updated to the latest one).
Now let me think about the fix. Given the issue says "No new public interfaces", I need to use the existing interface. The key insight:
The bug is that
getOrCreateConversationreuses the active conversation when the session key is reused, regardless of whether the run is "isolated" or not.The fix should:
- Detect when a session key is being reused with a different sessionId
- AND there's an existing active conversation for that session key
- AND this looks like an isolated run (heuristic: session file doesn't exist OR has different content)
But the issue says "isolated cron runs" - meaning the host signals this specifically. So maybe the host passes the
sessionFileas something that signals isolation (like a fresh empty file).Actually, wait. 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 word "isolated" here probably refers to the nature of cron jobs (they're inherently isolated). Each cron run is its own execution. The host (OpenClaw) treats them as isolated, so LCM should too.
The simplest interpretation: For cron runs, the session key identifies a job not an execution. Each execution has a different sessionId. LCM should treat each execution as a fresh start.
So the fix is to detect cron-like session keys (e.g., those matching the cron pattern) and rotate the conversation when the sessionId changes.
But wait - that would also affect the parent cron session (
agent:main:cron:nightly). Let me think...Actually, the README pattern
agent:*:cron:**matches both. If we apply the same logic to both, we'd treat the parent cron session as needing isolation too, which might be wrong.Let me look at the README pattern more carefully:
agent:*:cron:*- matchesagent:main:cron:nightly(one segment after cron)agent:*:cron:**- matches bothagent:main:cron:nightlyandagent:main:cron:nightly:run:run-123
The isolated run session specifically has a
run:run-Nsegment. So the pattern for isolated runs would beagent:*:cron:*:run:**oragent:*:*:run:**or similar.Hmm. This is getting complex. Let me look at how the host detects this. Maybe there's a simpler way:
Looking at the issue from a different angle: the OpenClaw host probably creates a session with a fresh transcript file at a new path for each isolated cron run. The sessionKey is stable. So when bootstrap is called:
- sessionId = new UUID
- sessionKey = stable key (e.g.,
agent:main:cron:daily-digest:run:run-123) - sessionFile = fresh transcript path (possibly same path as before)
If sessionFile is the same path and the prior run's transcript is gone, the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingwould handle it (because the file is missing). But if the host creates a fresh transcript at the same path before bootstrap, the file would exist with new content, and the function wouldn't trigger.OK let me look at this from yet another angle. The issue description says:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
So the host creates "isolated cron runtime sessions" with a "stable session key". Each new session is isolated. The LCM must not share context between them.
I think the cleanest interpretation is:
- The host signals "isolated" via the sessionFile content/size or via sessionId
- LCM detects this and rotates the conversation
Given the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingfunction only handles file-missing cases, we need to add handling for the file-exists-but-fresh case.But wait, the issue says "No new public interfaces are introduced". The fix must be internal. We can use the sessionFile path/content to detect "fresh transcript".
Actually, let me re-read the rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function:
// Tracked session file (from prior bootstrap) const trackedSessionFile = activeBootstrapState?.sessionFilePath; if (typeof trackedSessionFile !== "string" || trackedSessionFile.length === 0) { return false; // No tracked file } const transcriptRotated = params.sessionFile === undefined || trackedSessionFile !== params.sessionFile; if (!transcriptRotated) { return false; // Same file path } try { await stat(trackedSessionFile); return false; // File exists at tracked path } catch (err) { if (!isMissingFileError(err)) { return false; } }So if:
- The tracked session file path is different from current sessionFile path
- AND the tracked session file doesn't exist on disk
Then it rotates.
But if:
- The tracked session file path IS the same as current sessionFile path
- OR the tracked session file DOES exist on disk
Then it doesn't rotate.
For isolated cron runs where the host recreates the transcript file at the same path, the second condition fails (file exists with new content).
Now, the fix. Let me think about what data we have:
- sessionId - changes between isolated runs (new UUID)
- sessionKey - stable across isolated runs
- sessionFile - possibly same path or different
The most reliable signal is
sessionId !== activeByKey.sessionId. This means "the same session key is being used by a different runtime session". For ordinary session continuity (where the user is having an ongoing conversation), the sessionId stays the same.But for subagent spawns, the session key is different (parent vs child). So this doesn't apply.
For
/reset,handleBeforeResetis called with reason "reset", which archives and creates a replacement. So/resetis handled separately.For isolated cron runs, neither
before_resetnorsession_endis called between runs. The new run starts fresh with a new sessionId but same sessionKey.So the detection should be: session key has an active conversation with different sessionId, and the run is "isolated" (which we can infer from context).
Now, how to detect "isolated"? Looking at the codebase, I think we can:
- Check if sessionKey matches the cron pattern AND has the
run:run-Nsegment - OR check if sessionFile is "fresh" (doesn't exist or has very different content from when the prior conversation was bootstrapped)
Let me look at the simplest fix that satisfies the issue:
Approach: When bootstrap/ingest/etc. is called with a sessionKey that has an active conversation with a different sessionId:
- If the sessionFile at the prior conversation's tracked path is missing → use existing rotate logic
- If the sessionFile path is the same AND the prior conversation was never bootstrapped at this path → this might be an isolated run, archive prior
- If the sessionFile path is the same AND the prior conversation was bootstrapped at this path → likely ongoing session, don't rotate
Actually, I just realized - maybe the answer is simpler. The issue title says "isolated cron runs" specifically. The session keys for cron runs contain "cron". So we can use the session key pattern to detect cron runs.
Let me look at how the host (OpenClaw) might be handling this. If the host is signaling "isolated" via a specific key shape, maybe:
Looking at the README's
agent:*:cron:**example, cron session keys always have acronsegment. So we can use this pattern to identify cron sessions.For cron sessions:
- The session key identifies a cron job
- Each execution has a fresh sessionId
- The session key may be reused across executions
For non-cron sessions:
- The session key identifies a conversation
- The sessionId is stable throughout the conversation
- The session key may change (e.g., after /new)
So the detection logic could be:
- If sessionKey matches a cron pattern AND sessionId differs from active conversation's sessionId → it's an isolated cron run → archive prior
Let me check if there's a simpler approach by looking at the patterns:
Assistant
Now let me think about a different approach. Maybe the fix is to look at whether the existing conversation has any LCM context for the new session. If the new session is fresh (no DB messages yet), then we shouldn't reuse the old conversation even if sessionId is same.
Wait, let me actually look at the current behavior more carefully:
Assistant
Now I see clearly:
getOrCreateConversationreturns the active conversation by sessionKey, even when the sessionId differs. It just updates the sessionId.The fix should change this behavior to:
- Detect when sessionId differs (i.e., this is a new sessionId reusing the sessionKey)
- If this is an "isolated cron run" → archive the prior conversation and create a fresh one
But we need a way to know if it's isolated. Let me look at the broader architecture once more.
Actually, I think I've been overthinking this. Let me re-read the issue carefully one more time:
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.
OK so the key requirement is:
- Isolated cron runs (specific type of session)
- Reuse stable session key
- Must NOT share active context
- Prior runs remain archived (not deleted)
- Compaction within current run still works
- Ordinary non-cron session continuity is unchanged
The fix is to detect isolated cron runs. The most natural way is via the session key pattern, since OpenClaw's cron jobs use a specific pattern.
But there's another approach: maybe the host signals this via the
runtimeContextofcompact()(sincecompact()is called withruntimeContext). Let me check whencompact()is called in the cron scenario:Actually,
compact()is called when the context is over budget. It's not called on every cron run. So this isn't reliable.Let me look at this from the actual OpenClaw API perspective. The plugin's
register()is called per-agent-context (main, subagents, cron lanes). So the host DOES signal "this is a cron lane" somehow. Let me look:Assistant
Hmm, no obvious signal. Let me try a different approach. Let me see if there's some way OpenClaw communicates this through
runtimeContextor other means.Let me look at what we have in
bootstrapmore carefully:Actually, I think the issue is that I need to look at this from a different perspective. The OpenClaw plugin contract is what the engine receives. Let me look at the existing
contextMode: "isolated"and figure out what it means in the existingprepareSubagentSpawn:Looking at
prepareSubagentSpawn:- If
contextMode === "isolated": the child session is isolated from the parent - If
contextMode === "fork": the child session forks the parent's context (with fork-bounded bootstrap)
The existing implementation only creates a delegated expansion grant - it doesn't actually rotate the conversation. So for subagent spawns with
contextMode: "isolated", the child has its own session key (different from parent) and gets a fresh conversation.For cron runs with isolated mode, the host probably wants the same isolation but reuses the session key (perhaps for tracking purposes). So LCM should detect this and treat it like a fresh isolated session.
OK now I understand. The host signals "isolated" via... something. Since no public interface is added, the signal must be from the existing data. Let me look at what makes sense:
Hypothesis: The host calls
bootstrapwithsessionId(new UUID),sessionKey(stable), andsessionFile(the new transcript path). For isolated runs, the new sessionFile path is the same as the prior run's path (because OpenClaw creates a fresh transcript at the same location).OR
Hypothesis: The host calls
bootstrapand the sessionFile doesn't exist yet (or has been recreated fresh).Let me check the bootstrap path again. The
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingchecks if the prior tracked transcript file is missing. If it is missing AND the sessionFile path is different, it rotates.But what if the host uses the same sessionFile path AND the file exists (because the host created it for the new run)? Then:
activeByKey.sessionId !== params.sessionId→ yes (different sessionId)trackedSessionFile === params.sessionFile→ no rotation needed (same file path)stat(trackedSessionFile)succeeds → no rotation
So no rotation happens. Then
getOrCreateConversationfinds the active conversation by sessionKey and reuses it. BUG.For the fix, I think we need to:
- Detect when sessionId differs AND sessionKey has active conversation
- AND the existing conversation has been "wrapped" (i.e., the prior run completed)
- Treat this as an isolated cron run
How to detect "wrapped"? The conversation might be in various states:
- Empty (just created, never used) - this is fine, reuse
- Has messages from prior session - this is the bug
- Has been archived - this is fine, create new
- Has summary context - hmm, this could be ongoing
Let me look at the
applySessionReplacementfunction:- If
Assistant
This is helpful.
applySessionReplacementarchives the current conversation and creates a new one. This is what we need.Let me look at this from a practical angle. The fix should be: when bootstrap is called with a sessionKey that has an active conversation with a DIFFERENT sessionId, AND the conversation is not "fresh" (has messages or context), AND the host signals "isolated" via... something...
OK let me try yet another approach. Let me look at the runtime context for
compactand see if there's a way to signal isolation there:Assistant
OK, I think the right approach is:
- Look at what data is available in the bootstrap path (sessionId, sessionFile, sessionKey)
- Detect "isolated cron run" through a heuristic on the sessionKey pattern
- When detected, archive the prior active conversation before creating a fresh one
The heuristic for detecting an "isolated cron run":
- Session key matches the pattern of a cron-isolated run (e.g., has both
cronandrunsegments) - OR session key matches a configurable pattern
Actually, wait. Let me re-look at the issue from a totally different angle:
The issue says "isolated cron runs" - maybe this refers to a specific OpenClaw feature where:
- Each cron invocation creates an isolated session
- The session key is stable across invocations (for tracking)
- The session ID differs between invocations
In OpenClaw, this is exactly what
contextMode: "isolated"would handle if it were applied to cron runs. So the host probably passes some signal indicating isolation.Hmm. Let me look at
compactruntimeContext more carefully:Assistant
Only
compacthasruntimeContext. So the host can't signal isolation inbootstrap/ingest/assemble/afterTurn.OK let me approach this from a different angle. Let me look at the actual structure of an "isolated cron run" session key:
agent:main:cron:daily-digest:run:run-123The pattern is
<agent>:<agentId>:<segment>:<jobName>:run:<runId>.The
run:<runId>segment is what makes it "isolated". Each cron job has a unique runId, and the runId is stable for that job.Wait, the runId is stable? That doesn't make sense if it's a fresh run each time...
Unless... the runId is the SAME across multiple invocations of the same job (e.g.,
run:run-123is the "123rd run" of the cron job, and the key is stable for that run number). Or the runId is the job's identifier and stays constant.Looking at the README: "isolated run sessions like
agent:main:cron:daily-digest:run:run-123" - this suggestsrun-123is some stable identifier for that specific run.Maybe OpenClaw treats the cron run identifier as part of the session key, and the same cron job always uses the same
run-Nsuffix. So if the cron job isdaily-digest, it always usesrun:run-123regardless of which invocation.OK this is getting complex. Let me just focus on the fix design.
Given the issue constraints:
- No new public interfaces
- Must detect isolated cron runs
- Must archive prior conversation and create fresh
The natural detection mechanism is via the session key pattern. The cron-isolated run session keys have a specific shape:
<agent>:<agentId>:cron:<jobName>:run:<runId>or similar
For the fix, I'll:
- Add a new internal function to detect isolated cron runs by session key pattern
- In bootstrap/ingest/assemble/afterTurn, check if this is an isolated cron run
- If so, archive the prior active conversation before proceeding
Let me look at where exactly to add this. First, let me look at
bootstrapmore carefully:Assistant
OK so the bootstrap path:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing- rotates if tracked file missingfindAmbiguousSessionKeyRuntimeRollover- checks for ambiguous rollovergetOrCreateConversation- creates or reuses conversation
The fix should add: BEFORE step 3, check if this is an isolated cron run, and if so, archive the prior conversation.
Now I need to decide on the detection mechanism. Let me look at this from a different angle - maybe the detection is simpler than I thought.
Looking at the README:
agent:*:cron:**is the pattern for cron sessions. So cron sessions always havecronin their key.For an "isolated cron run", the session key has:
cronsegmentrunsegment (immediately or with depth)- A specific run ID
For the simplest detection, I think we should look at the session key pattern. Let me look at how the test uses session keys:
Assistant
Now let me design the fix more concretely. I'll add detection of "isolated cron runs" via session key patterns. The pattern would be:
agent:*:cron:*:run:**or similar- Detects session keys that have both
cronandrunsegments
Actually wait, let me reconsider. Let me look at this from yet another angle.
What if the fix is much simpler? What if the issue is that
bootstrap(or some entry point) doesn't callrotateStaleSessionKeyConversationIfTrackedTranscriptMissingin the right cases?Looking at the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing:- Only rotates if
trackedSessionFile !== params.sessionFileAND tracked file is missing
What if the host (OpenClaw) creates the new isolated cron run with:
- A different
sessionFilepath (because each run gets a fresh transcript) - AND the prior transcript file doesn't exist (because it was cleaned up)
Then the existing logic should handle it. Let me verify by simulating this:
Assistant
Excellent! So when the prior transcript file is deleted AND the new session file is different, the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissinglogic correctly creates a NEW conversation (id=2) instead of reusing (id=1).So the bug is specifically about when the prior transcript file still exists. Let me test that case:
Assistant
This confirms the bug. When the same session file path is reused, the prior conversation is reused (with both messages in it).
Now let me look at the real-world scenario. Looking at the issue:
- Isolated cron runs reuse a stable session key
- Each run is fresh (no shared context)
- Prior runs should be archived
The detection has to work with what the host gives us. Let me look at this from yet another angle. Maybe the host (OpenClaw) signals isolation through some other means. Let me check the existing
runtimeContextmore thoroughly:Assistant
OK, only one
contextModeexists in the contract. Let me now think about this more pragmatically. The issue must be addressed by looking at existing signals.Let me look at what happens during
bootstrapwhen the session file is the same but the transcript content might be different. The bootstrap process does a transcript reconcile. If the new transcript file is empty (0 bytes), the bootstrap shouldn't find any overlap with the prior content. Let me see whatreconcileTranscriptTailForAfterTurndoes:Assistant
OK let me look at the practical solution. I'll go with the heuristic that detects "isolated cron runs" by session key pattern. The detection rule:
A session is an "isolated cron run" if:
- The session key contains "cron" AND has the run-related pattern
- OR there's a configurable session key pattern
Looking at the README example
agent:main:cron:daily-digest:run:run-123, therun:run-Nsegment identifies it as an isolated run. So a possible pattern: any session key with bothcronandrunsegments.Hmm but this is brittle. Let me look at this from yet another angle. Maybe the issue is detected by looking at the session file:
When an isolated cron run reuses a session key with a session file that has been reset/cleared, the existing logic doesn't catch it because:
trackedSessionFile === params.sessionFile(same path)stat(trackedSessionFile)succeeds (file exists, even though cleared)
So we need to also check if the session file content has been "reset" (e.g., much smaller than before, or has different content).
But again, this is brittle. Let me look at the simplest possible fix:
The fix: When the session key has an active conversation with a DIFFERENT sessionId, archive the prior conversation. This handles the "isolated cron run" case because each run has a new sessionId.
But wait, this would also affect:
- Subagent spawns with same key? But subagents use different keys.
/reset? But/resetcallshandleBeforeResetwhich already archives.- Normal ongoing conversations? The sessionId stays the same, so we wouldn't trigger.
Let me check when sessionId changes normally:
- After
/reset:handleBeforeResetis called with reason "reset" - this archives and creates replacement - For ongoing conversation: sessionId is stable
- For isolated cron runs: sessionId changes for each run
So checking
sessionId !== activeByKey.sessionIdis a reliable indicator that this is a "new session reusing the key". The question is: should we always treat this as isolated? Or only for specific cases?Looking at the issue:
- "ordinary non-cron session continuity is unchanged"
This implies that for non-cron sessions, the sessionKey+sessionId combination is stable. If sessionId changes for non-cron, it's an unusual situation. The issue says we shouldn't change non-cron behavior.
So the fix should:
- Detect "isolated cron runs" specifically (via session key pattern)
- For these, archive prior conversation when sessionId differs
Let me check what the pattern should be. Looking at the README:
agent:*:cron:**matches cron sessionsagent:main:cron:daily-digest:run:run-123is an isolated run
The distinguishing feature of "isolated run" is the
run:run-Nsegment. So the pattern could beagent:*:cron:*:run:**or similar.But actually, let me think about this more carefully. The README says: "agent:*:cron:** excludes cron sessions for any agent, including isolated run sessions like agent:main:cron:daily-digest:run:run-123".
So ALL cron sessions (including isolated runs) match
agent:*:cron:**. The distinction between parent cron and isolated run is therun:run-Nsegment.For an isolated run, the session key is like
agent:main:cron:daily-digest:run:run-123. For a parent cron session, the key is likeagent:main:cron:daily-digest(just 4 segments after agent).So we can detect isolated runs by checking if the session key has both
cronANDrunsegments.OK let me design the fix. I'll:
- Add a helper function to detect "isolated cron run" session keys (based on pattern)
- In
bootstrapand other entry points, check if this is an isolated cron run AND the sessionId differs from the active conversation - If so, archive the prior conversation before proceeding
Let me look at the test to see how session keys are structured:
Assistant
Now let me look at how this is structured. The pattern
agent:*:cron:**matchesagent:main:cron:daily-digest:run:run-123. But also matchesagent:main:cron:nightly(parent cron session).So we need a more specific pattern for isolated cron runs. Looking at the README example, the isolated run has a
run:run-Nsegment. So the pattern would beagent:*:cron:*:run:**or similar.Let me now design the fix.
Actually, wait. Let me re-think. The issue says "isolated cron runs" - what if the host signals this through
runtimeContext? Let me check OpenClaw's runtime context once more:Assistant
OK no
isolatedfield in runtime context. The fix must be done based on existing data.Let me now design and implement the fix:
Approach:
- Add a new internal function
isIsolatedCronRunSessionKey(sessionKey)that detects if a session key is for an isolated cron run. - In
bootstrap,ingest,assemble,afterTurn, before getting/creating the conversation:- Check if the session key matches the isolated cron run pattern
- AND the session key has an active conversation with a different sessionId
- If so, archive the prior conversation
- The fix should be applied before
getOrCreateConversationso the new conversation is fresh.
Let me look at the bootstrap flow once more:
- Add a new internal function
Assistant
Now let me think about the fix. Let me add a new helper
rotateIsolatedCronRunConversationIfReusedthat:- Checks if the session key matches an isolated cron run pattern
- Checks if there's an active conversation for the session key with a different sessionId
- If both, archive the prior conversation and let
getOrCreateConversationcreate a fresh one
Let me think about what the "isolated cron run" detection pattern should be. Looking at:
agent:main:cron:daily-digest:run:run-123- isolated runagent:main:cron:nightly:run:run-456- another isolated runagent:main:cron:nightly- parent cron session (NOT an isolated run)
The distinguishing feature: the session key has BOTH
cronandrunsegments (withrunappearing aftercron).Actually, looking more carefully, the
run:run-Nsegment is what makes it isolated. So we need to detect session keys that have:cronsomewhererunaftercron- A specific run identifier (e.g.,
run-Nor similar)
Hmm, this is getting complex. Let me look at this from a different angle. Maybe the issue is that the host sets a specific signal.
Actually, let me look at this from yet another angle. What if I make the detection based on the session file existence and content? For an isolated cron run:
- The new session file should NOT have overlap with the prior conversation's messages (because it's a fresh run)
- The session file is "fresh" (recent mtime, much smaller, etc.)
But this is also brittle.
OK let me just go with the most pragmatic approach. The detection rule:
- If session key matches a pattern that includes BOTH
cronand arun-Nstyle identifier, AND there's an active conversation with different sessionId → isolated cron run → archive prior
Wait, let me think about this differently. Let me look at the OpenClaw runtime API more carefully:
Assistant
OK let me take a different approach. Let me look at the issue from the most pragmatic angle. Given the constraints:
- No new public interfaces
- Must detect isolated cron runs
- Prior runs archived, current run starts fresh
- Non-cron sessions unchanged
The detection mechanism should be based on:
- The session key (pattern matching)
- The session ID differing from the active conversation's session ID
Let me check what config options exist:
Assistant
Let me look at the config more carefully:
Assistant
OK now I have a clearer picture. Let me design the fix.
Looking at this again, I think the cleanest approach is:
- Add a new internal helper that detects "isolated cron runs" via session key pattern
- In bootstrap/ingest/etc., check this BEFORE getOrCreateConversation and archive the prior conversation
Let me also check the OpenClaw runtime contract more carefully - maybe there's a
runtimeContextfield with isolation info that I'm missing. Let me search the codebase more thoroughly:Assistant
Only
contextModeforprepareSubagentSpawn. OK let me just implement the fix based on session key pattern.Actually, let me look at this one more time. Let me look at
prepareSubagentSpawnmore carefully:Assistant
OK so
prepareSubagentSpawnwithcontextMode: "isolated"creates a child session with a DIFFERENT session key. The child gets a fresh conversation (because the key is different).For cron isolated runs, the host probably uses the SAME session key (stable across runs) but a DIFFERENT session ID. So the LCM should detect this and treat it as isolated.
OK let me design and implement the fix. The detection rule:
- The session key has an active conversation
- The active conversation has a different session ID
- The session key is detected as an "isolated cron run" (via pattern)
Let me now think about what pattern to use. Looking at the README:
agent:main:cron:nightly(parent cron)agent:main:cron:nightly:run:run-123(isolated run)
The isolated run has a specific structure. The simplest pattern:
agent:*:cron:*:run:**oragent:*:*:*:run:**(more generic).Actually, looking at the README more carefully, it says "isolated run sessions like
agent:main:cron:daily-digest:run:run-123". So the structure isagent:<agentId>:cron:<jobName>:run:<runId>.The pattern would be:
agent:*:cron:*:run:**.But wait, what if other session keys also have
:run:in them? Likeagent:main:run:foo. We need to be careful.Let me think about this differently. The host (OpenClaw) signals isolation somehow. Without a clear signal, I'll go with the most pragmatic heuristic:
- If a session key matches a configured pattern AND has an active conversation with a different sessionId → treat as isolated cron run
Actually, you know what, let me look at this from a totally different angle. What if the fix is simply to ALWAYS archive the prior conversation when sessionId differs from the active conversation's sessionId for cron sessions?
The check would be:
- If
sessionKey has active conversationANDactive.sessionId !== currentSessionIdANDsessionKey matches cron pattern→ archive
Let me check what the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingdoes and see if I can build on it.Actually, let me look at this once more. The issue says "isolated cron runs" specifically. Let me look at the existing tests around cron:
Assistant
So
agent:main:cron:nightly:run:run-123is treated as an "ignored session" pattern (agent:*:cron:**) by default. This means by default, cron sessions are excluded from LCM.Now, the issue says "isolated cron runs leak context when they reuse a stable session key". So the user is NOT using
agent:*:cron:**in their ignore patterns, and cron sessions ARE going through LCM. The fix needs to handle this case.Let me think about this more carefully. The bug:
- User has cron sessions in LCM (not excluded)
- Each cron run uses a stable session key with new sessionId
- LCM reuses prior conversation → context leaks
The fix:
- Detect this case (cron sessions with stable keys)
- Archive prior conversation, create fresh
Now, the detection. The user has cron sessions in LCM. So we need to identify "isolated cron runs" within LCM-managed cron sessions.
The session key pattern for isolated cron runs is
agent:*:cron:*:run:**(based on the README example).OK let me just implement the fix. I'll:
- Add a helper function
isIsolatedCronRunSessionKey(sessionKey)that uses session key pattern matching - In bootstrap/ingest/assemble/afterTurn, check if the session is an isolated cron run AND the active conversation has a different sessionId → archive prior
- Use
applySessionReplacementto do the archive
Let me clean up the temp test first:
Assistant
Now let me actually look at this once more. The issue says:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
This strongly suggests the host creates "isolated cron runtime sessions" with stable keys. The LCM must not share context.
I think the key insight is this:
- An "isolated cron runtime session" is a session created by OpenClaw for a cron job
- It has a stable session key (e.g.,
agent:main:cron:daily-digest:run:run-123) - Each run is a new "runtime session" with a new session ID
- The LCM must treat each run as isolated
So the fix should be:
- Detect that the session key has a
run:run-Nstyle identifier - AND the active conversation's sessionId differs from the current sessionId
- → Archive prior and create fresh
Let me now design the implementation. I'll add a helper function and integrate it into the bootstrap, ingest, etc.
Actually, looking at the code more carefully, I realize that the simplest way to detect this might be through the session key pattern itself. Let me define the pattern:
For "isolated cron runs", the session key looks like:
agent:<agentId>:cron:<jobName>:run:<runId>
So we can use a regex like
/^agent:[^:]+:cron:[^:]+:run:[^:]+/to detect this.But this is still a pattern match. Let me see if there's a simpler approach.
Actually, let me look at this from yet another angle. The
runtimeContextis only available incompactandmaintain. But maybe the host sets a session-level flag somewhere.Hmm, let me just go with the pattern matching approach. I'll add a helper function that detects isolated cron runs based on session key pattern.
Actually wait. Let me re-look at the issue title: "Isolated cron runs leak context when they reuse a stable session key".
OK I just realized something. Let me check what the host (OpenClaw) does for "isolated cron runs":
- Creates a session with stable key
- For each cron invocation, creates a new runtime session
- The session key is STABLE, so LCM sees the same key for multiple runs
The LCM currently:
- On first run: creates a new conversation
- On second run: finds the existing conversation by key, reuses it
- This is the bug
For LCM to detect "isolated" runs:
- Either the host signals this explicitly (which doesn't seem to be the case)
- Or we infer it from the pattern
Let me just go with the pattern-based approach. Here's my plan:
- Add a helper
isIsolatedCronRunSessionKey(sessionKey)that returns true if the session key looks like an isolated cron run - Use this helper in
bootstrap,ingest,assemble,afterTurn - When detected AND there's an active conversation with different sessionId, archive the prior conversation
Let me look at the existing
applySessionReplacementfunction more carefully to see how to use it:Assistant
OK this function:
- Archives the current conversation (if active)
- Creates a new conversation (if createReplacement=true)
But it uses
getConversationForSessionwhich looks up by sessionId OR sessionKey. For our case, we need to find the active conversation by sessionKey (which has a different sessionId from current). The currentgetConversationForSessionprioritizes sessionKey, so it would find the prior conversation.Wait, let me trace through this:
getConversationForSession({ sessionKey: "agent:main:cron:..." })- finds active conversation by key- Archives it
- Creates new conversation with current sessionId + sessionKey
Yes, this would work. Let me implement the fix.
But wait, I want to be careful. The
applySessionReplacementis a private function. Let me see if I should add a new public/internal method or use it directly.Actually, I should add a new helper function similar to
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingthat:- Detects isolated cron run by session key pattern
- If the active conversation has a different sessionId, archive it
- Then
getOrCreateConversationwill create a fresh one
Let me now implement the fix. First, let me look at the bootstrap flow once more:
Assistant
OK now I'll implement the fix. Let me first look at the existing patterns once more:
Assistant
Good, there's a pattern compilation utility. I can use this.
Let me also look at how the engine checks for cron patterns. Actually, looking at this more carefully, I don't see an existing "cron pattern" check beyond
ignoreSessionPatterns. So I'll need to add the detection.OK let me now design the fix more concretely:
-
Detection helper: Add
isIsolatedCronRunSessionKey(sessionKey)that returns true if the session key matches the isolated cron run pattern (e.g., has bothcronandrun:run-Nsegments). -
Apply in bootstrap, ingest, assemble, afterTurn: Before getting/creating the conversation, check if this is an isolated cron run AND the active conversation has a different sessionId. If so, archive the prior conversation.
-
Use existing patterns: Use the
compileSessionPatternfromsession-patterns.ts.
Actually wait, the host probably knows whether a session is "isolated". The OpenClaw runtime signals this through... let me check the runtime contract one more time. Looking at the
bootstrapinterface:bootstrap(params: { sessionId: string; sessionKey?: string; sessionFile?: string; messages?: AgentMessage[]; }): Promise<BootstrapResult>;No explicit "isolated" flag. So the detection must be based on sessionKey or sessionFile.
Let me also check the engine's view: maybe the host passes the isolation signal through some internal mechanism. Looking at
LcmDependencies:-
Assistant
OK so the
LcmDependenciesdoesn't have an "isolated" signal either.Alright, let me make the decision: I'll go with the session key pattern matching approach. The pattern for "isolated cron runs" will be derived from the session key shape.
But wait, I want to be more careful. Let me look at the actual session keys that the host uses for cron jobs. Based on the README example
agent:main:cron:daily-digest:run:run-123, the structure is:agent:<agentId>:cron:<jobName>:run:<runId>So the session key has at least 6 segments, with the 3rd being
cronand the 5th beingrun.Hmm, but this is just one example. Let me think if there could be other variations.
Actually, you know what, let me take a completely different approach. Let me check if maybe the host has a way to signal isolation via the sessionFile path. Looking at the OpenClaw runtime API:
Wait, I just realized something important. Looking at the description of
contextMode: "isolated"inprepareSubagentSpawn, this is used for subagent spawns where the child is isolated from the parent. For cron jobs, the OpenClaw host probably uses a similar mechanism - perhaps the host calls a function to indicate isolation.But looking at the bridge, there's no explicit "isolated cron run" interface. So the detection must be inferred from data.
Let me just look at this pragmatically: the issue describes a specific bug, and we need to fix it. Let me look at what data we have:
- sessionId - changes for each isolated run (new UUID)
- sessionKey - stable across isolated runs
- sessionFile - either same path or different
For the most robust detection:
- sessionId !== activeConversation.sessionId AND sessionKey matches cron run pattern
Let me look at the existing patterns more carefully:
Assistant
OK, no existing specific pattern for "isolated cron runs". Let me design the fix.
Here's my plan:
- Add an internal helper
isIsolatedCronRunSessionKey(sessionKey)in the engine - The helper detects session keys matching the pattern
agent:*:cron:*:run:**(or similar) - In
bootstrap,ingest,assemble,afterTurn, beforegetOrCreateConversation:- Check if sessionKey matches isolated cron run pattern
- If yes, AND there's an active conversation with different sessionId, archive the prior
- This ensures the new run starts with a fresh conversation
Wait, actually let me think about this once more. The pattern
agent:*:cron:*:run:**might be too restrictive. What if the host uses a different naming convention?Hmm. Let me see what makes the most sense:
- Pattern:
agent:*:cron:*:run:**- matchesagent:main:cron:daily-digest:run:run-123 - Pattern:
agent:*:*:*:run:**- matches any session key withrunsegment
Actually let me just go with the cron-specific pattern. It's the most precise.
OK let me now start implementing the fix. First, let me also look at where the bug manifests:
The bug manifests in:
bootstrapingestingestBatchassembleafterTurn
All of these call
getOrCreateConversation(directly or indirectly) which has the bug.The fix should be applied BEFORE
getOrCreateConversationso that the prior conversation is archived first, thengetOrCreateConversationcreates a fresh one.Let me implement this now. First, let me look at the existing test setup:
- Add an internal helper
Assistant
OK now I have a clearer picture. Let me implement the fix.
Looking at this once more, I realize I should focus on:
- The session key must be identified as an "isolated cron run" via pattern
- AND the session ID differs from the active conversation's session ID
Let me now write the code. I'll add a helper function and integrate it.
Wait, before I do that, let me re-read the issue one more time:
Different isolated cron runtime sessions that reuse a stable session key must not share active LCM context.
So the fix is about "isolated cron runtime sessions". This is a specific type of session. The session keys for these are stable (same across multiple runs).
OK let me implement this. The detection rule:
- Session key matches an "isolated cron run" pattern
- AND sessionId differs from active conversation's sessionId
Let me look at one more thing - the existing
applySessionReplacementto understand its behavior:Assistant
applySessionReplacementarchives the current conversation and optionally creates a new one. It usesgetConversationForSessionwhich:- First tries by sessionKey (finds active conversation)
- Falls back to sessionId
For our case:
- sessionId: new (different from prior)
- sessionKey: same as prior
So
getConversationForSession({ sessionId, sessionKey })will find the active conversation by sessionKey first.This is perfect. Let me now design my fix.
Plan:
- Add
isIsolatedCronRunSessionKey(sessionKey)helper - Add a private method
rotateIsolatedCronRunConversationIfReused(params)that archives the prior conversation if the session is an isolated cron run and the sessionId differs from the active conversation's sessionId - Call this method in bootstrap, ingest, assemble, afterTurn before getOrCreateConversation
Wait actually, the issue says "No new public interfaces are introduced." So I can add private methods.
Now let me think about the heuristic more carefully. The fix needs to:
- Detect "isolated cron runs" - via session key pattern
- Archive prior conversation when sessionId differs
The detection logic:
private isIsolatedCronRunSessionKey(sessionKey: string): boolean { // Pattern: agent:<agentId>:cron:<jobName>:run:<runId> const trimmed = sessionKey.trim(); if (!trimmed) return false; const parts = trimmed.split(":"); // Need at least 6 parts: agent, agentId, cron, jobName, run, runId if (parts.length < 6) return false; // 3rd part (index 2) should be "cron" if (parts[2] !== "cron") return false; // 5th part (index 4) should be "run" if (parts[4] !== "run") return false; return true; }Actually, let me think about this more. What if the host uses different naming? Like
agent:main:cron:nightly(4 segments, parent cron session) vsagent:main:cron:nightly:run:run-123(6 segments, isolated run)?The isolated run has the
run:<runId>segment. So the pattern should match that.Hmm, but I want to keep this generic. Let me just check for the
run:segment in the key.Actually, looking at the README once more:
agent:*:cron:**excludes cron sessions for any agent, including isolated run sessions likeagent:main:cron:daily-digest:run:run-123So
agent:*:cron:**matchesagent:main:cron:daily-digest:run:run-123. This means the cron pattern already covers isolated runs.But we don't want to treat ALL cron sessions as isolated. We only want isolated runs (with the
run:segment).Let me use a more specific pattern. Maybe
agent:*:cron:**:run:**(cron session with arun:segment somewhere).Or maybe simpler: any session key that has the
run:run-Nsegment is an isolated run.OK let me just go with a simple heuristic: the session key has both
cronandrun:run-Nsegments.Actually, you know what, let me think about this from yet another angle. What if the host signals isolation through the session file? For isolated runs, the host might:
- Create a fresh transcript file at the same path
- The session file size is much smaller than the prior conversation's transcript
- The session file mtime is much newer than the prior conversation's last message
Hmm, this is also brittle.
OK let me just go with the session key pattern approach. I'll use a regex pattern to detect "isolated cron run" session keys.
Wait, let me check one more time. What if the existing
ignoreSessionPatternsconfiguration could be used as a signal? If the user has configuredagent:*:cron:**in their ignore patterns, they're indicating cron sessions should be excluded. But by default, cron sessions are NOT excluded.Hmm, this doesn't quite help either.
OK let me just go with the pattern approach. Here's my plan:
private static readonly ISOLATED_CRON_RUN_KEY_PATTERN = /^agent:[^:]+:cron:[^:]+:run:[^:]+/; private isIsolatedCronRunSessionKey(sessionKey: string | undefined): boolean { if (!sessionKey) return false; return LcmContextEngine.ISOLATED_CRON_RUN_KEY_PATTERN.test(sessionKey.trim()); }Actually wait, let me check the example again:
agent:main:cron:daily-digest:run:run-123Breaking this down:
agent- agent prefixmain- agent IDcron- cron segmentdaily-digest- cron job namerun- run segmentrun-123- run ID
So the pattern would be:
^agent:[^:]+:cron:[^:]+:run:[^:]+. Let me verify:agent:main:cron:daily-digest:run:run-123matches ✓agent:main:cron:nightlydoesn't match (missing run/runId segments) ✓agent:main:maindoesn't match ✓
Now let me implement the fix.
Assistant
Good. Let me now design and implement the fix:
Assistant
Let me look at where I can add the helper function:
Assistant
Now let me implement the fix. I'll:
- Add a constant for the isolated cron run pattern
- Add a helper method
isIsolatedCronRunSessionKey - Add a helper method
archiveIsolatedCronRunConversationIfReusedthat archives prior conversation when the session is an isolated cron run with a different sessionId - Call this helper in bootstrap, ingest, assemble, afterTurn
Let me start implementing:
Assistant
Now let me look at where to add the constant:
Assistant
Now let me look at the relevant sections to add my helper. Let me first check the bootstrap and other entry points where I need to add the call:
Assistant
OK so there are MANY places where
getConversationForSessionandgetOrCreateConversationare called. The fix needs to be at strategic places.The most critical places are:
bootstrap(line 7183) - the entry point for new sessionsingestSingle(line 8105) - where messages are ingestedassemble(line 8786) - where context is assembledafterTurn(line 8451) - where turn-end persistence happens
Let me now implement the fix. The strategy:
- Add
isIsolatedCronRunSessionKeyhelper - Add
archiveIsolatedCronRunConversationIfReusedhelper that archives prior conversation - Call this in bootstrap, ingest, assemble, afterTurn before
getOrCreateConversation
Let me first check what the right approach is. Actually, let me look at this from a cleaner angle. Let me add the check INSIDE
getOrCreateConversationso it's centralized:Assistant
Hmm. The issue is in
getOrCreateConversation- when the sessionKey is reused with a different sessionId, it just updates the sessionId and reuses the conversation.The fix should detect this case. But we need a way to know if it's "isolated". The sessionKey pattern is one approach.
Actually, looking at this from yet another angle, maybe the cleanest fix is to add a check in
getOrCreateConversationitself. If the sessionKey has an active conversation with a different sessionId, we should... well, that depends on whether it's isolated or not.But
getOrCreateConversationdoesn't know about the isolation concept. It would need a way to detect this.OK let me just implement the fix at the engine level. I'll:
- Add a helper to detect isolated cron runs
- In
bootstrapand other entry points, archive the prior conversation if needed
Let me start coding:
Assistant
Now let me look at where to add the helper. Let me look at the structure of the engine:
Assistant
Good. Now I have a clear picture of where to add my helper. Let me now implement the fix.
Let me design the implementation:
-
Add a constant for the isolated cron run pattern
-
Add a private method
isIsolatedCronRunSessionKey(sessionKey) -
Add a private method
archiveIsolatedCronRunConversationIfReused(params)that:- Returns false if session key is not an isolated cron run
- Returns false if there's no active conversation with a different sessionId
- Otherwise, archives the prior conversation
-
Call
archiveIsolatedCronRunConversationIfReusedin:bootstrap- beforegetOrCreateConversationingest(iningestSingle) - beforegetOrCreateConversationassemble- beforegetConversationForSessionafterTurn- beforegetConversationForSession
Let me start implementing:
-
Assistant
Now let me implement the fix. First, let me add the constants and helper methods:
Assistant
Now let me make the edits. I'll add a constant for the pattern, the helper, and use it in the engine:
Assistant
Now let me find where the helper methods are and add the new ones:
Assistant
Now let me add the helper method after
isStatelessSession:Assistant
There's a duplicate. Let me fix that:
Assistant
I broke the
getCircuitBreakerStatemethod. Let me fix it:Assistant
There's a duplicate line and broken
isCircuitBreakerOpen. Let me fix both:Assistant
There's a stray
}at line 3623. Let me remove it:Assistant
I keep making it worse. Let me restore the original file and try again with a cleaner approach. Let me see what the original state is:
Assistant
Let me restore the file and start over more carefully:
Assistant
Good, the file is back. Now let me make a more careful change. Let me first add the constants:
Assistant
Now let me add the helper method after
isStatelessSession. Let me look at the exact location first:Assistant
Now let me add the helper. I'll add it after
isStatelessSessionand before the circuit breaker helpers:Assistant
There's a duplicate line at 3583 and missing blank line before
private getCircuitBreakerState. Let me fix it carefully:Assistant
I keep breaking things. Let me reset and try a different approach - use a temp script to make precise edits:
Assistant
Let me use a more careful approach - use a Python script to do the edits:
Assistant
OK only node. Let me use Node.js:
Assistant
Now let me verify the engine compiles. Let me run the typecheck:
Assistant
Good, typecheck passes. Now let me add the actual fix logic. I'll add a method
archiveIsolatedCronRunConversationIfReusedthat archives the prior conversation when an isolated cron run reuses a stable session key with a different sessionId.Let me look at where
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingis defined:Assistant
Good. Now let me add my new method after
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing. Let me write the fix using the Node script:Assistant
Now let me invoke this method in the right places. Let me first find the bootstrap path:
Assistant
Let me look at the bootstrap entry:
Assistant
Let me add the call after the rotate stale. The key insight is to add this BEFORE the getOrCreateConversation call:
Assistant
Now let me also add it to
ingestSingle. Let me check the structure:Assistant
Let me add the call to
ingestSingle:Assistant
Now let me verify the engine compiles:
Assistant
Typecheck passes. Now let me verify my reproduction script confirms the fix:
Assistant
The fix works! Let me check:
- Test 1: Two isolated cron runs - prior conversation (id=1) is archived, new conversation (id=2) is created with only the second message. ✓
- Test 2: Non-cron session with same sessionId - both messages are preserved in the same conversation. ✓
Now let me clean up and run the existing tests to make sure nothing is broken:
Assistant
All 317 engine tests pass. Now let me run more tests:
Assistant
All 1067 tests pass. Let me also verify that there are no edge cases I might have missed. Let me think about edge cases:
- Same session ID, isolated cron run key: Should NOT archive (it's the same run)
- No prior conversation: Should NOT archive (nothing to archive)
- Different session key, isolated cron run key: Should NOT archive (no prior conversation for this key)
- Non-isolated cron run key: Should NOT archive (it's a normal session)
- Prior conversation already archived: Should NOT archive (nothing active to archive)
Let me verify these by writing more tests:
Assistant
All 5 edge case tests pass:
- ✓ First isolated cron run - no prior conversation, no archival
- ✓ Same sessionId with isolated cron run key - no archival
- ✓ Non-cron session key - no archival (existing behavior preserved)
- ✓ Parent cron session (no run segment) - no archival (existing behavior preserved)
- ✓ Isolated cron run archives prior conversation (not deleted)
Let me clean up the temp test:
Assistant
Now let me also verify the original reproduction still works correctly:
Assistant
The original bug is now fixed. Let me clean up:
Assistant
Now let me also test bootstrap, assemble, and afterTurn paths to make sure the fix is applied there too:
Assistant
Both bootstrap and assemble paths correctly archive prior conversations. Let me clean up:
Assistant
Now let me also add a changeset for this change as the project requires:
Assistant
Now let me run all tests once more to ensure everything passes:
Assistant
All 1067 tests pass.
Now let me check that I should also handle the case of a subagent spawn with
contextMode: "isolated"and same session key. Wait, actually subagents always use a different session key, so this shouldn't be an issue.Let me also think about more edge cases:
- What if
sessionKeyis undefined? →isIsolatedCronRunSessionKeyreturns false, no archival - What if sessionKey is just whitespace? → returns false after trim, no archival
- What if there's a race condition where two runs start simultaneously? → The session queue should serialize
Let me also verify the typecheck passes:
- What if
Assistant
Now let me look at the changes I've made:
Assistant
Let me also check the changeset file:
Assistant
Now let me think about edge cases more carefully:
- What about when the host doesn't pass
runtimeContextfor an isolated cron run? → We use sessionKey pattern. ✓ - What if the sessionKey pattern doesn't match? → We don't archive, behavior unchanged. ✓
- What if the sessionFile is the same path? → Bootstrap goes through the new logic, archives prior. ✓
- What about the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing? → It still handles the file-missing case. ✓ - What if
archiveIsolatedCronRunConversationIfReusedis called inside a transaction? →applySessionReplacementalready handles transactions. ✓
Let me also consider: what happens if
applySessionReplacementis called but the conversation is fresh (no messages)? Looking atapplySessionReplacement:if (current?.active) { if (params.createReplacement && await this.isFreshLifecycleConversation(current)) { this.deps.log.info( `[lcm] ${params.reason} lifecycle no-op for already fresh conversation ${current.conversationId}`, ); return; } await this.conversationStore.archiveConversation(current.conversationId); }It checks if the conversation is "fresh" (no messages, no context items, no bootstrap). If fresh, it's a no-op. So if there's a fresh conversation, we don't archive. Good.
But wait - for the first isolated cron run, there's no prior conversation, so
getConversationBySessionKeyreturns null, and we don't archive. For subsequent runs, the prior conversation has been used, so it's not fresh, and we archive.Let me also check: what about the
assemblepath? TheassembleusescreateReplacement: falseinitially. Let me check what this does:- What about when the host doesn't pass
Assistant
Hmm, in
applySessionReplacement, whencreateReplacementis false, it only archives the prior conversation but doesn't create a new one. ThengetOrCreateConversationis called afterwards, which will create a new one.But wait, looking at the call sites:
assembleusescreateReplacement: falseafterTurnusescreateReplacement: falsebootstrapusescreateReplacement: true
For
assemble, we want to archive the prior conversation and letgetConversationForSessionreturn null. Then what does assemble do?Looking at the
assemblecode:Assistant
Hmm. For
assemble, the call is insiderotateStaleSessionKeyConversationIfTrackedTranscriptMissingandarchiveIsolatedCronRunConversationIfReused. These callapplySessionReplacementwhich (withcreateReplacement: false) just archives.But then
getConversationForSessionis called, which will:- Try by sessionKey (returns null, since prior is archived)
- Try by sessionId (might return existing if same)
If there's no existing conversation by either, returns null. Then assemble returns
safeFallback().But wait, in
assemble, we passcreateReplacementfrom the archive call:rotateStaleSessionKeyConversationIfTrackedTranscriptMissingusescreateReplacement: false(so doesn't create new conversation, only archives)archiveIsolatedCronRunConversationIfReusedusescreateReplacement: trueby default (so creates new conversation)
Wait, let me look again:
Assistant
OK so by default,
archiveIsolatedCronRunConversationIfReusedusescreateReplacement: true(i.e., creates a new conversation after archiving the prior). This is correct for the case where the next call (e.g.,getConversationForSession) needs to find a conversation.But wait, in
assemble, after the rotation,getConversationForSessionis called. If the new conversation has the same sessionKey, thengetConversationForSessionwill find it.Let me think about this:
- Before: sessionKey has active conversation A (sessionId: "session-run-1")
archiveIsolatedCronRunConversationIfReusedarchives A and creates B (sessionId: "session-run-2", sessionKey: same)getConversationForSession({sessionId: "session-run-2", sessionKey: K})is called- It first tries by sessionKey → finds B (active, sessionKey matches)
- Returns B
Yes, this works correctly.
But wait, there's a subtle issue. In
applySessionReplacement:if (!params.createReplacement) { this.deps.log.info( `[lcm] ${params.reason} lifecycle archived conversation ${current?.conversationId ?? "(none)"}`, ); return; }If
createReplacementis false, the function returns without creating a new conversation. SogetConversationForSessionwould return null.But in
archiveIsolatedCronRunConversationIfReused, the defaultcreateReplacementistrue. So unless explicitly overridden, a new conversation is created.In the assemble path, I didn't override
createReplacement, so it'strue. The new conversation is created. Good.Actually wait, let me think again. Looking at the
assemblecall:await this.archiveIsolatedCronRunConversationIfReused({ phase: "assemble", sessionId: params.sessionId, sessionKey: params.sessionKey, });I didn't pass
createReplacement, so it defaults totrue. The new conversation is created.For
bootstrap:await this.archiveIsolatedCronRunConversationIfReused({ phase: "bootstrap", sessionId: params.sessionId, sessionKey: params.sessionKey, });Same, defaults to
true. Good.For
afterTurn:await this.archiveIsolatedCronRunConversationIfReused({ phase: "afterTurn", sessionId: params.sessionId, sessionKey: params.sessionKey, });Same, defaults to
true. Good.For
ingestSingle:await this.archiveIsolatedCronRunConversationIfReused({ phase: "ingest", sessionId, sessionKey, });Same, defaults to
true. Good.OK so the default of
trueis correct for all entry points.Now let me check if there are any other entry points that I might have missed:
Assistant
Let me look at line 6467 - that's in
reconcileTranscriptTailForAfterTurnInSessionQueue- this is the afterTurn reconcile path:Assistant
Wait, I see that
archiveIsolatedCronRunConversationIfReuseduses defaultcreateReplacement: true, but this is called AFTERrotateStaleSessionKeyConversationIfTrackedTranscriptMissingwhich usescreateReplacement: false.If the second call (
archiveIsolatedCronRunConversationIfReused) creates a new conversation, that's good.But wait, there's a subtle issue.
archiveIsolatedCronRunConversationIfReusedusescreateReplacement: true(default). But the call inside the transaction wrapsapplySessionReplacementwhich itself doesn't start a new transaction (the caller is inside a transaction).Looking at
applySessionReplacement:Assistant
applySessionReplacementdoes:- Archive the current conversation (if active)
- If
createReplacementis true, create a new conversation
This works fine within a transaction. Good.
But wait, there's still a potential issue. In
reconcileTranscriptTailForAfterTurnInSessionQueue:await this.conversationStore.withTransaction(async () => { await this.rotateStaleSessionKeyConversationIfTrackedTranscriptMissing({ phase: "afterTurn", ... createReplacement: false, }); await this.archiveIsolatedCronRunConversationIfReused({ phase: "afterTurn", sessionId: params.sessionId, sessionKey: params.sessionKey, }); });If
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingarchives the prior conversation (with createReplacement: false), thenarchiveIsolatedCronRunConversationIfReusedis called. It checks:- sessionKey matches isolated cron pattern
- normalizedSessionKey exists
- sessionId exists
activeByKeyexists and is active (but it was just archived, so it's not active anymore!)- sessionId differs
If
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingalready archived the prior, thenactiveByKeywould be null or not active. SoarchiveIsolatedCronRunConversationIfReusedwould return false without doing anything.This is fine - no double archiving.
But what if
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingdidn't archive (e.g., sessionFile path matched)? ThenactiveByKeyis still active, andarchiveIsolatedCronRunConversationIfReusedcorrectly archives it.OK so the order is:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing- handles file-missing casearchiveIsolatedCronRunConversationIfReused- handles isolated cron run case
These are complementary, not overlapping. Good.
Now let me also think about a potential edge case. What if the prior conversation is "fresh" (no messages yet)? Let me check
isFreshLifecycleConversation:Assistant
isFreshLifecycleConversationreturns true if:- No messages
- No context items
- Not bootstrapped
If the conversation is fresh (e.g., brand new, not yet used), the replacement is a no-op. So if there's an existing fresh conversation for the same key, we don't archive it.
For isolated cron runs, the prior conversation likely has messages, so it's not fresh. Good.
But wait, there's an edge case: what if the first isolated cron run is interrupted (e.g., crash) before any messages are stored? The conversation exists but is fresh. Then the second run sees this fresh conversation and skips archiving (no-op). This might be wrong - we might want to archive and start fresh.
Hmm, let me think. If the first run was interrupted before any messages, the conversation is fresh. The second run starts and...
getOrCreateConversationwould return the existing fresh conversation. The second run would use it.This is actually fine behavior - if the conversation is fresh, there's nothing to leak. So no need to archive.
But to be more robust, maybe we should always archive for isolated cron runs, regardless of freshness. Let me check the existing
applySessionReplacementlogic again:if (current?.active) { if (params.createReplacement && await this.isFreshLifecycleConversation(current)) { this.deps.log.info( `[lcm] ${params.reason} lifecycle no-op for already fresh conversation ${current.conversationId}`, ); return; } await this.conversationStore.archiveConversation(current.conversationId); }If the conversation is fresh AND createReplacement is true, it's a no-op. So for fresh conversations, no archival happens.
For the isolated cron run case, if the prior conversation is fresh (no messages), should we archive and start fresh? Or should we reuse it?
I think it's better to reuse a fresh conversation - no harm in continuing the same conversation. So the current behavior is fine.
Actually wait, let me think again. If the prior isolated run was interrupted (no messages stored), the conversation might be in a "fresh" state. The new run starts and finds this fresh conversation. It continues from where the prior left off. This is actually fine - there's nothing to leak.
So the current behavior is correct. Let me move on.
Let me also verify that the existing
getOrCreateConversationlogic is compatible with my fix. After the fix:archiveIsolatedCronRunConversationIfReusedarchives the prior conversation and creates a new onegetOrCreateConversationis called - it finds the new conversation (created by step 1) and returns it
Yes, this is consistent.
Now let me also think about what happens if the new conversation is created with a different sessionKey (e.g.,
applySessionReplacementusesparams.sessionKeyfornextSessionKey). In my implementation:await this.applySessionReplacement({ reason: ISOLATED_CRON_RUN_REUSED_KEY_REASON, sessionId: activeByKey.sessionId, sessionKey: normalizedSessionKey, nextSessionId: params.sessionId, nextSessionKey: normalizedSessionKey, createReplacement: params.createReplacement ?? true, });So
sessionKeyandnextSessionKeyare bothnormalizedSessionKey(same). The new conversation gets the same sessionKey. Good.Let me look at the tests once more to ensure correctness:
Assistant
All 1067 tests pass. Let me also verify the typecheck:
Assistant
Typecheck passes. Let me also verify the build works:
Assistant
Build succeeds.
Now let me also verify the fix with a few more edge case tests. Let me also check if
ingestBatchshould also call the archive helper:Assistant
ingestBatchcallsingestSinglein a loop, which already callsarchiveIsolatedCronRunConversationIfReused. SoingestBatchis also covered.But wait, if the loop runs multiple times, it would archive the prior conversation multiple times. Let me check:
In
ingestBatch:for (const message of params.messages) { const result = await this.ingestSingle({...}); if (result.ingested) { ingestedCount += 1; } }For the first message,
ingestSinglecallsarchiveIsolatedCronRunConversationIfReusedwhich archives the prior and creates new. For the second message,archiveIsolatedCronRunConversationIfReusedwould check:- active conversation has same sessionId (yes, the new one) → return false
So no double archiving.
Let me also check the issue description one more time to ensure I'm addressing all the requirements:
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.
My fix:
- ✓ Detects isolated cron runs via session key pattern
- ✓ Archives the prior active conversation (prior runs remain archived)
- ✓ Creates a fresh conversation (no shared context)
- ✓ Compaction still works (we use the new conversation from then on)
- ✓ Non-cron session continuity is unchanged (we only act on isolated cron runs)
The fix satisfies all requirements. Let me also think about whether I should add
runtimeContext.isolatedas an additional signal. Looking at the issue constraints:No new public interfaces are introduced.
This means I can't add a new field to the bridge. But I could check for an undocumented
runtimeContextfield if it exists. However, sinceruntimeContextis only available incompactandmaintain, not inbootstrap,ingest, etc., it's not useful for cron runs.OK my fix is complete. Let me also run the relevant plugin tests:
Assistant
All tests pass. Let me also run the integration tests:
Assistant
All 97 integration tests pass.
Now let me also think about one more potential issue. What if the existing conversation has
active = 1but theactiveByKeylookup returns null (race condition)?Actually,
getConversationBySessionKeyis in the same transaction as the archive call, so there's no race.Let me also consider: what if the sessionKey has multiple active conversations? That shouldn't happen by design (UNIQUE constraint on session_key when active), but let me verify:
Assistant
Good - there's a UNIQUE INDEX on
conversations (session_key) WHERE session_key IS NOT NULL AND active = 1. So there's only one active conversation per sessionKey.Now let me also look at the change once more to ensure correctness:
Assistant
Let me verify everything one more time:
Assistant
Let me also run the full test suite once more:
Assistant
All 1067 tests pass.
Let me also verify the test setup for the existing
bootstrapandassembletests don't break:Assistant
This test uses
agent:main:cron:nightlywhich is a parent cron session (4 segments). My pattern requires 6+ segments. So this test is not affected by my fix. Good.Let me also check the test that uses
agent:main:cron:nightly:run:run-123:Assistant
This test uses
agent:main:cron:nightly:run:run-123(6 segments) which matches my pattern. But it hasignoreSessionPatterns: ["agent:*:cron:**"]which excludes it. SoshouldIgnoreSessionreturns true, and the bootstrap returns early without my fix being called.Let me verify:
Assistant
Wait, I'm looking at the wrong section. Let me find the bootstrap entry:
Assistant
Good. Bootstrap first checks
shouldIgnoreSession. If true, returns early. My fix is called AFTER this check, so ignored sessions are not affected.Now let me also think about whether my pattern might inadvertently match other session keys that shouldn't be treated as isolated cron runs. Let me consider various session keys:
agent:main:cron:daily-digest:run:run-123✓ matches (isolated run)agent:main:cron:nightly✗ doesn't match (parent cron session)agent:main:cron:nightly:run:run-456✓ matchesagent:main:user:alice✗ doesn't matchagent:main:run:foo:bar✗ doesn't match (nocronsegment)agent:main:cron:foo:bar:baz:qux:run:run-1✓ matches (has bothcronandrunsegments)
Hmm, let me check #6. The pattern requires:
agent- agent id (any)
cron- job name (any)
run- run id (any)
So
agent:main:cron:foo:bar:baz:qux:run:run-1- let me trace:agentmatchesmainmatches agent idcronmatches cron segmentfoo:bar:baz:qux- this has colons, so[^:]+won't match. The whole thing won't match.
Wait, the pattern is
/^agent:[^:]+:cron:[^:]+:run:[^:]+/. So:agent:- literal[^:]+- non-colon chars:cron:- literal[^:]+- non-colon chars:run:- literal[^:]+- non-colon chars
For
agent:main:cron:foo:bar:baz:qux:run:run-1:agent:matchesmainmatches[^:]+:cron:matchesfoomatches[^:]+(onlyfoo, notfoo:bar:...)- Need
:run:next, but we have:bar:instead. Doesn't match.
So the pattern is actually strict - it requires exactly 6 segments:
agent,<agent>,cron,<job>,run,<runId>. Anything longer wouldn't match.Hmm, but the README example
agent:main:cron:daily-digest:run:run-123is exactly 6 segments. So the pattern is correct.But what if someone has
agent:main:cron:jobName:run:runId(6 segments)? Yes, this matches. What ifagent:main:cron:job-name:run:run-123(6 segments)? Yes, matches (job-namehas a dash, which is fine for[^:]+).What about
agent:main:cron:job:run:run1:foo(7 segments)? Let me trace:agent:matchesmainmatches[^:]+:cron:matchesjobmatches[^:]+:run:matchesrun1matches[^:]+- Remaining
:foois unmatched, but the regex doesn't require exact match (no$anchor)
So
agent:main:cron:job:run:run1:foomatches! Hmm, this might be a false positive if the host uses 7-segment session keys.Let me make the pattern more strict with
$:Actually wait, let me look at the original pattern again.
compileSessionPatternuses^${escaped}$. So patterns are anchored. Let me make my regex anchored:Actually, the existing pattern doesn't need
$because[^:]+won't match colons. So if there are more segments after, the next would have to be:something, which doesn't match[^:]+. Hmm wait, that's not right.Let me think again. For
agent:main:cron:job:run:run1:foo:^agent:matchesagent:[^:]+matchesmain(greedy, but can't include:):cron:matches:cron:[^:]+matchesjob:run:matches:run:[^:]+matchesrun1- End of pattern, end of string NOT reached
Since there's no
$, the regex matches. Yes, this is a false positive.Let me fix this by anchoring the pattern:
Assistant
Let me check the test regex to confirm:
Actually, let me think about this more carefully. The session key is a string of colon-separated segments. If we want to match exactly 6 segments (
agent,<agentId>,cron,<jobName>,run,<runId>), we need:/^agent:[^:]+:cron:[^:]+:run:[^:]+$/The
$ensures exact match. Let me also check the test for pattern matching:Assistant
Looking at
compileSessionPattern:export function compileSessionPattern(pattern: string): RegExp { const escaped = pattern .replace(/[.+^${}()|[\]\\]/g, "\\$&") .replace(/\*\*/g, "\u0000") .replace(/\*/g, "[^:]*") .replace(/\u0000/g, ".*"); return new RegExp(`^${escaped}$`); }It uses
^...$anchoring. Foragent:*:cron:**:agent:matches literal*becomes[^:]*:cron:matches literal**becomes.*- anchored with
^...$
So
agent:*:cron:**requires:- starts with
agent: - then non-colon chars
- then
:cron: - then anything (including
:) - ends with that anything
For
agent:main:cron:nightly:run:run-123:agent:✓mainmatches[^:]*:cron:✓nightly:run:run-123matches.*- end ✓
So
compileSessionPattern("agent:*:cron:**")matchesagent:main:cron:nightly:run:run-123(5+ segments).For my pattern
^agent:[^:]+:cron:[^:]+:run:[^:]+, I should anchor it. Let me update:Assistant
Let me use Node.js script:
Assistant
Now let me verify the fix still works with the anchored pattern:
Assistant
All tests pass with the anchored pattern. Let me clean up:
Assistant
Let me run all tests once more to ensure nothing is broken:
Assistant
All 1067 tests pass.
Now let me review my changes one final time:
Assistant
Now let me check if there are any other places I should verify. Let me look at the
compactfunction:Assistant
Looking at
compact, it usesgetConversationForSession(notgetOrCreateConversation). This is fine because compact only operates on existing conversations. If the conversation doesn't exist, it returns early.For isolated cron runs, the conversation was already created (with the new session ID) by ingest/bootstrap. So compact would find the correct conversation.
Now let me verify that the fix works end-to-end with a comprehensive test:
Assistant
The test needs the session file to exist. Let me create it first:
Assistant
Hmm, the test is failing. Let me debug. The issue is
run1After?.activereturnsfalsenot0. The conversation'sactiveproperty might be a boolean:Assistant
The
ConversationRecord.activeis boolean, but the raw DB column is number. ThetoConversationRecordlikely converts it. Let me update the test:Assistant
Yes,
activeis a boolean. Let me update the test:Assistant
End-to-end test passes! Multiple isolated cron runs work correctly:
- Run 1: 2 messages
- Run 2: New conversation with 1 message (Run 1 archived)
- Run 3: New conversation with 1 message (Run 2 archived, Run 1 still archived)
Let me clean up:
Assistant
Now let me also make sure the existing
rotateStaleSessionKeyConversationIfTrackedTranscriptMissingdoesn't conflict with my new helper. Looking at the order of operations:For bootstrap:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing- handles stale session file case (file missing)archiveIsolatedCronRunConversationIfReused- handles isolated cron run case
These are different concerns:
rotateStaleSessionKeyConversationIfTrackedTranscriptMissing: detects when the session file path changed AND old file is missingarchiveIsolatedCronRunConversationIfReused: detects when session ID changed for an isolated cron run
For an isolated cron run where:
- Session file path is the same AND file exists → only
archiveIsolatedCronRunConversationIfReusedtriggers - Session file path is different AND old file missing → both could trigger, but
archiveIsolatedCronRunConversationIfReusedchecks if there's an active conversation first. IfrotateStaleSessionKeyConversationIfTrackedTranscriptMissingalready archived,activeByKeywould be null/inactive, soarchiveIsolatedCronRunConversationIfReusedwould be a no-op.
So they don't conflict. Good.
Now let me run the tests one final time:
Assistant
All 1067 tests pass.
Let me look at the final state of my changes:
Assistant
Let me also look at the changeset format once more:
Assistant
Let me now go through the checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- Yes, I reproduced the bug with a test that showed two isolated cron runs sharing the same conversation.
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- Yes, I verified the fix creates separate conversations for each isolated cron run, archiving the prior.
-
I have thought about edge cases and made sure my fix handles them as well.
- Yes, I tested:
- First isolated cron run (no prior conversation) - no archival
- Same sessionId with isolated cron run key - no archival
- Non-cron session keys - no archival (existing behavior preserved)
- Parent cron session (no run segment) - no archival
- Multiple sequential isolated cron runs - prior runs archived, current run fresh
- Yes, I tested:
-
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.
Let me also verify the changeset is in the correct format:
-
Assistant
Format is correct.
Now let me also look at my full diff one more time:
Assistant
All the changes look good. Let me run a final test to confirm everything is working:
Assistant
All 9 ignored session tests pass. The fix doesn't affect the existing behavior of ignored sessions.
Let me also look at the diff once more to verify the
compileSessionPatternstyle. The existing patterns are likeagent:*:cron:*etc. Let me check if I should use a similar approach:Actually, the existing
compileSessionPatternis for user-configurable ignore patterns. MyISOLATED_CRON_RUN_KEY_REGEXis for internal detection. Using a regex is simpler.Let me also verify the
compileSessionPatternwould work for the same purpose:Looking at
compileSessionPattern("agent:*:cron:*:run:*"):- Would match
agent:main:cron:daily-digest:run:run-123(6 segments) - The
$anchor ensures exact match
So I could also use the existing pattern compiler. But the regex is simpler and more explicit. Let me keep it as is.
Now let me look at one more potential edge case. What if the user has a session key with a hyphen, like
agent:main:cron:daily-digest-2:run:run-1? Let me check:- Would match
Assistant
The pattern works correctly:
- ✓ Matches 6-segment isolated cron run keys (including with hyphens or underscores)
- ✗ Doesn't match 4-segment parent cron session
- ✗ Doesn't match 7-segment keys with extras
- ✗ Doesn't match non-cron session keys
- ✗ Doesn't match keys with
runbut nocron
Now let me do a final test:
Assistant
All 1067 tests pass. Let me also verify the build:
Assistant
Build succeeds.
Let me review my changes one last time:
Assistant
Summary of Changes
- Added a constant
ISOLATED_CRON_RUN_REUSED_KEY_REASON- A reason string for the lifecycle rotation log - Added a constant
ISOLATED_CRON_RUN_KEY_REGEX- A regex pattern to detect isolated cron run session keys (6 segments:agent:<agent>:cron:<job>:run:<runId>) - Added a helper method
isIsolatedCronRunSessionKey- Returns true if a session key matches the isolated cron run pattern - Added a helper method
archiveIsolatedCronRunConversationIfReused- Archives the prior active conversation when an isolated cron run reuses its stable session key with a different session ID, then creates a fresh active conversation - Integrated the helper in 4 entry points:
bootstrap- beforegetOrCreateConversationingestSingle- beforegetOrCreateConversation(also coversingestBatchsince it callsingestSinglein a loop)assemble- in the lifecycle guard sectionafterTurn(inreconcileTranscriptTailForAfterTurnInSessionQueue) - in the transaction
- Added a changeset describing the fix
The fix satisfies all the requirements from the issue:
- ✅ Detects isolated cron runs via session key pattern
- ✅ Archives prior runs (not deleted)
- ✅ Fresh active conversation for each run (no context leakage)
- ✅ Compaction still works (the new conversation is used from then on)
- ✅ Non-cron session continuity is unchanged
Let me now do a final check to ensure everything is in order before submitting:
- Added a constant
Assistant
Everything is in order. Let me also verify the typecheck once more:
Assistant
Typecheck passes.
Final checklist:
- If an error was reported in the issue description, I have successfully reproduced it. - Yes, I confirmed that two isolated cron runs reusing the same stable session key share the same active conversation (bug).
- If an error was reported in the issue description, I have confirmed that my fix resolves the error. - Yes, after my fix, each isolated cron run creates a new active conversation and the prior conversation is archived.
- I have thought about edge cases and made sure my fix handles them as well. - Yes, tested:
- First isolated cron run (no prior conversation)
- Same sessionId (in-progress conversation)
- Non-cron session keys (existing behavior preserved)
- Parent cron session without
runsegment - Multiple sequential isolated cron runs
- 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.
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 →