Skip to content

fix(cli): conversation history is lost when a CLI session cannot be resumed - #125002

Closed
alfredjbclaw wants to merge 13 commits into
openclaw:mainfrom
alfredjbclaw:fix/cli-reseed-sqlite-store
Closed

alfredjbclaw wants to merge 13 commits into
openclaw:mainfrom
alfredjbclaw:fix/cli-reseed-sqlite-store

Conversation

@alfredjbclaw

@alfredjbclaw alfredjbclaw commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #124991

What Problem This Solves

Users holding a long-running conversation on a claude-cli backend 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. loadCliSessionEntries only read the legacy per-session JSONL transcript (<sessionsDir>/<sessionId>.jsonl). That file is only written by old single-agent installs; docs list sessions/ as "Legacy single-agent session store (old installs only)". On a SQLite session store the file never exists, lstat raises ENOENT, 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_reply synthetic turn, which returns clearCliSessionBinding before prepareCliRunContext runs and therefore carries no cliSessionAuthIdentity at all. When such a clear met a stored binding that had also recorded no identity (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 then 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. 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-cli turns, a real openclaw 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_reply synthetic turn supplies). after is produced by calling the production clearCliSession with the production CLI_SESSION_CLEAR_AUTH_UNKNOWN constant against the live store; before writes the record shape that same call produced prior to this revision.

before — the defect, reproduced on a running gateway:

cli exec: provider=claude-cli model=claude-sonnet-4-6 promptChars=1504 trigger=user \
  useResume=false session=none resumeSession=none reuse=none historyPrompt=present

after — the repair, same question, same store:

cli session reset: provider=claude-cli reason=auth-unknown
cli session history refused across auth boundary: reason=auth-unknown session=<redacted>
cli exec: provider=claude-cli model=claude-sonnet-4-6 promptChars=104 trigger=user \
  useResume=false session=none resumeSession=none reuse=invalidated:auth-unknown historyPrompt=none

historyPrompt=present → none; the prompt collapses from 1504 characters to 104 (the user message alone). useResume=false session=none in both arms confirms the CLI process really was fresh, so present in the before arm 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 before arm returns all three including the post-compaction fact; the after arm 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 + loadCliSessionReseedMessages against the same persisted SQLite entry, probing the constructed history prompt for every canary planted in the conversation:

######## before — record erased ########
stored binding: undefined
  same identity      reuse {"mode":"none"}  reason missing-transcript  messages 7  chars 2038  all canaries true
  CHANGED profile    reuse {"mode":"none"}  reason missing-transcript  messages 7  chars 2038  all canaries true
  CHANGED epoch      reuse {"mode":"none"}  reason missing-transcript  messages 7  chars 2038  all canaries true

######## after — unknown-provenance tombstone ########
stored binding: {"clearedAuthProvenance":"unknown"}
  same identity      reuse {"mode":"invalidate","invalidatedReason":"auth-unknown"}  messages 0  chars 0  all canaries false
  CHANGED profile    reuse {"mode":"invalidate","invalidatedReason":"auth-unknown"}  messages 0  chars 0  all canaries false
  CHANGED epoch      reuse {"mode":"invalidate","invalidatedReason":"auth-unknown"}  messages 0  chars 0  all canaries false

An erased record reads as "never bound", so in before a 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:

######## control — identity WAS recorded ########
stored binding: {"authEpochVersion":7}
  same identity      reuse {"mode":"none"}  reason missing-transcript  messages 7  chars 2038  all canaries true
  CHANGED profile    reuse {"mode":"invalidate","invalidatedReason":"auth-profile"}  messages 0  chars 0
  CHANGED epoch      reuse {"mode":"invalidate","invalidatedReason":"auth-epoch"}    messages 0  chars 0

The previous revision's evidence, retained verbatim

The auth-profile / auth-epoch gate 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. Real claude-cli turns, a real openclaw 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 CONTROL arm is the same-identity control that stops the GATED arm passing vacuously:

######## CONTROL (no auth crossing) ########
reuse: {"mode":"none"}          reseed reason: missing-transcript
reseed messages count: 7
  contains <pre-compaction canaries>: true    contains <post-compaction tail canary>: true

######## GATED (auth-profile crossing) ########
reuse: {"mode":"invalidate","invalidatedReason":"auth-profile"}
reseed reason: auth-profile
cli session history refused across auth boundary: reason=auth-profile
reseed messages count: 0
  contains <pre-compaction canaries>: false   contains <post-compaction tail canary>: false

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:

cli exec: provider=claude-cli model=claude-sonnet-4-6 promptChars=2241 trigger=user \
  useResume=false session=none resumeSession=none reuse=none historyPrompt=present

Gated — auth-profile crossing:

cli session history refused across auth boundary: reason=auth-profile session=<redacted>
cli exec: provider=claude-cli model=claude-sonnet-4-6 promptChars=145 trigger=user \
  useResume=false session=none resumeSession=none reuse=invalidated:auth-profile historyPrompt=none

historyPrompt=present → none, and the prompt collapses from 2241 characters to 145 (the user message alone). useResume=false session=none in both arms confirms the CLI process really was fresh, so present in the control is the reseed doing its job rather than a resumed session.

Focused tests

session-history.reseed-unknown-provenance.test.ts is 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's agentMeta reports clearCliSessionBinding: true and no cliSessionAuthIdentity. If that ever changes, the fixture the new suite starts from is stale and that test says so.

session-history.reseed-auth-boundary.test.ts keeps its three auth-profile / auth-epoch regressions 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 external claude-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:

  1. (a) The SQLite fallback that closes [Bug]: CLI session reseed is inert on SQLite session stores — loadCliSessionEntries reads the legacy per-session JSONL #124991. loadCliSessionEntries falls 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.
  2. (b) Auth-provenance retention after a cleared binding. A cleared binding now leaves an auth-boundary tombstone recording the identity the clearing turn ran under, instead of a markerless delete.
  3. (c) A new auth gate on the compacted reseed branch — see below.
  4. (d) A fail-closed tombstone for clears that cannot name any identity (new in this revision) — the hole in (b), see below.

Why This Change Was Made

loadCliSessionEntries now falls back to the transcript store via loadTranscriptEvents when the legacy file yields nothing, then runs the identical downstream projection (migrateSessionEntries → drop the session header → 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 — resolveCliSessionReuse returns {mode: "none"}, which is what shouldClearFailedCliSessionBinding produces on AbortError — there is neither a reusableCliSessionId nor an invalidatedReason, so rawTranscriptReseedReason is undefined and loadCliSessionReseedMessages refuses to reseed for lack of a reason. It now falls back to missing-transcript, which is already in RAW_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-cli install on the SQLite session store: 225 of 225 cold starts logged historyPrompt=none, splitting 194 reuse=none (86%) against 31 invalidated:* (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:

  • Not routed through claudeCliInvalidatedReason. That variable also drives reusableCliSession = {mode: "invalidate"}, so setting it would flip every fresh session into invalidate mode and inject session-drift context into ordinary new sessions.
  • Not a refactor of the loader onto the session accessor. Replacing the file read outright would drop the bounded-read and truncation-safety handling, so this stays a targeted fallback.
  • ENOENT still not logged. The issue suggested surfacing it, but with the fallback working it would fire on every genuinely new session.

Clear-Time Auth Provenance

clearCliSession built its auth-boundary tombstone only from the outgoing binding, via a helper that returns undefined when the binding recorded neither authProfileId nor authEpoch. Such a record was deleted outright, and the legacy cliSessionIds / claudeCliSessionId rows were erased with no marker at all. The next turn therefore read the missing binding as {mode: "none"}, the default resolved it to missing-transcript, and that reason is in RAW_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 produced undefined and 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 from session-store.ts, session-usage.ts, and run-finalize.ts. Bounded honestly: the ordinary claude-cli turn is safe, because resolveCliAuthEpoch runs 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. clearCliSession now 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 answer auth-profile on 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 clearCliSession takes a discriminated provenance argument rather than an optional. Two paths reach it with unknown: the pre-turn compaction-failure repair in src/agents/command/cli-compaction.ts, which passes CLI_SESSION_CLEAR_AUTH_UNKNOWN outright because the credential epoch cannot be resolved outside a prepared run; and any clear routed from a run that died before prepare, via cliSessionClearAuthFromRun(undefined). The most reachable instance of the second is a handled before_agent_reply synthetic turn: it returns clearCliSessionBinding from runCliAgent before prepareCliRunContext is even imported, so its agentMeta has no cliSessionAuthIdentity to 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. clearCliSession now writes an explicit unknown-provenance tombstone instead, reuse resolution maps it to a new auth-unknown reason, and both reseed branches refuse it — the raw tail by absence from RAW_TRANSCRIPT_RESEED_ALLOWED_REASONS, the compacted summary-plus-tail by membership in AUTH_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 answer auth-profile forever and re-introduce #124991. auth-unknown is 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 sessionId is a provenance record, not a resumable handle, so every caller asking "is there a usable CLI session" must test ?.sessionId rather 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 in src/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), and src/gateway/agent-turn/agent-handler-helpers.ts. All 20 production callers of getCliSessionBinding were swept for an unguarded sixth; there is none.

The Persisted Binding Contract (merge risk, stated explicitly)

This PR changes what a cliSessionBindings record is allowed to be. Before it, every record carried a native sessionId; a cleared provider had no record. After it, a record may be a provenance-only tombstone with no sessionId at all, in one of two shapes:

shape written when resolves as
{authProfileId?, authEpoch?, authEpochVersion?} an identity could be sourced — from the outgoing binding, or from the clearing turn auth-profile / auth-epoch on a crossing, no invalidation otherwise
{clearedAuthProvenance: "unknown"} no identity could be sourced from either side auth-unknown, always

Upgrade 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. clearedAuthProvenance is 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, and getCliSessionBinding falls through to undefined — 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 ?.sessionId rather 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 in src/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 getCliSessionBinding were swept, plus every production site that reads entry.cliSessionBindings directly. The five that make the "is there a usable session" decision all gate on ?.sessionId:

  • hasProviderOwnedSession — src/config/sessions/entry-freshness.ts
  • its reply-lane twin — src/auto-reply/reply/session.ts
  • resolveManualCompactionCliTarget — src/agents/session-runtime-compat.ts (all three ownership tests, including the post-normalization lookup)
  • resolveEligibleCliSessionBinding — src/gateway/cli-session-history.ts
  • src/gateway/agent-turn/agent-handler-helpers.ts

The deliberate exceptions, re-checked rather than assumed: resolveCliSessionReuse (src/agents/cli-session.ts) and hasCliSessionReuseMetadata (src/agents/cli-runner/run-executor.ts) accept tombstones by design; stored-model-override.ts already tests ?.sessionId !== undefined; doctor-session-state-providers.ts is presence-based repair tooling that tolerates any record shape; commands-export-session.ts inspects reseedReceipt, which a tombstone never carries; session-accessor.sqlite-message-cut.ts and cron/isolated-agent/run-session-state.ts clear the map wholesale. There is no unguarded caller.

The unknown shape adds no new reader risk over the shape this PR already introduced. It is the same "record with no sessionId" the identity tombstone already is, plus one field that only resolveCliSessionReuse and getCliSessionBinding read. Every gate above keys on the absence of sessionId, which both shapes share.

The Compacted-Branch Auth Gate (new in this revision)

Previous revisions of this PR carried a disclosure here: loadCliSessionReseedMessages consulted RAW_TRANSCRIPT_RESEED_ALLOWED_REASONS only inside loadRawTail, so when the transcript contained a compaction summary the function returned summary-plus-tail without consulting the reseed reason at all — for any reason, including auth-profile and auth-epoch. That structure is pre-existing upstream behavior and identical on main; 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. loadCliSessionReseedMessages now refuses up front, before the load, when the reseed reason is an auth crossing:

  • AUTH_CROSSING_RESEED_REASONS = { auth-profile, auth-epoch, auth-unknown } in src/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".
  • The check is the first statement of loadCliSessionReseedMessages, so a crossing does not even read the transcript store.
  • It blocks both the post-compaction tail and the summary. A summary is transcript-derived too — it is written from the turns the previous identity ran — so the clean line is that nothing transcript-derived crosses an auth boundary.

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 why auth-unknown is 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-profile crossing returns nothing, auth-epoch crossing 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:

what roughly why it is load-bearing
(a) SQLite fallback + its bounded read ~180 the fix itself, plus the byte ceiling and the branch-control guard that keep a bounded tail from projecting a severed branch
(b) auth provenance through the clear ~230 a transcript that is now readable must remember which identity wrote it, across every clear path; clearCliSession is the single owner, so the invariant lives there and the provenance argument threads to its callers
(c) compacted-branch auth gate ~40 the summary is transcript-derived too, and returned by a different code path than the raw tail
(d) unknown-provenance tombstone ~100 the case where nobody can name the identity; without it (b) has a hole that this PR itself makes reachable
doc comments on the above ~230 four review cycles on this PR were spent on a comment that had drifted from the code; the contracts are now written down where the next reader will look
type + reader plumbing ~160 one new optional field, its reader, and the reuse-resolution mapping

Removals 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

  • Rebased onto current main as a single commit (the branch was ~500 commits behind). One semantic conflict, in attempt-execution.cli.test.ts: upstream narrowed shouldClearFailedCliSessionBinding to session_expired, so auth failovers now preserve the binding. Resolved in upstream's favour — our older "clears on auth failover" expectation was obsolete.
  • Scope audit. Every production hunk was re-gated against (a)/(b)/(c) above. 27 of 30 traced through and were kept; three did not and were cut: a coerceHistoryText type-assertion tidy in a pre-existing function (plus its assertion-safety baseline line), and dead setCliSessionIdMock test 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.
  • One candidate follow-up recorded but not taken here, because it swaps one reviewed design for another rather than removing accretion: replacing the tombstone-through-getCliSessionBinding design with a dedicated getCliSessionAuthBoundary reader, which would delete the five ?.sessionId gate sites.
  • This revision adds item (d) and nothing else: auth-unknown in session-history.ts, clearedAuthProvenance on CliSessionBinding and its reader, the tombstone writer and reuse mapping in cli-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).

@clawsweeper

clawsweeper Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Aug 17, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 17, 2026
@clawsweeper

clawsweeper Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 1, 2026, 8:30 AM ET / 12:30 UTC.

ClawSweeper review

What this changes

The 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 provenance

Possible 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
Reviewed head: c563d7bf4e6a9f530ac44f3c1e111be3f0ca66e7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The PR has useful live evidence for the original recovery path, but two P1 blockers leave the remaining auth-boundary change unsafe to merge.
Proof confidence 🦐 gold shrimp (3/6) Needs stronger real behavior proof before merge: Authority-chain proof required: supplied terminal evidence convincingly shows SQLite reseed and the immediate unknown-provenance refusal, but it does not exercise the introduced unknown clear → successful fresh rebind → later clear path that reaches the provider prompt with retained earlier history. Post a redacted after-fix trace for that allowed/forbidden sequence after repairing it. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🧂 unranked krab (1/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Authority-chain proof required: supplied terminal evidence convincingly shows SQLite reseed and the immediate unknown-provenance refusal, but it does not exercise the introduced unknown clear → successful fresh rebind → later clear path that reaches the provider prompt with retained earlier history. Post a redacted after-fix trace for that allowed/forbidden sequence after repairing it. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Introduced all-history auth gate: The PR adds an early return that rejects compacted summaries and post-compaction messages as well as raw history for auth-profile, auth-epoch, and unknown-provenance reasons.
Current contract is raw-only: Current main documents normal compacted SQLite reseed while limiting the auth restriction specifically to raw transcript history.
Current main implements the documented split: The current loader checks the raw-reseed allowlist only when there is no compaction summary; its compacted branch returns the summary and tail.
Findings 2 actionable findings [P1] Keep compacted reseed within the approved auth policy
[P1] Preserve unknown-provenance quarantine after a fresh rebind
Security Needs attention Unknown provenance is downgraded after a fresh rebind: The binding-level tombstone is overwritten by the current-auth session binding without a durable transcript boundary; a subsequent clear makes old SQLite history reseedable again.

How this fits together

When 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]
Loading

Decision needed

Question Recommendation
Should an identity-unattributable transcript remain durably quarantined across a successful fresh rebind, while known profile or epoch changes keep the documented raw-only reseed restriction? Separate known and unknown boundaries: Preserve the documented raw-only behavior for known auth changes, but make unknown provenance durable at the transcript boundary until an explicit reset or migration resolves it.

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

  • Add real behavior proof - Needs stronger real behavior proof before merge: Authority-chain proof required: supplied terminal evidence convincingly shows SQLite reseed and the immediate unknown-provenance refusal, but it does not exercise the introduced unknown clear → successful fresh rebind → later clear path that reaches the provider prompt with retained earlier history. Post a redacted after-fix trace for that allowed/forbidden sequence after repairing it. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Keep compacted reseed within the approved auth policy (P1) - This new early return rejects a compaction summary and its post-compaction tail whenever auth changes. Current docs and main restrict only raw transcript history, so this silently removes established compacted recovery before the open policy question in Compacted reseed path returns the post-compaction tail verbatim without consulting the raw-transcript reseed allowlist — intended? #127677 is resolved.
  • Preserve unknown-provenance quarantine after a fresh rebind (P1) - The tombstone blocks one fresh prompt, but a successful run overwrites it with current auth while the earlier SQLite transcript remains intact. A later clear then defaults to missing-transcript and can reseed that prior content; retain or cut provenance at the durable transcript owner and cover unknown clear → successful rebind → later clear. This was visible on the earlier reviewed head but is raised late.
  • Resolve security concern: Unknown provenance is downgraded after a fresh rebind - The binding-level tombstone is overwritten by the current-auth session binding without a durable transcript boundary; a subsequent clear makes old SQLite history reseedable again.
  • Resolve merge risk (P1) - A successful fresh run replaces an unknown-provenance tombstone without recording or cutting the older durable transcript, so a later clear can reseed prior unknown-auth content into the current-auth provider session.
  • Resolve merge risk (P1) - The blanket compacted-history refusal changes established recovery behavior for auth-profile and auth-epoch transitions even though the published contract limits that restriction to raw transcript history.
  • Resolve merge risk (P1) - The PR retains substantial new session-state machinery after the central SQLite recovery was independently shipped, increasing the chance that an unresolved policy change lands as an incidental compatibility change.
  • Complete next step (P2) - A maintainer must set the durable transcript-isolation and compacted-history policy before a safe focused repair can be defined; the central SQLite recovery is already shipped.
  • Improve patch quality - Repair the durable unknown-provenance state transition and prove that a later failure cannot reseed the earlier transcript into the rebound provider session.
  • Improve patch quality - Obtain and apply a maintainer decision on whether known auth changes affect only raw reseed or all compacted history.

Findings

  • [P1] Keep compacted reseed within the approved auth policy — src/agents/cli-runner/session-history.ts:429-443
  • [P1] Preserve unknown-provenance quarantine after a fresh rebind — src/agents/cli-session.ts:256-263
  • [high] Unknown provenance is downgraded after a fresh rebind — src/agents/cli-session.ts:261
Agent review details

Security

Needs 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 surface

Source +519, Tests +1792, Other 0. Total +2311 across 46 files.

View PR surface stats
Area Files Added Removed Net
Source 25 601 82 +519
Tests 20 1824 32 +1792
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 46 2426 115 +2311

Review metrics

Metric Value Why it matters
Production versus test delta production +604/-82, tests and test support +1,821/-32, safety baseline +1/-1 This bug-fix branch has substantial positive production growth although the primary canonical-store repair is already shipped; the remaining state-machine surface needs a clear policy and isolation justification.

Stored data model

Persistent data-model change detected: serialized state: src/config/sessions/session-accessor.sqlite-read.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Repair durable unknown-provenance quarantine (recommended)
    Prevent a successful fresh binding from allowing a later failure to replay pre-boundary transcript content, and add the full clear–rebind–clear regression before merge.
  2. Resolve compacted-history policy explicitly
    Either remove the all-history auth gate to preserve the documented raw-only contract or approve the broader restriction with aligned product documentation.
  3. Replace the remaining branch work
    Keep the shipped canonical SQLite recovery and pause this branch if its policy and durable-state redesign cannot be narrowed safely.

Technical review

Best 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 missing-transcript and reload the retained SQLite branch. The supplied live trace covers the first refusal, not this later rebind sequence.

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:

  • [P1] Keep compacted reseed within the approved auth policy — src/agents/cli-runner/session-history.ts:429-443
    This new early return rejects a compaction summary and its post-compaction tail whenever auth changes. Current docs and main restrict only raw transcript history, so this silently removes established compacted recovery before the open policy question in Compacted reseed path returns the post-compaction tail verbatim without consulting the raw-transcript reseed allowlist — intended? #127677 is resolved.
    Confidence: 0.98
  • [P1] Preserve unknown-provenance quarantine after a fresh rebind — src/agents/cli-session.ts:256-263
    The tombstone blocks one fresh prompt, but a successful run overwrites it with current auth while the earlier SQLite transcript remains intact. A later clear then defaults to missing-transcript and can reseed that prior content; retain or cut provenance at the durable transcript owner and cover unknown clear → successful rebind → later clear. This was visible on the earlier reviewed head but is raised late.
    Confidence: 0.96
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 570815775a2a.

Labels

Label justifications:

  • P1: The branch can expose prior conversation content to a later CLI session after an unknown-provenance boundary and ordinary subsequent failure.
  • merge-risk: 🚨 compatibility: It changes established compacted-session recovery across profile and credential-epoch changes.
  • merge-risk: 🚨 session-state: It changes the persisted CLI binding contract and how durable transcript history is selected after clears and rebinds.
  • merge-risk: 🚨 security-boundary: Unknown provenance can be downgraded after a successful rebind, allowing earlier transcript content to reach a later authentication context.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦐 gold shrimp and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Authority-chain proof required: supplied terminal evidence convincingly shows SQLite reseed and the immediate unknown-provenance refusal, but it does not exercise the introduced unknown clear → successful fresh rebind → later clear path that reaches the provider prompt with retained earlier history. Post a redacted after-fix trace for that allowed/forbidden sequence after repairing it. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

Security concerns:

  • [high] Unknown provenance is downgraded after a fresh rebind — src/agents/cli-session.ts:261
    The binding-level tombstone is overwritten by the current-auth session binding without a durable transcript boundary; a subsequent clear makes old SQLite history reseedable again.
    Confidence: 0.96

What I checked:

Likely related people:

  • hcl: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (22 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-24T13:20:09.317Z sha 4f327980886652a801f9dcf62968cefafa35309d :: needs real behavior proof before merge. :: [P1] Gate compacted transcript tails at the auth boundary
  • reviewed 2026-08-26T03:43:56.447Z sha 3ddc75e :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-26T04:22:35.553Z sha 3ddc75e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-26T05:33:45.127Z sha 92d0cc8 :: needs real behavior proof before merge. :: [P1] Preserve a no-reseed marker for synthetic clears
  • reviewed 2026-08-26T09:13:33.262Z sha 51a8f13 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-26T09:33:19.141Z sha e4428ab :: needs real behavior proof before merge. :: [P1] Keep unknown-provenance transcript quarantined after rebind
  • reviewed 2026-08-28T02:20:15.134Z sha d92ef25 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-01T11:52:46.407Z sha ba4fdb4 :: found issues before merge. :: [P1] Keep compacted reseed within the approved auth policy

@alfredjbclaw
alfredjbclaw force-pushed the fix/cli-reseed-sqlite-store branch from 06ef40e to e48e24c Compare August 19, 2026 01:21
@alfredjbclaw

Copy link
Copy Markdown
Contributor Author

Both P1 findings are addressed in e48e24c2618 (branch rebased onto current main).

[P1] Bound the SQLite transcript read. Reused the existing loadTranscriptTailEventsSync(scope, maxEvents) bound rather than introducing a new constant or growing the accessor signature — capped at MAX_CLI_SESSION_HISTORY_MESSAGES, newest-first tail. Worth flagging: that helper had zero production callers and was missing the current-turn read fence that loadTranscriptEventsSync applies, so swapping readers naively would have leaked the just-admitted user row into the reseed prompt and duplicated <next_user_message>. It is now fenced inside the same deferred transaction. The legacy byte-bounded file loader is untouched.

[P1] Preserve auth invalidation when a binding is cleared. Implemented as refusing the clear when the clear path is auth-driven — mayClearCliSessionBindingOnSettlement in cli-run-settlement.ts, the lifecycle owner of the clear.

Persisting the invalidation reason instead was considered and rejected: clearCliSession hard-deletes the binding, and getCliSessionBinding ignores bindings without a non-empty sessionId, so preserving the reason would require a new persisted SessionEntry field — a state contract change that should not ride along on this fix. Keeping the stale auth-invalidated binding is safe: reuse resolution re-invalidates it every turn, and a flushed run overwrites it. Only the buildCliRunResult site (the one reachable from an auth invalidation) changed; the other two clear sites are untouched, and no existing exclusion is weakened.

Also fixed a red gate this PR introduced. Base commit 7a498d5ad2a pushed session-history.test.ts to 1042 counted lines against a 1000 limit with no baseline entry, so lint:core was already failing. Split the pure prompt-rendering block into session-history.prompt.test.ts rather than adding a suppression.

Validation: 19 tests pass in session-history.test.ts, plus the new settlement coverage, typecheck, formatter, and lint:core (now green).

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.

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. label Aug 19, 2026
@alfredjbclaw

Copy link
Copy Markdown
Contributor Author

Real-behavior proof: abort → fresh CLI run receives prior context (SQLite session store)

Captured on a gateway built from this branch (2026.8.1, head 61db221), running an isolated
profile on a SQLite session store with the claude-cli backend. Paths, session ids, and
host details are redacted.

1. Turn one plants a token

$ openclaw agent --session-key "proof:reseed" -m "Remember this token exactly: RESEED-CANARY-7741. Reply with just: stored."
stored.

It is persisted to the SQLite transcript store, not to a legacy JSONL file:

sqlite> select seq, substr(event_json,1,120) from transcript_events order by seq;
0|{"type":"session","version":3,"id":"<redacted-session-id>", ...}
1|{"type":"message", ... "message":{"role":"user","content":"Remember this token exactly: RESEED-CANARY-7741 ...
2|{"type":"message", ... "message":{"role":"assistant", ...

The CLI session binding exists at this point:

claudeCliSessionId  = "<redacted-cli-session-id>"
cliSessionIds       = {"claude-cli": "<redacted-cli-session-id>"}
cliSessionBindings  = {"claude-cli": {"sessionId": "...", "resumeCheckpointId": "...", "authEpoch": "..."}}

2. A turn is aborted

A long generation was started in the TUI and interrupted with Esc — the product's own abort
path, not a process kill. Killing the client does not reproduce this; the gateway keeps
running the turn.

The binding is gone afterwards:

claudeCliSessionId         = null
cliSessionIds              = null
cliSessionBindings         = {}          (no keys)
claudeCliInvalidatedReason = null

This is the state the bug report describes: no reusable session id, and no invalidation reason
either.

3. The next turn still receives the conversation

$ openclaw agent --session-key "proof:reseed" -m "What was the exact token I asked you to remember earlier? Reply with only the token."
RESEED-CANARY-7741

4. Why this exercises the fix

The gateway's own backend log shows how each turn was dispatched:

23:38:47 cli exec: ... promptChars=537   trigger=user useResume=false session=none    reuse=none                          historyPrompt=present
23:40:06 cli exec: ... promptChars=105   trigger=user useResume=true  session=present reuse=reusable                      historyPrompt=present
          <- long generation aborted with Esc here ->
23:42:30 cli exec: ... promptChars=13085 trigger=user useResume=false session=none    reuse=invalidated:message-policy    historyPrompt=present
23:43:05 cli exec: ... promptChars=13527 trigger=user useResume=false session=none    reuse=none                          historyPrompt=present
23:43:09 RESEED-CANARY-7741

The final turn ran with useResume=false, session=none, resumeSession=none, reuse=none —
no native resume and no session binding to fall back on — and still carried
historyPrompt=present at 13527 prompt characters. The only possible source for that history is
the transcript store read this PR adds.

On current main that read returns nothing on a SQLite session store (lstat raises ENOENT
for the legacy per-session JSONL file and the error is swallowed), so historyPrompt would be
absent on that final line and the model could not have answered. The bounded read added here is
what supplies it, and the settlement guard is what keeps the cleared binding from silently
re-enabling raw-transcript reseed across an auth invalidation.

@alfredjbclaw
alfredjbclaw force-pushed the fix/cli-reseed-sqlite-store branch from 61db221 to e081833 Compare August 19, 2026 03:54
@alfredjbclaw

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (the PR was BEHIND) and addressed the remaining P1 in e081833aff1.

[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 leaf control rows sit above the cut, selectSessionTranscriptLeafControlledPath returns undefined and the old ?? sessionEntries fallback projected the tail flat, feeding every retained row into the reseed prompt including rows on abandoned branches.

The fix is not simply refusing when controls are absent. A tail with no leaf rows is genuinely ambiguous: an ordinary linear conversation is indistinguishable from a severed branch history, and refusing both would silently drop reseed for the common case — two existing tests caught exactly that when I tried it.

So the ambiguity is resolved at the source instead. transcriptTailOmitsBranchControlSync runs a bounded existence check against the store: it takes the same fenced tail window, and only if the window is full (i.e. the read was actually truncated) does it look for a single leaf row below the cutoff seq. Linear transcripts still project flat; only the severed case is refused, with a log line rather than silent truncation.

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 session-history.test.ts (including a new skips transcript-store tails when branch controls sit above the bound), tsgo:core, format:check, lint:no-widen-then-assert, deadcode:exports, and the assertion-safety ratchet all pass.

The real-behavior capture you asked for is in the comment above.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Aug 19, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Aug 19, 2026
@alfredjbclaw

Copy link
Copy Markdown
Contributor Author

Fixed in bedc42c0ff3.

Both provider-owned-session predicates now require a live session id:

  • src/config/sessions/entry-freshness.ts — hasProviderOwnedSession
  • src/auto-reply/reply/session.ts — the duplicate reply-lane helper

Regression coverage in entry-freshness.test.ts asserts a cleared auth-boundary tombstone reads as unowned while a live binding still reads as owned.

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 resetPolicy.configured !== true && hasProviderOwnedSession(entry), and configured === false implies mode === "none" (DEFAULT_RESET_MODE, reset-policy.ts) — under which evaluateSessionFreshness reports every entry fresh anyway. So when the predicate is reachable there is no idle or daily expiry for a tombstone to suppress.

What the bad predicate actually suppressed is narrower: the short circuit skips evaluateSessionFreshness entirely, including its updatedAt === 0 pending-reset marker that older releases persisted and the function honors "even when automatic resets are disabled". A cleared session has no claim to that suppression, so the fix is still right — it just isn't a default-expiry break.

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 updatedAt, so the 0 marker isn't constructible through upsertSessionEntryCore to test end-to-end.

Gates on the new head: tsgo:core, lint:core, format:check, check:max-lines-ratchet, check:architecture, deadcode:exports, lint:no-widen-then-assert all pass; 598 tests across the 41 files covering the named lifecycle consumers (reply setup, command sessions, gateway prepare/patch, isolated cron) pass.

@clawsweeper clawsweeper Bot removed the rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. label Aug 20, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 26, 2026
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.
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 26, 2026
# 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.
@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 Aug 28, 2026
# 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
@alfredjbclaw
alfredjbclaw force-pushed the fix/cli-reseed-sqlite-store branch from 951b4dd to 6ec4b12 Compare August 30, 2026 20:52
…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.
@clawsweeper clawsweeper Bot removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 1, 2026
# Conflicts:
#	src/agents/cli-runner/prepare.test.ts
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Sep 1, 2026
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.
@VACInc

VACInc commented Sep 6, 2026

Copy link
Copy Markdown
Member

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.

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

Labels

agents Agent runtime and tooling gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: CLI session reseed is inert on SQLite session stores — loadCliSessionEntries reads the legacy per-session JSONL

2 participants