Skip to content

fix: restore context when CLI recovery starts a fresh session - #140294

Merged
VACInc merged 3 commits into
openclaw:mainfrom
VACInc:fix/cli-restart-history-reseed
Sep 6, 2026
Merged

VACInc merged 3 commits into
openclaw:mainfrom
VACInc:fix/cli-restart-history-reseed

Conversation

@VACInc

@VACInc VACInc commented Sep 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Related: #124991, #125002

Restores bounded conversation history and saved tool results when an eligible CLI session must start fresh, while keeping saved history isolated across authentication changes.

What Problem This Solves

Fixes an issue where users continuing an interrupted CLI conversation would lose saved task context and tool results when the native session could no longer resume. Recovery must also keep history from an earlier authentication account out of a replacement account.

Why This Change Was Made

The repair separates durable history ownership from native session continuity. It replays only independently recorded, continuously covered history for the selected credential, rather than trusting whichever native binding was stored most recently.

  • History authorization is independent of the replaceable native binding. Private session metadata records the selected account and the contiguous transcript generation/sequence coverage.
  • The actual admitted CLI runner carries a live history-writing capability through canonical user, assistant, and tool-result persistence. Turn finalization preserves metadata advanced by those appends.
  • Same-account recovery includes bounded raw or compacted history, saved tool-result text, and error markers. The already-admitted current user message is not repeated.
  • Account changes, unaccounted writes, imports, incompatible provenance, and unknown legacy history fail closed. Replacing or clearing a native binding cannot relabel historical content.
  • Fresh-history execution revalidates its read authority through deferred execution. Detached background work drops the parent’s history capability; it can persist its own results without borrowing a closed run’s proof.
  • Native bindings retain their existing native-only shape and clearing behavior. Public/plugin projections hide private provenance, same-session SDK round trips preserve it, and plugin extension slots cannot overwrite it.

User Impact

Known-account CLI conversations can recover saved requests and tool outcomes after losing their native handle without replaying another account’s history.

Persistence and upgrade contract

Vito (VACInc) directed this repair to preserve an independent history-account boundary and exclude other-account or unverifiable persisted history, including legacy state.

Automatic durable recovery requires a resolved static credential or a named OAuth account. Resolved SecretRef material is compared, not just its reference; named OAuth token rotation preserves the account boundary. Opaque CLI logins and identity-less OAuth do not establish verifiable durable-history ownership. Native resume remains governed by the backend’s existing rules. Explicit caller-owned in-memory input keeps its existing contract and cannot authorize access to a borrowed durable conversation.

Existing conversations are not backfilled from their latest native binding. Unknown or mixed history remains ineligible until a new session or genuinely empty reset establishes a fresh boundary; retained reset messages cannot be reassigned. The stored transcript is not deleted. This uses existing session-entry metadata and transcript counters, with no SQL schema/version, dependency, or configuration changes. Older binaries do not enforce this new security boundary; writes performed after a downgrade break coverage and fail closed after upgrading again.

Evidence

At original head 7b5ac5510cc5baa2e28003a36266837a093a0e0c, an isolated regression executed account A history → successful B replacement → native binding clear → B recovery. The initial B turn correctly omitted A’s canary; the later fresh B input contained it. The assertion failed on the actual prepared CLI execution input, not merely a reason code.

The repaired regression uses the real CLI runner, canonical user recorder, assistant persistence, binding settlement, and SQLite store. The allowed same-account control recovers the canary; the switched-account case does not. Additional coverage verifies A→B→A, raw/compacted history, empty starts, legacy/incompatible metadata, old-runtime write gaps, resolved SecretRef changes, named versus identity-less OAuth, revoked capabilities, detached background writes, and SDK round trips.

Validation runs use a task-owned, secretless direct AWS Crabbox with no instance role, no Tailscale, no Actions hydration, Node 24.19.0, and the repository-pinned pnpm 12.3.4. The initial focused run passed 274 tests plus core typechecking; the corrected boundary suite subsequently passed all 13 cases.

The expanded regression run passed 753 tests across 12 files, including the previously failing CI test owners, CLI reliability, SDK round trips, and accessor conformance. The full changed-file gate identified mechanical lint and fixture-type issues; those were corrected. Its final rerun progressed through the core and extension typechecks, but the AWS lease expired before a terminal result could be collected, so that rerun is not counted as passed. Fresh hosted CI on current head 1084b250e2ef736c616960613f7edb6f0fdc4ed5 is being followed to terminal completion.

A fresh independent autoreview of the complete staged candidate completed scoped-clean at P0–P2. Hosted checks and the current ClawSweeper review are reported on this PR’s current head; dispatch success is not treated as review clearance.

Hosted-CI follow-up

Hosted CI identified two test-only follow-ups: the SDK privacy assertions exceeded an existing test-file line limit, and four authority-race fixtures expected the old rejection message rather than the earlier fail-closed prepared-admission rejection. The SDK coverage now has a focused file covering single-entry and whole-store reads, mutation round trips, and injected-ownership refusal. The routing tests retain their empty-decision-work and no-dispatch assertions. All 34 affected tests and targeted repository lint passed in a fresh secretless AWS lease. After restoring the whole-store read assertion identified by independent review, all 30 SDK tests and targeted lint passed again. This follow-up does not change production code.

Proof limits

The execution-input boundary uses a synthetic CLI backend, not credentialed vendor inference. No live Gateway restart, live user conversation, external Claude/Codex process, deployment, or merge was performed. The proof does not recover tool results that were never persisted.

@clawsweeper

clawsweeper Bot commented Sep 6, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Sep 6, 2026
@clawsweeper clawsweeper Bot added 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. 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. labels Sep 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 4:16 PM ET / 20:16 UTC.

ClawSweeper review

What this changes

Restores bounded conversation history and saved tool results when CLI sessions start fresh, using independent account provenance to prevent cross-account replay.

Merge readiness

✅ Ready for maintainer review

The PR remains useful and has no remaining actionable findings. The earlier account-switch defect is addressed, and the documented, accepted legacy-history tradeoff does not require another approval or contributor action.

Priority: P1
Reviewed head: 1084b250e2ef736c616960613f7edb6f0fdc4ed5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A sound owner-level repair with focused production-boundary evidence and no remaining actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The captured Crabbox report and inspected production-path regression cover real CLI orchestration and SQLite persistence through account replacement, binding clear, and backend-input recovery: same-account history arrives and other-account history does not. Revocation and detached-write coverage supplement that boundary proof; the backend is synthetic and no vendor inference or live Gateway restart is claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured Crabbox report and inspected production-path regression cover real CLI orchestration and SQLite persistence through account replacement, binding clear, and backend-input recovery: same-account history arrives and other-account history does not. Revocation and detached-write coverage supplement that boundary proof; the backend is synthetic and no vendor inference or live Gateway restart is claimed.
Evidence reviewed 9 items Independent history ownership: History admission compares the selected credential fingerprint, transcript generation, contiguous sequence coverage, and active writer. Unknown or mixed history cannot acquire ownership from a replacement native binding; only proven-empty context can establish a fresh boundary.
Execution boundary and revocation: Fresh recovered prompts replace the execution assertion with the history owner's live read assertion. The production execution path propagates that assertion to plugin execution and process spawning. Closed admission invalidates retained history capabilities, and detached persistence drops the parent capability.
Prior finding covered at the backend input: The captured PR body reports a secretless Crabbox regression that failed at the original head and passed after repair. The inspected test runs the real CLI runner, canonical user recording, assistant persistence, binding settlement, and SQLite storage through account A → replacement → binding clear → recovery. The synthetic backend receives A's canary for the same-account control and does not receive it after switching accounts.
Findings None None.
Security None None.

How this fits together

OpenClaw's CLI runner sends agent requests to external CLI backends. When native session resume fails, it can reconstruct prior context from the canonical SQLite transcript before sending the current request.

flowchart TD
  A[Current request and selected account] --> B[CLI runner]
  C[SQLite transcript and account provenance] --> D{History belongs to selected account?}
  B --> D
  D -->|Yes| E[Bounded recovered context]
  D -->|No| F[Current request only]
  E --> G[Revalidate live authority]
  F --> G
  G --> H[CLI backend]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +405, Tests +668, Docs +10. Total +1083 across 23 files.

View PR surface stats
Area Files Added Removed Net
Source 16 417 12 +405
Tests 6 937 269 +668
Docs 1 11 1 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 23 1365 282 +1083

Review metrics

Metric Value Why it matters
Production versus regression coverage production net +405 lines; tests net +668 lines Production growth implements independently owned provenance and canonical-write fencing; regression coverage exercises account transitions, persistence, and SDK privacy.
Persistence surface 1 private session metadata field; 0 SQL schema or configuration changes The upgrade contract changes recovery eligibility without migrating or deleting transcript rows.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #124991
Summary: This PR is a candidate for the eligible binding-clear recovery portion of the reported problem; the older PR overlaps but remains unresolved.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Preserve the independent account boundary and canonical transcript recovery, including the accepted refusal to replay unverifiable legacy history.

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

Yes, source establishes the current-main binding-clear path: an uncompacted transcript has no eligible recovery reason after its native binding disappears. This review did not execute a current-main reproduction.

Is this the best way to solve the issue?

Yes. Independent transcript provenance fixes the replacement-and-clear failure at its owner, while canonical writes maintain coverage and execution revalidates authority; the stricter legacy behavior is explicitly accepted.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.

Label justifications:

  • P1: The repair addresses loss of conversation continuity after CLI resume failure while preserving account isolation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The captured Crabbox report and inspected production-path regression cover real CLI orchestration and SQLite persistence through account replacement, binding clear, and backend-input recovery: same-account history arrives and other-account history does not. Revocation and detached-write coverage supplement that boundary proof; the backend is synthetic and no vendor inference or live Gateway restart is claimed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Crabbox report and inspected production-path regression cover real CLI orchestration and SQLite persistence through account replacement, binding clear, and backend-input recovery: same-account history arrives and other-account history does not. Revocation and detached-write coverage supplement that boundary proof; the backend is synthetic and no vendor inference or live Gateway restart is claimed.

Evidence

What I checked:

  • Independent history ownership: History admission compares the selected credential fingerprint, transcript generation, contiguous sequence coverage, and active writer. Unknown or mixed history cannot acquire ownership from a replacement native binding; only proven-empty context can establish a fresh boundary. (src/agents/cli-runner/history-boundary.ts:87, 1084b250e2ef)
  • Execution boundary and revocation: Fresh recovered prompts replace the execution assertion with the history owner's live read assertion. The production execution path propagates that assertion to plugin execution and process spawning. Closed admission invalidates retained history capabilities, and detached persistence drops the parent capability. (src/agents/cli-runner/execute.ts:138, 1084b250e2ef)
  • Prior finding covered at the backend input: The captured PR body reports a secretless Crabbox regression that failed at the original head and passed after repair. The inspected test runs the real CLI runner, canonical user recording, assistant persistence, binding settlement, and SQLite storage through account A → replacement → binding clear → recovery. The synthetic backend receives A's canary for the same-account control and does not receive it after switching accounts. (src/agents/cli-runner/prepare.test.ts:5134, 1084b250e2ef)
  • Accepted persistence and upgrade contract: The supplied PR body records VACInc's direction to exclude other-account and unverifiable legacy history. Documentation explains that opaque logins and legacy conversations lose automatic recovery when native resume fails, transcripts remain intact, and downgrade writes invalidate coverage after re-upgrade. Fresh starts, legacy metadata, unaccounted writes, retained resets, and empty resets have focused coverage. These are recorded design choices, not outstanding approval requests. Public docs: docs/gateway/cli-backends.md. (docs/gateway/cli-backends.md:204, 1084b250e2ef)
  • Canonical persistence and SDK privacy: Transcript appends advance coverage within their transaction, and turn settlement rereads append-owned metadata before writing the session entry. Public SDK reads omit provenance; upsert, patch, and whole-store round trips preserve existing private provenance while refusing injected ownership. No parallel public SDK method or SQL schema change is introduced. (src/config/sessions/session-accessor.sqlite-transcript-turn.ts:256, 1084b250e2ef)
  • Current main and release still leave useful work: Inspected fetched main already loads canonical SQLite history, but its preparation still derives raw recovery eligibility only from a reusable session or invalidation reason, and its renderer omits tool results. The v2026.9.2 history source also retains the prior eligibility logic. The related SQLite-loader repair therefore does not make this PR redundant. (src/agents/cli-runner/session-history.ts:403, f3b41e04f92e)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • ruel225: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (3 earlier review cycles)
  • reviewed 2026-09-06T16:56:08.324Z sha 7b5ac55 :: needs real behavior proof before merge. :: [P1] Preserve the history auth boundary across replacement sessions
  • reviewed 2026-09-06T19:55:35.517Z sha 25fe661 :: blocked before merge. :: none
  • reviewed 2026-09-06T20:02:16.194Z sha 25fe661 :: blocked before merge. :: none

Keep transcript account ownership independent of native session bindings.
Track contiguous history coverage under the admitted CLI writer, preserve
append-owned metadata through turn settlement and SDK round trips, and
revalidate recovery reads before execution.

Fail closed for unknown, mixed, or unaccounted history without changing
the SQLite schema or native binding shape. Detach background work from
the parent history capability and retain bounded tool-result recovery.
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

Please review current head 25fe66132b966fef5b417a3b39c7f69246491d26. The PR description now records the reproduced account-switch/clear/recovery failure, independent history-boundary repair, 753-test regression evidence, and the approved persistence/upgrade direction. Hosted CI is running; no clean-CI claim is made yet. Review only—do not merge.

@clawsweeper

clawsweeper Bot commented Sep 6, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 6, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper explain

The fresh review for 25fe66132b966fef5b417a3b39c7f69246491d26 reports no actionable findings, no security concern, sufficient terminal proof, and an explicitly accepted upgrade contract, but still marks two compatibility risks as blocking. What concrete unresolved action or owner decision remains beyond the already-recorded fail-closed legacy/rollback direction? Please distinguish an accepted compatibility tradeoff from a missing approval or implementation defect. The two CI fixture/lint failures are being corrected separately. Do not merge or close the PR.

@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper status:

  • Current PR: 140294
  • Branch: fix/cli-restart-history-reseed
  • ClawSweeper PR: no
  • Automerge: not-enabled
  • Automerge job: jobs/openclaw/inbox/automerge-openclaw-openclaw-140294.md
  • Merge state: UNKNOWN
  • Checks: SKIPPED:38 SUCCESS:163 FAILURE:2 IN_PROGRESS:2 NEUTRAL:1
  • Check blockers: checks-node-compact-large-10:FAILURE, check-lint-core-1:FAILURE, check-lint-core-3:IN_PROGRESS, checks-windows-node-test-2:IN_PROGRESS

Move private history SDK checks into focused cases covering public reads,
mutation round trips, and injected-ownership refusal without exceeding
the existing test-file line limit.

Match the earlier prepared-admission rejection in routing race fixtures
while retaining the no-receipt and no-dispatch assertions.
@roboclaw-bot
roboclaw-bot requested a review from a team as a code owner September 6, 2026 20:09
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 6, 2026
@VACInc
VACInc enabled auto-merge (squash) September 6, 2026 21:01
obviyus added a commit that referenced this pull request Oct 11, 2026
When a chat switched back to Claude CLI after turns on other models, the resumed native Claude session had no idea those turns happened and answered from stale context. On an admitted resume of the same native session, OpenClaw now adds a one-turn note at the top of the native prompt: how many messages were missed, when, and on which models, plus the exact mcp__openclaw__sessions_history call to read them. No turn content is injected. Fresh native sessions, auth-profile or epoch changes, and reseeds get no note, which keeps the #140294 boundary. The native-history import strips the note so stored transcripts keep the user's original text without duplicate rows. Real Claude CLI proof: warm and Gateway-restart switch-backs both read history and answered from the other model's turn; the no-switch control got no note.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 11, 2026
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 #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 #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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…law#168726)

When a chat switched back to Claude CLI after turns on other models, the resumed native Claude session had no idea those turns happened and answered from stale context. On an admitted resume of the same native session, OpenClaw now adds a one-turn note at the top of the native prompt: how many messages were missed, when, and on which models, plus the exact mcp__openclaw__sessions_history call to read them. No turn content is injected. Fresh native sessions, auth-profile or epoch changes, and reseeds get no note, which keeps the openclaw#140294 boundary. The native-history import strips the note so stored transcripts keep the user's original text without duplicate rows. Real Claude CLI proof: warm and Gateway-restart switch-backs both read history and answered from the other model's turn; the no-switch control got no note.

Co-authored-by: Ayaan Zaidi <[email protected]>
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]>
obviyus added a commit that referenced this pull request Nov 20, 2026
…session (#202428)

## Problem

A fresh Claude CLI session only received a chat's saved history when OpenClaw could prove that every stored row was written by an earlier `claude-cli` run under the same account. Any row it could not attribute, such as turns written by Gemini or Codex, turns from a native Claude login without the attestation opt-in, legacy rows or imports, made the whole chat `auth-unknown` and refused for good.

As a result, switching an existing chat from another model to Claude dropped all context. The Gateway logged `cli session history refused across auth boundary: reason=auth-unknown`, and the new Claude session got only the current message. The rest of OpenClaw already replays the full conversation to Gemini, OpenAI and Codex on every switch without any such check.

The case #140294 actually guards against still matters: account A's history must not be replayed into a session for account B. Enforcing it took per-row coverage watermarks, a CLI history writer carried through every transcript write path, owner probes over `SharedArrayBuffer` in the SQLite workers, native-login rechecks at spawn, prompt send and prompt-hook time, refresh-due handling, a compaction coverage commit and a terminal write context. All of that existed only to keep the proof alive.

## Solution

The session now records the first identified CLI account that runs it. That is a fingerprint of a resolved API key or token, a named OAuth account, or an attested native login. The account is checked once, when a turn is prepared:

- **No account recorded yet:** history replays. This includes turns from other runtimes and from an unidentified login. The first identified account is recorded.
- **Same account as recorded:** history replays.
- **Different or unidentified account after one was recorded:** that turn runs without saved history and the session is marked `mixed`. Every later CLI turn in the session also runs without saved history, including a switch back to the original account. `/new` (a new session id) starts clean.

`admitCliHistoryAccount` is the single owner of this decision. Everything that existed only to keep the coverage proof alive is deleted: the writer async context, coverage advance in all worker and actor write paths, owner probes, the `cliHistory` patch guard, the compaction coverage commit, the native-login recheck hooks (`assertReadable`, `assertPrivateInputCurrent`, `bindExecutionEnv`, `settleNativeLogin`, the refresh-due handling), the node dispatch readable hook, and the CLI-only terminal write context (`bindAgentRunTerminalWriteContext`, `runInAgentRunWriteContext`, `clearAgentRunTerminalWriteContext`).

**Stored data:** no schema change. Existing `known` records keep their account fingerprint, which is derived the same way as before. Old `unknown` records mean "no proof", so they are treated as no account recorded. The new `mixed` state is never read as `known` by older binaries, so a downgrade fails closed.

**Accepted edge case:** if a chat runs on an unidentified login first and an identified account second, the unidentified turns replay to that account. These are the same session's own turns, and every other runtime already replays them.

## Impact

- Switching a chat from Gemini or Codex to `claude-cli` now carries its history into the fresh Claude session.
- Native Claude logins without the attestation opt-in now recover history in chats that no other identified account has run.
- An account change still keeps the earlier account's history out of the prompt. The transcript itself is untouched, and Claude can still read it through `sessions_history` when tool policy allows.
- Production code: **+455 −1,678 (net −1,223)**. Tests: net −2,102. Docs updated in `docs/gateway/cli-backends.md` and the anthropic plugin help text.

## Evidence

**Live E2E.** Each side ran on an isolated scratch Gateway with a real Gemini model and a real `claude-cli` (Claude Code 2.x) on an Anthropic API-key profile pinned with `sessions.patch` `anthropic/claude-sonnet-4-6@anthropic:manual`.

**Journey 1:** 10 Gemini turns that set `GOAL_TOKEN aurora-7` and `DEPLOY_REGION QUARTZ-ZETA-41`, then a switch to Claude asking for both values without using tools.

| | base `04d1dd10d05e` | head |
|---|---|---|
| Claude answer | `NOT_IN_CONTEXT` | `GOAL_TOKEN: aurora-7 \| DEPLOY_REGION: QUARTZ-ZETA-41` |
| first Claude prompt | current message only, refused (`auth-unknown`) | `<conversation_history>` envelope, 30,874 chars, both facts, no tool calls |

**Journey 2:** key A stores `SECRET_A`, then the session switches to a different key B, then back to A.

- **Base and head:** key B's fresh session received no history; head logged `refused ... auth-unknown`, and B's prompt was 95 characters with no `SECRET_A`.
- **Back on key A:** the run resumed A's own native Claude session, which already held the secret. Nothing was replayed.

**Tests:**
- New: `history-boundary.test.ts`, which covers other-runtime replay, the A→B→A no-laundering case, an unidentified login after a recorded account, `/new`, and named versus identity-less OAuth. Also `prepare-native-history.test.ts`, which covers an unidentified native login.
- Red on base: the other-runtime replay case was run against the base checkout and failed (no reseed prompt).
- Green: `tsgo:core`, `tsgo:extensions`, `check:test-types`, oxlint, oxfmt, the line-cap ratchet and `config:docs:check`. Touched directories pass under `ocx test`: `src/agents/cli-runner`, `src/config/sessions`, `src/agents/sessions`, `src/infra/outbound`, `extensions/anthropic`, `src/auto-reply/reply`, `src/agents/command`, plus the Gateway lifecycle and fallback transcript tests.

Related: #140294 (the original boundary), #202341 (unified context handoff; these changes are independent).

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…session (openclaw#202428)

## Problem

A fresh Claude CLI session only received a chat's saved history when OpenClaw could prove that every stored row was written by an earlier `claude-cli` run under the same account. Any row it could not attribute, such as turns written by Gemini or Codex, turns from a native Claude login without the attestation opt-in, legacy rows or imports, made the whole chat `auth-unknown` and refused for good.

As a result, switching an existing chat from another model to Claude dropped all context. The Gateway logged `cli session history refused across auth boundary: reason=auth-unknown`, and the new Claude session got only the current message. The rest of OpenClaw already replays the full conversation to Gemini, OpenAI and Codex on every switch without any such check.

The case openclaw#140294 actually guards against still matters: account A's history must not be replayed into a session for account B. Enforcing it took per-row coverage watermarks, a CLI history writer carried through every transcript write path, owner probes over `SharedArrayBuffer` in the SQLite workers, native-login rechecks at spawn, prompt send and prompt-hook time, refresh-due handling, a compaction coverage commit and a terminal write context. All of that existed only to keep the proof alive.

## Solution

The session now records the first identified CLI account that runs it. That is a fingerprint of a resolved API key or token, a named OAuth account, or an attested native login. The account is checked once, when a turn is prepared:

- **No account recorded yet:** history replays. This includes turns from other runtimes and from an unidentified login. The first identified account is recorded.
- **Same account as recorded:** history replays.
- **Different or unidentified account after one was recorded:** that turn runs without saved history and the session is marked `mixed`. Every later CLI turn in the session also runs without saved history, including a switch back to the original account. `/new` (a new session id) starts clean.

`admitCliHistoryAccount` is the single owner of this decision. Everything that existed only to keep the coverage proof alive is deleted: the writer async context, coverage advance in all worker and actor write paths, owner probes, the `cliHistory` patch guard, the compaction coverage commit, the native-login recheck hooks (`assertReadable`, `assertPrivateInputCurrent`, `bindExecutionEnv`, `settleNativeLogin`, the refresh-due handling), the node dispatch readable hook, and the CLI-only terminal write context (`bindAgentRunTerminalWriteContext`, `runInAgentRunWriteContext`, `clearAgentRunTerminalWriteContext`).

**Stored data:** no schema change. Existing `known` records keep their account fingerprint, which is derived the same way as before. Old `unknown` records mean "no proof", so they are treated as no account recorded. The new `mixed` state is never read as `known` by older binaries, so a downgrade fails closed.

**Accepted edge case:** if a chat runs on an unidentified login first and an identified account second, the unidentified turns replay to that account. These are the same session's own turns, and every other runtime already replays them.

## Impact

- Switching a chat from Gemini or Codex to `claude-cli` now carries its history into the fresh Claude session.
- Native Claude logins without the attestation opt-in now recover history in chats that no other identified account has run.
- An account change still keeps the earlier account's history out of the prompt. The transcript itself is untouched, and Claude can still read it through `sessions_history` when tool policy allows.
- Production code: **+455 −1,678 (net −1,223)**. Tests: net −2,102. Docs updated in `docs/gateway/cli-backends.md` and the anthropic plugin help text.

## Evidence

**Live E2E.** Each side ran on an isolated scratch Gateway with a real Gemini model and a real `claude-cli` (Claude Code 2.x) on an Anthropic API-key profile pinned with `sessions.patch` `anthropic/claude-sonnet-4-6@anthropic:manual`.

**Journey 1:** 10 Gemini turns that set `GOAL_TOKEN aurora-7` and `DEPLOY_REGION QUARTZ-ZETA-41`, then a switch to Claude asking for both values without using tools.

| | base `1740e1e9be50` | head |
|---|---|---|
| Claude answer | `NOT_IN_CONTEXT` | `GOAL_TOKEN: aurora-7 \| DEPLOY_REGION: QUARTZ-ZETA-41` |
| first Claude prompt | current message only, refused (`auth-unknown`) | `<conversation_history>` envelope, 30,874 chars, both facts, no tool calls |

**Journey 2:** key A stores `SECRET_A`, then the session switches to a different key B, then back to A.

- **Base and head:** key B's fresh session received no history; head logged `refused ... auth-unknown`, and B's prompt was 95 characters with no `SECRET_A`.
- **Back on key A:** the run resumed A's own native Claude session, which already held the secret. Nothing was replayed.

**Tests:**
- New: `history-boundary.test.ts`, which covers other-runtime replay, the A→B→A no-laundering case, an unidentified login after a recorded account, `/new`, and named versus identity-less OAuth. Also `prepare-native-history.test.ts`, which covers an unidentified native login.
- Red on base: the other-runtime replay case was run against the base checkout and failed (no reseed prompt).
- Green: `tsgo:core`, `tsgo:extensions`, `check:test-types`, oxlint, oxfmt, the line-cap ratchet and `config:docs:check`. Touched directories pass under `ocx test`: `src/agents/cli-runner`, `src/config/sessions`, `src/agents/sessions`, `src/infra/outbound`, `extensions/anthropic`, `src/auto-reply/reply`, `src/agents/command`, plus the Gateway lifecycle and fallback transcript tests.

Related: openclaw#140294 (the original boundary), openclaw#202341 (unified context handoff; these changes are independent).

Co-authored-by: Ayaan Zaidi <[email protected]>
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 maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

2 participants