Skip to content

fix(agents): restore saved history for fresh Claude CLI sessions on a native login - #164796

Merged
roboclaw-bot merged 18 commits into
openclaw:mainfrom
etzelm:fix/cli-native-history-owner
Oct 21, 2026
Merged

roboclaw-bot merged 18 commits into
openclaw:mainfrom
etzelm:fix/cli-native-history-owner

Conversation

@etzelm

@etzelm etzelm commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Related: #154716

Supersedes #156600 (builds on its account-fingerprint approach; its author is credited as co-author on the commits)

Note: #154716 carries the clawsweeper:needs-product-decision and clawsweeper:no-new-fix-pr labels and this PR does not fix the existing-session gap described under Gaps, so it uses Related: and should not auto-close the issue.

What Problem This Solves

Fixes: a Claude CLI conversation on a native Claude login loses its saved history whenever its Claude session is replaced or lost, because OpenClaw cannot name the login's owner and so refuses to replay it.

With the claude-cli backend on a native Claude CLI login and no OpenClaw-managed credential, the history boundary cannot build an owner fingerprint. prepareCliHistoryBoundary writes no cliHistoryBoundary, prepare.ts turns the missing writer into rawTranscriptReseedReason: "auth-unknown", and loadCliSessionPromptContext refuses to seed saved history into any fresh CLI session (replacement session, cleared binding, lost native transcript). On the base commit every native turn logs cli session history refused across auth boundary: reason=auth-unknown (scenario 1 below). On the author's own install (a file-backed native login) all 301 session entries carry an empty boundary.

The guard exists so saved history never crosses to a different account. This change keeps that property and adds the native login as an accepted owner only when the operator opts in (plugins.entries.anthropic.config.historyRecovery.attestNativeLogin: true), only when Anthropic attests which account its credential belongs to, and only for the environment the Claude process is actually started with. Without the opt-in, nothing changes: the native login has no owner and saved history stays refused, as on main.

User Impact

Nothing changes for an install that does not opt in. With plugins.entries.anthropic.config.historyRecovery.attestNativeLogin: true on a Gateway host whose Claude CLI login is a readable credential, a fresh Claude session for a conversation that started after the opt-in gets its saved history reseeded again, with or without the anthropic:claude-cli profile. If the login changes, is revoked, is selected differently by the child environment, or Anthropic does not attest it, saved history is refused, as the contract table below lists.

What an operator who opts in sees differently (without the opt-in, OpenClaw never reads the native token for history recovery and makes no profile request: row 35 below, 0 requests, the same prompt as current main):

  • The Gateway makes one GET https://api.anthropic.com/api/oauth/profile per access token it has not attested yet, with the token Claude CLI itself would send there (834 ms measured once on a real login). Later turns on the same token make no request. openclaw agent --local starts a new process per turn, so it makes one request per turn.
  • A turn prepared within ten minutes of its access token's expiry runs without saved history, because Claude CLI rotates the token before it accepts the prompt (measured below). The next turn is offered history again.
  • A turn whose writer may replay saved history fails with CLI history authority changed before execution if its login changes, or cannot be attested, between preparation and the prompt reaching Claude, instead of sending that history to another account. That is every turn of a conversation the native login owns, fresh or resumed, except a turn prepared within ten minutes of token expiry, which runs without saved history. Conversations the native login does not own are never refused because of it.

One new plugin config key, historyRecovery.attestNativeLogin in the Anthropic plugin's config schema, default false. No schema migration. Conversations that already have history and no recorded boundary stay fenced, including conversations written before the opt-in (see Gaps).

Why This Change Was Made

Main documents opaque CLI logins as unable to authorize replay (docs/gateway/cli-backends.md, "History account boundaries"). That is right when the login is only a profile name or a local record. It is wrong when the Gateway host holds a readable credential and Anthropic can say which account it belongs to. An acceptable owner has to cover the no-profile install (the bundled backend sets autoSelectAuthProfile: false), must be bound to the credential rather than to the .claude.json account record beside it, must be rechecked wherever saved history is sent to Claude or a turn becomes the owner's history, must survive Claude CLI's own token rotation, and must not put a network request or a subprocess on every transcript write.

The change in one sentence

Once the operator opts in, the native Claude login's owner is the account uuid Anthropic's OAuth profile endpoint returns for the exact access token the child Claude would use, attested asynchronously at preparation and after the run, and rechecked synchronously at every spawn, prompt send, prompt hook answer that carries the turn's private context, and coverage commit against an in-process attestation cache keyed by a per-process HMAC of the token.

Shape of the whole PR against base cab0df90f87 (seventeen commits, all signed): 23 production files +865/-143 (21 TypeScript files and the Anthropic plugin manifest), 12 test files +1785/-134, and three docs files (the contract paragraphs and the config baseline counts and hash); 38 files, +2658/-283 in total (two for the CI fix below). The attestation lives in provider-auth-claude-compat.ts (credential read, profile request, cache), cli-credentials.ts (the resolver seam), history-boundary.ts (async attestation, synchronous rechecks, background re-attestation, refresh window), execute.ts (one post-run settle call) and prepare.ts. The owner confirmation inside worker transactions is in the turn commit and transcript report paths in src/config/sessions and in the SessionManager metadata worker in src/agents/sessions. The check on the prompt hook answer is in extensions/anthropic/cli.runtime.ts. The opt-in is declared in extensions/anthropic/openclaw.plugin.json and read by isNativeCliLoginAttestationEnabled in cli-credentials.ts.

Simplification (08f918dca3a, on 13078e36c7e): one Keychain reader instead of two (the shipped reader returns the same results); no unused env and now parameters, dead cache delete, duplicate installation-target merge or report-worker target move; history-boundary.native-login-metadata.test.ts folded into history-boundary.native-login.test.ts, cli-history-owner-probe.test.ts cut to one case (deleted in the second pass), restated cases dropped; prepare-native-history.test.ts now releases its prepared backends (it leaked one session sharing read per case). Against 13078e36c7e: 14 files +240/-694 (production +41/-88, tests +199/-606).

Second pass (d688a94fc48): a native login lookup that throws (an unreadable config root) means "no owner" in one place, readNativeOwner, not only in the worker probe answer. So the host actor-memory check keeps such rows uncovered instead of failing the write, and a turn without saved history runs on; one with saved history is refused as before. cli-history-owner-probe.test.ts became one native-login case (RED11, RED12). Against 0f431092595: 5 files +37/-41.

Third pass (27ff3327776, 8d822e2632d): 75 production mutations found three unpinned paths: the host actor check on incognito sessions (a case in history-boundary.incognito.test.ts), interrupted inputs on a refresh-due turn, and a parseable Keychain item without a usable login. Six cases whose every caught mutation a kept case on the same path also catches are gone, and resolveCliChildEnv drops a baseEnv parameter no caller passed, so that extraction is a pure move. Against 5fffaf68380: 5 files +93/-75 (production +6/-6).

Design:

  • The attestation runs only when the operator opts in: plugins.entries.anthropic.config.historyRecovery.attestNativeLogin: true, declared in the Anthropic plugin's config schema with default false and a UI hint that names the endpoint the token goes to. prepareCliHistoryBoundary checks isNativeCliLoginAttestationEnabled(provider, params.config) before it resolves the native owner, so without the opt-in no credential is read for history recovery, no request is made and the turn is prepared exactly as on main (auth-unknown). The rechecks below exist only on writers whose owner was attested at preparation. The run's config is read per turn, so turning the opt-in off takes effect on the next turn.

  • attestClaudeNativeLoginOwner({ env }) (src/plugin-sdk/provider-auth-claude-compat.ts) reads the access token the CLI would use under env with the CLI's own precedence (Keychain first on macOS, bounded non-interactive lookups, tri-state so only security's item-not-found exit 44 lets .credentials.json stand; then the file). It sends that token, and nothing else, to https://api.anthropic.com/api/oauth/profile (Authorization: Bearer, redirect: "error", 3 s AbortSignal.timeout, the process global fetch, so the env-proxy dispatcher OpenClaw installs at startup applies). Claude CLI 2.1.283 calls the same URL with the same header (bundle excerpt below). The owner is uuid:<account.uuid> from the response. No owner on any failure: network error, timeout, non-2xx, a body without account.uuid, no credential, or an access token already expired. The error is dropped, not logged. The .claude.json account record is no longer read.

  • The cache maps HMAC-SHA256(key, token) to the attested owner, with key from randomBytes(32) per process, at most 64 entries, only in memory. A token belongs to one account for its whole life, so an entry can stop matching (rotation, logout) but never start naming someone else. Only successes are cached. Nothing about the token is persisted; the stored boundary keeps only the existing cli-history-v1 fingerprint over ["native-login", "uuid:<account>"].

  • readClaudeNativeLoginOwner({ env }) is the synchronous recheck: it rereads the credential and returns the cached owner for that exact token, or nothing. It never touches the network. The seam stays resolveNativeCliLoginOwner(backendId, env) (now asynchronous, returning { owner?, refreshDueAt? }) plus readAttestedNativeCliLoginOwner(backendId, env) for the synchronous checks; both return nothing for backends other than claude-cli.

  • Preparation awaits the attestation for the environment the child will start from (resolveCliChildEnv, under the run's skill env snapshot, as before). Spawn, prompt send and coverage commits call the synchronous recheck, so the per-turn Keychain budget stays at 10 lookups for a readable item.

  • Claude CLI rotates its access token itself, before it answers initialize and so before the prompt is sent, once the token is within 5 minutes of expiry (bundle: now + 300000 >= expiresAt; probe below). Two rules follow:

    • A turn prepared with a token that expires within 10 minutes runs without saved history (writer.replaysHistory === false; prepare.ts treats it like auth-unknown), and still covers its rows.
    • A boundary check on a turn without saved history that sees a token this process has not attested starts a background attestation of it. Coverage waits until it settles and stops for good if it names another account. A turn carrying saved history refuses an unattested token outright.
  • After the child exits and before the turn's rows commit, writer.settleNativeLogin() awaits any background attestation and, if the prepared token had entered the refresh window, attests whatever token the child left behind.

  • Worker coverage confirms the owner from inside the worker's write transaction. The host no longer decides before it dispatches the command. When coverage is about to advance, the worker puts a probe (a SharedArrayBuffer cell) on a transaction admission request (turn commits) or on the commit admission of the write (transcript reports). The host answers the cell with the live owner check, synchronously, right before it grants that admission, and the worker reads the answer after the grant. A missing answer, a missing owner check or a check that throws means the owner does not hold. On a mismatch the rows commit and coverage is not advanced. The check runs once per coverage commit, so the Keychain budget is unchanged. The in-process path checks inside its transaction as before.

  • A resumed Claude session also receives saved data: durable reference context from the transcript and the conversation's interrupted inputs. So any native turn whose writer replays history counts as carrying saved history at spawn and prompt send, fresh or resumed, including a conversation's first turn. A turn prepared inside the refresh window runs without saved history and receives no interrupted inputs either.

  • Claude asks for the turn's private context (interrupted inputs, durable reference context) through its UserPromptSubmit hook after it has received the prompt, so the hook answer is the last place that saved data leaves OpenClaw. The stdio transport writes each answer through a closure the Claude runtime returns, called synchronously at the final write. The host passes the bundled Claude runtime a host-internal assertPrivateInputCurrent (set only for a native-login writer, like the forwarded auth credential: it is not part of the plugin SDK CliBackendExecuteContext type, ClaudeCliExecuteContext in cli.runtime.ts declares it), which runs the turn's full assertCurrent (on a native login: reread the credential and require this process's attestation of that exact token for the same owner). The runtime calls it before it sends the prompt and again when it answers a UserPromptSubmit hook with additionalContext. If the second check fails, Claude receives an empty hook answer and the saved context is withheld. The public execution context is unchanged from main.

  • SessionManager appends committed by the metadata worker take the same host owner check. The probe rides on the command's one transaction admission and the host answers it before it grants. Coverage facts that ask for the check advance coverage only on a confirmed answer, so a write path that cannot ask keeps its rows and leaves coverage where it is. Writers whose owner cannot change during the run (a static credential or a named OAuth account) carry no owner check.

  • What a mismatch does depends on what is at stake, as before: a turn that may carry saved history is refused before Claude receives it; a change after the prompt was sent withholds the turn's private context from the prompt hook answer; that change, or one on a turn prepared inside the refresh window, lets the turn run, and its rows are kept but not covered, so coverage stops and the next turn is refused that history until /new or an empty reset.

docs/gateway/cli-backends.md states the contract: what is attested, the request and its timeout, fail-closed cases, what is held in memory and what is persisted, the synchronous rechecks, the refresh window, and the restart limitation.

What changed in the port onto current main

Base moved eight times by merges of main (port commit 5f246effb0c); latest: 53ff5be1f3b (79506514289), 57501c047f7 (051bf6fa4d0), 12b692d36b0 (cab0df90f87). Contract unchanged.

CI fix (9385a46b41d): test/gateway-openai-compaction-replay.e2e.test.ts (selected by this PR's changed files) fails on main since 07b59a0 (#177050): it persists internal retry prompts, and #136236 still appends the retained compaction instruction to the next invisible retry, so the model got it twice. Once its internal prompt is persisted, the retained copy is dropped (session-prompt-state.ts +4, one unit case +12). The e2e test fails 3/3 on main and on the previous head, passes 3/3 with the fix (bisect and runs). The seventh merge (57501c047f7): two conflicts with main's #178173, kept beside it; gates, RED1 to RED14 and harness rerun; check failures as on main.

The sixth merge (53ff5be1f3b): main's #177839 folded live-session-fingerprint.ts into createCliLiveSessionCapability in cli-live-session-registry.ts, so the warm-reuse nativeLoginOwnerHash field moves there unchanged (RED13).

Earlier merges (5fffaf68380, 0f431092595, 13078e36c7e, 9134c56b403) resolved import lists, cli-runtime.test.ts (main's rewrite absorbs the private-input tests) and generated baselines.

The first merge (5fa23ce27fc, 5f246effb0c): execute-process.ts is identical to main, which checks private history at send time itself (async assertReadable), so the native-login recheck stays in execute.ts and execute-plugin.ts; the metadata worker takes main's bindSqliteWorkerDatabase shape with the owner probe re-applied on top; history-boundary.test.ts uses history-boundary.test-support.ts on main's admission fixture.

What this PR decides, and why

The question is what may authorize native replay: the local account record beside a readable credential, or an identity bound to the credential itself. This PR binds the owner to the credential with Anthropic's own account lookup (option C below), and only for an operator who opts in. Every other install keeps D, main's behavior.

A: local account record B: claude auth status C: authenticated profile request (this PR) D: keep native replay fenced
Owner source .claude.json oauthAccount.accountUuid, read from the child's environment while a credential exists the same record, as the CLI reports it the account.uuid Anthropic returns for the exact access token the child would use none
Credential for account B beside a record for account A owned by A: history replayed to B's credential owned by A owned by B: A's history refused refused
Bound to the executing environment yes yes, if run with the child env yes: attested for the child env at preparation, rechecked at spawn, send and every coverage commit not applicable
Cost per turn 10 Keychain lookups (readable item) one subprocess per check, 135 to 1673 ms measured the same 10 lookups; one request per new access token (834 ms measured), none for a token already attested none
Token rotation by Claude CLI owner unchanged owner unchanged the rotated token is attested before the turn's rows are covered; a turn prepared inside the refresh window runs without saved history not applicable
What it sends where nothing nothing the access token, to the Anthropic endpoint Claude CLI itself sends it to nothing

Why C:

  • A and B cannot detect the mismatch. Run against synthetic files with the real Claude CLI 2.1.283, claude auth status --json reports a fake token as logged in and returns whatever account the record holds; editing the record moves the same credential from account A to account B (identity/claude-auth-status-probe.txt). The CLI's own refresh path never rewrites accountUuid or emailAddress (identity/cli-bundle-excerpt.txt).
  • Anything keyed on token material alone changes owner on every refresh: one real refresh rotated both the access and the refresh token while the account stayed the same (identity/refresh-rotation.txt). C keys the cache on the token but takes the owner from Anthropic, so a rotation needs one new attestation, not a new owner.
  • The profile request is the one Claude CLI makes itself. The bundle's AFe(e) is gt.get(`${BASE_API_URL}/api/oauth/profile`, {headers: {Authorization: `Bearer ${e}`, ...}, timeout: 1e4}), validated against {account: {uuid, email}, organization: {uuid}}. OpenClaw already sends Claude OAuth tokens to the same host for usage (src/infra/provider-usage.fetch.claude.ts, GET /api/oauth/usage).
  • D keeps native conversations losing history when their Claude session is replaced. It stays the default: C sends the token to Anthropic, so it runs only for an operator who sets historyRecovery.attestNativeLogin.

Contract table

Case Result
Native login, historyRecovery.attestNativeLogin unset or false (the default) no owner, no credential read and no request for history recovery, history refused: unchanged from main (row 35)
Opt-in removed after a covered turn no request; history refused; the stored boundary becomes unknown (row 36)
Opt-in set after a conversation already has rows those rows stay fenced; a conversation started after the opt-in recovers (row 37)
The cases below assume attestNativeLogin: true
Native login, no profile selected, credential attested owner named, history seeded into a fresh session
Native login with anthropic:claude-cli pinned same
Credential for account B beside the unchanged account-A record owner is B: A's history refused
Account record relabelled to B beside account A's credential owner is still A: history seeded
Login switched A to B between turns history refused
Credential removed between turns history refused
Profile endpoint times out (3 s), returns 401/5xx, or returns no account.uuid no owner, history refused; the turn runs
Access token already expired and not attested in this process no owner, no request made, history refused
Access token attested earlier in this process, now expired same owner
Access token within 10 minutes of expiry at preparation turn runs without saved history; the token Claude rotates to is attested after the run; rows covered; the next turn is seeded
Turn on a native login whose writer replays history (fresh or resumed Claude session, including the conversation's first turn); credential replaced or removed after preparation, before spawn or send step refused with CLI history authority changed before execution; nothing reaches Claude
Same turn; credential replaced or removed after the prompt is sent, before Claude's UserPromptSubmit hook is answered the hook answer carries no private context; the turn runs; rows kept, coverage stops; the next turn is refused history (rows 33, 34)
Turn prepared within 10 minutes of token expiry (runs without saved history); credential replaced by an unattested token before send turn runs; the token is attested in the background; rows covered only if it is the same account
Credential rotated to another account's token during a turn, then switched back coverage stops for the run
Credential replaced during an awaited worker commit preparation rows recorded; coverage not advanced
Credential reassigned to another account while the coverage command is queued for the SQLite worker (turn commit or transcript report) rows recorded; coverage not advanced; the next turn is refused history (scenario 22)
SessionManager append committed by the metadata worker while the login holds row recorded and covered
The same append after the login is replaced by an unattested credential row recorded; coverage not advanced
Same-account token rotated after send, outside the refresh window rows recorded; coverage not advanced; next turn refused history
Skill env config selects another config dir, on every turn that login's attested account is the owner; history recovered
Skill env config selecting another login is added mid-conversation that turn is a login switch: history refused, the turn runs
Backend env selects another config dir than the Gateway process owner is the one in the child's environment
Child environment, or its user settings env block, selects an API key, token or cloud provider no owner, history refused, no request made
Relative CLAUDE_CONFIG_DIR, split credential roots, apiKeyHelper no owner, no request made
macOS Keychain item exists but is unreadable, or both lookups fail, stale .credentials.json beside it no owner, no request made
Keychain item confirmed absent (security exit 44), .credentials.json present the file is the credential
Readable Keychain login, one turn 10 security lookups (base: none)
Plan upgrade, or token rotation for the same account same owner, still seeded
Forwarded credential (api key, token, named OAuth) credential decides the owner, native login not consulted, no request made
Node-placed Claude CLI host login not used
Backend other than claude-cli no native owner, no request made
Warm Claude child started under a different native owner not reused
Session with existing history and no stored boundary, including history written by v2026.10.4 unchanged: stays unknown, rows kept (scenario 27)

Evidence

All of the following in this section, up to "Earlier captures", ran on one machine (a Mac Studio) at commit c8e525c2f12, whose tree 934c1340971d65c3c7717818c3a97daacdb5e5c5 is the pre-merge head 8d822e2632d (the signed commit of the same tree, gates/identity.txt), base 372095136ef. Every build, lane, check, red/green run and harness scenario in this section ran at that tree (the mutation matrix at e72e9e9a14c, the parameter removal aside); the records labelled before 05501c8a ran the built previous head 05501c8acd9 with the same harness. Rows 38 and 39 ran a build of 95a27d0779d; the main-alone checks ran a checkout of 372095136ef. Every scenario sets attestNativeLogin: true except rows 35 to 39. Captures for this head: head-8d822e26/; the harness as run is in its harness/scripts/ (head-5fd72055/ plus the queued-switch shim and outcomes2.sh). Paths in them are redacted to $RUN, $TREE, $BASE and $HOME.

Build

pnpm build at the tested tree (pnpm build EXIT 0, gates/summary.txt) and, as for the previous head, at base 95a27d0779d (BUILDEXIT 0) (build-final.log, build-base.log). The tested tree's build summary (total and slowest phase; full line in build-final.log):

[build-all] phase timings: total 2m 31.9s; slowest write-unified-entry-dts 56.6s

The scenario harness ran against the tested-tree build, and the base arms against the base build.

Real built binary

The real openclaw agent --local (built dist), a real SQLite session and worker threads, synthetic login files on disk, the real Anthropic Claude runtime and stream-json transport. The claude executable is a synthetic child (harness/bin/claude) that speaks the control protocol and records every record that reaches it, with the account named by the login's .claude.json record (loginAccount) and by its credential (credentialAccount) at that instant. It can rewrite the login at chosen moments: FAKE_ON_INIT after it initializes and before the prompt is sent, FAKE_ON_USER after it receives the prompt. It answers OpenClaw's UserPromptSubmit hook before each prompt and records the context that comes back (interrupted inputs, durable reference context; .context-* files). By default it writes no Claude project transcript, so every later turn enters the fresh-session reseed branch; with FAKE_WRITE_TRANSCRIPT=1 (scenarios 23 to 26) it writes one under the session id OpenClaw passed, so later turns resume. Each turn is a new process.

The Anthropic profile endpoint is a local STUB (harness/profile-stub.mjs), reached through a preload that redirects only that one URL (harness/shim/profile-fetch-shim.mjs). Synthetic tokens synthetic-<account> attest to <account>, and the stub can answer 401 or hold the request open. Production code is unchanged and always calls the real URL. Scenarios 10 to 13 also shim the Keychain at the child_process.execSync seam (harness/shim/security-shim.mjs); the others use the real security binary, which finds no item and exits 44.

harness/run-all.sh <tree> after          # scenarios 1 to 13 and 15 to 26
harness/run-all.sh <tree> after optout-allowed optin-withdrawn optin-later    # rows 35 to 37
HARNESS_ATTEST=0 harness/scenario.sh <base tree> base allowed    # row 38 (and resumed-allowed, row 39)
harness/scenario2.sh <tree> after skill-config-dir-added    # scenario 14
UPGRADE_FROM=<v2026.10.4 install> harness/scenario.sh <tree> after upgrade    # scenario 27
harness/gateway-probe.sh <tree> after <scenario>    # scenarios 28 to 31, 33, 34

Per turn: the characters of the user message the child received and whether that child was spawned fresh or resumed, from the synthetic child's own records (harness/outcomes2.sh: main's 447128e3a84 removed the cli exec: log line whose promptChars, historyPrompt and useResume fields the earlier tables read; the saved-history prompt now shows as the message size, 449 characters without it on turn 2, 516 and up with it). The UserPromptSubmit context of every delivered prompt is in the same file, with its own canary counts; refused is CLI history authority changed before execution, exit 1, with no user message delivered (still read from the OpenClaw log). PINEAPPLE-7 is the turn-1 canary. Boundary is the stored cliHistoryBoundary after the last turn. One line per scenario, every turn: outcomes-after.txt and outcomes-base.txt. Every row, the upgrade rows included, matches the previous head's captures (outcomes-after.txt at 5fffaf68) except, in the six Gateway-interrupt rows, turn 2's client exit code (1 or 143, the known race) and context sizes 9 bytes lower: those contexts name the run workspace, whose path is 9 characters shorter in this run (compare.txt).

# Scenario (turn 1 under account A) Pushed head
1 Same login, fresh Claude session turn 2: 516 chars with PINEAPPLE-7; boundary known seq 4
2 Login rewritten to account B turn 2: 449 chars, no canary (auth-unknown); boundary unknown
3 Credential removed 449, no canary, no profile request for turn 2
4 Turn 2 may carry history; login reassigned to B at initialize refused
5 Same, credential removed at initialize refused
6 First turn, login reassigned to B before send; then back to A turn 1 refused; turn 2 back on A: 467 chars with turn 1's own message
7 Login reassigned to B after delivery, before commit; then back to A turn 3: 451, no canary; boundary unknown
8 Skill env selects another login on turn 1 only 449, no canary
9 Same skill env on both turns 516 with PINEAPPLE-7
10 Keychain readable 516 with PINEAPPLE-7
11 Both Keychain lookups time out, stale file on disk 449, no canary, no profile request
12 Keychain fails at initialize, turn may carry history refused
13 Keychain fails after delivery, before commit turn 3: 451, no canary; boundary unknown
14 Skill env selecting another login added from turn 3 turn 2: 516 with PINEAPPLE-7; turns 3, 4: 449, no canary
15 Credential for account B beside the unchanged account-A record 449, no canary (auth-unknown); boundary unknown
16 Record relabelled to B beside account A's credential 516 with PINEAPPLE-7
17 Profile endpoint holds the request open 449, no canary: no owner after the 3 s timeout; the turn runs
18 Profile endpoint answers 401 449, no canary
19 Token rotated elsewhere and already expired 449, no canary; no profile request for that token
20 Token expires in 2 min; the child rotates it at initialize turn 2: 484, no history, covered; turn 3: 655 with PINEAPPLE-7 and BANANA-3; boundary known seq 6
21 Token valid for hours; the child rotates it after delivery turn 3: 451, no canary; boundary unknown (Gaps)
22 Login reassigned to B while turn 2's coverage commit is queued for the SQLite worker turn 3: 451, no canary; rows kept, coverage stopped at seq 3, then unknown
23 Resumed Claude session, same login (resumed on turns 2 and 3) turns 2, 3 run; boundary known seq 6
24 Resumed session; login reassigned to B at initialize of turn 2 turn 2 refused, nothing delivered; turn 3 back on A resumes; boundary known seq 5
25 Resumed session; credential removed at initialize of turn 2 turn 2 refused; turn 3 resumes; boundary known seq 5
26 Resumed session; login reassigned to B after delivery, before commit turn 3 back on A: boundary unknown
28 A Gateway turn 2 left unfinished; turn 3 resumes the Claude session on the same login turn 3 receives the interrupted input MANGO-5 in its context ("Saved context on a resumed Claude session")
29 Same, with the native transcript removed before turn 3 fresh session: 529 chars with PINEAPPLE-7, context with MANGO-5
30 Same as 28; login reassigned to B at initialize of turn 3 turn 3 refused, no prompt and no context delivered; turn 4 back on A receives MANGO-5
31 Same as 28; credential removed at initialize of turn 3 turn 3 refused; turn 4 receives MANGO-5
32 A local plugin appends a saved note through the plugin SDK at llm_output of turn 1 note row kept and not covered; turn 2 refused history (auth-unknown), boundary unknown (see "SessionManager appends")
33 Same as 28; login reassigned to B after turn 3's prompt is sent, before Claude's UserPromptSubmit hook is answered turn 3 runs; its hook answer carries no context (0 bytes, no MANGO-5); turn 4 back on A is refused history; boundary unknown
34 Same as 33, credential removed instead turn 3 runs; hook answer 0 bytes; turn 4 refused history; boundary unknown
35 attestNativeLogin not set; same login, fresh Claude session turn 2: 449 chars, no canary (auth-unknown), context 1145 bytes; no boundary stored; 0 profile requests
36 Opt-in set for turn 1, removed before turn 2 (fresh session) turn 1 covered (known seq 2), 1 profile request; turn 2: 449, no canary, no request; boundary unknown
37 Turn 1 without the opt-in; opt-in set before turn 2; turns 3 and 4 in a new conversation turn 2: 449, no canary (turn 1's rows have no recorded owner); turn 4: 510 chars with MANGO-5; new conversation's boundary known seq 4
38 Main 95a27d0779d, row 1's turns turn 2: 449, no canary (auth-unknown), context 1145 bytes; no boundary stored; 0 profile requests
39 Resumed Claude session (row 23's turns) without the opt-in, on current main base 95a27d0779d: turns 2 and 3 resume the Claude session with 83 and 50 characters (no saved-history prompt), context 1145 bytes on every turn; no boundary; 0 profile requests. Same at the pushed-head tree (outcomes-optout.txt)

What the rows show:

  • Rows 35 and 38: without the opt-in, the pushed head makes no profile request and prepares the same 449-character prompt without history and the same 1145-byte context as current main. Row 36: removing the opt-in stops recovery on the next turn. Row 37: rows written before the opt-in stay fenced, and a conversation started after it recovers.
  • Row 15: a credential for account B beside the unchanged account-A record is refused A's history. The owner follows the credential (row 16) and fails closed on every endpoint failure (rows 17 to 19).
  • Row 20: Claude's own rotation inside the refresh window keeps the conversation recoverable. Row 21 is the stated limitation for a rotation outside that window.
  • Rows 4, 5, 12 and 24, 25: a turn on a login whose writer may replay history is refused before the prompt reaches Claude when its credential is replaced or removed during launch, for a fresh and for a resumed Claude session.
  • Row 6: the same rule applies to a conversation's first turn. That turn is refused, not run, when its login changes during launch.
  • Rows 22 and 26: rows written after the login moved stay in the transcript and are not covered, so the next turn on account A is refused that history.

Whole records: runs/after-<scenario>/ in the evidence folder, for example row 15 record-credential-mismatch, row 24 resumed-reassign-before-send and row 33 interrupted-reassign-before-context.

Saved context on a resumed Claude session (rows 28 to 31)

harness/gateway-probe.sh, same login files, synthetic child and profile STUB. Turn 1 runs with openclaw agent --local. For turn 2 the harness starts the real built Gateway (openclaw gateway run) on the same state dir, sends the turn through it, and kills the Gateway (kill -9) while the STUB holds turn 2's attestation request, before the user message is written. The staged input is left unfinished and the next reader marks it interrupted. Turns 3 and 4 run with openclaw agent --local on the same conversation. In rows 28, 30 and 31 the child writes a native transcript, so turn 3 resumes the Claude session (spawned with --resume); in row 29 the transcript is removed first, so turn 3 starts a fresh session.

# Turn 3 Pushed head
28 resumed session, same login 61 chars, resumed; context 1800 bytes with ## Interrupted inputs and MANGO-5; boundary known seq 4
29 fresh session (native transcript removed), same login 529 chars with PINEAPPLE-7; context 1798 bytes with MANGO-5
30 resumed session; login reassigned to B at initialize refused: no prompt and no context delivered. Turn 4 back on A: context with MANGO-5; the input is still interrupted and unconsumed
31 resumed session; credential removed at initialize refused. Turn 4 with the credential back: context with MANGO-5

Whole records: interrupted-allowed and interrupted-reassign-before-send (rows 28 and 30), with fake-claude.log and the .context-* files beside them. In row 28 turn 3's context contains the ## Interrupted inputs section with MANGO-5 and the stored input stays interrupted; in row 30 the refused turn 3 delivers no prompt and no context, and turn 4 on account A receives the input.

On 5d840900899 without this change the turn context has no ## Interrupted inputs header at all (no history writer); it has no attestation to hold, so its turn 2 completes and consumes the input: not a like-for-like BEFORE.

Login changed after the prompt is sent, before its context (rows 33, 34)

Same Gateway kill as row 28, so turn 3 resumes the Claude session with the interrupted input MANGO-5 staged for its context. The synthetic child runs FAKE_BEFORE_CONTEXT after it has received turn 3's prompt and before it sends its UserPromptSubmit hook request: row 33 reassigns the login to account B, row 34 removes the credential. Turn 4 runs on account A again.

# Turn 3 hook answer 05501c8acd9 Pushed head
33 login reassigned to B 1419 bytes with ## Interrupted inputs and MANGO-5, received under account B 0 bytes
34 credential removed 1419 bytes with MANGO-5, received with no credential present 0 bytes

In both arms turn 3 runs, its rows are kept, coverage stops at seq 3, turn 4 on account A is refused history (61-character prompt without saved history, context without the interrupted section) and the input stays interrupted and unconsumed.

Whole records: row 33 AFTER turns.log (turn 3 hook answer 0 bytes in outcomes-after.txt), row 34 turns.log. The BEFORE records at 05501c8acd9 are rec-before-ctx and rec-before-ctx-revoke (not rerun).

extensions/anthropic/cli-runtime.test.ts pins the same rule in the runtime: withholds private turn context when the private-input check fails after the prompt was sent (RED4 below).

Upgrade from v2026.10.4

Scenario 27 ran at the tested tree 934c1340971 on base 372095136ef from [email protected] and from the latest stable, [email protected], with identical rows (rec-upgrade-1005.txt, rec-upgrade.txt, release-install.log, whole run turns.log). Turns 1 and 2 run the released [email protected] (npm install in a scratch directory) on a fresh state dir; the candidate then runs openclaw doctor --fix --non-interactive (exit 0) on the same state dir. Turn 3 runs the candidate in the same conversation; turns 4 and 5 start a new conversation.

  • Transcript rows written by 2026.10.4 load and are kept. The released package refuses saved history on its own turn 2 (reason=auth-unknown, 48-character prompt).
  • History written by 2026.10.4 has no recorded boundary, so the candidate does not adopt it: turn 3 is refused history (reason=auth-unknown), the turn runs, and the stored boundary stays absent.
  • A conversation started on the candidate gets a boundary on its first turn and recovers its history in a fresh Claude session (turn 5, MANGO-5; boundary known seq 4).
  • The released schema has no historyRecovery key, so the harness sets attestNativeLogin: true only after doctor --fix.

SessionManager appends in the metadata worker

The CLI runner does not reach this path. Row 32 records, with the queued-command preload in log-only mode, every command a native openclaw agent --local turn posts to the SQLite workers: there is no session.metadata.append and no session.transcript.appendMessage, the two commands the metadata worker handles. The turn's rows commit through session.turn.commit, which takes the owner check on its transaction admission (rows 7, 22, 26). A local plugin note appended through the plugin SDK at llm_output goes through session.transcript.lock.*, which carries no history-writer facts, here or on main. That row is kept and not covered, and the next turn is refused history (auth-unknown, boundary unknown). That is the existing rule for unaccounted rows, not a native-login rule.

The case covers a SessionManager append only while the native login owner holds in history-boundary.native-login.test.ts therefore exercises the metadata worker on the real worker thread and SQLite, with real login files and a stubbed fetch: SessionManager.appendMessageAsync under account A (covered), then the login rewritten to an unattested account-B credential and a second append (row kept, coverage not advanced).

Red and green

Each mutation applied alone to production code, the owning test file run (must fail), the file restored, the same run repeated (must pass), checkout clean (redgreen.log, script redgreen.sh). All eleven rerun at this tree; RED1 to RED5 are unchanged from the previous head (redgreen.log at 5f246eff). RED1 and RED2 fail one case in history-boundary.native-login.test.ts; RED7 to RED12 (this head's log) cover the split-root guard, the auth env list, the request's timeout signal, a fresh recovery turn and a login lookup that throws (RED11 drops its catch; RED12 catches it only at the coverage check, so the boundary throws the raw error). RED6 left with the probe test.

# Mutation Failing assertion (mutated) Restored
RED1 host sends SessionManager writer facts without the owner-check request history-boundary.native-login.test.ts > covers a SessionManager append only while the native login owner holds: AssertionError: expected 2 to be 1 Tests 22 passed (22)
RED2 metadata host never answers the owner probe same case: AssertionError: expected 0 to be greater than 0 Tests 22 passed (22)
RED3 execute.ts back to "only a fresh recovery prompt is strict" execute.native-history-owner.test.ts > spawns nothing for a resumed turn that replays history under another login: promise resolved "{ text: 'done', ...(5) }" instead of rejecting Tests 4 passed (4)
RED4 UserPromptSubmit answer goes out on the stream check alone extensions/anthropic/cli-runtime.test.ts > withholds private turn context when the private-input check fails after the prompt was sent: AssertionError: expected 'saved private context' to be undefined Tests 53 passed (53)
RED5 native login attested without the operator opt-in prepare-native-history.test.ts > never sends the native token to Anthropic unless the operator opted in: AssertionError: expected { ...(12) } to be undefined Tests 3 passed (3)

Unmutated run of the owning files: Test Files 3 passed (3), Tests 29 passed (29) (22 + 4 + 3, the cli-runner files) and Test Files 1 passed (1), Tests 53 passed (53) (cli-runtime.test.ts).

RED1 covers the row written under account B. RED2 never covers the row written under account A. RED3 is the rule of an earlier head, where only a fresh recovery prompt was strict at spawn and send. RED4 sends the hook answer without the private-input check, so the saved context reaches Claude after the check failed. RED5 removes the opt-in check, so preparation attests a token the process has not seen and the next fresh session receives saved history although the operator never opted in.

Queued reassignment

A login reassigned while a coverage command is queued for the SQLite worker does not advance coverage. The worker asks the host from inside its write transaction (see the design bullet above). Scenario 22 adds one preload, harness/shim/queued-switch-shim.mjs. It wraps Worker.prototype.postMessage and, right after the host posts turn 2's final session.turn.commit (the rows plus coverage) to the SQLite worker, runs the "reassign the login to account B" script synchronously, while the worker has not opened its transaction and the host has not serviced its admission request. Turn 3 then returns the login to account A.

Main transfers the worker command buffer, so the shim decodes the command before postMessage (queued-switch-shim.fixed.mjs); product code is untouched. With it the row reads t1:known/2 t2:known/3 t3:unknown, 3 profile requests, as at the previous head, and turn 3 is 451 characters with no canary. Turn 2's rows stay (seq 3 and 4), coverage stops at seq 3, and turn 3 on account A is refused that history. The tests does not cover a turn commit whose login is reassigned while the command is queued and does not cover a transcript report whose login is reassigned while the command is queued in history-boundary.native-login.test.ts wrap Worker.prototype.postMessage the same way and assert that the switch happened, so they cannot pass vacuously. Whole record: queued-reassign.

Tests and checks

Typecheck, all EXIT 0: pnpm tsgo:core, pnpm tsgo:core:test, pnpm tsgo:extensions, pnpm tsgo:extensions:test (f-tsgo-core.log, f-tsgo-core-test.log, f-tsgo-extensions.log, f-tsgo-extensions-test.log); the exit codes of the typechecks and of the lanes below are recorded in summary.txt.

Targeted vitest, the 10 test files this PR adds or changes: 227 tests in 5 shards, EXIT 0 (f-targeted.log).

Owning directories, the runner's own summary lines:

Lane Result
src/agents/cli-runner/ Test Files 13 passed, 3 passed, 7 passed, 37 passed, 1 passed; Tests 59, 12, 233, 445, 5 passed; [test] passed 5 Vitest shards in 120.88s (log)
extensions/anthropic/ Test Files 37 passed (37), Tests 417 passed | 1 skipped (418), [test] passed 1 Vitest shard in 21.72s (log)
src/plugin-sdk/provider-auth-claude-compat.test.ts Test Files 1 passed (1), Tests 28 passed (28) (log)
src/agents/sessions/ Test Files 15 passed | 1 skipped (16), 7 passed, 28 passed, 55 passed | 1 skipped (56); Tests 89 passed | 1 skipped (90), 62 passed, 375 passed, 703 passed | 4 skipped (707); [test] passed 4 Vitest shards in 154.93s (log)
src/config/sessions/ first run EXIT 1 at load average 31 to 54: 1 of 224 tests in the first shard, startup-migration.registry-recovery.test.ts (database is locked) (log); rerun here Test Files 18 passed (18) and 364 passed | 2 skipped (366), Tests 224 passed (224) and 3322 passed | 11 skipped (3333), [test] passed 2 Vitest shards in 971.43s (log)

That file is not in and does not import this diff, and passes alone here three times out of three (repro-registry-recovery-1.log).

node scripts/check-changed.mjs --base 372095136ef (f-check-changed.log): 42 checks ok, 2 failed. No failure involves a file in this diff; each fails identically on a pristine checkout of 372095136ef (main-alone log linked per check):

  • max-lines suppression ratchet: ui/src/pages/chat/components/chat-message.test.tsx, ui/src/pages/config/config-page-state.ts, ui/src/pages/sessions/sessions-page-state.ts. No ui/ path is in the diff; pristine 372095136ef against itself (empty diff) reports the same three files (main-check-max-lines-ratchet.log).
  • core tsgo graph boundary: core test shard root budget, gateway-root 724 and plugins-platform 725 roots against an advisory 720; the same 724 and 725 on 372095136ef, so this diff adds no root there (main-check-tsgo-core-boundary.log).

check-env-var-count is not among the 44 steps check:changed selected for this diff. Run alone at the previous head's tree it failed as on 372095136ef: OPENCLAW_* count 460 exceeds budget 452 (f-check-env-var-count.log, main-check-env-var-count.log); this diff adds no OPENCLAW_* variable.

Earlier captures

The subsections below ran at earlier heads of this PR on base 0816aa1b57dc (the earlier heads), each stated in its first line. Their production behavior is the same as at the pushed head except where the table above differs (row 6, and turns that resume a Claude session). Captures: attested/, queued/, real/.

A real attestation

Ran once on the Mac Studio during the c276e5e3b6c round; it exercises only the endpoint, not OpenClaw. One real GET https://api.anthropic.com/api/oauth/profile with the access token of the Studio's logged-in Claude CLI 2.1.283 account returned status=200 latencyMs=834, an account object with uuid (equal to the .claude.json record) and an organization object, and left the credential on disk unchanged; a synthetic token returned status=401 latencyMs=96 (identity/real-profile-attestation.txt). No token, uuid or email was printed or stored. Not exercised against the real endpoint: an expired real token (the code never sends one), a revoked token, a token without the user:profile scope, and a request through an HTTPS proxy.

When Claude CLI rotates its token

Ran once during the c276e5e3b6c round against the real claude 2.1.283 binary with a synthetic login whose token had expired, its HTTPS sent to a local CONNECT proxy that logs and refuses each connection, so nothing reached Anthropic: the CLI tried the refresh (CONNECT platform.claude.com:443) 213 ms after spawn and before it answered initialize, and OpenClaw sends the prompt only after that answer. So a rotated token can already be on disk at the send check, which is why a refresh-due turn runs without saved history (identity/refresh-timing.txt).

Real Claude recovery proof

Real claude 2.1.283 (Keychain-held claude.ai login), real api.anthropic.com profile attestation and real model replies (claude-cli/claude-haiku-4-5), through the built openclaw agent --local with an isolated state dir and no Gateway, at 69861729ddf (AFTER) and the PR merge-base 0816aa1b57d (BEFORE). Two turns per arm; between them the Claude session is dropped by deleting that run's own Claude project dir, so turn 2 starts a replacement session (reuse=invalidated:missing-transcript).

AFTER  turn 2: promptChars=771 historyPrompt=present   reply: PINEAPPLE-1296762355   boundary known seq 2
BEFORE turn 2: cli session history refused across auth boundary: reason=auth-unknown
               promptChars=260 historyPrompt=none      reply: UNKNOWN
AFTER, login changed between turns (synthetic CLAUDE_CONFIG_DIR): reason=auth-unknown, promptChars=260, historyPrompt=none, boundary unknown

Covers: authenticated replacement-session recovery with the real binary and real attestation, the BEFORE refusal, and refusal after a login change. Does not cover: a second real account (the switch uses a fake credential, so the log reads auth-unknown and does not separate "owner differs" from "owner unattestable"; the stub scenarios do), repeated runs (one run per arm), a long-lived claude setup-token login (see Gaps), and the queued-coverage window with the real binary.

Keychain cost

Counted at 69861729ddf on base 0816aa1b57dc with the scenario 10 harness: 10 security lookups per turn for a readable Keychain item, against none at base; 20.9 ms p50 per readable lookup with the real /usr/bin/security, about 0.21 s per turn. history-boundary.native-login.test.ts pins the split.

Gaps

  • The access token leaves the process, for an operator who opts in. Only with historyRecovery.attestNativeLogin: true (default false, row 35: no request without it). It goes only to https://api.anthropic.com/api/oauth/profile, once per token not yet attested in the process, with redirects refused, a 3 s timeout and errors dropped unread. The token is never logged, stored, refreshed or written back. A proxy was not exercised. The opt-in's UI hint names the endpoint.
  • An idle, expired token after a Gateway restart has no owner. An access token that expired while the Gateway was down cannot be attested until Claude refreshes it. The first turn on it has no owner, and that conversation's history stays refused until /new or an empty reset. Persisting attestations across restarts would mean persisting a token-derived value, which this PR does not do.
  • A refresh-due turn runs without saved history. A turn prepared within 10 minutes of token expiry runs without saved history, because Claude rotates the token before the prompt and the send check could not prove the new one. The next turn is offered history again (scenario 20).
  • A rotation outside the CLI's refresh window stops coverage. If the CLI rotates the token outside that window (for example after a server-side revocation and a 401 recovery), the new token is not attested before the turn's rows commit, so coverage stops and later turns are refused history (scenario 21). Detecting this would cost a Keychain read after every turn; the settle reads only when a rotation is expected.
  • Transient failures fence the conversation. A profile request that fails at preparation, and a Keychain lookup that fails at a coverage commit, stop coverage until /new or an empty reset. The reply is kept. Only successes are cached, so a failed attestation retries on the next turn.
  • A login without the user:profile scope has no owner. A long-lived claude setup-token credential carries only user:inference; the real profile endpoint answers it with HTTP 403 (OAuth token does not meet scope requirement any_of(user:profile, user:office)). Run against a login like that, the branch refuses saved history exactly as BEFORE does (reason=auth-unknown, historyPrompt=none, reply UNKNOWN), so those installs get no recovery. That is the fail-closed outcome; the run is in the evidence folder, mini-setup-token.
  • Some endpoint behaviors were not exercised. A real successful token refresh, a revoked token and an HTTPS proxy were not run against the real endpoint; the harness endpoint is a stub.
  • Sessions that already have history and no recorded boundary stay unknown. Only conversations that start empty after the opt-in benefit (row 37); /new or an empty reset establishes the boundary. History written by v2026.10.4 is kept and not adopted (scenario 27).
  • Plugin-defined backends wrapping Claude (id other than claude-cli) are not covered.
  • A last-instant window remains in worker coverage. The worker asks the host for the owner check from inside its write transaction and the host answers right before it grants. A credential replaced between that answer and the end of the same SQLite transaction (microseconds on the worker) is not seen for that write, and is caught at the next boundary. The worker cannot read the Keychain or the attestation cache itself, so a fully atomic check is not possible. A reassignment while the command is queued, or during any awaited preparation, is seen (scenario 22 and the queued tests).
  • Saved notes are not shown reaching a resumed session. A note reaches a Claude CLI turn only when its row is covered, and no shipped path reachable from openclaw agent writes a covered note into a claude-cli conversation (the plugin-SDK append in row 32 is uncovered, as on main). The resumed-session context that is shown is the interrupted input (rows 28 to 31). The refusal does not depend on which saved data is present (rows 24, 25, 30, 31, 33, 34; RED3, RED4).
  • The metadata-worker path is shown by a test, not by the built binary. The CLI runner never posts session.metadata.append or session.transcript.appendMessage (row 32), so no shipped CLI flow reaches it. history-boundary.native-login.test.ts runs it, in one case, on the real worker thread and SQLite (RED1, RED2).
  • The real Claude recovery run was not repeated at the pushed head. It ran at 69861729ddf on base 0816aa1b57dc; at the pushed head the same paths are shown by the harness scenarios above with a synthetic child and the stub endpoint.
  • Three checks fail without this change (max-lines ratchet, core test shard budget, env-var count); each fails identically on pristine 372095136ef, on files this diff does not touch (Tests and checks).
  • Incognito sessions on a native login may stop coverage. The in-memory incognito actor confirms the owner only through the running turn's writer when that writer is in scope; otherwise it keeps the rows and stops coverage. history-boundary.incognito.test.ts covers the in-scope case; no harness scenario runs an incognito session.
  • One new plugin config key. plugins.entries.anthropic.config.historyRecovery.attestNativeLogin grows the plugin config surface by two entries, so docs/.generated/config-baseline.counts.json raises the plugin budget by two (4759 to 4761 on this base) and config-baseline.sha256 is regenerated with pnpm config:docs:gen.
  • Unrelated suites were not run. The full suite, the e2e and live lanes, and the Docker lanes were not run. check:changed selects core, coreTests, extensions, extensionTests and docs for this diff, all of which ran above together with the owning-directory lanes.

@clawsweeper

clawsweeper Bot commented Oct 4, 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 labels Oct 4, 2026
@github-actions

github-actions Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR adds opt-in Claude account attestation so newly started native-login conversations can recover saved history after losing their native session.

Example: A native Claude conversation saves PINEAPPLE-1296762355, then its native transcript disappears.

  • Before: The replacement session receives no saved history and replies UNKNOWN.
  • After: With attestNativeLogin enabled and the same account verified, the replacement session replies PINEAPPLE-1296762355.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong supplied behavior and upgrade evidence supports the recovery design, but the outstanding unrelated-scope finding prevents a clean patch verdict.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Inspected real Claude recovery captures through built openclaw agent --local and later production CLI/Gateway traces exercising fresh and resumed sessions, login reassignment/removal before prompt send and hook response, and queued coverage commits. The real-provider run is from an earlier head; later captures use a synthetic Claude child and profile endpoint through the actual production owners, with reruns documented after integration. These distinguish allowed recovery from forbidden disclosure and retained-but-uncovered writes.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Feature · Worth it: Yes · Fix scope: Partial
User problem: A native Claude conversation loses recoverable context when its native session disappears because OpenClaw cannot verify which account owns the saved history.
Reason: Production reports establish value, and recorded exact-head maintainer approval settles the optional attestation direction; legacy unowned conversations and plugin-defined backends remain explicitly outside this PR.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR addresses a demonstrated native-login history-recovery gap that remains on main, but the previously reported unrelated embedded compaction repair still needs to be split out.

Priority: P2
Reviewed head: 1bf2ffd7706085563a9751cc7f0d1564b5410b71

Before merge

  • Split the embedded compaction repair into a separate PR (P2) - This remains unresolved from the previous review. When an embedded compaction continuation is persisted and followed by another invisible retry, these lines change how the instruction is retained independently of Claude native-login ownership. Commit 9385a46 and the linked main-versus-fix captures establish a separate pre-existing defect. Move these lines and the added run.session-prompt-state regression test into a focused PR so every hunk serves the stated native-history problem, as required by the scope and simplification policy.

Findings

  • [P2] Split the embedded compaction repair into a separate PR — src/agents/embedded-agent-runner/run/session-prompt-state.ts:157-160
Agent review details

How this fits together

The CLI runner combines the selected child environment, admitted run, and saved transcript into a Claude request; account checks gate history disclosure and the persistence owners advance contiguous history coverage.

flowchart TD
A[Agent turn and child environment] --> B[Native credential reader]
B --> C[Anthropic account attestation]
C --> D[CLI history boundary]
E[Saved SQLite transcript] --> D
D --> F[Claude transport and prompt hook]
F --> G[Transcript persistence owners]
G --> E
Loading

Technical review

Best possible solution:

Keep native-login recovery within the existing history and persistence owners, and publish the independent embedded compaction repair separately.

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

Current-main source still cannot identify a native login as a history owner, matching the reported released-install incidents and the supplied before/after CLI captures; no target code was executed during this review.

Is this the best way to solve the issue?

Credential-bound provider attestation avoids trusting a stale local account record, while final transport checks and transaction-time coverage checks preserve account isolation; the separate embedded retry repair exceeds the stated scope.

Full review comments:

  • [P2] Split the embedded compaction repair into a separate PR — src/agents/embedded-agent-runner/run/session-prompt-state.ts:157-160
    This remains unresolved from the previous review. When an embedded compaction continuation is persisted and followed by another invisible retry, these lines change how the instruction is retained independently of Claude native-login ownership. Commit 9385a46 and the linked main-versus-fix captures establish a separate pre-existing defect. Move these lines and the added run.session-prompt-state regression test into a focused PR so every hunk serves the stated native-history problem, as required by the scope and simplification policy.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Account-owned contiguous history coverage keeps the original intent (e20b56c: Recover saved context without letting replacement native bindings authorize another account's transcript.)
  • Claude native transport keeps the original intent (58d8871: Keep Claude execution in the installed native executable while retaining host admission, permission checks, and transport lifecycle ownership.)
  • Shipped Claude credential reader keeps the original intent (b1ea61e: Preserve the released SDK credential reader, credential-root precedence, bounded Keychain behavior, and intent-specific caching.)
  • Worker-owned transcript persistence keeps the original intent (ca77256: Keep transcript appends, entry predicates, custody, and commit receipts within the existing executor transaction.)
  • Retained embedded compaction continuation changes intended behavior with a stated reason (fix(agents): preserve post-compaction continuation prompts #136236: Retain the compaction instruction across invisible retries; after fix: rate-limited runs lose the prompt cache on retry #177050 began persisting internal prompts, this PR explains that the retained copy duplicates replayed history.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vito Cappello: Raw commit e20b56c adds src/agents/cli-runner/history-boundary.ts:115 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/history-boundary.ts)
  • Peter Steinberger: Raw commit ad3c930 adds src/agents/cli-runner/history-boundary.ts:115 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ad3c93078e7f; files: src/agents/cli-runner/history-boundary.ts)
  • Tak Hoffman: Raw commit b1ea61e adds src/plugin-sdk/provider-auth-claude-compat.ts:175 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: b1ea61e84703; files: src/plugin-sdk/provider-auth-claude-compat.ts)

PR surface

Source +722, Tests +1651, Docs +2, Generated 0. Total +2375 across 38 files. Added test files: 5.

View PR surface stats
Area Files Added Removed Net
Source 23 865 143 +722
Tests 12 1785 134 +1651
Docs 1 5 3 +2
Config 0 0 0 0
Generated 2 3 3 0
Other 0 0 0 0
Total 38 2658 283 +2375

Review metrics

Metric Value Why it matters
New configuration surface 1 Boolean option, default false historyRecovery.attestNativeLogin explicitly controls reading and sending the native credential for account attestation.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Useful recovery improvement for native Claude conversations after session replacement, with ordinary native resume and the default behavior preserved.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • 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 execution lanes are retired.

History

Review history (21 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-16T15:13:22.975Z sha 13078e3 :: blocked before merge. :: none
  • reviewed 2026-10-18T15:56:57.355Z sha 0f43109 :: blocked before merge. :: none
  • reviewed 2026-10-19T15:47:14.844Z sha 5fffaf6 :: blocked before merge. :: none
  • reviewed 2026-10-20T06:06:40.874Z sha 8d822e2 :: blocked before merge. :: none
  • reviewed 2026-10-20T08:38:54.899Z sha 53ff5be :: blocked before merge. :: none
  • reviewed 2026-10-20T19:47:45.313Z sha 57501c0 :: blocked before merge. :: [P2] Split the embedded compaction repair into a separate PR
  • reviewed 2026-10-20T20:13:57.905Z sha 12b692d :: blocked before merge. :: [P2] Split the embedded compaction repair into a separate PR
  • reviewed 2026-10-20T23:28:42.623Z sha 1bf2ffd :: blocked before merge. :: [P2] Split the embedded compaction repair into a separate PR

Reviewed October 20, 2026, 7:39 PM ET / 23:39 UTC (Revision 22).

@etzelm
etzelm force-pushed the fix/cli-native-history-owner branch from de1dc67 to f32e17d Compare October 4, 2026 18:04
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 4, 2026
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 4, 2026
@etzelm
etzelm force-pushed the fix/cli-native-history-owner branch from f32e17d to 4ff780a Compare October 4, 2026 19:14
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 4, 2026
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 5, 2026
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 5, 2026
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 5, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 5, 2026
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 20, 2026
@etzelm

etzelm commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 20, 2026
- openclaw#177050 (07b59a0) persists internal retry prompts as hidden internal_system rows.
- openclaw#136236 retained the compaction continuation instruction across later invisible retries because that prompt was not saved.
- A reasoning-only retry after a compaction continuation then sent the instruction twice: once replayed from history and once appended to the retry prompt.
- Drop the retained instruction once the internal prompt carrying it is persisted.
- Fixes test/gateway-openai-compaction-replay.e2e.test.ts on main.
…y-owner

# Conflicts:
#	src/config/sessions/session-accessor.sqlite-cli-history-boundary.ts
#	src/config/sessions/session-accessor.sqlite-transcript-reports.worker.ts
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 20, 2026
@etzelm

etzelm commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 20, 2026
…y-owner

# Conflicts:
#	docs/.generated/config-baseline.sha256
etzelm added a commit to etzelm/openclaw that referenced this pull request Oct 20, 2026
@etzelm

etzelm commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Resolve generated config-baseline conflicts by regenerating them from current main plus this branch's Anthropic manifest change.
@roboclaw-bot

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

/allow-security-sensitive-change

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Maintainer landing review for head 1bf2ffd7706085563a9751cc7f0d1564b5410b71

  • Security-sensitive approval: @Patrick-Erichsen approved this exact head in fix(agents): restore saved history for fresh Claude CLI sessions on a native login #164796 (comment). openclaw/security-sensitive-review passes.
  • Owner decision on attestation: @Patrick-Erichsen accepted the opt-in contract. With plugins.entries.anthropic.config.historyRecovery.attestNativeLogin (default false), Anthropic profile attestation can become the native-login history owner for new conversations. Unknown history is still rejected, and the documented refresh-window and transient-failure limits stay in place.
  • ClawSweeper P2 (split the embedded compaction fix): kept in this PR by @Patrick-Erichsen's decision. The 4-line session-prompt-state.ts fix repairs the gateway-openai-compaction-replay e2e failure that is still unfixed on main.
  • Follow-up (not blocking): the native-login check reads user settings, apiKeyHelper and the spawn environment, but not Claude's admin-managed settings env block. Only the host administrator can write that file, so it is tracked as a follow-up: treat managed-settings auth keys as non-native.
  • CI: run 39513549559 passed except check-lint-core-5. That job fails on src/flows/doctor-repair-flow.ts:73 (unbound-method). The error came from main in fix(doctor): show progress while checks and repairs run #178767 and is fixed on main in 5d80482. This PR does not touch that file, so the failure is inherited from main and not caused by this PR.

Conflict resolution (1bf2ffd7): merged origin/main and regenerated only the two docs/.generated/config-baseline.* files. The product diff is unchanged.

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

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 extensions: anthropic gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants