Skip to content

fix(memory): CLI-backed sessions never flush memory before native compaction - #138129

Closed
zijunl wants to merge 1 commit into
openclaw:mainfrom
zijunl:fix/memory-flush-cli-backends
Closed

zijunl wants to merge 1 commit into
openclaw:mainfrom
zijunl:fix/memory-flush-cli-backends

Conversation

@zijunl

@zijunl zijunl commented Sep 4, 2026 •

Copy link
Copy Markdown

Related: #137613

What Problem This Solves

Fixes: sessions on a CLI backend (for example claude-cli) never save durable memory before Claude's native auto-compaction, because the pre-compaction memory flush is skipped for CLI runtimes.

User Impact

User impact: CLI-backed agents now write their pre-compaction memory notes the same way embedded sessions do, re-arming every 256 KiB of transcript growth. Native compaction stays owned by the backend. Existing sessions need no migration; rows written before this change never suppress a flush.

Why This Change Was Made

Branch rewritten on current main (the previous head was ~27k commits behind and conflicted with the memory-flush restructure).

  • Reply and command turns reach the flush only through the preflight-compaction beforeCompaction hook, and preflight returned before calling it for CLI sessions. CLI sessions now run that hook before returning to native compaction (codex and other non-CLI native owners are unchanged).
  • CLI compaction counts never advance, so the compaction-cycle dedup would lock after one flush. CLI sessions dedup on a transcript-byte window persisted as memoryFlush.cliRearmBucket; only a succeeded record suppresses.
  • The flush dispatches through the CLI backend with a read/write allowlist, and the host-minted memoryFlushWritePath is carried through CLI dispatch → loopback grant → gateway tool resolution, so the writer stays append-only to the prepared target (a memory trigger without one still fails closed). Provider-owned tool plans keep the original skip.
  • The private flush prompt stays out of the CLI dispatch transcript.
  • Threshold and CLI byte-window rules live in memory-flush-cycle.ts so agent-runner-memory.ts does not grow past its line cap.

Evidence

Live run (OpenClaw 2026.11.2 with the equivalent change applied to the packaged dist, claude-cli runtime, Claude Code 2.1.296, forceFlushTranscriptBytes temporarily set to 4096 for the run):

15:48:13 cli exec: provider=claude-cli model=claude-opus-5-5 trigger=user          # turn 1, transcript below threshold
15:48:19 dispatching embedded run through CLI backend: provider=claude-cli model=claude-sonnet-5-5
15:48:19 ... unavailable here: memory-triggered compaction runs expose only read and append-only write.
15:48:19 cli exec: provider=claude-cli model=claude-sonnet-5-5 trigger=memory      # turn 2: flush via CLI
15:48:22 cli exec: provider=claude-cli model=claude-opus-5-5 trigger=user useResume=true
15:48:25 cli exec: provider=claude-cli model=claude-opus-5-5 trigger=user useResume=true   # turn 3: no flush (same window)
session memoryFlush: {"kind":"succeeded","compactionCount":0,"cliRearmBucket":0}

Before the preflight-hook change, the same three turns produced no trigger=memory run. The flush model chose not to write for that filler transcript, so this run shows the bounded grant but not an actual append; the append-only writer is covered by the existing writer tests.

Tests: agent-runner-memory.cli-flush.test.ts (flush through CLI dispatch with the bounded grant; flush from the preflight hook without compacting — fails without the hook change; same-window suppression; re-arm on a new window; failed records do not suppress), memory-flush-cycle.test.ts, session-shape round trips for the bucket (including bucket-free older rows), CLI dispatch and grant-context forwarding. 48 related test files / 538 tests pass; tsgo:core, tsgo:core:test, oxlint, oxfmt and the line-cap ratchet pass.

Limits / decision needed: this still needs the maintainer call from the earlier review — recurring CLI memory maintenance at a fixed 256 KiB re-arm interval. Each re-arm costs one flush turn on the configured memory-flush model.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@zijunl

zijunl commented Sep 4, 2026

Copy link
Copy Markdown
Author

Moving this to draft: CI is red on the change itself, not on infrastructure, and two of the failures show my model of the gate is incomplete.

src/auto-reply/reply/agent-runner-memory.test.ts
  → expected 'skipped' not to be 'skipped' // Object.is equality
  → expected { sessionEntry: { …(8) }, …(1) } to deeply equal { sessionEntry: { …(6) }, …(1) }

The first is one of the two tests I rewrote. It still returns skipped with the CLI condition removed, so something else in that setup also declines the flush — the exclusion I removed was not the only thing holding it there, and my rewrite asserted otherwise.

The second is a test I did not touch. A session entry arrives with eight keys where it expected six, so the flush now runs somewhere it previously did not and mutates session state a neighbouring test depends on. That is real blast radius beyond the two backends this was aimed at, and it is the kind of thing the original exclusion was keeping simple.

The live A/B in the description still stands — on a real gateway, lifting the gate does let the flush run on claude-cli, and the byte bucket does persist and re-arm. What it does not show is that lifting it globally is safe for every path that reaches this function, and CI is now saying it is not.

I do not have a local test run for this repo, so iterating here would be guesswork against CI. Leaving it in draft rather than pushing speculative fixes. The evidence and the reproduction in the description are the parts I would keep; #137613 still needs the ownership decision either way.

@zijunl
zijunl marked this pull request as draft September 4, 2026 09:48
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Enable file-based memory flushes for CLI-backed sessions, re-arm them with persisted transcript-byte checkpoints, and carry restricted write targets through CLI dispatch.

Example: A claude-cli conversation crosses the configured flush threshold and later grows by 256 KiB.

  • Before: OpenClaw skips its memory flush because the CLI backend owns compaction.
  • After: OpenClaw can run a restricted memory-flush turn and re-arm it in a different transcript-byte window while leaving compaction to the backend.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful source-backed repair with partial live evidence, an introduced policy-propagation defect, and an unresolved product decision.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: CLI-backed conversations skip configured durable-memory maintenance before their backend compacts context.
Reason: The durability gap has clear value, but recurring automatic maintenance and its fixed cadence change intentional runtime behavior without a recorded owner decision.

Merge readiness

⛔ Blocked before merge - 4 items remain

This PR addresses a current CLI memory-flush gap, but the newly enabled dispatch loses source conversation restrictions and still needs an owner decision on recurring maintenance.

Priority: P2
Reviewed head: c5aca631bdaa2ee72496fab44fcbfda6aff8e6c3
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should CLI-backed conversations run recurring memory maintenance using the proposed fixed 256 KiB transcript-growth window?
  • Recommendation: Approve bounded recurring maintenance: Accept the proposed cadence while retaining native compaction ownership, subject to the policy repair and behavior-proof gates.
  • Why: This changes an intentional exclusion and adds repeated inference work; the author explicitly requests this decision, and the discussion contains no approval of the cadence.

Before merge

  • Add real behavior proof - Authority-chain proof required: The latest packaged-release trace exercises CLI memory dispatch and same-window suppression, but performs no append; the contributor must demonstrate allowed append, a conversation-denied write, a different target, and revoked-grant rejection before filesystem mutation through the corrected production route, using redacted logs or terminal output. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Preserve source conversation policy when dispatching the flush (P1) - The newly enabled memory run carries conversationToolPolicy, requesterOrigin, and the source sandboxSessionKey, but this bridge's explicit runCliAgent arguments discard them and never map the source key to runtimePolicySessionKey. For a CLI-backed conversation whose policy denies write while agent-wide policy permits it, the loopback grant therefore exposes the requested read/write pair without that conversation deny, allowing an append the embedded path would reject. The grant builder already accepts these restrictions, and Gateway resolution consumes them. Forward the source policy identity and requester/conversation context through that existing path and test rejection at the final writer.
  • Resolve security concern: A bounded target does not preserve conversation authorization - Append-only confinement limits the destination but does not restore a source conversation's denial of the write tool; preserve that authority through the bridge and demonstrate final-effect rejection.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P1] Preserve source conversation policy when dispatching the flush — src/agents/embedded-agent-runner/cli-backend-dispatch.ts:157-161
  • [medium] A bounded target does not preserve conversation authorization — src/agents/embedded-agent-runner/cli-backend-dispatch.ts:161

Tests

  • Low-value test src/auto-reply/reply/memory-flush-cycle.test.ts: The same-bucket, changed-bucket, and failed-record helper assertions duplicate scenarios in the new maintenance-owner suite; consolidate those while retaining distinct zero-threshold and non-CLI cases.
  • Missing end-to-end proof: Show the corrected CLI route preserving conversation restrictions, allowed append and forbidden/revoked rejection before I/O, plus a latest-stable persisted-session upgrade, reopen, suppression, and re-arm.
Agent review details

How this fits together

Reply maintenance reads session accounting, prepares a detached memory run, and dispatches it through the selected runtime; CLI tools reach filesystem operations through a host-issued loopback MCP grant.

flowchart TD
  A[Conversation turn] --> B[Preflight maintenance]
  B --> C[Flush eligibility and byte checkpoint]
  C --> D[Detached memory run]
  D --> E[CLI backend dispatch]
  E --> F[Loopback MCP grant]
  F --> G[Gateway tool policy]
  G --> H[Append-only memory writer]
Loading

Technical review

Best possible solution:

Keep native compaction ownership, preserve source policy through the existing CLI grant path, and ship recurring flushes only with an accepted cadence and verified persistence behavior.

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

Current main explicitly excludes CLI sessions before flush eligibility, and the supplied live comparison supports that path; no target code was executed during this review.

Is this the best way to solve the issue?

The separate checkpoint and existing append-only writer fit the problem, but enabling CLI dispatch must preserve the source conversation's policy rather than resolving tools under a detached identity alone.

Full review comments:

  • [P1] Preserve source conversation policy when dispatching the flush — src/agents/embedded-agent-runner/cli-backend-dispatch.ts:157-161
    The newly enabled memory run carries conversationToolPolicy, requesterOrigin, and the source sandboxSessionKey, but this bridge's explicit runCliAgent arguments discard them and never map the source key to runtimePolicySessionKey. For a CLI-backed conversation whose policy denies write while agent-wide policy permits it, the loopback grant therefore exposes the requested read/write pair without that conversation deny, allowing an append the embedded path would reject. The grant builder already accepts these restrictions, and Gateway resolution consumes them. Forward the source policy identity and requester/conversation context through that existing path and test rejection at the final writer.
    Confidence: 0.96

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6091f622fe4d.

Provenance checked

  • CLI maintenance exclusion changes intended behavior with a stated reason (942d3d7: Resolve the effective CLI runtime and prevent OpenClaw maintenance from compacting backend-owned transcript state.)
  • Subscription-auth CLI dispatch keeps the original intent (3590f7d: Keep subscription-auth utility inference on the CLI runtime instead of silently using metered direct-API requests.)
  • Memory-slot persistence plans keeps the original intent (32339db: Let the memory-slot owner supply persistence tools while retaining file-based flush behavior and released resolver contracts.)
  • Persisted memory-flush state keeps the original intent (8ee1d04: Consolidate parallel flush fields into nested states normalized at the session-store boundary.)
  • Optional flush failure settlement keeps the original intent (0e45646: Contain optional maintenance failures, persist retry outcomes, and let the foreground reply continue.)

Testing

Proof path: shipped entry point.

Security

Needs attention: The new maintenance route drops source conversation restrictions before constructing its filesystem tool grant.

Evidence

Security concerns:

  • [medium] A bounded target does not preserve conversation authorization — src/agents/embedded-agent-runner/cli-backend-dispatch.ts:161
    Append-only confinement limits the destination but does not restore a source conversation's denial of the write tool; preserve that authority through the bridge and demonstrate final-effect rejection.
    Confidence: 0.96

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 32339db adds src/agents/agent-tools.memory-flush.ts:94 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 32339db16b0d; files: src/agents/agent-tools.memory-flush.ts)
  • Bill: Raw commit 3590f7d adds src/agents/embedded-agent-runner/cli-backend-dispatch.ts:49 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3590f7df7ee1; files: src/agents/embedded-agent-runner/cli-backend-dispatch.ts)

PR surface

Source +213, Tests +330. Total +543 across 18 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 11 243 30 +213
Tests 7 388 58 +330
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 18 631 88 +543

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #137613
Summary: The underlying issue owns CLI flush eligibility and re-arming; native-compaction status accounting is related but remains a separate behavior.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The underlying failure affects durable-memory maintenance on CLI-backed conversations with limited runtime scope.
  • merge-risk: 🚨 security-boundary: The newly enabled CLI route can lose conversation-specific read/write restrictions before Gateway tool execution.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (18 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-06T18:04:30.579Z sha 9abff67d4a3a2f51cefb207ee51e0caee8e6c9a3 :: needs real behavior proof before merge. :: [P1] Carry the memory-write target through CLI tool construction | [P2] Preserve the internal transcript prompt when selecting CLI dispatch
  • reviewed 2026-09-06T18:32:55.303Z sha bdc08f2f60740eaf2910a68ebcb40f7f7c4ea626 :: needs real behavior proof before merge. :: [P1] Carry the memory-write target through CLI tool construction | [P2] Preserve the internal transcript prompt when selecting CLI dispatch
  • reviewed September 22, 2026, 11:55 PM ET / September 23, 2026, 03:55 UTC (Revision 13) sha unknown :: needs real behavior proof before merge. :: [P1] [P1] Carry the memory-write target through CLI tool construction | [P2] [P2] Preserve the internal transcript prompt during CLI dispatch
  • reviewed September 22, 2026, 11:55 PM ET / September 23, 2026, 03:55 UTC (Revision 14) sha unknown :: needs real behavior proof before merge. :: [P1] [P1] Carry the memory-write target through CLI tool construction | [P2] [P2] Preserve the internal transcript prompt during CLI dispatch
  • reviewed 2026-09-24T14:10:16.757Z sha 10cef09a2430b0850b41c72fd99f8b6631754e9d :: needs real behavior proof before merge. :: [P1] [P1] Carry the memory write target into CLI tool construction | [P2] [P2] Preserve the private transcript prompt on CLI dispatch
  • reviewed 2026-09-24T14:59:35.538Z sha c9f0c7b07dea348abbcdaade2385d945ac98a82d :: needs real behavior proof before merge. :: [P1] Carry the memory write target into CLI tool construction | [P2] Preserve the private transcript prompt on CLI dispatch
  • reviewed 2026-10-07T00:29:38.759Z sha 72e1205a9166efe85757ff30ec7a0ab58eb46f42 :: needs real behavior proof before merge. :: [P2] Reuse the imported test parameter types | [P2] Narrow resolved buckets before calling the dedup helper
  • reviewed 2026-10-07T00:37:53.472Z sha 72e1205a9166efe85757ff30ec7a0ab58eb46f42 :: needs real behavior proof before merge. :: [P2] Reuse and extend the imported test parameter types | [P2] Narrow resolved buckets before calling the dedup helper

Reviewed November 9, 2026, 6:56 PM ET / 23:56 UTC (Revision 19).

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 4, 2026
@zijunl

zijunl commented Sep 4, 2026

Copy link
Copy Markdown
Author

Rebuilt against a local checkout, so this is now verified rather than reasoned about.

The defect the first cut had. Removing the CLI condition outright let the flush run on sessions with no transcript size, where the compaction watermark is still the only anchor available. Two of my rewritten tests and one I had not touched caught it:

→ expected 'skipped' not to be 'skipped'
→ expected { sessionEntry: { …(8) }, …(1) } to deeply equal { sessionEntry: { …(6) }, …(1) }

The second was keeps ownsNativeCompaction absolute over the SQLite transcript byte guard — a session entry arriving with eight keys where it expected six, because the flush ran and mutated state that test depends on.

The fix. The exclusion now lifts exactly where resolveCliMemoryFlushRearmBucket can replace the watermark, and nowhere else. A CLI session without a byte anchor keeps the original skip rather than flushing once and locking the dedup — which is strictly better than the "flushes exactly once" failure mode the original exclusion was avoiding.

Tests. Locally, with pnpm deps installed:

src/auto-reply/reply/agent-runner-memory.test.ts   106 passed (106)
src/auto-reply/reply/memory-flush.test.ts           19 passed (19)
src/auto-reply/reply/ (whole directory)           5602 passed | 1 skipped (5603), 271 files
oxfmt --check                                      clean

Three tests encoded the old exclusion and now assert the new contract. Two keep skipping, with names that say why (no transcript anchor). The third asserts the flush runs on the byte guard while compaction ownership stays with the backend — that half is unchanged, and compactEmbeddedAgentSessionMock is still asserted not to be called.

Still the maintainer's call. Those three tests are the current intent, and changing them is the decision this PR is asking for. What has changed is that the shape is now narrow enough to state precisely: the flush becomes available to CLI sessions that have a transcript to anchor on, and to nothing else.

@zijunl
zijunl marked this pull request as ready for review September 4, 2026 17:49
@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 4, 2026
@zijunl

zijunl commented Sep 4, 2026

Copy link
Copy Markdown
Author

Exact-head proof, replacing the earlier A/B that predated the cliRearmBucket representation.

Built this branch from source and ran real turns against it: openclaw --version reports 2026.8.1 (ab41309), this branch's head. dist/agent-runner-memory-*.js carries kind === "succeeded" && memoryFlush.cliRearmBucket, so the running code is the final representation, not the earlier overloaded field.

Three real claude-cli turns on a gateway-backed workspace, forceFlushTranscriptBytes: 500 to reach the trigger without a million-token session. Gate state captured at the decision point:

{"isCli": true, "transcriptByteSize": 846, "cliRearmBucket": 0,
 "storedBucket": null, "storedKind": null, "storedCompactionCount": null,
 "cliAlreadyFlushed": false, "forceByBytes": true}

isCli: true and the decision is reached at all — on current main this returns skipped before evaluating either trigger.

The persisted state afterwards, read back from the session store:

proofa: memoryFlush = {"kind": "failed",    "cliRearmBucket": 0, "failureCount": 1}   compactionCount = null
proofb: memoryFlush = {"kind": "succeeded", "compactionCount": 0, "cliRearmBucket": 0} compactionCount = null
proofc: memoryFlush = {"kind": "succeeded", "compactionCount": 0, "cliRearmBucket": 0} compactionCount = null

That covers the three things the last review asked about:

  • proofa is the failure path. Its flush model was rate-limited (429 ... weekly usage limit), and the record is kind: "failed" carrying the bucket with failureCount: 1. It does not suppress — the retry and exhaustion lifecycle still owns that bucket, which is the regression the last review caught.
  • proofb/proofc are completed flushes. compactionCount and cliRearmBucket are stored as separate values; neither stands in for the other.
  • compactionCount is null in all three. That is the reason the byte anchor exists: on this backend the compaction count genuinely never advances, so it cannot re-arm anything.

A completed flush also wrote to memory/<date>.md on the same turn, so the run reached the durable write rather than only the gate.

Local against this head: agent-runner-memory.test.ts 106 passed, memory-flush.test.ts 19 passed, src/auto-reply/reply/ 5602 passed across 271 files, tsgo:core and oxlint/oxfmt --check clean.

The probe was added to the local build only and is not in the diff. Test fixtures written during these runs were removed afterwards.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Sep 5, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Sep 6, 2026
@zijunl

zijunl commented Sep 6, 2026

Copy link
Copy Markdown
Author

Addressed: "Preserve the selected CLI runtime before enabling maintenance" (P1)

Fixed in ad1d8426b.

The finding was right, and it invalidates my earlier proof comment. I reported a successful CLI-session flush showing provider=anthropic api=anthropic-messages status=200. That line is the defect: it shows the run took cli_runtime_passthrough_openclaw — the direct-API call — not the CLI backend. So that comment demonstrated the billing bypass rather than correct routing. Treat its routing claim as withdrawn; the flush-fires-and-writes part still holds.

What the passthrough costs

Per cli-backend-dispatch.ts, Anthropic routes direct anthropic-messages calls made on subscription OAuth tokens to metered "extra usage": without balance the run fails closed on a billing error, and with balance it silently draws paid usage instead of the plan limits the CLI runtime was configured for. Lifting the CLI exclusion without this fix would have pointed automatic, unattended maintenance at that route.

Fix

The flush now opts into cliBackendDispatch: "subscription-auth". Eligibility stays entirely with the existing gate, which resolves on stored credential metadata: providers whose backend does not declare subscriptionAuthDispatch, and api-key/mixed/aws-sdk stores, keep the faster passthrough untouched. Only the subscription case — the one that was billing wrong — changes route.

Restrictions are preserved, not widened

The gate requires the run's tool state as a named allowlist. Rather than hand-write a second copy free to drift, this exports the set agent-tools already constructs for a flush (MEMORY_FLUSH_ALLOWED_TOOLS = ["read", "write"]) and declares it. Under dispatch the tool surface is narrower than the passthrough, not wider:

  • native: [] — Claude Code's own Read/Write/Bash are unavailable.
  • The MCP list bounds the loopback grant server-side, so tools outside it can be neither listed nor called, and the message tool plus user/plugin MCP servers stay unreachable.
  • write is still the wrapToolMemoryFlushAppendOnlyWrite instance, so append-only-to-one-path is in force.

Test

keeps a flush on the configured CLI runtime instead of the direct-API passthrough pins the opt-in and the allowlist shape the gate needs — the gate fails closed on an absent, empty, or wildcard allowlist by silently dropping back to the passthrough, so asserting the flag alone would not catch a regression that reintroduces it.

Verified the regression actually fails against the unfixed source: expected undefined to be 'subscription-auth'. Suites green: 184 tests across the flush, dispatch, and append-only-write files, plus 196 across tool construction/policy. tsgo:core exit 0, oxlint/oxfmt clean, deadcode:knip clean.

Known limit

The gate declines sourceReplyDeliveryMode: "message_tool_only" because the one-shot bridge cannot carry authenticated source-channel delivery context. That mode is set by heartbeat runs, which the flush already excludes, so I do not expect it to bite here — but if some other caller sets it, that flush degrades to today's passthrough rather than failing.

🤖 Generated with Claude Code

https://claude.ai/code/session_01BjsHL4YEa67pAiPpSY3svm

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. labels Sep 6, 2026
@zijunl

zijunl commented Sep 6, 2026

Copy link
Copy Markdown
Author

Also closed: old-entry upgrade coverage for the re-arm bucket

dbeadde67. The re-arm bucket is a new persisted field, so every row written by an existing build reaches it absent. Suppression matches the bucket exactly, so a normalizer that defaulted the field to 0 rather than omitting it would skip the first CLI flush after upgrade — silently reintroducing the bug the field exists to fix.

The current normalizer already omits it. What was missing was anything pinning that, so this adds the round trip through normalizePersistedSessionEntryShape: an older row keeps no bucket and suppresses nothing at any bucket value, and a row that does carry one still round-trips.

Verified it fails against the regression rather than merely passing — defaulting the field to 0 in the normalizer produces expected { kind: 'succeeded', …(2) } to deeply equal { kind: 'succeeded', …(1) }.

That leaves one open merge-risk I flagged and have not resolved: the 256 KiB re-arm interval is a chosen constant, not a calibrated one. I have no measurement justifying 256 KiB over, say, 128 KiB or 512 KiB — it trades flush frequency against transcript growth between flushes, and I'd rather name that as a reviewer decision than defend a number I picked. Happy to change it or make it configurable if you have a preference.

🤖 Generated with Claude Code

https://claude.ai/code/session_01BjsHL4YEa67pAiPpSY3svm

@zijunl
zijunl force-pushed the fix/memory-flush-cli-backends branch from 9abff67 to bdc08f2 Compare September 6, 2026 18:26
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 6, 2026
@zijunl
zijunl force-pushed the fix/memory-flush-cli-backends branch from bdc08f2 to 10cef09 Compare September 24, 2026 13:56
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 24, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Oct 7, 2026
@zijunl

zijunl commented Oct 7, 2026

Copy link
Copy Markdown
Author

Repair pushed for the CLI memory-flush boundary findings (branch fix/memory-flush-cli-backends, now at 72e1205a).

What changed

  • P1 / security (unrestricted CLI memory-flush write): memoryFlushWritePath is now carried end-to-end on the CLI dispatch path. The bridge (cli-backend-dispatch.ts) forwards it into runCliAgent params (new optional field on RunCliAgentParams); buildCliMcpGrantContext stamps it into the host-minted McpLoopbackRequestContext (never sourced from MCP request headers); the Gateway's loopback tool construction (tool-resolution.ts) passes it into createOpenClawCodingTools, which applies the append-only wrapper and throws when a memory trigger arrives without a target — fail closed. Both tools/list and tools/call go through this resolution, and the loopback tool-cache key includes the grant context, so a stale target can't leak across grants.
  • P2 (private transcript prompt): the bridge now forwards the explicit transcriptPrompt ("" for flushes) to runCliAgent, so the runner no longer defaults it to the maintenance prompt. The bridge's own transcript mirror also records transcriptPrompt ?? prompt, matching the embedded path. Non-flush dispatches are unchanged (both fields omitted).

Evidence (vitest; no live CLI run)

  • Final write-tool boundary via createOpenClawCodingTools (the exact Gateway call): allowed append to the prepared target succeeds (two appends accumulate); a write to a different path rejects with Memory flush writes are restricted to … before any filesystem I/O (neither the forbidden path nor the target is created); a memory trigger without a target throws at construction.
  • Grant carry: buildCliMcpGrantContext includes the target; omitted when the run carries none.
  • Bridge (mocked runCliAgent): receives memoryFlushWritePath + transcriptPrompt: ""; the transcript recorder is built with prompt: ""; non-flush runs keep prompt and omit both fields.
  • Upgrade/re-arm sequence with the real functions: old row without cliRearmBucket → first CLI flush not suppressed → same bucket suppressed → next bucket re-armed.
  • 116 tests green across the four touched files (6 + 30 + 51 + 29).

Honest limits: no live restricted CLI run was possible in this sandbox (needs CLI subscription auth/API keys not available here), so the end-to-end "allowed append + rejected write inside one live CLI process" and "same live session suppression, then re-arm after reopening" remain unproven. The boundary is proven at the final tool-construction layer the live path executes.

Still needs maintainer decision:

  • 256 KiB re-arm interval: no representative session evidence available here. Calibration only: 256 KiB ≈ ~65k tokens at ~4 bytes/token, roughly a third to a half of a typical flush token threshold (context window minus reserve and soft margin) — so a long CLI session re-arms a few times per flush cycle rather than every turn or never. Whether that cadence is the product contract is still the maintainer's call.
  • Full tsgo typecheck could not complete in this environment (OOM under load); the changed files are covered by the passing suites above — CI will confirm.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Oct 7, 2026
CLI backends were excluded from the pre-compaction memory flush because
their compaction count never advances: a single flush would lock the
compaction-cycle dedup for the rest of the session. Sessions on the
claude-cli runtime therefore never saved durable memory before Claude's
native auto-compaction.

- Run the memory hook from preflight compaction for CLI sessions before
  returning to native compaction: reply and command turns reach the flush
  only through that hook, which CLI sessions never called.
- Lift the CLI exclusion for file-arm flushes only; provider-owned tool
  plans and native compaction stay as before.
- Re-arm CLI flushes on a transcript-byte window (256 KiB) persisted as
  memoryFlush.cliRearmBucket. Only a succeeded record suppresses; older
  rows without a bucket never suppress.
- Dispatch the flush through the CLI backend with a read/append-only
  allowlist, and carry the host-minted memoryFlushWritePath through the
  CLI dispatch, the loopback grant and gateway tool resolution so the
  writer stays confined to the prepared target (memory triggers without
  one still fail closed).
- Keep the private flush prompt out of the CLI dispatch transcript.
- Move the flush threshold and the CLI byte-window rules into
  memory-flush-cycle.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@zijunl
zijunl force-pushed the fix/memory-flush-cli-backends branch from 72e1205 to c5aca63 Compare November 9, 2026 23:49
@zijunl zijunl changed the title fix(memory): run the pre-compaction flush on CLI backends fix(memory): CLI-backed sessions never flush memory before native compaction Nov 9, 2026
@zijunl

zijunl commented Nov 9, 2026

Copy link
Copy Markdown
Author

Rewrote this branch on current main (single commit c5aca631bda); the PR body has the details.

Prior findings:

  • Test-type findings (P2 ×2): gone — the tests were rewritten against main's current test support; tsgo:core:test passes.
  • Conflicts with the memory-slot owner: resolved by reimplementing on main rather than rebasing.
  • Real behavior proof: a live claude-cli run is in the body. It also surfaced a gap the unit tests missed: on main, reply and command turns reach the flush only through the preflight beforeCompaction hook, which CLI sessions skipped. That is fixed and now covered by a regression test that fails without it.
  • Upgrade compatibility: rows without cliRearmBucket round-trip unchanged and never suppress a flush.

Still open for a maintainer: should CLI-backed sessions get recurring memory flushes, and is the fixed 256 KiB re-arm window acceptable?

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed 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. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 9, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the careful work here and in #137613. I'm closing this PR without merging.

On claude-cli, Claude Code owns compaction. OpenClaw does not compact these sessions, and it gets no signal before Claude Code compacts. So there is no OpenClaw compaction for a "pre-compaction" flush to run before. This PR replaces that trigger with a new recurring flush turn every 256 KiB of transcript growth, and each window costs one extra model turn. That adds a new product behavior; it does not repair a broken one. It needs a product decision first, which #137613 (left open) still tracks.

On current main (34600e99e21c), the flush is skipped on purpose for every runtime that owns native compaction (CLI backends and Codex), and a regression test covers this. If the decision is to add a trigger, a native signal from Claude Code before it compacts is a better starting point than a byte timer. A timer only guesses when context is lost.

@obviyus obviyus closed this Nov 13, 2026
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: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L 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.

2 participants