Repository navigation
fix(agents): restore saved history for fresh Claude CLI sessions on a native login - #164796
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
✅ Maintainer security changes approvedA maintainer approved this revision with an explicit security approval comment.
A later push requires a fresh approval comment for an external contributor's PR. |
|
Codex review: needs changes before merge. What this changesThis 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.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Partial 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 Before merge
Findings
Agent review detailsHow this fits togetherThe 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
Technical reviewBest 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:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 163b4f9c0cf2. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +722, Tests +1651, Docs +2, Generated 0. Total +2375 across 38 files. Added test files: 5. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (21 earlier review cycles; latest 8 shown)
Reviewed October 20, 2026, 7:39 PM ET / 23:39 UTC (Revision 22). |
de1dc67 to
f32e17d
Compare
f32e17d to
4ff780a
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
- 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
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…y-owner # Conflicts: # docs/.generated/config-baseline.sha256
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Resolve generated config-baseline conflicts by regenerating them from current main plus this branch's Anthropic manifest change.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
/allow-security-sensitive-change |
|
Maintainer landing review for head
Conflict resolution ( |
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
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-decisionandclawsweeper:no-new-fix-prlabels and this PR does not fix the existing-session gap described under Gaps, so it usesRelated: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-clibackend on a native Claude CLI login and no OpenClaw-managed credential, the history boundary cannot build an owner fingerprint.prepareCliHistoryBoundarywrites nocliHistoryBoundary,prepare.tsturns the missing writer intorawTranscriptReseedReason: "auth-unknown", andloadCliSessionPromptContextrefuses to seed saved history into any fresh CLI session (replacement session, cleared binding, lost native transcript). On the base commit every native turn logscli 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: trueon 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 theanthropic:claude-cliprofile. 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):
GET https://api.anthropic.com/api/oauth/profileper 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 --localstarts a new process per turn, so it makes one request per turn.CLI history authority changed before executionif 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.attestNativeLoginin the Anthropic plugin's config schema, defaultfalse. 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 setsautoSelectAuthProfile: false), must be bound to the credential rather than to the.claude.jsonaccount 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 inprovider-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) andprepare.ts. The owner confirmation inside worker transactions is in the turn commit and transcript report paths insrc/config/sessionsand in the SessionManager metadata worker insrc/agents/sessions. The check on the prompt hook answer is inextensions/anthropic/cli.runtime.ts. The opt-in is declared inextensions/anthropic/openclaw.plugin.jsonand read byisNativeCliLoginAttestationEnabledincli-credentials.ts.Simplification (
08f918dca3a, on13078e36c7e): one Keychain reader instead of two (the shipped reader returns the same results); no unusedenvandnowparameters, dead cache delete, duplicate installation-target merge or report-worker target move;history-boundary.native-login-metadata.test.tsfolded intohistory-boundary.native-login.test.ts,cli-history-owner-probe.test.tscut to one case (deleted in the second pass), restated cases dropped;prepare-native-history.test.tsnow releases its prepared backends (it leaked one session sharing read per case). Against13078e36c7e: 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.tsbecame one native-login case (RED11, RED12). Against0f431092595: 5 files +37/-41.Third pass (
27ff3327776,8d822e2632d): 75 production mutations found three unpinned paths: the host actor check on incognito sessions (a case inhistory-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, andresolveCliChildEnvdrops abaseEnvparameter no caller passed, so that extraction is a pure move. Against5fffaf68380: 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 defaultfalseand a UI hint that names the endpoint the token goes to.prepareCliHistoryBoundarychecksisNativeCliLoginAttestationEnabled(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 underenvwith the CLI's own precedence (Keychain first on macOS, bounded non-interactive lookups, tri-state so onlysecurity's item-not-found exit 44 lets.credentials.jsonstand; then the file). It sends that token, and nothing else, tohttps://api.anthropic.com/api/oauth/profile(Authorization: Bearer,redirect: "error", 3 sAbortSignal.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 isuuid:<account.uuid>from the response. No owner on any failure: network error, timeout, non-2xx, a body withoutaccount.uuid, no credential, or an access token already expired. The error is dropped, not logged. The.claude.jsonaccount record is no longer read.The cache maps
HMAC-SHA256(key, token)to the attested owner, withkeyfromrandomBytes(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 existingcli-history-v1fingerprint 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 staysresolveNativeCliLoginOwner(backendId, env)(now asynchronous, returning{ owner?, refreshDueAt? }) plusreadAttestedNativeCliLoginOwner(backendId, env)for the synchronous checks; both return nothing for backends other thanclaude-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
initializeand so before the prompt is sent, once the token is within 5 minutes of expiry (bundle:now + 300000 >= expiresAt; probe below). Two rules follow:writer.replaysHistory === false;prepare.tstreats it likeauth-unknown), and still covers its rows.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
SharedArrayBuffercell) 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
UserPromptSubmithook 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-internalassertPrivateInputCurrent(set only for a native-login writer, like the forwarded auth credential: it is not part of the plugin SDKCliBackendExecuteContexttype,ClaudeCliExecuteContextincli.runtime.tsdeclares it), which runs the turn's fullassertCurrent(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 aUserPromptSubmithook withadditionalContext. 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
/newor an empty reset.docs/gateway/cli-backends.mdstates 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 foldedlive-session-fingerprint.tsintocreateCliLiveSessionCapabilityincli-live-session-registry.ts, so the warm-reusenativeLoginOwnerHashfield 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.tsis identical to main, which checks private history at send time itself (asyncassertReadable), so the native-login recheck stays inexecute.tsandexecute-plugin.ts; the metadata worker takes main'sbindSqliteWorkerDatabaseshape with the owner probe re-applied on top;history-boundary.test.tsuseshistory-boundary.test-support.tson 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.
claude auth status.claude.jsonoauthAccount.accountUuid, read from the child's environment while a credential existsaccount.uuidAnthropic returns for the exact access token the child would useWhy C:
claude auth status --jsonreports 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 rewritesaccountUuidoremailAddress(identity/cli-bundle-excerpt.txt).AFe(e)isgt.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).historyRecovery.attestNativeLogin.Contract table
historyRecovery.attestNativeLoginunset orfalse(the default)unknown(row 36)attestNativeLogin: trueanthropic:claude-clipinnedaccount.uuidCLI history authority changed before execution; nothing reaches ClaudeUserPromptSubmithook is answeredenvconfig selects another config dir, on every turnenvconfig selecting another login is added mid-conversationenvselects another config dir than the Gateway processenvblock, selects an API key, token or cloud providerCLAUDE_CONFIG_DIR, split credential roots,apiKeyHelper.credentials.jsonbeside itsecurityexit 44),.credentials.jsonpresentsecuritylookups (base: none)claude-cliEvidence
All of the following in this section, up to "Earlier captures", ran on one machine (a Mac Studio) at commit
c8e525c2f12, whose tree934c1340971d65c3c7717818c3a97daacdb5e5c5is the pre-merge head8d822e2632d(the signed commit of the same tree,gates/identity.txt), base372095136ef. Every build, lane, check, red/green run and harness scenario in this section ran at that tree (the mutation matrix ate72e9e9a14c, the parameter removal aside); the records labelledbefore 05501c8aran the built previous head05501c8acd9with the same harness. Rows 38 and 39 ran a build of95a27d0779d; the main-alone checks ran a checkout of372095136ef. Every scenario setsattestNativeLogin: trueexcept rows 35 to 39. Captures for this head: head-8d822e26/; the harness as run is in itsharness/scripts/(head-5fd72055/ plus the queued-switch shim andoutcomes2.sh). Paths in them are redacted to$RUN,$TREE,$BASEand$HOME.Build
pnpm buildat the tested tree (pnpm build EXIT 0,gates/summary.txt) and, as for the previous head, at base95a27d0779d(BUILDEXIT 0) (build-final.log, build-base.log). The tested tree's build summary (total and slowest phase; full line inbuild-final.log):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(builtdist), a real SQLite session and worker threads, synthetic login files on disk, the real Anthropic Claude runtime and stream-json transport. Theclaudeexecutable 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.jsonrecord (loginAccount) and by its credential (credentialAccount) at that instant. It can rewrite the login at chosen moments:FAKE_ON_INITafter it initializes and before the prompt is sent,FAKE_ON_USERafter it receives the prompt. It answers OpenClaw'sUserPromptSubmithook 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; withFAKE_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 tokenssynthetic-<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 thechild_process.execSyncseam (harness/shim/security-shim.mjs); the others use the realsecuritybinary, which finds no item and exits 44.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's447128e3a84removed thecli exec:log line whosepromptChars,historyPromptanduseResumefields 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). TheUserPromptSubmitcontext of every delivered prompt is in the same file, with its own canary counts;refusedisCLI history authority changed before execution, exit 1, with no user message delivered (still read from the OpenClaw log).PINEAPPLE-7is the turn-1 canary. Boundary is the storedcliHistoryBoundaryafter 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).PINEAPPLE-7; boundaryknownseq 4auth-unknown); boundaryunknownunknownenvselects another login on turn 1 onlyenvon both turnsPINEAPPLE-7PINEAPPLE-7unknownenvselecting another login added from turn 3PINEAPPLE-7; turns 3, 4: 449, no canaryauth-unknown); boundaryunknownPINEAPPLE-7PINEAPPLE-7andBANANA-3; boundaryknownseq 6unknown(Gaps)unknownknownseq 6knownseq 5knownseq 5unknownMANGO-5in its context ("Saved context on a resumed Claude session")PINEAPPLE-7, context withMANGO-5MANGO-5MANGO-5llm_outputof turn 1auth-unknown), boundaryunknown(see "SessionManager appends")UserPromptSubmithook is answeredMANGO-5); turn 4 back on A is refused history; boundaryunknownunknownattestNativeLoginnot set; same login, fresh Claude sessionauth-unknown), context 1145 bytes; no boundary stored; 0 profile requestsknownseq 2), 1 profile request; turn 2: 449, no canary, no request; boundaryunknownMANGO-5; new conversation's boundaryknownseq 495a27d0779d, row 1's turnsauth-unknown), context 1145 bytes; no boundary stored; 0 profile requests95a27d0779d: 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:
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 withopenclaw 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 itinterrupted. Turns 3 and 4 run withopenclaw agent --localon 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.## Interrupted inputsandMANGO-5; boundaryknownseq 4PINEAPPLE-7; context 1798 bytes withMANGO-5MANGO-5; the input is stillinterruptedand unconsumedMANGO-5Whole records: interrupted-allowed and interrupted-reassign-before-send (rows 28 and 30), with
fake-claude.logand the.context-*files beside them. In row 28 turn 3's context contains the## Interrupted inputssection withMANGO-5and the stored input staysinterrupted; in row 30 the refused turn 3 delivers no prompt and no context, and turn 4 on account A receives the input.On
5d840900899without this change the turn context has no## Interrupted inputsheader 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-5staged for its context. The synthetic child runsFAKE_BEFORE_CONTEXTafter it has received turn 3's prompt and before it sends itsUserPromptSubmithook request: row 33 reassigns the login to account B, row 34 removes the credential. Turn 4 runs on account A again.05501c8acd9## Interrupted inputsandMANGO-5, received under account BMANGO-5, received with no credential presentIn 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
interruptedand 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 at05501c8acd9are rec-before-ctx and rec-before-ctx-revoke (not rerun).extensions/anthropic/cli-runtime.test.tspins 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
934c1340971on base372095136effrom[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 installin a scratch directory) on a fresh state dir; the candidate then runsopenclaw 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.reason=auth-unknown, 48-character prompt).reason=auth-unknown), the turn runs, and the stored boundary stays absent.MANGO-5; boundaryknownseq 4).historyRecoverykey, so the harness setsattestNativeLogin: trueonly afterdoctor --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 --localturn posts to the SQLite workers: there is nosession.metadata.appendand nosession.transcript.appendMessage, the two commands the metadata worker handles. The turn's rows commit throughsession.turn.commit, which takes the owner check on its transaction admission (rows 7, 22, 26). A local plugin note appended through the plugin SDK atllm_outputgoes throughsession.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, boundaryunknown). 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 holdsinhistory-boundary.native-login.test.tstherefore exercises the metadata worker on the real worker thread and SQLite, with real login files and a stubbedfetch:SessionManager.appendMessageAsyncunder 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.history-boundary.native-login.test.ts>covers a SessionManager append only while the native login owner holds:AssertionError: expected 2 to be 1Tests 22 passed (22)AssertionError: expected 0 to be greater than 0Tests 22 passed (22)execute.tsback 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 rejectingTests 4 passed (4)UserPromptSubmitanswer goes out on the stream check aloneextensions/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 undefinedTests 53 passed (53)prepare-native-history.test.ts>never sends the native token to Anthropic unless the operator opted in:AssertionError: expected { ...(12) } to be undefinedTests 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) andTest 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 wrapsWorker.prototype.postMessageand, right after the host posts turn 2's finalsession.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 readst1: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 testsdoes not cover a turn commit whose login is reassigned while the command is queuedanddoes not cover a transcript report whose login is reassigned while the command is queuedinhistory-boundary.native-login.test.tswrapWorker.prototype.postMessagethe 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:
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.tsTest 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/EXIT 1at load average 31 to 54: 1 of 224 tests in the first shard,startup-migration.registry-recovery.test.ts(database is locked) (log); rerun hereTest Files 18 passed (18)and364 passed | 2 skipped (366),Tests 224 passed (224)and3322 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 checksok, 2failed. No failure involves a file in this diff; each fails identically on a pristine checkout of372095136ef(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. Noui/path is in the diff; pristine372095136efagainst itself (empty diff) reports the same three files (main-check-max-lines-ratchet.log).core tsgo graph boundary: core test shard root budget,gateway-root724 andplugins-platform725 roots against an advisory 720; the same 724 and 725 on372095136ef, so this diff adds no root there (main-check-tsgo-core-boundary.log).check-env-var-countis not among the 44 stepscheck:changedselected for this diff. Run alone at the previous head's tree it failed as on372095136ef:OPENCLAW_* count 460 exceeds budget 452(f-check-env-var-count.log, main-check-env-var-count.log); this diff adds noOPENCLAW_*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
c276e5e3b6cround; it exercises only the endpoint, not OpenClaw. One realGET https://api.anthropic.com/api/oauth/profilewith the access token of the Studio's logged-in Claude CLI 2.1.283 account returnedstatus=200 latencyMs=834, anaccountobject withuuid(equal to the.claude.jsonrecord) and anorganizationobject, and left the credential on disk unchanged; a synthetic token returnedstatus=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 theuser:profilescope, and a request through an HTTPS proxy.When Claude CLI rotates its token
Ran once during the
c276e5e3b6cround against the realclaude2.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 answeredinitialize, 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
claude2.1.283 (Keychain-held claude.ai login), realapi.anthropic.comprofile attestation and real model replies (claude-cli/claude-haiku-4-5), through the builtopenclaw agent --localwith an isolated state dir and no Gateway, at69861729ddf(AFTER) and the PR merge-base0816aa1b57d(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).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-unknownand does not separate "owner differs" from "owner unattestable"; the stub scenarios do), repeated runs (one run per arm), a long-livedclaude setup-tokenlogin (see Gaps), and the queued-coverage window with the real binary.Keychain cost
Counted at
69861729ddfon base0816aa1b57dcwith the scenario 10 harness: 10securitylookups 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.tspins the split.Gaps
historyRecovery.attestNativeLogin: true(defaultfalse, row 35: no request without it). It goes only tohttps://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./newor an empty reset. Persisting attestations across restarts would mean persisting a token-derived value, which this PR does not do./newor an empty reset. The reply is kept. Only successes are cached, so a failed attestation retries on the next turn.user:profilescope has no owner. A long-livedclaude setup-tokencredential carries onlyuser: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, replyUNKNOWN), so those installs get no recovery. That is the fail-closed outcome; the run is in the evidence folder,mini-setup-token./newor an empty reset establishes the boundary. History written by v2026.10.4 is kept and not adopted (scenario 27).idother thanclaude-cli) are not covered.openclaw agentwrites 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).session.metadata.appendorsession.transcript.appendMessage(row 32), so no shipped CLI flow reaches it.history-boundary.native-login.test.tsruns it, in one case, on the real worker thread and SQLite (RED1, RED2).69861729ddfon base0816aa1b57dc; at the pushed head the same paths are shown by the harness scenarios above with a synthetic child and the stub endpoint.372095136ef, on files this diff does not touch (Tests and checks).history-boundary.incognito.test.tscovers the in-scope case; no harness scenario runs an incognito session.plugins.entries.anthropic.config.historyRecovery.attestNativeLogingrows the plugin config surface by two entries, sodocs/.generated/config-baseline.counts.jsonraises the plugin budget by two (4759 to 4761 on this base) andconfig-baseline.sha256is regenerated withpnpm config:docs:gen.check:changedselectscore,coreTests,extensions,extensionTestsanddocsfor this diff, all of which ran above together with the owning-directory lanes.