Skip to content
TheChatArchiveThe Chat Archive
MiniMaxminimax/minimax-m3· unknownHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION Isolated cron runs leak context when they reuse a stable session key…

  1. 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 using git reset --hard command. Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands. However you don't need to use git add or git commit before submitting your changes. In fact, submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.

    CHECKLIST

    Before submitting your solution, please go over the following checklist and make sure you've done everything:

    • If an error was reported in the issue description, I have successfully reproduced it.
    • If an error was reported in the issue description, I have confirmed that my fix resolves the error.
    • I have thought about edge cases and made sure my fix handles them as well.
    • I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.

    Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!

    (Current directory: /lossless-claw, current file: none) bash-$

  2. MiniMax Assistant

    I'll start by exploring the repository structure to understand what we're working with.

  3. MiniMax Assistant

    Now let's look for "cron" or "isolated" in the codebase:

  4. MiniMax Assistant

    Let me look at the engine code that handles contextMode:

  5. MiniMax Assistant

    Let me search for how cron is handled in the context of LCM context loading:

  6. MiniMax Assistant

    Now let's look at wirePluginHandlers and how the engine gets called:

  7. MiniMax Assistant

    Let me look at how the engine handles session context loading:

  8. MiniMax 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:

  9. MiniMax Assistant

    Now I understand more about the context. Let me check git log and recent commits to understand the project better:

  10. MiniMax Assistant

    Now let me look at how the engine processes the before_agent_run hook to understand context loading:

  11. MiniMax Assistant

    Let me look at how the context engine handles "isolated" mode and the bootstrap:

  12. MiniMax Assistant

    Now let me search for ingest and how it handles context loading for a session run:

  13. MiniMax Assistant

    Now let me understand: when an isolated cron run reuses a stable session key, what happens? Let's look at getOrCreateConversation more carefully:

  14. MiniMax Assistant

    Now I see the key behavior. When getConversationBySessionKey is called, it returns the ACTIVE conversation. So if a session key like agent:main:cron:daily-digest:run:run-123 is 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:

  15. MiniMax Assistant

    Now let's check contextMode in engine:

  16. MiniMax 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:

  17. MiniMax Assistant

    Now let's see the existing tests for prepareSubagentSpawn:

  18. MiniMax Assistant

    Now let me look for the existing engine tests around cron sessions:

  19. MiniMax Assistant

    Now let me look at how cron sessions 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:

  20. MiniMax Assistant

    Now let me understand how the host OpenClaw differentiates isolated vs. non-isolated cron runs. Let me look for contextMode in tests:

  21. MiniMax Assistant

    Now let me look at where the issue applies in the engine. Let's look at bootstrap to see if there is any handling for contextMode:

  22. MiniMax Assistant

    Now I understand the issue better. When a session key is reused, getOrCreateConversation finds 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::

  23. MiniMax Assistant

    Now let me look at the README about cron sessions:

  24. MiniMax 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 prepareSubagentSpawn work with contextMode:

  25. MiniMax 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:

  26. MiniMax Assistant

    Now let me check what applySessionReplacement and handleBeforeReset does:

  27. MiniMax 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 contextMode is involved:

    • isolated means no shared context
    • fork means forked context

    Let me check how OpenClaw handles cron session runs to understand:

  28. MiniMax Assistant

    Now let me look at the existing handleSessionEnd to see when it fires, to understand how to detect the start of a new isolated cron run:

  29. MiniMax Assistant

    Now let me look at how OpenClaw hosts isolated sessions:

  30. MiniMax Assistant

    Now let me look at how getConversationBySessionKey and how it handles the situation. Let me trace the lifecycle:

  31. MiniMax 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:

  32. MiniMax Assistant

    Now I see! getOrCreateConversation will 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:

    1. 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.

    2. 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:

  33. MiniMax Assistant

    Let me see the engine parameters for bootstrap:

  34. MiniMax Assistant

    Let me look at the ContextEngine interface to see how it defines operations:

  35. MiniMax Assistant

    Now let me understand the design. The contextMode: "isolated" only exists for prepareSubagentSpawn. 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:

  36. MiniMax Assistant

    Let me now look for the recent fix that handles similar issues:

  37. MiniMax Assistant

    Let me look at this prior fix to see how similar issues were addressed:

  38. MiniMax Assistant

    Let me look at the existing changeset files to understand the changeset format:

  39. MiniMax Assistant

    Now let me look at the rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function:

  40. MiniMax Assistant

    Now I have a clearer picture. There's an existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing that 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 isolated flag:

  41. MiniMax Assistant

    Let me look for any references to isolated in CHANGELOG:

  42. MiniMax Assistant

    Let me check recent fixes to understand pattern:

  43. MiniMax Assistant

    Now let me check the OpenClaw node_modules to see if there's any cron session info there:

  44. MiniMax 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 in prepareSubagentSpawn for subagents. For cron runs in OpenClaw, there isn't an explicit isolated flag.

    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 pattern agent:*:cron:** (or agent:*:cron:*:run:**).

    But more importantly, OpenClaw's contextMode may also exist for cron jobs. Let me look at how the host provides contextMode:

  45. MiniMax Assistant

    Now, the question is how do we detect an isolated cron run? Let me check the existing getConversationBySessionKey logic 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 like agent: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:

  46. MiniMax Assistant

    Now let me check the assemble and bootstrap flow once more to understand where the issue might arise:

  47. MiniMax Assistant

    Now I think I understand. The detection would happen via the runtimeContext field. Let me check:

  48. MiniMax Assistant

    Now let me check what code paths use runtimeContext:

  49. MiniMax 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 runtimeContext indicating isolation.

    Let me check what kinds of things are in runtimeContext:

  50. MiniMax Assistant

    Now let me search how runtimeContext could signal isolation. Actually, given the issue says "isolated cron runs" specifically and given the contextMode: "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:

  51. MiniMax 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 isolated flag in the engine or host contract.

    Let me think about this practically. The fix needs to be:

    1. Detect when a session is "isolated" (i.e., the host signals this in some way)
    2. When detected, archive the prior active conversation before bootstrap/ingest
    3. 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:

  52. MiniMax Assistant

    Let me look at recent fix-related issues to understand what tests are expected:

  53. MiniMax Assistant

    No existing tests. Let me look at how the openclaw bridge passes runtime info:

  54. MiniMax Assistant

    Now, let me look at the test setup to see how the engine is being constructed and tested:

  55. MiniMax 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: true or contextMode: "isolated" set for cron jobs.

    Looking at the existing prepareSubagentSpawn with contextMode: "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:

  56. MiniMax Assistant

    OK so contextMode: "isolated" only exists in prepareSubagentSpawn. For cron jobs, the only signal we have is probably through runtimeContext.

    Let me look more at the runtime context to see if we need to add isolation detection:

  57. MiniMax Assistant

    Now let me look at the plugin's before_prompt_build hook more carefully:

  58. MiniMax 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 isolated flag for cron in the current bridge.

    Let me check more carefully the bootstrap path to find where I might need to detect this:

  59. MiniMax Assistant

    Now I understand the bootstrap path. The issue is that when getOrCreateConversation is 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:

    1. The host (OpenClaw) creates an isolated cron run session
    2. The session key is stable across runs
    3. The host likely indicates "isolated" via runtimeContext (e.g., runtimeContext.isolated === true or similar)

    OR

    1. The host may not pass an explicit isolation flag
    2. We may need to detect the case via some heuristic

    Let me check what existing PRs in the codebase look like for similar fixes:

  60. MiniMax Assistant

    Now let me approach this differently. Let me look at how the OpenClaw source actually identifies isolated cron sessions:

  61. MiniMax Assistant

    Let me look at the broader context of the issue - the test setup createEngineWithDeps:

  62. MiniMax Assistant

    OK now let me run existing tests to see the current state:

  63. MiniMax Assistant

    Now let me write a small reproduction script to verify the bug exists:

  64. MiniMax Assistant

    Let me write a vitest test instead:

  65. MiniMax 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:

  66. MiniMax 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 runtimeContext field. 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:

  67. MiniMax Assistant

    Now, the question is: how do we know the run is "isolated"?

    Looking again at the runtimeContext mechanism - I believe the host OpenClaw sets an isolated flag 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" - the run:run-123 part of the key is what makes it isolated. This means OpenClaw creates a stable session key like agent:main:cron:daily-digest:run:run-123 for each isolated run.

    So the detection mechanism might be the session key pattern run:run- itself, or just any stable session key that has a cron: 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 in prepareSubagentSpawn. The fact that the issue title uses "isolated" terminology (same as contextMode) suggests OpenClaw might be signaling isolation through contextMode for these cron runs too.

    Let me look at what runtimeContext actually contains in practice. Let me check the bridge for clues:

  68. MiniMax 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 === true or similar.

    Let me think about this differently. The fix should:

    1. Accept a signal from the host indicating isolation
    2. 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 bootstrap more carefully to understand how I can add this logic:

  69. MiniMax Assistant

    Now I see the structure. There are functions like rotateStaleSessionKeyConversationIfTrackedTranscriptMissing and findAmbiguousSessionKeyRuntimeRollover that 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 runtimeContext would naturally contain. Looking at the runtimeContext documentation in OpenClaw docs is not available to me, so let me check what fields the existing code expects:

  70. MiniMax Assistant

    Now let me look at the OpenClaw spec more carefully. Let me check the test for the contextMode related scenarios:

  71. MiniMax 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:

    1. There's no public interface change
    2. Prior runs should be archived (not deleted)
    3. Compaction within current run should still work
    4. Ordinary non-cron session continuity is unchanged

    Let me see what the engine already has for similar detection. Let me look at assemble for how it handles the rotation:

  72. MiniMax Assistant

    Hmm. The contextMode parameter only exists for prepareSubagentSpawn. 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:

    1. Each cron run is its own isolated execution
    2. They reuse a stable session key (i.e., agent:main:cron:daily-digest:run:run-123)
    3. 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 getOrCreateConversation does for sessionId - but it does NOT do this for sessionKey when there's already an active conversation.

    The fix should:

    1. 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:

  73. MiniMax Assistant

    OK so the only isolated flag in the current contract is contextMode: "isolated" in prepareSubagentSpawn. But for cron runs, this doesn't apply.

    Let me look at this from yet another angle. Perhaps the design is:

    1. The host passes runtimeContext: { isolated: true } or similar for cron runs
    2. We need to add this detection

    OR

    1. The host passes the session key itself in a specific format
    2. We detect it from the key pattern

    Let me check the OpenClaw changelog/docs again:

  74. MiniMax 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 runtimeContext since that's the runtime context. Let me check what runtimeContext is for the host.

    Actually wait. Let me look at how the runtime context flows. In bootstrap, we don't get a runtimeContext. In ingest, we don't get one either. In assemble, we don't. In afterTurn, we don't. Only compact and maintain get a runtimeContext.

    So runtimeContext is 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 shouldIgnoreSession does with cron:**:

    Looking at shouldIgnoreSession, it returns true for sessions matching the ignoreSessionPatterns. By default, cron sessions 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 isolated handling in the bootstrap path 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 is run: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 existing cron session handling:

  75. MiniMax 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:

    1. Different session ID for each run (yes - because sessionId is the runtime UUID per execution)
    2. Possibly a different session file
    3. The session key is stable (yes)

    Let me look at the prior logic for the "stale session key rollover" issue:

  76. MiniMax 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:

    1. Creates a new sessionId (a fresh runtime UUID)
    2. Sets the session key to the stable key
    3. Possibly creates a new session file

    But how does it know it's "isolated"? Maybe the host calls before_reset or something? Or maybe via runtime context.

    Let me check if there's any signal in runtimeContext:

  77. MiniMax Assistant

    Now let me think about it. The fix needs to detect the case where:

    1. A sessionKey already has an active conversation
    2. 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:

    1. The sessionKey matches the pattern agent:*:cron:** (similar to how cron sessions are excluded)
    2. OR there's a new runtime signal

    Wait, let me re-read the README again:

  78. MiniMax 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 an isolated flag 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., /reset semantics)? 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 an isolated (or contextMode) 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 runtimeContext is on compact and maintain. We don't get one in bootstrap, ingest, assemble, or afterTurn. 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. The run:run-123 segment 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 prefix
    • main - agent ID
    • cron - cron segment
    • daily-digest - cron job name
    • run - segment
    • run-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 AND run: 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 bootstrap and ingest again:

  79. MiniMax Assistant

    OK so we have sessionId, sessionFile, and sessionKey. The host doesn't pass anything else to bootstrap.

    Let me look at OpenClaw architecture docs/specs more carefully to find if there's any clue:

  80. MiniMax 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 isolated flag for bootstrap, 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 K is invoked, if there was a prior active conversation for K with 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 /reset semantics 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:

    1. Session key has active conversation
    2. Session ID is different
    3. Tracked transcript file path is different from current session file
    4. 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 rotateStaleSessionKeyConversationIfTrackedTranscriptMissing wouldn't trigger.

    Let me check what the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing does 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, getOrCreateConversation finds 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 like agent: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 session
    • agent:main:cron:nightly:run:run-123 - isolated run session (stable key)

    For an isolated run session:

    • It has a run:run-NNN segment
    • 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:

    1. The session key has a run:run-N segment
    2. The session key has an active conversation from a prior run
    3. 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 rotateStaleSessionKeyConversationIfTrackedTranscriptMissing already checks sessionId differences and session file differences. The issue might be that:

    1. The session file path is the same (OpenClaw recreates the file at the same path)
    2. So rotateStaleSessionKeyConversationIfTrackedTranscriptMissing doesn't trigger
    3. So getOrCreateConversation reuses the prior active conversation

    The fix should:

    1. Detect the case where sessionKey has an active conversation with different sessionId
    2. Detect that the session file at the tracked path is "fresh" (different content, different mtime, etc.)
    3. 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 /reset is handled. When /reset is issued, the existing logic calls handleBeforeReset with reason reset, which archives and creates a replacement. So /reset is 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 runtimeContext in assemble, and we just need to pass it through? Let me check the assemble flow:

  81. MiniMax Assistant

    OK no runtimeContext in assemble. 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 bootstrap with sessionId and sessionKey. 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:

    1. bootstrap({sessionId: 'new-uuid', sessionKey: 'agent:main:cron:daily-digest:run:run-123', sessionFile: '/path/to/file'})
    2. rotateStaleSessionKeyConversationIfTrackedTranscriptMissing - this only rotates if the prior transcript file is missing AND the new sessionFile is different
    3. getOrCreateConversation - 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 runtimeContext is part of bootstrap or some other path I'm missing:

  82. MiniMax 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 session
    • agent:main:cron:nightly:run:run-123 - isolated run session

    The run:run-123 part 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 both agent:main:cron:nightly and agent:main:cron:nightly:run:run-123. So the cron pattern itself is agent:*:cron:** or agent:*:cron:*.

    Let me approach this with a clear plan:

    1. Detect "isolated cron runs" by session key pattern + session ID differs from active conversation's sessionId
    2. When detected, archive the prior active conversation and create a fresh one
    3. 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_reset and session_end:

  83. MiniMax Assistant

    OK, so for cron runs, the host:

    1. May call session_end to close the previous run's session
    2. Creates a new session with stable key

    If session_end is 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 binding
    • completed - revoke grant
    • released - remove grant
    • swept - 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 applySessionReplacement does:

    Actually, let me think about this issue more concretely. The simplest test case to write would be:

    1. First, do a bootstrap for a stable cron key
    2. Then, do a second bootstrap with a new sessionId but same sessionKey
    3. Verify the new run doesn't share context with the first run

    Let me write that test now:

  84. MiniMax 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 getOrCreateConversation reuses the active conversation when the session key is reused, regardless of whether the run is "isolated" or not.

    The fix should:

    1. Detect when a session key is being reused with a different sessionId
    2. AND there's an existing active conversation for that session key
    3. 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 sessionFile as 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:* - matches agent:main:cron:nightly (one segment after cron)
    • agent:*:cron:** - matches both agent:main:cron:nightly and agent:main:cron:nightly:run:run-123

    The isolated run session specifically has a run:run-N segment. So the pattern for isolated runs would be agent:*:cron:*:run:** or agent:*:*: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 rotateStaleSessionKeyConversationIfTrackedTranscriptMissing would 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 rotateStaleSessionKeyConversationIfTrackedTranscriptMissing function 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, handleBeforeReset is called with reason "reset", which archives and creates a replacement. So /reset is handled separately.

    For isolated cron runs, neither before_reset nor session_end is 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:

    1. Check if sessionKey matches the cron pattern AND has the run:run-N segment
    2. 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:

    1. If the sessionFile at the prior conversation's tracked path is missing → use existing rotate logic
    2. 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
    3. 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 a cron segment. 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:

  85. MiniMax 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:

  86. MiniMax Assistant

    Now I see clearly: getOrCreateConversation returns the active conversation by sessionKey, even when the sessionId differs. It just updates the sessionId.

    The fix should change this behavior to:

    1. Detect when sessionId differs (i.e., this is a new sessionId reusing the sessionKey)
    2. 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:

    1. Isolated cron runs (specific type of session)
    2. Reuse stable session key
    3. Must NOT share active context
    4. Prior runs remain archived (not deleted)
    5. Compaction within current run still works
    6. 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 runtimeContext of compact() (since compact() is called with runtimeContext). Let me check when compact() 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:

  87. MiniMax Assistant

    Hmm, no obvious signal. Let me try a different approach. Let me see if there's some way OpenClaw communicates this through runtimeContext or other means.

    Let me look at what we have in bootstrap more 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 existing prepareSubagentSpawn:

    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 bootstrap with sessionId (new UUID), sessionKey (stable), and sessionFile (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 bootstrap and the sessionFile doesn't exist yet (or has been recreated fresh).

    Let me check the bootstrap path again. The rotateStaleSessionKeyConversationIfTrackedTranscriptMissing checks 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 getOrCreateConversation finds the active conversation by sessionKey and reuses it. BUG.

    For the fix, I think we need to:

    1. Detect when sessionId differs AND sessionKey has active conversation
    2. AND the existing conversation has been "wrapped" (i.e., the prior run completed)
    3. 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 applySessionReplacement function:

  88. MiniMax Assistant

    This is helpful. applySessionReplacement archives 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 compact and see if there's a way to signal isolation there:

  89. MiniMax Assistant

    OK, I think the right approach is:

    1. Look at what data is available in the bootstrap path (sessionId, sessionFile, sessionKey)
    2. Detect "isolated cron run" through a heuristic on the sessionKey pattern
    3. 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 cron and run segments)
    • 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 compact runtimeContext more carefully:

  90. MiniMax Assistant

    Only compact has runtimeContext. So the host can't signal isolation in bootstrap/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-123

    The 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-123 is 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 suggests run-123 is 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-N suffix. So if the cron job is daily-digest, it always uses run:run-123 regardless of which invocation.

    OK this is getting complex. Let me just focus on the fix design.

    Given the issue constraints:

    1. No new public interfaces
    2. Must detect isolated cron runs
    3. 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:

    1. Add a new internal function to detect isolated cron runs by session key pattern
    2. In bootstrap/ingest/assemble/afterTurn, check if this is an isolated cron run
    3. If so, archive the prior active conversation before proceeding

    Let me look at where exactly to add this. First, let me look at bootstrap more carefully:

  91. MiniMax Assistant

    OK so the bootstrap path:

    1. rotateStaleSessionKeyConversationIfTrackedTranscriptMissing - rotates if tracked file missing
    2. findAmbiguousSessionKeyRuntimeRollover - checks for ambiguous rollover
    3. getOrCreateConversation - 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 have cron in their key.

    For an "isolated cron run", the session key has:

    • cron segment
    • run segment (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:

  92. MiniMax 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 cron and run segments

    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 call rotateStaleSessionKeyConversationIfTrackedTranscriptMissing in the right cases?

    Looking at the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing:

    • Only rotates if trackedSessionFile !== params.sessionFile AND tracked file is missing

    What if the host (OpenClaw) creates the new isolated cron run with:

    • A different sessionFile path (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:

  93. MiniMax Assistant

    Excellent! So when the prior transcript file is deleted AND the new session file is different, the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing logic 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:

  94. MiniMax 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 runtimeContext more thoroughly:

  95. MiniMax Assistant

    OK, only one contextMode exists 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 bootstrap when 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 what reconcileTranscriptTailForAfterTurn does:

  96. MiniMax 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:

    1. The session key contains "cron" AND has the run-related pattern
    2. OR there's a configurable session key pattern

    Looking at the README example agent:main:cron:daily-digest:run:run-123, the run:run-N segment identifies it as an isolated run. So a possible pattern: any session key with both cron and run segments.

    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 /reset calls handleBeforeReset which already archives.
    • Normal ongoing conversations? The sessionId stays the same, so we wouldn't trigger.

    Let me check when sessionId changes normally:

    • After /reset: handleBeforeReset is 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.sessionId is 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:

    1. Detect "isolated cron runs" specifically (via session key pattern)
    2. For these, archive prior conversation when sessionId differs

    Let me check what the pattern should be. Looking at the README:

    • agent:*:cron:** matches cron sessions
    • agent:main:cron:daily-digest:run:run-123 is an isolated run

    The distinguishing feature of "isolated run" is the run:run-N segment. So the pattern could be agent:*: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 the run:run-N segment.

    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 like agent:main:cron:daily-digest (just 4 segments after agent).

    So we can detect isolated runs by checking if the session key has both cron AND run segments.

    OK let me design the fix. I'll:

    1. Add a helper function to detect "isolated cron run" session keys (based on pattern)
    2. In bootstrap and other entry points, check if this is an isolated cron run AND the sessionId differs from the active conversation
    3. If so, archive the prior conversation before proceeding

    Let me look at the test to see how session keys are structured:

  97. MiniMax Assistant

    Now let me look at how this is structured. The pattern agent:*:cron:** matches agent:main:cron:daily-digest:run:run-123. But also matches agent: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-N segment. So the pattern would be agent:*: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:

  98. MiniMax Assistant

    OK no isolated field in runtime context. The fix must be done based on existing data.

    Let me now design and implement the fix:

    Approach:

    1. Add a new internal function isIsolatedCronRunSessionKey(sessionKey) that detects if a session key is for an isolated cron run.
    2. 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
    3. The fix should be applied before getOrCreateConversation so the new conversation is fresh.

    Let me look at the bootstrap flow once more:

  99. MiniMax Assistant

    Now let me think about the fix. Let me add a new helper rotateIsolatedCronRunConversationIfReused that:

    1. Checks if the session key matches an isolated cron run pattern
    2. Checks if there's an active conversation for the session key with a different sessionId
    3. If both, archive the prior conversation and let getOrCreateConversation create 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 run
    • agent:main:cron:nightly:run:run-456 - another isolated run
    • agent:main:cron:nightly - parent cron session (NOT an isolated run)

    The distinguishing feature: the session key has BOTH cron and run segments (with run appearing after cron).

    Actually, looking more carefully, the run:run-N segment is what makes it isolated. So we need to detect session keys that have:

    • cron somewhere
    • run after cron
    • A specific run identifier (e.g., run-N or 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 cron and a run-N style 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:

  100. MiniMax 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:

    1. The session key (pattern matching)
    2. The session ID differing from the active conversation's session ID

    Let me check what config options exist:

  101. MiniMax Assistant

    Let me look at the config more carefully:

  102. MiniMax Assistant

    OK now I have a clearer picture. Let me design the fix.

    Looking at this again, I think the cleanest approach is:

    1. Add a new internal helper that detects "isolated cron runs" via session key pattern
    2. 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 runtimeContext field with isolation info that I'm missing. Let me search the codebase more thoroughly:

  103. MiniMax Assistant

    Only contextMode for prepareSubagentSpawn. 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 prepareSubagentSpawn more carefully:

  104. MiniMax Assistant

    OK so prepareSubagentSpawn with contextMode: "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:** or agent:*:*:*: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 is agent:<agentId>:cron:<jobName>:run:<runId>.

    The pattern would be: agent:*:cron:*:run:**.

    But wait, what if other session keys also have :run: in them? Like agent: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 conversation AND active.sessionId !== currentSessionId AND sessionKey matches cron pattern → archive

    Let me check what the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing does 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:

  105. MiniMax Assistant

    So agent:main:cron:nightly:run:run-123 is 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:

    1. Add a helper function isIsolatedCronRunSessionKey(sessionKey) that uses session key pattern matching
    2. In bootstrap/ingest/assemble/afterTurn, check if the session is an isolated cron run AND the active conversation has a different sessionId → archive prior
    3. Use applySessionReplacement to do the archive

    Let me clean up the temp test first:

  106. MiniMax 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:

    1. Detect that the session key has a run:run-N style identifier
    2. AND the active conversation's sessionId differs from the current sessionId
    3. → 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 runtimeContext is only available in compact and maintain. 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:

    1. Add a helper isIsolatedCronRunSessionKey(sessionKey) that returns true if the session key looks like an isolated cron run
    2. Use this helper in bootstrap, ingest, assemble, afterTurn
    3. When detected AND there's an active conversation with different sessionId, archive the prior conversation

    Let me look at the existing applySessionReplacement function more carefully to see how to use it:

  107. MiniMax Assistant

    OK this function:

    • Archives the current conversation (if active)
    • Creates a new conversation (if createReplacement=true)

    But it uses getConversationForSession which 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 current getConversationForSession prioritizes sessionKey, so it would find the prior conversation.

    Wait, let me trace through this:

    1. getConversationForSession({ sessionKey: "agent:main:cron:..." }) - finds active conversation by key
    2. Archives it
    3. Creates new conversation with current sessionId + sessionKey

    Yes, this would work. Let me implement the fix.

    But wait, I want to be careful. The applySessionReplacement is 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 rotateStaleSessionKeyConversationIfTrackedTranscriptMissing that:

    1. Detects isolated cron run by session key pattern
    2. If the active conversation has a different sessionId, archive it
    3. Then getOrCreateConversation will create a fresh one

    Let me now implement the fix. First, let me look at the bootstrap flow once more:

  108. MiniMax Assistant

    OK now I'll implement the fix. Let me first look at the existing patterns once more:

  109. MiniMax 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:

    1. Detection helper: Add isIsolatedCronRunSessionKey(sessionKey) that returns true if the session key matches the isolated cron run pattern (e.g., has both cron and run:run-N segments).

    2. 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.

    3. Use existing patterns: Use the compileSessionPattern from session-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 bootstrap interface:

    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:

  110. MiniMax Assistant

    OK so the LcmDependencies doesn'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 cron and the 5th being run.

    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" in prepareSubagentSpawn, 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:

  111. MiniMax Assistant

    OK, no existing specific pattern for "isolated cron runs". Let me design the fix.

    Here's my plan:

    1. Add an internal helper isIsolatedCronRunSessionKey(sessionKey) in the engine
    2. The helper detects session keys matching the pattern agent:*:cron:*:run:** (or similar)
    3. In bootstrap, ingest, assemble, afterTurn, before getOrCreateConversation:
      • Check if sessionKey matches isolated cron run pattern
      • If yes, AND there's an active conversation with different sessionId, archive the prior
    4. 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:** - matches agent:main:cron:daily-digest:run:run-123
    • Pattern: agent:*:*:*:run:** - matches any session key with run segment

    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:

    • bootstrap
    • ingest
    • ingestBatch
    • assemble
    • afterTurn

    All of these call getOrCreateConversation (directly or indirectly) which has the bug.

    The fix should be applied BEFORE getOrCreateConversation so that the prior conversation is archived first, then getOrCreateConversation creates a fresh one.

    Let me implement this now. First, let me look at the existing test setup:

  112. MiniMax Assistant

    OK now I have a clearer picture. Let me implement the fix.

    Looking at this once more, I realize I should focus on:

    1. The session key must be identified as an "isolated cron run" via pattern
    2. 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 applySessionReplacement to understand its behavior:

  113. MiniMax Assistant

    applySessionReplacement archives the current conversation and optionally creates a new one. It uses getConversationForSession which:

    1. First tries by sessionKey (finds active conversation)
    2. 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:

    1. Add isIsolatedCronRunSessionKey(sessionKey) helper
    2. 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
    3. 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) vs agent: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 like agent:main:cron:daily-digest:run:run-123

    So agent:*:cron:** matches agent: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 a run: segment somewhere).

    Or maybe simpler: any session key that has the run:run-N segment is an isolated run.

    OK let me just go with a simple heuristic: the session key has both cron and run:run-N segments.

    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 ignoreSessionPatterns configuration could be used as a signal? If the user has configured agent:*: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-123

    Breaking this down:

    • agent - agent prefix
    • main - agent ID
    • cron - cron segment
    • daily-digest - cron job name
    • run - run segment
    • run-123 - run ID

    So the pattern would be: ^agent:[^:]+:cron:[^:]+:run:[^:]+. Let me verify:

    • agent:main:cron:daily-digest:run:run-123 matches ✓
    • agent:main:cron:nightly doesn't match (missing run/runId segments) ✓
    • agent:main:main doesn't match ✓

    Now let me implement the fix.

  114. MiniMax Assistant

    Good. Let me now design and implement the fix:

  115. MiniMax Assistant

    Let me look at where I can add the helper function:

  116. MiniMax Assistant

    Now let me implement the fix. I'll:

    1. Add a constant for the isolated cron run pattern
    2. Add a helper method isIsolatedCronRunSessionKey
    3. Add a helper method archiveIsolatedCronRunConversationIfReused that archives prior conversation when the session is an isolated cron run with a different sessionId
    4. Call this helper in bootstrap, ingest, assemble, afterTurn

    Let me start implementing:

  117. MiniMax Assistant

    Now let me look at where to add the constant:

  118. MiniMax 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:

  119. MiniMax Assistant

    OK so there are MANY places where getConversationForSession and getOrCreateConversation are called. The fix needs to be at strategic places.

    The most critical places are:

    1. bootstrap (line 7183) - the entry point for new sessions
    2. ingestSingle (line 8105) - where messages are ingested
    3. assemble (line 8786) - where context is assembled
    4. afterTurn (line 8451) - where turn-end persistence happens

    Let me now implement the fix. The strategy:

    1. Add isIsolatedCronRunSessionKey helper
    2. Add archiveIsolatedCronRunConversationIfReused helper that archives prior conversation
    3. 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 getOrCreateConversation so it's centralized:

  120. MiniMax 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 getOrCreateConversation itself. If the sessionKey has an active conversation with a different sessionId, we should... well, that depends on whether it's isolated or not.

    But getOrCreateConversation doesn'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:

    1. Add a helper to detect isolated cron runs
    2. In bootstrap and other entry points, archive the prior conversation if needed

    Let me start coding:

  121. MiniMax Assistant

    Now let me look at where to add the helper. Let me look at the structure of the engine:

  122. MiniMax 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:

    1. Add a constant for the isolated cron run pattern

    2. Add a private method isIsolatedCronRunSessionKey(sessionKey)

    3. 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
    4. Call archiveIsolatedCronRunConversationIfReused in:

      • bootstrap - before getOrCreateConversation
      • ingest (in ingestSingle) - before getOrCreateConversation
      • assemble - before getConversationForSession
      • afterTurn - before getConversationForSession

    Let me start implementing:

  123. MiniMax Assistant

    Now let me implement the fix. First, let me add the constants and helper methods:

  124. MiniMax Assistant

    Now let me make the edits. I'll add a constant for the pattern, the helper, and use it in the engine:

  125. MiniMax Assistant

    Now let me find where the helper methods are and add the new ones:

  126. MiniMax Assistant

    Now let me add the helper method after isStatelessSession:

  127. MiniMax Assistant

    There's a duplicate. Let me fix that:

  128. MiniMax Assistant

    I broke the getCircuitBreakerState method. Let me fix it:

  129. MiniMax Assistant

    There's a duplicate line and broken isCircuitBreakerOpen. Let me fix both:

  130. MiniMax Assistant

    There's a stray } at line 3623. Let me remove it:

  131. MiniMax 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:

  132. MiniMax Assistant

    Let me restore the file and start over more carefully:

  133. MiniMax Assistant

    Good, the file is back. Now let me make a more careful change. Let me first add the constants:

  134. MiniMax Assistant

    Now let me add the helper method after isStatelessSession. Let me look at the exact location first:

  135. MiniMax Assistant

    Now let me add the helper. I'll add it after isStatelessSession and before the circuit breaker helpers:

  136. MiniMax Assistant

    There's a duplicate line at 3583 and missing blank line before private getCircuitBreakerState. Let me fix it carefully:

  137. MiniMax Assistant

    I keep breaking things. Let me reset and try a different approach - use a temp script to make precise edits:

  138. MiniMax Assistant

    Let me use a more careful approach - use a Python script to do the edits:

  139. MiniMax Assistant

    OK only node. Let me use Node.js:

  140. MiniMax Assistant

    Now let me verify the engine compiles. Let me run the typecheck:

  141. MiniMax Assistant

    Good, typecheck passes. Now let me add the actual fix logic. I'll add a method archiveIsolatedCronRunConversationIfReused that archives the prior conversation when an isolated cron run reuses a stable session key with a different sessionId.

    Let me look at where rotateStaleSessionKeyConversationIfTrackedTranscriptMissing is defined:

  142. MiniMax Assistant

    Good. Now let me add my new method after rotateStaleSessionKeyConversationIfTrackedTranscriptMissing. Let me write the fix using the Node script:

  143. MiniMax Assistant

    Now let me invoke this method in the right places. Let me first find the bootstrap path:

  144. MiniMax Assistant

    Let me look at the bootstrap entry:

  145. MiniMax Assistant

    Let me add the call after the rotate stale. The key insight is to add this BEFORE the getOrCreateConversation call:

  146. MiniMax Assistant

    Now let me also add it to ingestSingle. Let me check the structure:

  147. MiniMax Assistant

    Let me add the call to ingestSingle:

  148. MiniMax Assistant

    Now let me verify the engine compiles:

  149. MiniMax Assistant

    Typecheck passes. Now let me verify my reproduction script confirms the fix:

  150. MiniMax 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:

  151. MiniMax Assistant

    All 317 engine tests pass. Now let me run more tests:

  152. MiniMax 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:

    1. Same session ID, isolated cron run key: Should NOT archive (it's the same run)
    2. No prior conversation: Should NOT archive (nothing to archive)
    3. Different session key, isolated cron run key: Should NOT archive (no prior conversation for this key)
    4. Non-isolated cron run key: Should NOT archive (it's a normal session)
    5. Prior conversation already archived: Should NOT archive (nothing active to archive)

    Let me verify these by writing more tests:

  153. MiniMax Assistant

    All 5 edge case tests pass:

    1. ✓ First isolated cron run - no prior conversation, no archival
    2. ✓ Same sessionId with isolated cron run key - no archival
    3. ✓ Non-cron session key - no archival (existing behavior preserved)
    4. ✓ Parent cron session (no run segment) - no archival (existing behavior preserved)
    5. ✓ Isolated cron run archives prior conversation (not deleted)

    Let me clean up the temp test:

  154. MiniMax Assistant

    Now let me also verify the original reproduction still works correctly:

  155. MiniMax Assistant

    The original bug is now fixed. Let me clean up:

  156. MiniMax Assistant

    Now let me also test bootstrap, assemble, and afterTurn paths to make sure the fix is applied there too:

  157. MiniMax Assistant

    Both bootstrap and assemble paths correctly archive prior conversations. Let me clean up:

  158. MiniMax Assistant

    Now let me also add a changeset for this change as the project requires:

  159. MiniMax Assistant

    Now let me run all tests once more to ensure everything passes:

  160. MiniMax 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:

    1. What if sessionKey is undefined? → isIsolatedCronRunSessionKey returns false, no archival
    2. What if sessionKey is just whitespace? → returns false after trim, no archival
    3. What if there's a race condition where two runs start simultaneously? → The session queue should serialize

    Let me also verify the typecheck passes:

  161. MiniMax Assistant

    Now let me look at the changes I've made:

  162. MiniMax Assistant

    Let me also check the changeset file:

  163. MiniMax Assistant

    Now let me think about edge cases more carefully:

    1. What about when the host doesn't pass runtimeContext for an isolated cron run? → We use sessionKey pattern. ✓
    2. What if the sessionKey pattern doesn't match? → We don't archive, behavior unchanged. ✓
    3. What if the sessionFile is the same path? → Bootstrap goes through the new logic, archives prior. ✓
    4. What about the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing? → It still handles the file-missing case. ✓
    5. What if archiveIsolatedCronRunConversationIfReused is called inside a transaction? → applySessionReplacement already handles transactions. ✓

    Let me also consider: what happens if applySessionReplacement is called but the conversation is fresh (no messages)? Looking at applySessionReplacement:

    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 getConversationBySessionKey returns 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 assemble path? The assemble uses createReplacement: false initially. Let me check what this does:

  164. MiniMax Assistant

    Hmm, in applySessionReplacement, when createReplacement is false, it only archives the prior conversation but doesn't create a new one. Then getOrCreateConversation is called afterwards, which will create a new one.

    But wait, looking at the call sites:

    • assemble uses createReplacement: false
    • afterTurn uses createReplacement: false
    • bootstrap uses createReplacement: true

    For assemble, we want to archive the prior conversation and let getConversationForSession return null. Then what does assemble do?

    Looking at the assemble code:

  165. MiniMax Assistant

    Hmm. For assemble, the call is inside rotateStaleSessionKeyConversationIfTrackedTranscriptMissing and archiveIsolatedCronRunConversationIfReused. These call applySessionReplacement which (with createReplacement: false) just archives.

    But then getConversationForSession is called, which will:

    1. Try by sessionKey (returns null, since prior is archived)
    2. 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 pass createReplacement from the archive call:

    • rotateStaleSessionKeyConversationIfTrackedTranscriptMissing uses createReplacement: false (so doesn't create new conversation, only archives)
    • archiveIsolatedCronRunConversationIfReused uses createReplacement: true by default (so creates new conversation)

    Wait, let me look again:

  166. MiniMax Assistant

    OK so by default, archiveIsolatedCronRunConversationIfReused uses createReplacement: 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, getConversationForSession is called. If the new conversation has the same sessionKey, then getConversationForSession will find it.

    Let me think about this:

    1. Before: sessionKey has active conversation A (sessionId: "session-run-1")
    2. archiveIsolatedCronRunConversationIfReused archives A and creates B (sessionId: "session-run-2", sessionKey: same)
    3. getConversationForSession({sessionId: "session-run-2", sessionKey: K}) is called
    4. It first tries by sessionKey → finds B (active, sessionKey matches)
    5. 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 createReplacement is false, the function returns without creating a new conversation. So getConversationForSession would return null.

    But in archiveIsolatedCronRunConversationIfReused, the default createReplacement is true. So unless explicitly overridden, a new conversation is created.

    In the assemble path, I didn't override createReplacement, so it's true. The new conversation is created. Good.

    Actually wait, let me think again. Looking at the assemble call:

    await this.archiveIsolatedCronRunConversationIfReused({
      phase: "assemble",
      sessionId: params.sessionId,
      sessionKey: params.sessionKey,
    });
    

    I didn't pass createReplacement, so it defaults to true. 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 true is correct for all entry points.

    Now let me check if there are any other entry points that I might have missed:

  167. MiniMax Assistant

    Let me look at line 6467 - that's in reconcileTranscriptTailForAfterTurnInSessionQueue - this is the afterTurn reconcile path:

  168. MiniMax Assistant

    Wait, I see that archiveIsolatedCronRunConversationIfReused uses default createReplacement: true, but this is called AFTER rotateStaleSessionKeyConversationIfTrackedTranscriptMissing which uses createReplacement: false.

    If the second call (archiveIsolatedCronRunConversationIfReused) creates a new conversation, that's good.

    But wait, there's a subtle issue. archiveIsolatedCronRunConversationIfReused uses createReplacement: true (default). But the call inside the transaction wraps applySessionReplacement which itself doesn't start a new transaction (the caller is inside a transaction).

    Looking at applySessionReplacement:

  169. MiniMax Assistant

    applySessionReplacement does:

    1. Archive the current conversation (if active)
    2. If createReplacement is 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 rotateStaleSessionKeyConversationIfTrackedTranscriptMissing archives the prior conversation (with createReplacement: false), then archiveIsolatedCronRunConversationIfReused is called. It checks:

    • sessionKey matches isolated cron pattern
    • normalizedSessionKey exists
    • sessionId exists
    • activeByKey exists and is active (but it was just archived, so it's not active anymore!)
    • sessionId differs

    If rotateStaleSessionKeyConversationIfTrackedTranscriptMissing already archived the prior, then activeByKey would be null or not active. So archiveIsolatedCronRunConversationIfReused would return false without doing anything.

    This is fine - no double archiving.

    But what if rotateStaleSessionKeyConversationIfTrackedTranscriptMissing didn't archive (e.g., sessionFile path matched)? Then activeByKey is still active, and archiveIsolatedCronRunConversationIfReused correctly archives it.

    OK so the order is:

    1. rotateStaleSessionKeyConversationIfTrackedTranscriptMissing - handles file-missing case
    2. archiveIsolatedCronRunConversationIfReused - 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:

  170. MiniMax Assistant

    isFreshLifecycleConversation returns 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... getOrCreateConversation would 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 applySessionReplacement logic 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 getOrCreateConversation logic is compatible with my fix. After the fix:

    1. archiveIsolatedCronRunConversationIfReused archives the prior conversation and creates a new one
    2. getOrCreateConversation is 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., applySessionReplacement uses params.sessionKey for nextSessionKey). 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 sessionKey and nextSessionKey are both normalizedSessionKey (same). The new conversation gets the same sessionKey. Good.

    Let me look at the tests once more to ensure correctness:

  171. MiniMax Assistant

    All 1067 tests pass. Let me also verify the typecheck:

  172. MiniMax Assistant

    Typecheck passes. Let me also verify the build works:

  173. MiniMax Assistant

    Build succeeds.

    Now let me also verify the fix with a few more edge case tests. Let me also check if ingestBatch should also call the archive helper:

  174. MiniMax Assistant

    ingestBatch calls ingestSingle in a loop, which already calls archiveIsolatedCronRunConversationIfReused. So ingestBatch is 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, ingestSingle calls archiveIsolatedCronRunConversationIfReused which archives the prior and creates new. For the second message, archiveIsolatedCronRunConversationIfReused would 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:

    1. ✓ Detects isolated cron runs via session key pattern
    2. ✓ Archives the prior active conversation (prior runs remain archived)
    3. ✓ Creates a fresh conversation (no shared context)
    4. ✓ Compaction still works (we use the new conversation from then on)
    5. ✓ 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.isolated as 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 runtimeContext field if it exists. However, since runtimeContext is only available in compact and maintain, not in bootstrap, ingest, etc., it's not useful for cron runs.

    OK my fix is complete. Let me also run the relevant plugin tests:

  175. MiniMax Assistant

    All tests pass. Let me also run the integration tests:

  176. MiniMax Assistant

    All 97 integration tests pass.

    Now let me also think about one more potential issue. What if the existing conversation has active = 1 but the activeByKey lookup returns null (race condition)?

    Actually, getConversationBySessionKey is 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:

  177. MiniMax 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:

  178. MiniMax Assistant

    Let me verify everything one more time:

  179. MiniMax Assistant

    Let me also run the full test suite once more:

  180. MiniMax Assistant

    All 1067 tests pass.

    Let me also verify the test setup for the existing bootstrap and assemble tests don't break:

  181. MiniMax Assistant

    This test uses agent:main:cron:nightly which 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:

  182. MiniMax Assistant

    This test uses agent:main:cron:nightly:run:run-123 (6 segments) which matches my pattern. But it has ignoreSessionPatterns: ["agent:*:cron:**"] which excludes it. So shouldIgnoreSession returns true, and the bootstrap returns early without my fix being called.

    Let me verify:

  183. MiniMax Assistant

    Wait, I'm looking at the wrong section. Let me find the bootstrap entry:

  184. MiniMax 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:

    1. agent:main:cron:daily-digest:run:run-123 ✓ matches (isolated run)
    2. agent:main:cron:nightly ✗ doesn't match (parent cron session)
    3. agent:main:cron:nightly:run:run-456 ✓ matches
    4. agent:main:user:alice ✗ doesn't match
    5. agent:main:run:foo:bar ✗ doesn't match (no cron segment)
    6. agent:main:cron:foo:bar:baz:qux:run:run-1 ✓ matches (has both cron and run segments)

    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:

    • agent matches
    • main matches agent id
    • cron matches cron segment
    • foo: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: matches
    • main matches [^:]+
    • :cron: matches
    • foo matches [^:]+ (only foo, not foo: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-123 is 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 if agent:main:cron:job-name:run:run-123 (6 segments)? Yes, matches (job-name has a dash, which is fine for [^:]+).

    What about agent:main:cron:job:run:run1:foo (7 segments)? Let me trace:

    • agent: matches
    • main matches [^:]+
    • :cron: matches
    • job matches [^:]+
    • :run: matches
    • run1 matches [^:]+
    • Remaining :foo is unmatched, but the regex doesn't require exact match (no $ anchor)

    So agent:main:cron:job:run:run1:foo matches! 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. compileSessionPattern uses ^${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: matches agent:
    • [^:]+ matches main (greedy, but can't include :)
    • :cron: matches :cron:
    • [^:]+ matches job
    • :run: matches :run:
    • [^:]+ matches run1
    • 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:

  185. MiniMax 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:

  186. MiniMax 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. For agent:*: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: ✓
    • main matches [^:]*
    • :cron: ✓
    • nightly:run:run-123 matches .*
    • end ✓

    So compileSessionPattern("agent:*:cron:**") matches agent:main:cron:nightly:run:run-123 (5+ segments).

    For my pattern ^agent:[^:]+:cron:[^:]+:run:[^:]+, I should anchor it. Let me update:

  187. MiniMax Assistant

    Let me use Node.js script:

  188. MiniMax Assistant

    Now let me verify the fix still works with the anchored pattern:

  189. MiniMax Assistant

    All tests pass with the anchored pattern. Let me clean up:

  190. MiniMax Assistant

    Let me run all tests once more to ensure nothing is broken:

  191. MiniMax Assistant

    All 1067 tests pass.

    Now let me review my changes one final time:

  192. MiniMax Assistant

    Now let me check if there are any other places I should verify. Let me look at the compact function:

  193. MiniMax Assistant

    Looking at compact, it uses getConversationForSession (not getOrCreateConversation). 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:

  194. MiniMax Assistant

    The test needs the session file to exist. Let me create it first:

  195. MiniMax Assistant

    Hmm, the test is failing. Let me debug. The issue is run1After?.active returns false not 0. The conversation's active property might be a boolean:

  196. MiniMax Assistant

    The ConversationRecord.active is boolean, but the raw DB column is number. The toConversationRecord likely converts it. Let me update the test:

  197. MiniMax Assistant

    Yes, active is a boolean. Let me update the test:

  198. MiniMax 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:

  199. MiniMax Assistant

    Now let me also make sure the existing rotateStaleSessionKeyConversationIfTrackedTranscriptMissing doesn't conflict with my new helper. Looking at the order of operations:

    For bootstrap:

    1. rotateStaleSessionKeyConversationIfTrackedTranscriptMissing - handles stale session file case (file missing)
    2. archiveIsolatedCronRunConversationIfReused - handles isolated cron run case

    These are different concerns:

    • rotateStaleSessionKeyConversationIfTrackedTranscriptMissing: detects when the session file path changed AND old file is missing
    • archiveIsolatedCronRunConversationIfReused: 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 archiveIsolatedCronRunConversationIfReused triggers
    • Session file path is different AND old file missing → both could trigger, but archiveIsolatedCronRunConversationIfReused checks if there's an active conversation first. If rotateStaleSessionKeyConversationIfTrackedTranscriptMissing already archived, activeByKey would be null/inactive, so archiveIsolatedCronRunConversationIfReused would be a no-op.

    So they don't conflict. Good.

    Now let me run the tests one final time:

  200. MiniMax Assistant

    All 1067 tests pass.

    Let me look at the final state of my changes:

  201. MiniMax Assistant

    Let me also look at the changeset format once more:

  202. MiniMax Assistant

    Let me now go through the checklist:

    1. 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.
    2. 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.
    3. 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
    4. I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.

      • Yes, all 1067 tests pass.

    Let me also verify the changeset is in the correct format:

  203. MiniMax Assistant

    Format is correct.

    Now let me also look at my full diff one more time:

  204. MiniMax Assistant

    All the changes look good. Let me run a final test to confirm everything is working:

  205. MiniMax 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 compileSessionPattern style. The existing patterns are like agent:*:cron:* etc. Let me check if I should use a similar approach:

    Actually, the existing compileSessionPattern is for user-configurable ignore patterns. My ISOLATED_CRON_RUN_KEY_REGEX is for internal detection. Using a regex is simpler.

    Let me also verify the compileSessionPattern would 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:

  206. MiniMax 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 run but no cron

    Now let me do a final test:

  207. MiniMax Assistant

    All 1067 tests pass. Let me also verify the build:

  208. MiniMax Assistant

    Build succeeds.

    Let me review my changes one last time:

  209. MiniMax Assistant

    Summary of Changes

    1. Added a constant ISOLATED_CRON_RUN_REUSED_KEY_REASON - A reason string for the lifecycle rotation log
    2. 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>)
    3. Added a helper method isIsolatedCronRunSessionKey - Returns true if a session key matches the isolated cron run pattern
    4. 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
    5. Integrated the helper in 4 entry points:
      • bootstrap - before getOrCreateConversation
      • ingestSingle - before getOrCreateConversation (also covers ingestBatch since it calls ingestSingle in a loop)
      • assemble - in the lifecycle guard section
      • afterTurn (in reconcileTranscriptTailForAfterTurnInSessionQueue) - in the transaction
    6. 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:

  210. MiniMax Assistant

    Everything is in order. Let me also verify the typecheck once more:

  211. MiniMax 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 run segment
      • 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:

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.