Skip to content

refactor(agents): one deterministic context handoff for native and CLI switches - #202341

Draft
obviyus wants to merge 6 commits into
mainfrom
refactor/unified-context-handoff
Draft

obviyus wants to merge 6 commits into
mainfrom
refactor/unified-context-handoff

Conversation

@obviyus

@obviyus obviyus commented Nov 20, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Switching models mid-session hands history to the next runtime through three separate owners:

  • src/agents/harness/host-seed.ts seeded a fresh native thread (Codex) and could run an LLM compaction while seeding.
  • src/agents/cli-runner/session-history.ts reseeded a fresh CLI session by slicing the transcript text at a character budget (8% of the context window, 12–256 KiB), cutting messages in half.
  • The Codex plugin delivered resumed-thread deltas, but on the default (legacy) context engine both delta paths skipped when the host seed capability existed. Result: Codex → Gemini/Claude → Codex resumed the old Codex thread and silently dropped every turn the other model handled.

Solution

One owner: src/agents/harness/context-handoff.ts.

  • selectHandoff packs intact turns only (never slices a message, never calls a model). It keeps the compaction summary, the latest user and assistant turns and the first user turn (the original goal), then fills newest to oldest.
  • One fixed cap for every handoff: 16k tokens / 64 KB. This replaces the context-share CLI budget.
  • Turns that do not fit are named by messageId with a pointer to the existing sessions_history tool (only when that tool is available). No new tool.
  • bindHandoff replaces bindBoundedSeed for fresh native threads. Authority is checked once at start; the mid-seed LLM compaction and its re-checks are gone.
  • The bounded seed reader (session-context-seed.ts) owns the cut: it keeps the first user turn ahead of the newest suffix and returns the transcript entry ids of kept and omitted turns. Those are the ids sessions_history accepts. Its unread facts (omittedNonSummary, retainedInputTokens) are removed.
  • The notice is reserved at its real size. An allowance that cannot fit it delivers no history and logs native handoff allowance … cannot fit any history instead of failing the turn.
  • buildCliSessionHistoryPrompt renders the same selection into the existing <conversation_history> envelope (parseCliReseedPrompt still parses it).
  • Codex: a resumed thread on the default engine now receives the turns newer than its historyCoveredThrough through thread/inject_items, once, then acknowledges coverage on the binding.

Direct API ↔ direct API keeps full structured replay (sanitizeSessionHistory / transformMessages); this PR does not change it.

Impact

  • Production code: +386 / −486 (net −100). Tests: +263 / −528 (net −265).
  • Deleted: host-seed.ts (351) and host-seed.test.ts (516), the CLI char-slicing renderer and resolveAutoCliSessionReseedHistoryChars.
  • Behavior change: a CLI reseed whose compaction summary alone exceeds the cap now omits the summary whole (and says so) instead of truncating it mid-text.

Evidence

Unit / integration (exact head):

  • New Codex test injects only turns from another model when selected history resumes a Codex thread: red on base (expected … to contain 'GEMINI_DELTA_USER…'), green on head.
  • src/agents/harness/context-handoff.test.ts (5), Codex run-attempt.test.ts, history-seed, context-engine, prompt-continuity (172), CLI runner + cli-session-history suites (247 + 53 + 8): all pass.
  • pnpm tsgo:core, pnpm check:test-types, pnpm codex-app-server:validators:check, oxlint, oxfmt: clean.

Live E2E (isolated scratch Gateway from source, env -i, random port, real providers):

Leg A, default config, session sw2: 30 tool-heavy turns on google/gemini-3.5-flash, then Codex (openai/gpt-5.5, agentRuntime: codex), then Gemini, then Codex.

Turn Model Last-call input tokens Result
30 Gemini (full structured replay) 130,540 ok
31 Codex, fresh thread 24,868 GOAL_TOKEN aurora-7; DEPLOY_REGION QUARTZ-ZETA-41 ✅
32–33 Gemini ~2.4k + 129k cache picks ticket BLU-552, delimiter ;
34 Codex, same thread resumed 1,297 (+23,936 cached) Ticket BLU-552; CSV delimiter semicolon (;) ✅

The Codex rollout for turn 34 shows the same native thread id as turn 31 and one injected quoted_history_fragment (~1 KB) holding only the two Gemini exchanges. On base the unit test shows those turns are dropped.

Leg B, authored contextTokens: 400000 on openai/gpt-5.5 (selected-history seed path), fresh session sw5: 30 Gemini turns with ~9 KB tool outputs, then Codex on a fresh thread.

  • Seed: [OpenClaw context handoff] Included 13 intact turns; omitted 110 earlier turns. Newest omitted messageIds: 8a44e336-…, 345538db-…. Seeded turns: 1 (goal, pinned), 28, 29, 30.
  • The model pulled omitted turns with sessions_history({ sessionKey: "agent:main:sw5", messageId: "8a44e336-…", limit: 6 }) (4 messageId calls, then paging) and answered GOAL_TOKEN aurora-7; DEPLOY_REGION QUARTZ-ZETA-41 ✅. No compaction call.

Leg C, authored contextTokens: 60000 (Codex base fills the window), session sw6: 5 Gemini turns, then Codex.

  • Base on the same shape fails the turn: Native history allowance cannot fit its omission notice.
  • Head: the turn runs. Log: native handoff allowance (1 tokens) cannot fit any history; 20 turns stay in the session transcript. The model called sessions_history itself and answered SMALLCAP-5 ✅.

Known gaps

  1. Live claude-cli reseed not exercised. We ran a live switch from Gemini to claude-cli: 30 Gemini turns, then a session pinned with sessions.patch to anthropic/claude-sonnet-4-6@anthropic:manual, an api_key profile. A saved Anthropic API key is used only through an explicit session pin. auth.order and a bare model ref still fall back to native login, which fails with Not logged in. The Claude turn ran on the API key and answered GOAL_TOKEN aurora-7 | DEPLOY_REGION QUARTZ-ZETA-41. It got there by calling sessions_history twice. The first Claude prompt was 173 characters, with no <conversation_history> envelope, because the Gateway logged cli session history refused across auth boundary: reason=auth-unknown. That refusal comes from the existing transcript-ownership gate (fix: restore context when CLI recovery starts a fresh session #140294), which this PR does not change. The gate only reseeds history that earlier claude-cli runs wrote under the same account fingerprint. Turns written by another harness are classed as unknown, so any switch from Gemini or Codex into claude-cli is refused, whatever credential is used. This leg therefore proves that recovery through sessions_history works, but it does not prove the reseed envelope. The envelope is covered by prepare.test.ts, the reseed suites and context-handoff.test.ts.
  2. Deferred to the next PR per plan: collapsing native-session/* binding authority and the Codex binding assertCurrent chains.

…I switches

Replace the LLM-compacting native seed (host-seed.ts) and the CLI
char-slicing reseed with one owner, src/agents/harness/context-handoff.ts:
intact turns only; keeps the summary, first user goal and latest turns;
names omitted messageIds and points the model at sessions_history. One
fixed cap (16k tokens / 64 KB) replaces the context-share reseed budget.

Fix: on the default context engine, a resumed Codex thread dropped the
turns another model added meanwhile (Codex -> Gemini/Claude -> Codex).
It now injects only that delta through thread/inject_items.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 20, 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head eea7069ffb88d32dcae3b300ca902f58ae2f6914, but the PR head is now 23d0199c43470c5e4215c4118a4ab667e4fea63a. Its old verdict and PR readiness labels are no longer current.

Next step
Comment @clawsweeper re-review when the current head is ready; pushes after the first review are not reviewed automatically.

Review history (1 earlier review cycle)
  • reviewed 2026-11-20T08:21:58.847Z sha eea7069 :: needs changes before merge. :: [P2] Restore publication of the bounded-context warning | [P2] Keep the omission notice when no CLI history item fits | [P2] Reserve the actual omission-notice cost before packing | [P2] Select the original goal before cutting the native history suffix | [P2] Gate the native recovery hint on the enabled history tool

obviyus and others added 4 commits November 20, 2026 13:57
…doff seeds

The bounded seed reader now owns the cut: it keeps the first user turn ahead
of the newest suffix and returns the transcript entry ids of kept and omitted
turns, so the handoff notice lists ids sessions_history accepts. The notice is
reserved at its real size; an allowance that cannot fit it delivers no history
and logs a warning instead of failing the turn. Unread seed facts are removed.

Co-authored-by: obviyus <[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]>
@clawsweeper clawsweeper Bot removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 21, 2026

This branch has not been deployed

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

Labels

agents Agent runtime and tooling extensions: codex P2 Normal backlog priority with limited blast radius. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant