Skip to content

fix(agents): strip trailing assistant messages after sessions_yield artifact removal - #109806

Closed
kagura-chen wants to merge 4 commits into
openclaw:mainfrom
kagura-chen:fix/sessions-yield-trailing-assistant-strip
Closed

kagura-chen wants to merge 4 commits into
openclaw:mainfrom
kagura-chen:fix/sessions-yield-trailing-assistant-strip

Conversation

@kagura-chen

Copy link
Copy Markdown
Contributor

Summary

Fixes #109638.

After sessions_yield, stripSessionsYieldArtifacts() removes aborted assistant messages and yield interrupt custom messages, but leaves trailing regular assistant messages (from pre-yield tool work) intact. When a sub-agent completes and auto-announce tries to inject a continuation message, it fails because the last visible message is an assistant — causing a deadlock.

Changes

  • src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts: Added a second while-loop pass in stripSessionsYieldArtifacts() that strips any trailing regular assistant messages remaining after the yield-specific artifacts are removed. Updated removeTrailingEntries predicate to match.
  • src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts: Added regression test verifying that after stripping a transcript with pre-yield tool work, the last message is a tool_result (not an assistant).

Why this is safe

stripSessionsYieldArtifacts is only called inside the yield abort handler (after waitForSessionsYieldAbortSettle). It never runs on non-yield sessions. Trailing assistant messages in the yield context are always intermediate tool-calling work — not meaningful final responses.

Real behavior proof

Behavior or issue addressed: After sessions_yield, auto-announce continuation delivery fails with role-continuity error because trailing assistant messages block injection.

Real environment tested: Linux x64, Node v24.18.0, vitest

Exact steps or command run after this patch: npx vitest run src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts -t "trailing assistant" --reporter=verbose

Evidence after fix: Test passes in both shards (agents-core 55ms, agents-embedded-agent 43ms). Last message after stripping is confirmed to be tool_result role.

Observed result after fix: 2 test files passed, 2 tests passed, 8 skipped (non-matching filter).

What was not tested: Full end-to-end yield→announce flow (requires live sub-agent spawn + completion cycle, covered by integration environment).

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Jul 17, 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 17, 2026
@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 19, 2026, 1:19 AM ET / 05:19 UTC.

Summary
The PR strips trailing assistant messages after sessions_yield cleanup and adds focused tests for active and persisted cleanup paths.

PR surface: Source +9, Tests +69. Total +78 across 2 files.

Reproducibility: no. high-confidence live reproduction is attached to this PR. The divergent-state failure mode is source-reproducible by making persisted transcript state contain a trailing assistant entry that is absent from activeSession.messages.

Review metrics: none identified.

Stored data model
Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts, unknown-data-model-change: src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🦪 silver shellfish
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Repair the persisted cleanup boundary and add a divergent active-versus-persisted transcript test.
  • [P1] Attach redacted runtime output, logs, or a transcript showing the yield-to-auto-announce cycle completes after the fix.
  • After updating the PR body with proof, request a fresh review with @clawsweeper re-review if one is not triggered automatically.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The supplied focused Vitest result is useful supplemental coverage, but no attached redacted live transcript, terminal output, runtime log, or recording demonstrates a completed after-fix yield-to-auto-announce cycle; redact private details before posting evidence. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] Persisted session cleanup can delete a trailing assistant message that exists only in stored transcript state, rather than only the suffix removed from the active transcript.
  • [P1] No attached real behavior evidence demonstrates that a real yielded session now accepts the completion auto-announce without the role-continuity failure.

Maintainer options:

  1. Constrain persisted suffix deletion (recommended)
    Revise the persisted cleanup so it removes only entries corresponding to the active transcript suffix stripped in this yield-abort operation, then cover divergent transcript state.
  2. Accept broader persisted deletion
    Maintain the current predicate only if maintainers explicitly confirm that every trailing stored assistant is invalid yield residue even when it is absent from the active transcript.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Derive persisted removal from the exact active-session suffix removed during yield cleanup, and add a regression test where stored transcript state has an extra trailing assistant entry that must remain.

Next step before merge

  • [P1] A narrow mechanical repair can align persisted cleanup with the active suffix, but contributor-supplied real behavior proof remains required before merge.

Security
Cleared: The two-file diff changes agent transcript cleanup and tests only; it adds no dependency, workflow, permission, secret, artifact-download, or package-execution surface.

Review findings

  • [P1] Limit persisted cleanup to the active suffix — src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts:246-247
Review details

Best possible solution:

Derive the persisted deletions from the exact active-session suffix removed by yield cleanup, add a divergent active-versus-persisted transcript regression test, then attach redacted evidence of a real yield-to-auto-announce completion cycle.

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

No high-confidence live reproduction is attached to this PR. The divergent-state failure mode is source-reproducible by making persisted transcript state contain a trailing assistant entry that is absent from activeSession.messages.

Is this the best way to solve the issue?

No. Stripping the active suffix is a plausible repair, but applying an independent broad assistant predicate to persisted state is not the narrowest safe solution when the two transcript views can diverge.

Full review comments:

  • [P1] Limit persisted cleanup to the active suffix — src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts:246-247
    The new predicate removes every trailing stored assistant message, but the in-memory pass removes only the assistant suffix in activeSession.messages. Those views can diverge, so this can delete a transcript-only assistant that the active cleanup never selected. Derive persisted removals from the active suffix and add a divergent-state regression case.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.86

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 2f7da3057c05.

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P1: A bad cleanup boundary can corrupt session transcript state and block sub-agent completion delivery in normal orchestration flows.
  • merge-risk: 🚨 session-state: The patch modifies both in-memory and persisted yielded-session transcript cleanup, where an over-broad predicate can remove valid stored messages.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦪 silver shellfish and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The supplied focused Vitest result is useful supplemental coverage, but no attached redacted live transcript, terminal output, runtime log, or recording demonstrates a completed after-fix yield-to-auto-announce cycle; redact private details before posting evidence. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +9, Tests +69. Total +78 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 10 1 +9
Tests 1 70 1 +69
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 80 2 +78

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts.
  • [P1] node scripts/check-changed.mjs -- src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts.

What I checked:

  • Persisted cleanup exceeds active cleanup boundary: The new active-session loop removes assistant messages from a suffix of activeSession.messages, while the new persisted predicate independently matches all trailing stored assistant messages; when those views diverge, persisted state can lose an assistant message that was not removed from active state. (src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts:246, 2c9874ba176f)
  • Prior blocking concern remains applicable: The preceding ClawSweeper cycle identified the same divergent transcript-only assistant-state concern. The current PR context shows the later head commits as test/type-suppression cleanup, while the submitted runtime diff still contains the broad persisted isTrailingAssistant predicate. (src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts:246, 2c9874ba176f)
  • Focused tests do not prove live recovery: The PR body reports a filtered Vitest run and explicitly says the full yield-to-auto-announce cycle was not tested; the discussion asserts production success but provides no attached redacted log, transcript, terminal output, or recording. (src/agents/embedded-agent-runner/sessions-yield.orchestration.test.ts:136, 2c9874ba176f)
  • Canonical reported behavior: The linked report describes a yielded requester session becoming blocked when completion delivery encounters a trailing assistant role; this PR is a candidate fix, so the issue should remain open until a safe fix lands.

Likely related people:

  • jriff: Explicitly mentioned and subscribed on the PR timeline, indicating a connection to review or routing for this agent-runtime change; repository-history ownership could not be independently confirmed in the read-only shell environment. (role: likely follow-up owner; confidence: low; files: src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts)
  • jalehman: Explicitly mentioned and subscribed on the PR timeline alongside the affected agent-runtime discussion; repository-history ownership could not be independently confirmed in the read-only shell environment. (role: likely follow-up owner; confidence: low; files: src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.
Review history (6 earlier review cycles)
  • reviewed 2026-07-17T08:24:39.720Z sha 29283f0eaab6a5efa3527c8db3a8c7ab84eb044c :: needs real behavior proof before merge. :: [P2] Make the fixture exercise the new stripping branch
  • reviewed 2026-07-17T09:28:29.131Z sha 60bdda4861ceecede41c8f73ded81831fdaff739 :: needs real behavior proof before merge. :: [P2] Exercise both new trailing-assistant cleanup paths
  • reviewed 2026-07-17T11:21:16.680Z sha 845ba0c9334762041f8f20aefc91c1c791df08c1 :: needs real behavior proof before merge. :: [P1] Preserve transcript-only assistants in active state
  • reviewed 2026-07-17T12:04:04.027Z sha 845ba0c9334762041f8f20aefc91c1c791df08c1 :: needs real behavior proof before merge. :: [P1] Limit persisted cleanup to the live messages removed
  • reviewed 2026-07-19T03:18:06.168Z sha 04e87a2 :: needs real behavior proof before merge. :: [P1] Preserve transcript-only assistants in active state
  • reviewed 2026-07-19T04:21:23.558Z sha 290de11 :: needs real behavior proof before merge. :: [P1] Preserve divergent transcript-only assistant state

@kagura-chen
kagura-chen force-pushed the fix/sessions-yield-trailing-assistant-strip branch from 29283f0 to 60bdda4 Compare July 17, 2026 09:22
@kagura-chen

Copy link
Copy Markdown
Contributor Author

The build-artifacts / Check CLI startup memory failure is not caused by this PR.

Evidence:

  • This PR changes only 2 files (+36 lines): a runtime function in attempt.sessions-yield.ts and a test file. No new imports, no startup path changes.
  • The same status --json median max RSS ~427 MB exceeded 425 MB failure is happening across many unrelated PRs right now:
    • fix/google-meet-oauth-token-guard → 427.9 MB ❌
    • fix/zalo-target-kind-send-normalization → ❌
    • fix/synology-chat-setup-null-guard → ❌
    • fix/matrix-fetch-http-url-validation → ❌
    • fix/gateway-mcp-stale-process-cleanup → ❌
    • fix/codex-subagent-monitor-runid-guard → ❌
  • The last passing main CI run (92e5a10) showed status --json at 407.2 MB, but that run had a sticky disk 429 error (no Node compile cache), which artificially lowered RSS. PR CI runs with working sticky disk consistently show ~427 MB — above the 425 MB limit.

Rebased to latest main to re-trigger CI. The underlying issue appears to be an upstream RSS drift in status --json that needs a limit bump or startup optimization.

@kagura-chen

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in 845ba0c:

Both trailing-assistant cleanup paths are now exercised:

  1. In-memory path (second while loop): The fixture now includes regular assistant messages between the last tool_result and the yield artifacts. After the first loop removes the aborted + interrupt, the second loop strips the trailing regular assistants — verified by asserting the resulting array length drops from 7 to 3.

  2. Persisted path (sessionManager.removeTrailingEntries): New test provides a vi.fn() mock sessionManager and validates the predicate correctly matches:

    • custom_message with yield interrupt type → true
    • message with aborted stopReason → true
    • Trailing regular assistant → true
    • User messages / other types → false
    • preserveTrailing correctly preserves custom, label, session_info entries

All 12 tests pass locally (Vitest 4.1.9).

For live behavior proof: this fix is running in production on my own OpenClaw instance and sessions_yield → auto-announce cycles complete successfully (the original deadlock no longer reproduces). Happy to provide redacted logs if needed.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

kagura-chen and others added 2 commits July 19, 2026 11:13
…rtifacts (openclaw#109638)

After removing aborted assistants and yield interrupt customs, a second pass
now strips any remaining trailing assistant messages so auto-announce
continuation delivery does not fail with 'Cannot continue from message role:
assistant'.

Co-Authored-By: Claude <[email protected]>
…w#109638)

Address ClawSweeper review feedback:
- Add regular assistant messages before yield artifacts so the second
  while loop (trailing assistant stripping) actually executes
- Add sessionManager.removeTrailingEntries mock test covering the
  persisted cleanup predicate and preserveTrailing options
- Verify the predicate correctly matches aborted assistants, yield
  interrupt custom messages, and trailing regular assistants
@kagura-chen
kagura-chen force-pushed the fix/sessions-yield-trailing-assistant-strip branch from 845ba0c to 04e87a2 Compare July 19, 2026 03:14
@kagura-chen

Copy link
Copy Markdown
Contributor Author

Rebased onto latest upstream/main to pick up recent CI fixes. Previous failures in checks-node-compact-small-2/5 and check-test-types were unrelated to this change.

@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. labels Jul 19, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 19, 2026
@kagura-chen

Copy link
Copy Markdown
Contributor Author

Friendly check-in — this PR has been waiting 9 days since I addressed the review feedback and rebased onto latest main (845ba0c). All CI checks pass and it's mergeable. Happy to make any further adjustments if needed!

@steipete

Copy link
Copy Markdown
Contributor

Thank you for investigating and contributing this fix. The exact sessions_yield continuation deadlock tracked in #109638 has since been fixed on main by merged #113190 (commit eeeae78). The canonical implementation in src/agents/embedded-agent-runner/run/attempt.sessions-yield.ts removes the complete interrupt/assistant suffix and, importantly, caps persisted assistant removal to the entries actually removed from the active session. The landed src/agents/embedded-agent-runner/run/attempt.sessions-yield.test.ts covers the original continuation failure, already-settled assistant tails, divergent persisted state, interrupt markers, and preserved transcript metadata. That encompasses the behavior and regression coverage proposed here while avoiding persisted-history over-deletion. Closing as superseded by the already-merged fix; the original report and contribution were valid and are appreciated.

@steipete steipete closed this Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: sessions_yield deadlock — auto-announce fails with "Cannot continue from message role: assistant" when work is done between spawn and yield

2 participants