Skip to content

fix(memory-core): recover narrative text from trajectory when session archived early (#87182) - #87206

Closed
bladin wants to merge 1 commit into
openclaw:mainfrom
bladin:fix/87182-narrative-session-race
Closed

bladin wants to merge 1 commit into
openclaw:mainfrom
bladin:fix/87182-narrative-session-race

Conversation

@bladin

@bladin bladin commented May 27, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR fixes #87182 where the gateway's post-completion session cleanup races with memory-core's narrative extraction, causing model-generated narrative text to be silently discarded.

Root Cause

After subagent runs complete, the gateway immediately archives the session JSONL file (renames to .deleted.<ISO>). However, memory-core's generateAndAppendDreamNarrative() tries to read messages via getSessionMessages() after this cleanup happens, resulting in empty message arrays and lost narrative text.

Solution

Implement trajectory-based recovery as suggested in the issue:

  1. Add extractNarrativeFromTrajectory(): Reads .trajectory.jsonl files which persist longer than session JSONL files
  2. Add extractSessionIdFromMessages(): Extracts session ID for trajectory lookup
  3. Modify generateAndAppendDreamNarrative(): Attempts trajectory recovery before falling back to snippet-based entries

Changes

  • extensions/memory-core/src/dreaming-narrative.ts: +163 lines
    • New helper functions for trajectory recovery
    • Modified narrative extraction logic to try multiple recovery paths
    • Preserves existing fallback behavior as last resort

Verification

The fix follows the workaround already proven effective in production (mentioned in #87182):

"Observed effect of this workaround on our deployment: 17 diary entries written per cron sweep (vs 2-3 before), 11 of them via trajectory recovery, 0 net produced no text failures."

Real Behavior Proof

Will verify with:

  1. Run dreaming cron with multiple workspaces
  2. Check journal logs for "recovered narrative text from trajectory" messages
  3. Verify DREAMS.md contains full narrative entries instead of fallback snippets
  4. Confirm reduction in "narrative generation produced no text" warnings

Fixes: #87182
Type: Bug fix
Breaking: No
Migration: None required - backward compatible recovery mechanism

@openclaw-barnacle openclaw-barnacle Bot added extensions: memory-core Extension: memory-core size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 27, 2026
@clawsweeper

clawsweeper Bot commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 2, 2026, 3:01 AM ET / 07:01 UTC.

ClawSweeper review

What this changes

The branch preserves hidden session records for keep-mode subagent runs, lets transcript reads fall back to deleted archives, and adds a memory-core retry-read regression test so dream diaries can retain generated narrative text.

Merge readiness

⛔ Blocked by patch quality or review findings - 11 items remain

Keep this PR open for a scoped redesign: its lifecycle direction addresses a real narrative-read race and has credible real-run evidence, but the patch makes explicitly deleted transcripts eligible for a reset-only history fallback and broadens hidden-session retention to every keep-mode subagent run.

Priority: P1
Reviewed head: c87ceecb15e953159ba4bd75f8cd9a9da9e2b668
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The branch has strong real-behavior evidence for the reported symptom, but its current lifecycle and deletion semantics are not safe to merge unchanged.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): A third-party A/B run on the proposed head reports fewer empty narrative results and more diary writes; the evidence is meaningful but does not cover the newly identified deletion and cleanup-scope risks.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): A third-party A/B run on the proposed head reports fewer empty narrative results and more diary writes; the evidence is meaningful but does not cover the newly identified deletion and cleanup-scope risks.
Evidence reviewed 5 items Current lifecycle owner: Current main unconditionally schedules removal of the run-owned hidden SQLite session whenever preserveTranscript is false; this is the owner boundary the PR changes.
Keep mode is not plugin-only: Visible subagent spawning also registers cleanup: "keep" and returns the session to its caller, so a cleanup === "keep" exemption affects more than Memory Core's host-managed narrative sessions.
Deleted archives are outside the current fallback contract: Current main names and implements this as a reset-archive resolver; its callers opt into allowResetArchiveFallback, so adding deleted archives changes a reset-only recovery path into a read-after-delete path.
Findings 2 actionable findings [P1] Keep deleted archives out of reset-only fallback
[P1] Do not exempt every keep-mode run from hidden-session deletion
Security Needs attention Deleted transcript content can be recovered: The patch adds .deleted.* files to a reset-only archive resolver, allowing callers that request reset fallback to receive content from an explicitly deleted session.

How this fits together

Memory Core starts detached Gateway subagent runs for dream narratives, reads the resulting session transcript, then explicitly deletes the temporary session. Gateway lifecycle bookkeeping owns the hidden SQLite session record and the transcript reader selects live or reset-archive history for session reads.

flowchart LR
  A[Dreaming workspace] --> B[Memory Core narrative run]
  B --> C[Gateway subagent lifecycle]
  C --> D[Hidden session record]
  C --> E[Session transcript]
  D --> F[Post-run message read]
  E --> F
  F --> G[Dream diary entry]
  F --> H[Explicit session deletion]
Loading

Decision needed

Question Recommendation
Should a host-owned in-flight narrative read be allowed to access a just-archived transcript without making explicitly deleted transcripts available to every reset-history fallback caller? Add a scoped in-flight read path: Preserve reset-only fallback and allow archived text only for the verified host-owned narrative session before its explicit delete.

Why: The patch changes the semantics of deletion and transcript recovery across Gateway callers; choosing the permanent privacy and lifecycle boundary requires maintainer intent.

Before merge

  • Keep deleted archives out of reset-only fallback (P1) - This changes a reset-history resolver to also select .deleted.* transcripts. Its callers opt into allowResetArchiveFallback; a matching session header verifies identity but not that deletion should be reversible, so an explicitly deleted transcript can be read again. Add a narrowly authenticated in-flight host-read path instead. This concern was visible on the prior c87ceec review head.
  • Do not exempt every keep-mode run from hidden-session deletion (P1) - cleanup: "keep" is also used by visible subagent runs, not only the Memory Core host flow. This condition prevents the hard deletion of their run-owned hidden SQLite sessions even though those callers do not establish the host's immediate explicit-delete contract. Scope the exemption to a verified owner/read lease and test cleanup after that owner releases it. This concern was visible on the prior c87ceec review head.
  • Resolve security concern: Deleted transcript content can be recovered - The patch adds .deleted.* files to a reset-only archive resolver, allowing callers that request reset fallback to receive content from an explicitly deleted session.
  • Resolve merge risk (P2) - The deleted-archive change can make text from an explicitly deleted session readable through a reset-history fallback, changing deletion semantics for potentially sensitive transcript content.
  • Resolve merge risk (P1) - The cleanup exemption is keyed only by cleanup mode, although visible subagent runs also use keep mode and do not share Memory Core's immediate explicit-delete contract.
  • Resolve merge risk (P1) - The branch predates substantial current-main lifecycle and narrative-session refactors, so its existing retry test does not establish upgrade-safe behavior after rebasing.
  • Complete next step (P2) - A focused code repair is possible, but maintainers must first choose the deletion/read boundary before automation can safely rebase or narrow the behavior.
  • Improve patch quality - Rebase onto current main's agent-scoped narrative flow and split lifecycle ownership from generic keep-mode behavior.
  • Improve patch quality - Keep .deleted.* out of reset-only fallback; prove the narrowed in-flight read path cannot serve content after explicit deletion.
  • Improve patch quality - Add focused Gateway lifecycle coverage for Memory Core's post-run read followed by explicit deletion and a non-Memory-Core keep-mode caller.

Findings

  • [P1] Keep deleted archives out of reset-only fallback — src/gateway/session-transcript-files.fs.ts:260-279
  • [P1] Do not exempt every keep-mode run from hidden-session deletion — src/agents/subagent-registry-lifecycle.ts:1230-1236
  • [medium] Deleted transcript content can be recovered — src/gateway/session-transcript-files.fs.ts:260
Agent review details

Security

Needs attention: The deleted-transcript fallback weakens the expected deletion boundary by making archived content readable through a generic recovery path.

PR surface

Source +23, Tests +33. Total +56 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 28 5 +23
Tests 1 33 0 +33
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 61 5 +56

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: extensions/memory-core/src/dreaming-narrative.test.ts, serialized state: src/gateway/session-transcript-files.fs.ts, vector/embedding metadata: extensions/memory-core/src/dreaming-narrative.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Scope recovery to the host-owned run (recommended)
    Rebase and replace the global deleted-archive fallback with a verified, temporary read path for the narrative host, plus lifecycle tests for cleanup after explicit deletion.
  2. Accept global read-after-delete semantics
    Merge only if maintainers intentionally want deleted transcript archives to remain readable through normal reset-history fallback callers.
  3. Pause the branch for a dedicated lifecycle contract
    Close or defer this branch if a narrow Gateway post-run transcript ownership API is preferred over changing keep-mode and archive fallback semantics.

Technical review

Best possible solution:

Rebase onto current main and add a narrowly authenticated in-flight transcript-read path for host-owned narrative runs, while preserving reset-only archive fallback and retaining cleanup for keep-mode callers that have no explicit completion owner.

Do we have a high-confidence way to reproduce the issue?

Unclear for the exact current-main shape: the PR discussion contains a real A/B reproduction on the proposed head, and current source still shows the lifecycle/read boundary, but current main has since materially refactored the narrative session flow.

Is this the best way to solve the issue?

No. Fixing the lifecycle owner is preferable to the original trajectory workaround, but the current branch must not turn deleted archives into generic reset-history fallback or make all keep-mode callers retain hidden sessions.

Full review comments:

  • [P1] Keep deleted archives out of reset-only fallback — src/gateway/session-transcript-files.fs.ts:260-279
    This changes a reset-history resolver to also select .deleted.* transcripts. Its callers opt into allowResetArchiveFallback; a matching session header verifies identity but not that deletion should be reversible, so an explicitly deleted transcript can be read again. Add a narrowly authenticated in-flight host-read path instead. This concern was visible on the prior c87ceec review head.
    Confidence: 0.93
    Late finding: first raised on code an earlier review cycle already covered.
  • [P1] Do not exempt every keep-mode run from hidden-session deletion — src/agents/subagent-registry-lifecycle.ts:1230-1236
    cleanup: "keep" is also used by visible subagent runs, not only the Memory Core host flow. This condition prevents the hard deletion of their run-owned hidden SQLite sessions even though those callers do not establish the host's immediate explicit-delete contract. Scope the exemption to a verified owner/read lease and test cleanup after that owner releases it. This concern was visible on the prior c87ceec review head.
    Confidence: 0.87
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 339b9ce0c25e.

Labels

Label changes:

  • add P1: The proposed fallback can expose or resurrect deleted session text in an existing Gateway read path.
  • add merge-risk: 🚨 compatibility: Existing keep-mode callers and deletion expectations can change without an upgrade or caller-contract proof.
  • add merge-risk: 🚨 security-boundary: Explicitly deleted transcript archives become eligible for a caller-visible history fallback.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (logs): A third-party A/B run on the proposed head reports fewer empty narrative results and more diary writes; the evidence is meaningful but does not cover the newly identified deletion and cleanup-scope risks.
  • remove P2: Current review triage priority is P1, so this older priority label is no longer current.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P1: The proposed fallback can expose or resurrect deleted session text in an existing Gateway read path.
  • merge-risk: 🚨 session-state: The branch changes hidden-session deletion timing and transcript selection after a session has completed.
  • merge-risk: 🚨 security-boundary: Explicitly deleted transcript archives become eligible for a caller-visible history fallback.
  • merge-risk: 🚨 compatibility: Existing keep-mode callers and deletion expectations can change without an upgrade or caller-contract proof.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (logs): A third-party A/B run on the proposed head reports fewer empty narrative results and more diary writes; the evidence is meaningful but does not cover the newly identified deletion and cleanup-scope risks.
  • proof: sufficient: Contributor real behavior proof is sufficient. A third-party A/B run on the proposed head reports fewer empty narrative results and more diary writes; the evidence is meaningful but does not cover the newly identified deletion and cleanup-scope risks.

Evidence

Security concerns:

  • [medium] Deleted transcript content can be recovered — src/gateway/session-transcript-files.fs.ts:260
    The patch adds .deleted.* files to a reset-only archive resolver, allowing callers that request reset fallback to receive content from an explicitly deleted session.
    Confidence: 0.93

What I checked:

  • Current lifecycle owner: Current main unconditionally schedules removal of the run-owned hidden SQLite session whenever preserveTranscript is false; this is the owner boundary the PR changes. (src/agents/subagent-registry-lifecycle-bookkeeping.ts:41, 4b26a15a1f42)
  • Keep mode is not plugin-only: Visible subagent spawning also registers cleanup: "keep" and returns the session to its caller, so a cleanup === "keep" exemption affects more than Memory Core's host-managed narrative sessions. (src/agents/tools/sessions-spawn-visible.ts:359, 4b26a15a1f42)
  • Deleted archives are outside the current fallback contract: Current main names and implements this as a reset-archive resolver; its callers opt into allowResetArchiveFallback, so adding deleted archives changes a reset-only recovery path into a read-after-delete path. (src/gateway/session-transcript-files.fs.ts:171, 4b26a15a1f42)
  • Current main has materially moved: The proposed branch still edits the former monolithic lifecycle file, while current main has split that behavior into lifecycle bookkeeping and substantially changed all three touched paths; the branch needs a real rebase and current-main regression coverage. (src/agents/subagent-registry-lifecycle.ts:1, c87ceecb15e9)
  • Recent adjacent maintenance: Recent main history includes first-class archived-session work and a Memory Core repair that agent-scopes dream narrative sessions; these changes make the older branch context insufficient for a direct merge. (extensions/memory-core/src/dreaming-narrative.ts:297, 10c6c0cb98dd)

Likely related people:

  • Peter Steinberger: Recent history shows work on archived-session handling and agent-scoped Memory Core narrative sessions, both directly adjacent to this PR's lifecycle and transcript-reader changes. (role: recent area contributor; confidence: high; commits: d4f19bfd797d, 10c6c0cb98dd, 4b26a15a1f42; files: src/gateway/session-transcript-files.fs.ts, src/agents/subagent-registry-lifecycle-bookkeeping.ts, extensions/memory-core/src/dreaming-narrative.ts)
  • obviyus: The prior review identified the lifecycle owner as the preferred repair boundary and requested a redesign away from fuzzy trajectory recovery. (role: reviewer; confidence: medium; files: src/agents/subagent-registry-lifecycle-bookkeeping.ts, src/gateway/session-transcript-files.fs.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-06-29T15:39:05.927Z sha e25d440d34fab5f91f175b87d4166c82a0ac9a64 :: needs real behavior proof before merge. :: [P1] Resolve trajectory files by run or session id | [P1] Verify trajectory event identity before using text | [P2] Keep settled message reads before trajectory fallback | [P2] Pass the active runtime environment to resolveStateDir
  • reviewed 2026-07-21T00:42:29.504Z sha c87ceec :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-21T20:26:36.828Z sha c87ceec :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-30T13:02:14.412Z sha c87ceec :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels May 27, 2026
@clawsweeper

clawsweeper Bot commented May 27, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@bladin
bladin force-pushed the fix/87182-narrative-session-race branch 2 times, most recently from e7476f8 to e25d440 Compare May 27, 2026 08:30
@dimonnld

Copy link
Copy Markdown

Hi @bladin — reporter of #87182 here. We independently implemented the same trajectory-recovery approach as a local dist patch yesterday (before this PR existed) and have been running it in production for ~24 hours. Sharing concrete numbers in case "needs-real-behavior-proof" can be partially satisfied from a parallel implementation.

Live metrics (two cron windows)

Smoke after first apply (2026-05-27 07:18 UTC, manual cron of the nightly dreaming job):

metric value
dream diary entry written 17
narrative recovered from trajectory 12
narrative generation produced no text 0
recovery internal failures 0

Re-applied today after a packaging regression broke the patch (2026-05-28 19:30 UTC, same manual cron):

metric value
dream diary entry written 16
narrative recovered from trajectory 12
produced no text / errors 0

So in both runs ~70% of the workspaces×phases that would have hit the race were recovered with the actual model-generated narrative, not the snippet fallback. The recovered text matches what we'd see written directly to DREAMS.md on a healthy run (sample line lengths 200-500 chars, normal dream-diary content).

Two latent bugs we hit you may want to pre-empt

When porting this to our bundled dist (so caveats may not all apply to a clean TS source PR):

  1. successfulRunId must be declared in the outer scope. First version of our patch only assigned successfulRunId = runId inside the if (result.status === "ok") branch, expecting JS to hoist. Strict-mode bundle threw ReferenceError: successfulRunId is not defined at runtime — node --check doesn't catch it. We added an explicit let successfulRunId = null; next to let successfulSessionKey = null;. Easy to forget in TS where the type checker would catch it; just flagging since the test matrix should cover the recovery code path actually firing.

  2. os.homedir() requires node:os import. Our dist file imports only path and fs/promises. Switched to process.env.HOME || "/home/deploy" to avoid the dependency. Your extensions/memory-core/src/dreaming-narrative.ts likely has full imports already, so this is just a heads-up if the helper ever gets extracted into a smaller bundle.

Lookup strategy

We index trajectories by runId (scan ~/.openclaw/agents/<agent>/sessions/*.trajectory.jsonl, grep for runId match, find the model.completed event with matching runId, pull data.assistantTexts[0]). I see your PR uses extractSessionIdFromMessages() for lookup — both should work, but runId is more direct and survives the case where messages itself is empty (which was actually the failure mode in our trace — getSessionMessages returned [], not "messages with no session ID").

Happy to share the exact diff if helpful for cross-checking. Will swap our local patch out as soon as this merges.

Happy to re-test on the production target on request — a single manual cron run reproduces the recovery path deterministically against existing trajectory files.

@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 29, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 15, 2026
@C-LaForest

Copy link
Copy Markdown

Corroborating evidence for the recovery approach (and the runId point)

We hit this exact failure on OpenClaw 2026.6.5 with provider ollama (qwen3.6:35b): memory-core logged produced no text → fallback diary while the model had in fact generated a complete ~140-word narrative. The assistant turn was durably persisted (content:[{type:"text",...}], stopReason:"stop", ~136 output tokens) and gateway sessions.get returns it in the shape extractNarrativeText expects — i.e. the narrative existed and was recoverable; the host plugin's read just came back empty (consistent with the archive-vs-read race in #87182). So recovering the text rather than writing a snippet-fallback is the right direction, and matches @dimonnld's point that the read by session key returns nothing.

On the keying concern raised in review: in our capture the recoverable text was correctly associated with its own dreaming-narrative-rem-* session (no cross-session bleed observed) — but that's a single run, so I'd agree resolving the trajectory by runId/sessionId rather than reconstructing the session key is the safer anchor to rule out the misattribution risk entirely.

@obviyus

obviyus commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

Maintainer review — the race is real (session archived before narrative extraction reads it) but the recovery shape can't land as-is, keeping open for redesign:

  1. The trajectory lookup is an unkeyed filename scan with a hardcoded main fallback — if it ever matches the wrong session, the diary gets another session's narrative. Recovery must resolve by sessionId/runId (session store / resolveTrajectoryFilePath / known attempt.runId), never fuzzy sessionKey matching.
  2. Better than recovery: fix the lifecycle. memory-core deletes the session in finally after extraction; the archive race exists because the one-shot spawn path auto-archives earlier. Deferring auto-archive/delete until the host's explicit deleteSession (or letting sessions.get resolve the just-archived transcript for the last known sessionId) removes the race instead of patching around it.
  3. The branch also conflicts with current main and has no tests for the race window.

The lifecycle fix (option 2) is the shape most likely to be accepted — happy to re-review.

@bladin

bladin commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

Redesigned per maintainer review (@obviyus)

The original trajectory-recovery approach has been replaced with the lifecycle fix (option 2 from the review), which removes the race at the source instead of patching around it.

Changes

1. Preserve session store entries for keep-mode subagent runs (src/agents/subagent-registry-lifecycle.ts)

completeCleanupBookkeeping now skips removeInternalSessionEffectsSession when cleanup === "keep", so the host plugin's getSessionMessages call still resolves the entry. The host's explicit deleteSession (in memory-core's finally block) handles full cleanup. This is the core fix: plugin subagents use cleanup: "keep" (set by registerPluginSubagentRunFromGateway at src/gateway/server-methods/agent-task-tracking.ts:181), so their session store entries survive until the host explicitly deletes them.

2. Include .jsonl.deleted.<ISO> archives in transcript history fallback (src/gateway/session-transcript-files.fs.ts)

listResetArchiveCandidatesForTranscriptAsync previously only matched .jsonl.reset.<ISO> files. Now it also resolves .jsonl.deleted.<ISO> so sessions.get can read archived transcripts when the live file is gone but the store entry still exists. This is a defense-in-depth fallback for cases where the store entry survives but the file was already archived by store maintenance.

3. Keeps readSettledNarrativeText (already on main)

The settled retry with 50/150/300/750 ms delays (from #89091) is preserved instead of the trajectory-based recovery, since the lifecycle fix removes the race at the source.

4. Removes extractNarrativeFromTrajectory (the fuzzy sessionKey matching approach)

The trajectory-based recovery with unkeyed filename scanning and no identity verification is removed entirely. If trajectory recovery is ever needed again, it must resolve by sessionId/runId and verify event identity before using text.

Test

Added dreaming-narrative.test.ts: verifies readSettledNarrativeText recovers narrative text when getSessionMessages initially returns empty (simulating the archive race).

Branch

The redesigned code is at clhey/openclaw:fix/87206-lifecycle-narrative-archive-race. If the PR author or a maintainer can update the branch, the commit SHA is 6a3e0f6ac1a9361b0775ed8600ecae42fcb340dd.

Two changes that together fix the race where the gateway archives a session
transcript before the host plugin (memory-core dreaming) can read it:

1. Preserve session store entries for keep-mode subagent runs.
   completeCleanupBookkeeping now skips removeInternalSessionEffectsSession
   when cleanup=keep, so the host's getSessionMessages call still resolves
   the entry. The host's explicit deleteSession handles full cleanup.

2. Include .jsonl.deleted.<ISO> archives in transcript history fallback.
   listResetArchiveCandidatesForTranscriptAsync previously only matched
   .jsonl.reset.<ISO> files. Now it also resolves .jsonl.deleted.<ISO>
   so sessions.get can read archived transcripts when the live file is gone.

Keeps readSettledNarrativeText (settled retry with 50/150/300/750 ms
delays) instead of the trajectory-based recovery removed from the prior
approach, since the lifecycle fix removes the race at the source.
@bladin
bladin force-pushed the fix/87182-narrative-session-race branch from e25d440 to c87ceec Compare July 21, 2026 00:37
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 21, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 21, 2026
@C-LaForest

Copy link
Copy Markdown

AI-assisted comment (Human contributor reviewed). Data captured mechanically; no new hypothesis.

Third-party empirical A/B of c87ceec vs its parent e27e2d0, run out-of-tree.

Test env

  • Fork clone of openclaw at c87ceec + e27e2d0, built from source (pnpm install && pnpm build) into dist-c87ceec/ and dist-c87ceec-parent/
  • Rocky Linux 10.2, kernel 6.12, x86_64, Node.js v24.18.0 LTS (node:sqlite 3.53.1)
  • CLI dispatch: openclaw cron run <cron-id> --url ws://<scratch-gateway>:PORT --token <redacted>
  • Backend: Ollama v0.32.1 serving qwen3.6:35b (36B params) over WebSocket; single request path (not batched)
  • Dreaming enabled via state/openclaw.json patch; dist symlink flipped between the two builds; gateway restarted per side

Method

Two conditions per sweep-count. Each sweep = one cron run on the dreaming cron. Counts are raw grep -c occurrences in the gateway log: produced no text (phase-instances, each sweep touches ≤3 phases), embedded run start vs embedded run done (retry cycles), dream diary entry written (successful narrative writes).

Actions / Outcomes

Condition Sweeps produced no text dream diary entry written Starts Completes Notes
parent e27e2d0, fresh workspace 10 6 1 16 10 6 orphan starts (retry cycles)
fix c87ceec, fresh workspace 10 2 2 13 10 3 orphan starts
parent e27e2d0, warm (~100 prior sweeps) 30 0 9 32 30 2 orphan starts
fix c87ceec, warm 30 0 9 30 30 0 orphan starts

Why

  • Row 1: fresh workspace reproduces the failure mode on parent.
  • Row 2: fix cuts produced no text incidence 3× (6→2) in the same measurement window; real narrative diary entries doubled (1→2). Small N.
  • Row 3: warm/steady-state does not reproduce the visible failure at N=30 on parent — supports "timing-sensitive, workspace-state-dependent".
  • Row 4: at N=30 warm the fix additionally eliminates retry-cycle starts (starts == completes), a secondary effect visible even where the primary failure does not fire.

Log excerpt (parent e27e2d0, one of 6 occurrences)

[plugins] memory-core: narrative generation produced no text for rem phase; writing fallback diary entry.
[plugins] memory-core: narrative generation used fallback for rem phase because the narrative run produced no text.
[diagnostic] aborting run: sessionId=<redacted>

On c87ceec under the same setup: 2 occurrences of the same phrase across 10 sweeps.

Notes

Available on request: raw sweep logs (gateway-*-N{10,30}-sweeps.log), per-run duration extract, openclaw.json config used, exact fork/build commands.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. labels Jul 30, 2026
@obviyus obviyus self-assigned this Aug 3, 2026
@obviyus

obviyus commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Thanks for investigating this race and redesigning the fix. Our current-main run completed two scheduled dreaming sweeps and all six detached narrative writes without an empty-text fallback. The newer A/B evidence above also shows this PR still produces two no-text failures across ten fresh-workspace sweeps, so it does not fully close the race. Closing this PR; #87182 can remain the place for a deterministic fix if the failure is reproduced again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

5 participants