Skip to content

fix: preserve Claude CLI chat context across account switches - #168781

Merged
obviyus merged 2 commits into
mainfrom
fix/claude-cli-account-switch-note
Oct 11, 2026
Merged

obviyus merged 2 commits into
mainfrom
fix/claude-cli-account-switch-note

Conversation

@obviyus

@obviyus obviyus commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes loss of conversation continuity when an existing Claude CLI chat starts a fresh native session after an account change.

Related: #140294 and #168726.

User Impact

Account switches now keep continuity through on-demand history reading, including opaque native logins. The new session gets a metadata-only note; raw transcript replay and durable context remain blocked across accounts. No configuration or schema change is required.

Why This Change Was Made

Reuse the switch-back note renderer, inline prompt delivery, tool-policy-aware history hint, and importer stripping for fresh Claude sessions after auth-profile, auth-epoch, or auth-unknown invalidation. The note describes earlier recorded messages without including their contents. Subsequent native turns do not repeat it. Brand-new chats receive no note, and unavailable sessions_history tools are never advertised.

Evidence

  • Pinned origin/main (f28e5ba25b1) fails both memory/durable fresh-account regression cases: expected earlier-message note, received undefined (44 other tests passed).
  • Focused coverage includes account/profile/epoch and opaque-auth starts, no raw replay or durable context, count/time/model/session-key metadata, unavailable history tool, empty chat, next-turn omission, importer deduplication and routed-prompt provenance.
  • Final focused run: 104 tests passed across four files, 156.24s with pnpm exec vitest run … --maxWorkers=1 and OPENCLAW_RUN_NODE_SKIP_DTS_BUILD=1; formatting and git diff --check passed. Full CI on the implementation head passed in 7m51s. The subsequent docs-only review repair passed link checks (14,991 links, zero broken), docs formatting and git diff --check.
  • Real Claude CLI with keychain login, isolated Gateway and workspace: 2/2 account-switch loops called mcp__openclaw__sessions_history with the exact chat key and returned the original token. Account changes were simulated by changing only the saved native binding's prior auth-profile identity while the isolated Gateway was stopped, forcing the ordinary auth-invalidation path on restart.
  • No-switch control returned the original token with no note or history read. All three following turns had no note. Native stdin/stream-json and stored chat history confirm exactly two metadata-only notes, original stored user text and no duplicate recall rows.
  • ~/.claude/CLAUDE.md and settings*.json SHA-256 and mtimes unchanged. The one created native project directory was removed; no unexpected project directories were created.
  • pnpm build completed successfully. Its existing Control UI startup-size advisory was printed; this change does not touch UI assets.

Two-way door: reverting removes the metadata note behavior without a migration. Blast radius is Claude CLI conversation preparation and decoration matching; other runtimes and raw-history account boundaries are unchanged.

Inspected native proof excerpts (synthetic tokens only)

Native stdin for loop 1 (exact user-prompt text):

[OpenClaw: 2 earlier messages in this chat from 2026-10-11T01:02:58.479Z to 2026-10-11T01:03:05.904Z, using "claude-cli/claude-haiku-4-5". Their contents are not included here. Before answering a question that may depend on these messages, call mcp__openclaw__sessions_history({"sessionKey":"agent:main:account-switch-1","limit":100}) to read them; page older messages with offset if needed.]

What token did I give you? Reply with only that token. Do not guess.

Native stream-json tool call:

{"type":"tool_use","id":"toolu_01F5b3ZCq9mnqUYpXbTjQbzq","name":"mcp__openclaw__sessions_history","input":{"sessionKey":"agent:main:account-switch-1","limit":100},"caller":{"type":"direct"}}

The matching tool_result contains the earlier user message Remember token ALPHA1739. Reply ACK only. and assistant ACK under agent:main:account-switch-1. The final answer was ALPHA1739. Projecting the final chat.history response to user text gives exactly:

[
  "Remember token ALPHA1739. Reply ACK only.",
  "What token did I give you? Reply with only that token. Do not guess."
]

Loop 2 independently called the same tool with {"sessionKey":"agent:main:account-switch-2","limit":100}, received the earlier ALPHA2739 message and answered ALPHA2739. The no-switch control answered ALPHA3739 without calling history. All three next-turn prompts were Reply AFTER only. without an earlier-message note, and all three answered AFTER.

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: S labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR gives fresh Claude CLI sessions a metadata-only history notice after account changes and recognizes that notice during native-history imports.

Example: A chat remembers ALPHA1739, then an account change starts a fresh native Claude session.

  • Before: The replacement session receives neither earlier conversation content nor a notice explaining how to retrieve it.
  • After: The session receives an earlier-message notice and can retrieve ALPHA1739 through the permitted sessions_history tool.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused implementation with relevant shipped-path evidence, resolved prior feedback, no migration requirement, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Inspected native stdin, stream-json tool-call excerpts, reported matching results, and final chat rows exercise the changed CLI preparation and importer through a real Claude CLI and isolated Gateway after induced binding invalidation; controls cover no switch and subsequent turns, while actual vendor-account credential rotation is outside the demonstrated scenario.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A continuing chat loses usable conversation context when an account change forces Claude CLI to start a fresh native session.
Reason: The bounded change restores discovery of existing, permitted history without replaying private content automatically or introducing another capability surface.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: current main still lacks fresh-account history notices, the prior documentation finding is resolved, and no new actionable defect was found.

Priority: P2
Reviewed head: 0fab2715d7e6af5eef2a1c05f357010744a4c544

Before merge

None.

Findings

None.

Agent review details

How this fits together

CLI preparation reads the canonical conversation and admitted session identity, adds bounded metadata to the native prompt, and lets the existing history tool retrieve content; native-history imports correlate decorated prompts with original local rows.

flowchart TD
  A[Existing OpenClaw chat] --> B[CLI session preparation]
  C[Account invalidation] --> B
  B --> D[Metadata notice]
  D --> E[Fresh Claude CLI session]
  E --> F[Authorized history tool]
  F --> A
  E --> G[Native history correlation]
Loading

Technical review

Best possible solution:

Retain the shared metadata-notice and import-correlation implementation while preserving the existing automatic-replay boundary.

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

Current-main source establishes the missing fresh-account notice, and the contributor reports baseline failures for both memory and durable cases; this read-only review ran no target code.

Is this the best way to solve the issue?

The focused extension reuses the existing renderer, prompt delivery, tool-policy hint, and import-normalization owner while leaving raw replay and saved notes blocked.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 626eeac26d62.

Provenance checked

  • Fresh-session metadata eligibility and documentation changes intended behavior with a stated reason (93964e5: The preceding change deliberately limited notices to native resumes to preserve account isolation; this PR explains allowing metadata-only notices while retaining the content-replay prohibition.)
  • Automatic account-history recovery boundary keeps the original intent (e20b56c: Historical content must not acquire another account's authority through native-binding replacement or clearing.)
  • Native prompt correlation and routed provenance keeps the original intent (93964e5: Generated notices must not duplicate local user rows or conceal inter-session provenance; the shared normalization now recognizes both notice forms.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduced change: The introduced hunks extend the existing notice renderer and importer normalization without adding configuration, storage fields, dependencies, or a parallel history owner. (src/agents/cli-runner/session-history.ts:546, 0fab2715d7e6)
  • Current-main gap: Fetched main still requires an admitted native resume for metadata notices and returns early for authentication-profile and epoch invalidations, leaving fresh account sessions without this guidance. (src/agents/cli-runner/session-history.ts:541, 626eeac26d62)
  • Account-content boundary preserved: The changed path checks live admission before and after loading entries and still returns empty reseed messages and no durable context across authentication boundaries; the history-tool hint depends on the prepared tool set. (src/agents/cli-runner/session-history.ts:572, 0fab2715d7e6)
  • Previous finding resolved: The docs-only follow-up replaces the contradictory fresh-session exclusion with an explicit distinction between metadata notices and blocked automatic content replay. Public docs: docs/gateway/cli-backends.md. (docs/gateway/cli-backends.md:378, 0fab2715d7e6)
  • Inspected real-Claude evidence: The PR body supplies native stdin, a sessions_history call for agent:main:account-switch-1, the matching historical token and final answer ALPHA1739, and final chat rows without duplication. It reports a second successful loop, a no-switch control, and following turns without repeated notices. Account invalidation was induced through the saved binding while the isolated Gateway was stopped; an actual vendor-account login change was not exercised. (0fab2715d7e6)
  • History and ownership: Feature history identifies the existing resume-notice implementation, the independent account-history boundary, and substantial canonical transcript-reader work; these support routing to the listed contributors rather than relying only on the PR author. (src/agents/cli-runner/session-history.ts, 626eeac26d62)

Likely related people:

  • Ayaan Zaidi: Raw commit 93964e5 adds src/agents/cli-runner/session-history.ts:545 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 93964e5bd082; files: src/agents/cli-runner/session-history.ts)
  • Vito Cappello: Raw commit e20b56c adds src/agents/cli-runner/session-history.ts:413 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e20b56c0b26e; files: src/agents/cli-runner/session-history.ts)
  • Peter Steinberger: Raw commit dbd3bf7 adds src/agents/cli-runner/session-history.ts:347 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dbd3bf7da26b; files: src/agents/cli-runner/session-history.ts)

PR surface

Source +7, Tests +42, Docs +2. Total +51 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 21 14 +7
Tests 3 54 12 +42
Docs 1 3 1 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 78 27 +51

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The change repairs conversation continuity after Claude CLI account invalidation without expanding configuration or affecting other runtimes.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-11T01:15:04.786Z sha e94106c :: needs changes before merge. :: [P3] Update the existing history-boundary description

Reviewed October 10, 2026, 9:28 PM ET / October 11, 2026, 01:28 UTC (Revision 2).

@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Corrected the existing history-boundary paragraph to distinguish fresh-session metadata notices from blocked automatic replay. Added inspected native stdin, tool-call and final-history excerpts from the successful 2/2 real-Claude account-switch campaign to the PR body. Documentation link and formatting checks pass. @clawsweeper re-review

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@obviyus
obviyus merged commit c8a4e51 into main Oct 11, 2026
127 of 130 checks passed
@obviyus
obviyus deleted the fix/claude-cli-account-switch-note branch October 11, 2026 01:31
@obviyus

obviyus commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in c8a4e51. Switching Claude CLI accounts now keeps the conversation through on-demand history reading.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…aw#168781)

When a Claude CLI chat moved to a different account (for example after one account's quota ran out), the new account started a fresh native Claude session with no idea the chat had history. The openclaw#140294 boundary blocked all context, and keychain logins (the common setup) never got same-account recovery either. The fresh native session now gets a one-turn note with metadata only: how many earlier messages the chat has, when, and on which models, plus the exact mcp__openclaw__sessions_history call to read them under normal tool policy. Raw transcript content is still never replayed across accounts. The note reuses the switch-back renderer, inline delivery and importer stripping from openclaw#168726, and it is omitted when tool policy hides sessions_history. Real Claude CLI proof: 2/2 account-switch loops read history with the exact session key and answered the original token; the no-switch control got no note; following turns did not repeat it.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 14, 2026
…164175)

* fix(agents): carry isolated CLI completion turns into the next resume

- A preserved inter-session turn that runs outside the bound native CLI
  session reports its prompt and reply; the binding owner stores them on
  that binding, bounded like other context blocks, only when the auth
  identity matches.
- The next turn that resumes the bound session prepends them once as a
  marked context block; any completed turn in that session consumes them,
  and a fresh session recovers them from saved history instead.
- The completion turn's tool projection, MCP configuration, and loopback
  grant are unchanged.
- A real-seam regression covers continuity and denial; store guard,
  resume-context order, and chat-history dedupe tests cover the new
  binding field.
- The Claude CLI Gateway live announce probe now sends one more requester
  turn and checks Claude's transcript for the session it resumed.
- CLI backend and sub-agent tool policy docs describe the contract.

* fix(agents): replay carried CLI exchanges only under the history account boundary

- The resume renderer prepends pending completion exchanges only when the turn holds the CLI history writer, the authority that already gates saved-history recovery
- Settlement keeps no exchange for a binding without an auth epoch (opaque native login)
- Regression covers a named account (carried once), an opaque native login (nothing kept) and an identity-less login whose token is replaced (withheld and dropped)
- The live continuity probe expects the exchange only when the requester's history boundary is known
- Docs state the account requirement

* fix(agents): carry completion replies from the canonical transcript

- Drop the persisted unseenTurns binding field, its settlement
  (settlePreservedCliSessionTurn) and the cliUnseenTurn run meta; the
  native binding contract is back to main's
- Derive the carried context at resume time from the requester transcript:
  completion replies saved after the bound session's last ordinary Claude
  reply, recognized by their announce run id (announce:) or by a saved user
  row with completion provenance, newest 8, each bounded like context JSON
- Replay still requires the turn's CLI history writer; without it the
  session-gap note now counts those completion turns instead of treating
  the completion reply as the last turn the session saw
- Add isAnnounceIdempotencyKey next to buildAnnounceIdempotencyKey
- Regression harness mirrors the Gateway: completions run under the
  announce key and save no user row; credential replacement covers a named
  account as well as an identity-less login
- Move the transcript-derivation unit test to
  session-history.preserved-turns.test.ts (line cap)

* fix(agents): name carried completion turns as delivered events

- Label the carried block as completion events delivered in a separate
  session, each with the reply sent then, and give each record its
  source tool; with only a bare reply, installed Claude answered the
  next message as if no completion had arrived
- Read the transcript run id with asOptionalRecord
- Keep the preserved-turn check inside session-history; input-provenance
  is unchanged
- Publish the runtime config snapshot in the regression harness, as the
  sibling attempt tests do since #169714
- Pin the newest-8 bound in the preserved-turns test

* test(gateway): match the carried completion record in the live announce probe

The live CLI-backend announce probe searched the resumed Claude session's
user turns for the inter-session prompt envelope. A completion saved without
a user row renders a reply-only record, so the authorized branch failed even
when the resumed session received the result; when the handoff resumed the
bound session instead, the probe matched the handoff prompt itself.

Parse the marked context blocks of the follow-up turn and match the record's
source and reply. Whether the handoff resumed the bound session (prompt drift
only) or ran in its own session (an MCP hash change) is recorded, not
asserted: the follow-up turn owes the record either way.

* fix(agents): describe carried completions without naming where they ran

A completion handoff resumes the requester's bound Claude session when only
prompt content drifted, and runs in its own session when its MCP projection
hashes differently. The transcript does not record which one happened, yet
the carried-completion label told Claude the events arrived in a separate
session, and the session-gap note for a withheld login said they occurred
outside this session. Both were wrong in the resumed case.

Say what is known: the completion events were recorded in the conversation
since the session's last reply here, and the session may already hold some
of them. The gap note counts preserved turns with the same wording, and the
prompt-text stripper recognizes it like the existing notes. The account gate
and the bounded carry are unchanged.

* fix(agents): simplify resumed Claude completion context

Keep completion recovery in the canonical transcript owner, reuse bounded context rendering, and preserve account-authorized replay. Retain focused history, renderer, and import regressions; remove duplicate live proof scaffolding. Mark historical facts and preserve original user transcript text.

Co-authored-by: Mitchell Etzel <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Mitchell Etzel <[email protected]>
(cherry picked from commit d472fc5)

Backport note: semantic port onto 2026.10.5. The release line lacks the
Claude session-gap note (#168726/#168781), createCliCurrentPromptRenderer and
cli-session-history.prompt-text.ts, so this keeps only the completion carry:
session-history classifies Claude replies from the canonical transcript and
renders the newest 8 preserved/announce exchanges since the last ordinary reply
for a resumed claude-cli native session; prepare.ts prepends them (after any
drift note) only when the turn holds the CLI history writer, via the renamed
prependCliSessionResumeUserContext. Auth-boundary reasons already return before
the transcript read, so withheld turns carry nothing. Gap-note wording, its
stripper regex and their routed-prompt/dedupe test cases are dropped; docs say
withheld content is not replayed. Renderer tests target the release helper;
the preserved-turns test drops gap-note and admission assertions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant