Repository navigation
fix(cli): conversation history is lost when a CLI session cannot be resumed - #125002
alfredjbclaw wants to merge 13 commits into
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs real behavior proof before merge. Reviewed September 1, 2026, 8:30 AM ET / 12:30 UTC. ClawSweeper reviewWhat this changesThe branch adds auth-provenance tombstones for cleared CLI sessions, blocks reseeding across those boundaries, updates lifecycle callers and tests, and removes an obsolete SQLite tail-reader export. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked until stronger real behavior proof is added - 11 items remain Keep this PR open for revision: current main already ships the SQLite-history recovery, but the remaining auth-boundary changes introduce a transcript-isolation hole and expand documented raw-only policy without a maintainer decision. Priority: P1 Review scores
Verification
How this fits togetherWhen a native CLI session cannot resume, agent preparation reconstructs context from OpenClaw’s SQLite transcript and supplies it to a fresh provider process. Session bindings record whether that transcript can safely cross an authentication boundary before the reseed prompt is built. flowchart LR
A[Prior SQLite transcript] --> B[CLI session binding]
C[New agent turn] --> D[Reuse decision]
B --> D
D -->|Native session available| E[Resume provider session]
D -->|Fresh session| F[Transcript reseed]
F --> G[Provider prompt]
D -->|Auth boundary| H[History refusal]
Decision needed
Why: This choice balances established compacted-session recovery against a cross-auth transcript-disclosure boundary; the current code cannot safely infer the intended permanent policy. Before merge
Findings
Agent review detailsSecurityNeeds attention: The proposed unknown-provenance guard can be bypassed by a successful fresh rebind followed by another session clear, allowing previously unattributable transcript content into a later authentication context. PR surfaceSource +519, Tests +1792, Other 0. Total +2311 across 46 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep known auth-profile and auth-epoch behavior aligned with the documented raw-only contract, and move any unknown-provenance protection to the durable transcript owner so a later successful rebind cannot downgrade the quarantine; cover the complete clear–rebind–clear sequence. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: unknown clear → fresh successful binding write → later binding clear makes preparation use Is this the best way to solve the issue? No. Current main already provides the canonical SQLite recovery; the remaining branch both misses durable unknown-provenance isolation and changes compacted-history policy beyond the documented raw-only contract. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 570815775a2a. LabelsLabel justifications:
EvidenceSecurity concerns:
What I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (22 earlier review cycles; latest 8 shown)
|
06ef40e to
e48e24c
Compare
|
Both P1 findings are addressed in [P1] Bound the SQLite transcript read. Reused the existing [P1] Preserve auth invalidation when a binding is cleared. Implemented as refusing the clear when the clear path is auth-driven — Persisting the invalidation reason instead was considered and rejected: Also fixed a red gate this PR introduced. Base commit Validation: 19 tests pass in The real-behavior capture you asked for is still outstanding — I'm recording an abort-then-fresh-run sequence against a SQLite session store and will post it redacted before asking for the final pass. |
Real-behavior proof: abort → fresh CLI run receives prior context (SQLite session store)Captured on a gateway built from this branch ( 1. Turn one plants a tokenIt is persisted to the SQLite transcript store, not to a legacy JSONL file: The CLI session binding exists at this point: 2. A turn is abortedA long generation was started in the TUI and interrupted with The binding is gone afterwards: This is the state the bug report describes: no reusable session id, and no invalidation reason 3. The next turn still receives the conversation4. Why this exercises the fixThe gateway's own backend log shows how each turn was dispatched: The final turn ran with On current |
61db221 to
e081833
Compare
|
Rebased onto current [P1] Reject SQLite tails missing branch controls. Correct, and it was mine — the bounded read I added in the previous round introduced it. The store reader returns a tail; if the transcript's The fix is not simply refusing when controls are absent. A tail with no So the ambiguity is resolved at the source instead. The file loader needs no equivalent change — it reads the whole transcript, so its branch controls are always in hand. That asymmetry is why this only ever affected the store path. Validation: 20 tests in The real-behavior capture you asked for is in the comment above. |
|
Fixed in Both provider-owned-session predicates now require a live session id:
Regression coverage in One correction to the impact analysis, since it affects how this should be weighed: The finding says a tombstone lets a cleared session "skip default expiry indefinitely" / "remain indefinitely fresh under the default reset policy". That overstates it. The guard is What the bad predicate actually suppressed is narrower: the short circuit skips That is also why the new test asserts the predicate rather than a freshness difference: under an unconfigured policy both entries resolve fresh either way, so a freshness assertion would pass with or without the fix. The current writer stamps Gates on the new head: |
A handled `before_agent_reply` synthetic turn returns `clearCliSessionBinding` before `prepareCliRunContext` resolves any auth, so it carries no `cliSessionAuthIdentity`. When that clear met a stored binding that had also recorded none — a legacy `cliSessionIds` / `claudeCliSessionId` row, or a modern binding written by the bare-id fallback — `clearCliSession` had no boundary to source from either side and erased the record outright. The next turn read the session as never-bound, `rawTranscriptReseedReason` defaulted to `missing-transcript` (which is allowlisted), and the prior identity's transcript replayed into a fresh CLI session under whatever identity showed up next. The clear now writes an explicit unknown-provenance tombstone instead. Reuse resolution maps it to a new `auth-unknown` reason, which both reseed branches refuse: the raw tail by absence from RAW_TRANSCRIPT_RESEED_ALLOWED_REASONS, the compacted summary-plus-tail by membership in AUTH_CROSSING_RESEED_REASONS. Both memberships are required — a reason on neither list still leaks by the compacted route. The marker is deliberately not identity-shaped and is checked before any identity comparison. An empty identity tombstone would match every install that also resolves no identity, which is exactly the match an unattributable transcript must never make; it would also answer `auth-profile` against every profiled run and re-introduce openclaw#124991. Cost is one history reseed, on the first fresh prompt after an ambiguous clear: the next successful run writes a real binding with a session id and current auth, replacing the tombstone. Native resume is unaffected — the tombstone never carried a resumable handle. Adds session-history.reseed-unknown-provenance.test.ts, which drives the clear through real session persistence with the transcript in the SQLite transcript store and asserts on the constructed prompt: legacy-rows and bare-binding shapes x raw-tail and compacted branches x changed profile, changed epoch, and the same-identity narrowness control. Pins the producer property in cli-runner.before-agent-reply-cron.test.ts. Six existing tests asserted the old erase and now assert the tombstone.
…lear case Upstream openclaw#129092 added a third routing-provenance argument to the model fallback runner and updated every fixture in this file. The auth-boundary clear case added by this PR still called params.run with two arguments, so merging with main failed check-test-types-core-4 (TS2554) and, because the mock never forwarded the attempt options, the clear never ran and checks-node-compact-large-20 saw the stale binding survive.
# Conflicts: # src/auto-reply/reply/agent-runner-cli-candidate.ts
… suite Upstream openclaw#130475 grew agent-runner-execution-cli-sessions.test.ts past the 1000-line oxlint cap once this PR's cases merged in, and it moved the replacement-drop cleanup assertion inside the placement admission callback, where it still expected the binding record to vanish outright. Move this PR's auth-boundary case into agent-runner-execution-cli-session-auth.test.ts and update the relocated assertion to the unknown-provenance tombstone this PR keeps.
# Conflicts: # src/agents/cli-runner/session-history.test.ts # src/agents/cli-runner/session-history.ts # src/agents/cli-runner/types.ts # src/agents/command/attempt-execution.ts # src/config/sessions/entry-freshness.test.ts
951b4dd to
6ec4b12
Compare
…int drift
Refresh onto main and repair the two CI reds this PR owned.
The gateway compaction path now takes an `{ onCommitted }` host argument
(upstream openclaw#133260). That change updated its own native-CLI assertion but
merged textually clean over this PR's auth-tombstone test, which still
asserted the old single-argument arity.
The six cleared-binding assertions this PR converted from `toBeUndefined()`
to a `toStrictEqual` tombstone check added twelve counted lines to
agent-runner-execution-cli-sessions.test.ts, pushing it to 1004 against the
1000-line cap. Collapse them onto a shared `expectClearedAuthTombstone`
helper in the sibling test-support module, which the file's other assertion
helpers already live in. No behavior code changes.
# Conflicts: # src/agents/cli-runner/prepare.test.ts
Upstream openclaw#132185 moved bounded CLI history onto SessionManager.openBounded, so this branch's fallback tail reader lost its last caller. The barrel re-exports kept deadcode:exports satisfied, hiding that nothing — not even a test — called loadTranscriptTailWindowSync or transcriptTailOmitsBranchControlSync. Removes both functions, their private helpers, and the re-export lines. No production caller existed, so behavior is unchanged.
|
Thank you for the investigation and recovery/auth-boundary work here. The underlying recovery work is now superseded on main by #132185 and the newly merged #140294. #132185 provides the canonical-store reader. #140294 adds eligible binding-less recovery, protects both compacted and uncompacted history, and keeps durable history ownership independent of native session bindings. It covers successful account replacement followed by binding clear and subsequent recovery, rather than treating the most recently stored binding as ownership proof for older transcript content. The merged implementation preserves native bindings’ existing shape and uses separate private history provenance, so the alternative binding-tombstone implementation in this PR is no longer the implementation to land. Closing this PR as superseded, not merged. Thank you for the detailed reproductions and evidence that helped establish the problem. |
Closes #124991
What Problem This Solves
Users holding a long-running conversation on a
claude-clibackend would find the assistant had lost the entire conversation when it could not resume the native CLI session — most visibly after aborting a turn, which clears the CLI session binding by design.The recovery mechanism for exactly this case, CLI session reseed, never ran.
loadCliSessionEntriesonly read the legacy per-session JSONL transcript (<sessionsDir>/<sessionId>.jsonl). That file is only written by old single-agent installs; docs listsessions/as "Legacy single-agent session store (old installs only)". On a SQLite session store the file never exists,lstatraisesENOENT, the catch swallows it without logging, and reseed returned no history at all.The symptom is an assistant that silently forgets an entire conversation — no error, no warning, and a log line (
historyPrompt=none) indistinguishable from a session that genuinely has no history.Second problem, found in review of this PR and fixed in this revision. The auth-boundary retention below (item (b)) had a hole. Some clears run outside a turn's resolved auth and cannot name an identity — most reachably, a handled
before_agent_replysynthetic turn, which returnsclearCliSessionBindingbeforeprepareCliRunContextruns and therefore carries nocliSessionAuthIdentityat all. When such a clear met a stored binding that had also recorded no identity (a legacycliSessionIds/claudeCliSessionIdrow, or a modern binding written by the bare-id fallback),clearCliSessionhad no boundary to source from either side and erased the record outright. The next turn then read the session as never-bound,rawTranscriptReseedReasondefaulted tomissing-transcript— which is allowlisted — and the prior identity's transcript replayed into a fresh CLI session under whatever identity showed up next. Because this PR is what makes that transcript readable on SQLite, the exposure is ours.Evidence
Captured on an isolated dev gateway with a scratch home and a SQLite session store, running the code this revision pushes. Real
claude-cliturns, a realopenclaw sessions compact(so the transcript really does take the compacted branch), and a real post-compaction tail. Every arm shares the same transcript, store, session id and install; arms differ only in what the clear wrote.Decisive result — the unknown-provenance clear, before and after
Both arms start from the same auth-less stored binding and apply the same clear (unknown provenance, the shape a handled
before_agent_replysynthetic turn supplies).afteris produced by calling the productionclearCliSessionwith the productionCLI_SESSION_CLEAR_AUTH_UNKNOWNconstant against the live store;beforewrites the record shape that same call produced prior to this revision.before— the defect, reproduced on a running gateway:after— the repair, same question, same store:historyPrompt=present→none; the prompt collapses from 1504 characters to 104 (the user message alone).useResume=false session=nonein both arms confirms the CLI process really was fresh, sopresentin thebeforearm is the reseed, not a resumed session.The model's answers make the mechanism visible. Asked "what is my lucky number, my dog's name, and where does the ferry depart from?", the
beforearm returns all three including the post-compaction fact; theafterarm returns "No information about a ferry in my memory." That last canary was spoken after the compaction, so it exists only in OpenClaw's transcript store — it is precisely the fact only an OpenClaw reseed could have supplied, and precisely the one that disappears.The same A/B at the loader, under a changed profile and a changed epoch
Real
resolveCliSessionReuse+loadCliSessionReseedMessagesagainst the same persisted SQLite entry, probing the constructed history prompt for every canary planted in the conversation:An erased record reads as "never bound", so in
beforea changed identity is not even detected. Seven messages carrying every canary become zero on identical stored state, changing only what the clear wrote.The control that stops the above passing vacuously (#124991 stays fixed)
A binding that did record an identity sources its boundary from that identity even under an unknown-provenance clear, so only the identity comparison decides — reseed still works where an identity is recoverable:
The previous revision's evidence, retained verbatim
The
auth-profile/auth-epochgate added in the previous revision was captured the same way and is unchanged by this revision. Reproduced in full rather than summarised, because the 18th review cited these logs directly.Captured the same way at head
3ddc75e. Realclaude-cliturns, a realopenclaw sessions compact(so the transcript really does take the compacted branch), and a real post-compaction tail. Both arms have no resumable session id, so both run a fresh CLI process and attempt a reseed; the only difference is whether an auth identity crossing is recorded.Auth-crossing A/B at the loader
A/B at the loader, against the same persisted SQLite entry, probing for each canary planted in the conversation. The
CONTROLarm is the same-identity control that stops theGATEDarm passing vacuously:Seven messages carrying every canary become zero on identical stored state, changing only the recorded auth identity — the summary refused alongside the tail.
The same A/B at the fresh CLI process
Control — no auth crossing:
Gated —
auth-profilecrossing:historyPrompt=present→none, and the prompt collapses from 2241 characters to 145 (the user message alone).useResume=false session=nonein both arms confirms the CLI process really was fresh, sopresentin the control is the reseed doing its job rather than a resumed session.Focused tests
session-history.reseed-unknown-provenance.test.tsis new: it drives the clear through real session persistence (persistSessionUsageUpdate→ session store → re-read), with the transcript in the SQLite transcript store, and asserts on the constructed prompt rather than on a reason code. It covers the legacy-rows and bare-binding record shapes × the raw-tail and compacted branches × a changed profile, a changed epoch, and the same-identity control. With the fix reverted, 24 of its 32 cases fail and the failure message is the leak itself (expected '…' not to contain 'prior-auth raw secret'); the 8 that still pass are the #124991 narrowness controls, which is the correct signature.The producer side is pinned where it belongs, in
cli-runner.before-agent-reply-cron.test.ts: a handled synthetic turn'sagentMetareportsclearCliSessionBinding: trueand nocliSessionAuthIdentity. If that ever changes, the fixture the new suite starts from is stale and that test says so.session-history.reseed-auth-boundary.test.tskeeps its threeauth-profile/auth-epochregressions plus their control. Separate suites cover the SQLite byte budget, the branch-control probe on truncated tails, and every named tombstone-reader call site.Scope stated plainly
This gate governs what OpenClaw reseeds. In the repaired arm the model still recalled two facts from the earliest turns while not recalling the post-compaction tail; that recall does not arrive through OpenClaw (
historyPrompt=none, 104 prompt chars) but from the externalclaude-cli's own on-disk transcript store, which it keys by working directory independently of OpenClaw's session store. No change in this repo can govern that, and this proof does not claim to.What This PR Does
Four things, and nothing else:
loadCliSessionEntriesfalls back to the transcript store when the legacy file yields nothing, then runs the identical downstream projection. The file path is untouched, so legacy installs keep their exact current behavior and bounded-read protections; only the previously-empty case changes. The store read is bounded by rows and bytes and fails closed when a truncated tail is missing branch controls.Why This Change Was Made
loadCliSessionEntriesnow falls back to the transcript store vialoadTranscriptEventswhen the legacy file yields nothing, then runs the identical downstream projection (migrateSessionEntries→ drop thesessionheader →selectSessionTranscriptLeafControlledPath→projectLatestCliHistoryBoundary).The same user-visible failure also arrives by a second path, and by observed frequency it is the more common one. When a session has no stored binding at all —
resolveCliSessionReusereturns{mode: "none"}, which is whatshouldClearFailedCliSessionBindingproduces onAbortError— there is neither areusableCliSessionIdnor aninvalidatedReason, sorawTranscriptReseedReasonisundefinedandloadCliSessionReseedMessagesrefuses to reseed for lack of a reason. It now falls back tomissing-transcript, which is already inRAW_TRANSCRIPT_RESEED_ALLOWED_REASONS.Third-party field data argues for weighting this path at least as heavily as the loader repair. An outside contributor independently reproducing the bug aggregated several months of journal from a production
claude-cliinstall on the SQLite session store: 225 of 225 cold starts loggedhistoryPrompt=none, splitting 194reuse=none(86%) against 31invalidated:*(14%). The 86% bucket is this binding-less path — those turns do reach the loader, and its raw tail is then discarded for want of an eligible reason. That is their install and their measurement rather than ours, and the ratio will vary with how often a given install aborts turns or drops bindings; but on the one install where it has been counted, repairing the loader alone would leave roughly six occurrences in seven still silent.These are one fix, not two: with the loader repaired but no reason supplied, an aborted turn still reseeds nothing; with the reason supplied but the loader unrepaired, there is no data to reseed from.
Deliberate boundaries:
claudeCliInvalidatedReason. That variable also drivesreusableCliSession = {mode: "invalidate"}, so setting it would flip every fresh session into invalidate mode and inject session-drift context into ordinary new sessions.Clear-Time Auth Provenance
clearCliSessionbuilt its auth-boundary tombstone only from the outgoing binding, via a helper that returnsundefinedwhen the binding recorded neitherauthProfileIdnorauthEpoch. Such a record was deleted outright, and the legacycliSessionIds/claudeCliSessionIdrows were erased with no marker at all. The next turn therefore read the missing binding as{mode: "none"}, the default resolved it tomissing-transcript, and that reason is inRAW_TRANSCRIPT_RESEED_ALLOWED_REASONS— so the prior transcript replayed into a fresh CLI session under whatever auth happened to be current. Before this PR the same case producedundefinedand reseed was refused for want of a reason, so the widening is ours.Exposure. Not legacy-only. The gate is "did this binding record an auth identity", not "is this row legacy", so it also catches a modern binding written by the bare-id fallback
setCliSessionId→setCliSessionBinding({ sessionId }), reached fromsession-store.ts,session-usage.ts, andrun-finalize.ts. Bounded honestly: the ordinaryclaude-cliturn is safe, becauseresolveCliAuthEpochruns during prepare and the epoch lands on the binding. What remains is (a) pre-migration stored rows, (b) those three bare-id fallback branches, and (c) installs where both profile and epoch resolve empty.The fix. A binding that recorded no identity has exactly one identity anyone can honestly attribute to it: the one the clearing turn is running under.
clearCliSessionnow takes that provenance as an explicit third argument and falls back to it when the outgoing binding has none of its own. Same identity next turn → reuse resolution reports no invalidation → the session reads as unbound →missing-transcript→ reseed proceeds, which is the behavior this PR exists to deliver. Changed identity →auth-profile/auth-epoch→ reseed refused.Why not the smaller version. Making the tombstone helper always return a marker — empty when there is no identity — looks minimal and is wrong. An empty marker has
storedAuthProfileId === undefined, which never matches a run that does have an auth profile, so reuse resolution would answerauth-profileon every bare-binding clear and refuse the reseed unconditionally. That is #124991 re-introduced. The provenance argument is a discriminated union rather than an optional so no caller can drift into that shape by omission.Unknown provenance now fails closed (new in this revision). Some clears run outside a turn's resolved auth and cannot honestly attribute an identity, so
clearCliSessiontakes a discriminated provenance argument rather than an optional. Two paths reach it withunknown: the pre-turn compaction-failure repair insrc/agents/command/cli-compaction.ts, which passesCLI_SESSION_CLEAR_AUTH_UNKNOWNoutright because the credential epoch cannot be resolved outside a prepared run; and any clear routed from a run that died before prepare, viacliSessionClearAuthFromRun(undefined). The most reachable instance of the second is a handledbefore_agent_replysynthetic turn: it returnsclearCliSessionBindingfromrunCliAgentbeforeprepareCliRunContextis even imported, so itsagentMetahas nocliSessionAuthIdentityto offer.Earlier revisions of this PR kept the pre-existing erase in that case. That was wrong, and it is the defect this revision fixes: erasing the record is what lets the next turn read the session as never-bound, default to
missing-transcript, and replay the prior identity's transcript.clearCliSessionnow writes an explicit unknown-provenance tombstone instead, reuse resolution maps it to a newauth-unknownreason, and both reseed branches refuse it — the raw tail by absence fromRAW_TRANSCRIPT_RESEED_ALLOWED_REASONS, the compacted summary-plus-tail by membership inAUTH_CROSSING_RESEED_REASONS. An unattributable transcript is treated exactly as if it were known to be someone else's.Why the marker is not identity-shaped. The tombstone carries
clearedAuthProvenance: "unknown"and no identity fields, and reuse resolution checks that marker before any identity comparison. An identity-shaped tombstone would be compared against the next turn's identity and could match it — an empty one matches every install that also resolves no identity, which is exactly the match a transcript nobody can attribute must never make. It is also the mirror of the trap described above: an empty identity marker never matches a run that does have a profile, so it would answerauth-profileforever and re-introduce #124991.auth-unknownis not an identity comparison at all, which is what lets it be both unconditional and narrow.What this costs, exactly. One history reseed, on the first fresh prompt after an ambiguous clear. The next successful run writes a real binding with a session id and current auth, which replaces the tombstone — observed directly in the capture above, where each arm had to be re-armed because the live turn left a full binding behind. Native resume is unaffected: the tombstone never carried a resumable handle. The trade is one lost reseed against a path that today replays one identity's conversation to another.
Tombstone reader contract. A binding with no
sessionIdis a provenance record, not a resumable handle, so every caller asking "is there a usable CLI session" must test?.sessionIdrather than the object. That is not enforced by the return type, so the five call sites that make this decision are named in a comment above the tombstone branch insrc/config/sessions/cli-session-binding.ts, and all five were re-verified in source at this head:hasProviderOwnedSession(src/config/sessions/entry-freshness.ts), its reply-lane twin (src/auto-reply/reply/session.ts),resolveManualCompactionCliTarget(src/agents/session-runtime-compat.ts),resolveEligibleCliSessionBinding(src/gateway/cli-session-history.ts), andsrc/gateway/agent-turn/agent-handler-helpers.ts. All 20 production callers ofgetCliSessionBindingwere swept for an unguarded sixth; there is none.The Persisted Binding Contract (merge risk, stated explicitly)
This PR changes what a
cliSessionBindingsrecord is allowed to be. Before it, every record carried a nativesessionId; a cleared provider had no record. After it, a record may be a provenance-only tombstone with nosessionIdat all, in one of two shapes:{authProfileId?, authEpoch?, authEpochVersion?}auth-profile/auth-epochon a crossing, no invalidation otherwise{clearedAuthProvenance: "unknown"}auth-unknown, alwaysUpgrade behavior. Purely additive and forward-only. Nothing rewrites existing rows and no migration runs: an install that upgrades keeps every stored binding byte-for-byte, and tombstones appear only as clears happen after the upgrade.
clearedAuthProvenanceis a new optional field on an existing type persisted as JSON, so an older build reading a newer store sees an unrecognized key on a record it would have found absent anyway, andgetCliSessionBindingfalls through toundefined— exactly the pre-upgrade behavior. Downgrade therefore reopens the original bug rather than corrupting anything.The all-reader contract. Because a record can now exist without a
sessionId, every reader asking "is there a usable CLI session here" must test?.sessionIdrather than the object's truthiness. This is not enforced by the return type — deliberately, since reuse resolution and the auth-provenance readers want the tombstone precisely because it has no id — so it is documented in a comment above the tombstone branch insrc/config/sessions/cli-session-binding.ts, and any new caller has to pick a side explicitly.Readers verified at this head. All 20 production callers of
getCliSessionBindingwere swept, plus every production site that readsentry.cliSessionBindingsdirectly. The five that make the "is there a usable session" decision all gate on?.sessionId:hasProviderOwnedSession—src/config/sessions/entry-freshness.tssrc/auto-reply/reply/session.tsresolveManualCompactionCliTarget—src/agents/session-runtime-compat.ts(all three ownership tests, including the post-normalization lookup)resolveEligibleCliSessionBinding—src/gateway/cli-session-history.tssrc/gateway/agent-turn/agent-handler-helpers.tsThe deliberate exceptions, re-checked rather than assumed:
resolveCliSessionReuse(src/agents/cli-session.ts) andhasCliSessionReuseMetadata(src/agents/cli-runner/run-executor.ts) accept tombstones by design;stored-model-override.tsalready tests?.sessionId !== undefined;doctor-session-state-providers.tsis presence-based repair tooling that tolerates any record shape;commands-export-session.tsinspectsreseedReceipt, which a tombstone never carries;session-accessor.sqlite-message-cut.tsandcron/isolated-agent/run-session-state.tsclear the map wholesale. There is no unguarded caller.The
unknownshape adds no new reader risk over the shape this PR already introduced. It is the same "record with nosessionId" the identity tombstone already is, plus one field that onlyresolveCliSessionReuseandgetCliSessionBindingread. Every gate above keys on the absence ofsessionId, which both shapes share.The Compacted-Branch Auth Gate (new in this revision)
Previous revisions of this PR carried a disclosure here:
loadCliSessionReseedMessagesconsultedRAW_TRANSCRIPT_RESEED_ALLOWED_REASONSonly insideloadRawTail, so when the transcript contained a compaction summary the function returned summary-plus-tail without consulting the reseed reason at all — for any reason, includingauth-profileandauth-epoch. That structure is pre-existing upstream behavior and identical onmain; what this PR changed was its reachability on SQLite installs, since the loader previously returned nothing there.This revision closes it rather than disclosing it.
loadCliSessionReseedMessagesnow refuses up front, before the load, when the reseed reason is an auth crossing:AUTH_CROSSING_RESEED_REASONS= {auth-profile,auth-epoch,auth-unknown} insrc/agents/cli-runner/session-history.ts. The third is new in this revision and is the fail-closed member: not "this turn resolved a different identity" but "nobody can say which identity this transcript belongs to".loadCliSessionReseedMessages, so a crossing does not even read the transcript store.Why conservative. Blocking the summary as well as the tail is the stricter of the two readings. It is chosen deliberately: the alternative (carry the summary, drop the tail) requires asserting that a summary of prior-auth content is itself safe under a new identity, which is exactly the claim nobody upstream has ruled on. Refusing both cannot be wrong in the direction that leaks.
Why a separate reason set rather than reusing the raw allowlist. "Absent from
RAW_TRANSCRIPT_RESEED_ALLOWED_REASONS" is the wrong test to reuse here: a reason may be kept off that allowlist for grounds that have nothing to do with auth, and the compacted branch would then refuse content it has no cause to refuse. The three auth reasons are therefore named explicitly. Both memberships matter independently — a reason kept off the raw allowlist but absent here would still leak through the compacted branch, which is whyauth-unknownis added to both.Relationship to #127677. That issue asks upstream to rule on this branch's allowlist bypass in general, and deliberately takes no position on which way it should go. It remains the right place for the general ruling, and this PR does not pre-empt it: what changed is that this PR now closes its own instance conservatively instead of shipping a reachable bypass and waiting. If upstream rules the permissive way, this gate is a small, self-contained thing to relax.
Covered by three regression tests plus a control (
session-history.reseed-auth-boundary.test.ts):auth-profilecrossing returns nothing,auth-epochcrossing returns nothing, and — the control that stops the other two passing vacuously — a no-crossing run still reseeds summary and post-compaction tail.Why the Production Diff Is +938/-78
A reasonable objection to a bug fix this size is that it has accreted. It has been audited for that twice, and the answer is that the durable state boundary is the repair, not scaffolding around it.
The one-line version of #124991 — make the loader read the transcript store — is about 20 lines and is genuinely present here as item (a). It is also, on its own, wrong to ship. Making a transcript readable where it previously was not changes who can be shown it, and everything else in this diff is the boundary that makes that safe:
clearCliSessionis the single owner, so the invariant lives there and the provenance argument threads to its callersRemovals are 78 lines and are almost entirely the code these replace.
What is deliberately not here: no loader refactor onto the session accessor (it would drop the bounded-read and truncation handling), no reseed-semantics changes beyond the reasons named above, no drive-by cleanups. A scope audit in the previous revision traced all 30 production hunks against (a)/(b)/(c) and cut the three that did not trace — a type-assertion tidy in a pre-existing function and dead test scaffolding. This revision adds only (d) and its tests.
Tests are +2274 against +938 of production. That ratio is the point rather than an overrun: the failure mode here is silent, so the regression suites assert on the constructed prompt and on stored state, and each carries the control that keeps it from passing vacuously.
User Impact
Conversations survive a CLI session that cannot be resumed. Aborting a turn, or any other event that drops the session binding, no longer silently erases the conversation on the next message. This affects any install on the SQLite session store, which is every install that is not a legacy single-agent one. Legacy installs are unaffected.
Housekeeping in This Revision
mainas a single commit (the branch was ~500 commits behind). One semantic conflict, inattempt-execution.cli.test.ts: upstream narrowedshouldClearFailedCliSessionBindingtosession_expired, so auth failovers now preserve the binding. Resolved in upstream's favour — our older "clears on auth failover" expectation was obsolete.coerceHistoryTexttype-assertion tidy in a pre-existing function (plus its assertion-safety baseline line), and deadsetCliSessionIdMocktest scaffolding that was declared but never asserted anywhere. The diff is now 47 files, +3212/-391 (production 27 files, +938/-78); the growth over the previous revision's 44 files / +2707/-379 is item (d) and its regression suite.getCliSessionBindingdesign with a dedicatedgetCliSessionAuthBoundaryreader, which would delete the five?.sessionIdgate sites.auth-unknowninsession-history.ts,clearedAuthProvenanceonCliSessionBindingand its reader, the tombstone writer and reuse mapping incli-session.ts, one new regression suite, and the doc comment that previously described the erase as intended behaviour. Six existing tests asserted that erase; they now assert the tombstone, and each carries a comment saying why. All gates green (tsgo:core,lint:core,format:check,check:max-lines-ratchet,check:architecture,deadcode:exports,lint:no-widen-then-assert,check:assertion-safety --base upstream/main).