Repository navigation
fix: restore context when CLI recovery starts a fresh session - #140294
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 6, 2026, 4:16 PM ET / 20:16 UTC. ClawSweeper reviewWhat this changesRestores 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 Review scores
Verification
How this fits togetherOpenClaw'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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +405, Tests +668, Docs +10. Total +1083 across 23 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
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.
|
@clawsweeper re-review Please review current head |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper explain The fresh review for |
|
🦞👀
|
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.
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]>
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]>
…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]>
…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]>
…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]>
…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]>
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.
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
1084b250e2ef736c616960613f7edb6f0fdc4ed5is 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.