Skip to content

fix: Claude live sessions lose prompt cache on every captured turn - #125972

Closed
VACInc wants to merge 1 commit into
openclaw:mainfrom
VACInc:fix/claude-live-capture-keep-warm
Closed

VACInc wants to merge 1 commit into
openclaw:mainfrom
VACInc:fix/claude-live-capture-keep-warm

Conversation

@VACInc

@VACInc VACInc commented Aug 18, 2026

Copy link
Copy Markdown
Member

Related: #124300

What Problem This Solves

Fixes an issue where users running OpenClaw through the Claude CLI live backend with MCP delivery capture (the default Gateway message-tool path, including Telegram) would lose prompt-cache continuity after every completed turn. Each message spawned a fresh claude process that resumed from disk, so the first resume of a process could rewrite the entire prompt prefix.

Measured today on one Telegram Fable session (09:28–10:48 UTC, 2026-08-18): 42 API iterations, 7,237,084 cache-read tokens, and 1,174,177 one-hour cache-write tokens (billed 2x input). The final iteration read 0 cached tokens and rewrote 215,064. Gateway journals showed every completed Claude turn logging claude live session close: ... reason=restart.

This is the remaining steady-state cost after #124300 (7f93011562d), which already restored cache reuse within a live process. Per-turn process death made that worst case the normal path.

Why This Change Was Made

The capture key must ride child process environment and MCP headers (OPENCLAW_MCP_CLI_CAPTURE_KEY, x-openclaw-cli-capture-key). Claude materializes those at spawn; there is no stdio control to rotate them without a new process. Commit 0ea08076c3b5 therefore killed the warm process after every captured turn so the attempt could release the key without leaving it usable for later sends (f5aba544373 later moved that finally block).

This change keeps that security invariant without the kill:

  • Mint one capture key per live process at spawn.
  • Each turn activates the MCP loopback grant for that key before writing the user prompt, then deactivates it after drain/finalize. Late or cross-turn requests fail grant resolution because activeCaptureKey is cleared.
  • If MCP delivery drain cannot prove idle (CLI_MCP_DELIVERY_DRAIN_GRACE_MS, plus 250ms admission grace), close the session with mcp-capture-rotation so the env key dies with the child.
  • Genuine restarts stay: fingerprint/env change, non-resume vs resume-capable, forceNewSession, fork (closeClaudeSession(..., "restart")), idle timeout, abort, and run-end live-session cleanup.

Non-live one-shot CLI still gets a unique per-attempt key. Unchanged.

Accepted remaining window: a delayed HTTP packet from turn N that arrives after turn N+1 reactivates the same process-stable key would be attributed to N+1. Drain + admission grace + deactivate-between-turns is the mitigation. Fully closing that window requires killing the process (the old behavior). The one-time cold-resume prefix rewrite after a genuine process death (gateway reboot, model switch) remains an accepted cost from #124300.

User Impact

Claude CLI live sessions with MCP delivery capture keep the warm process across messages, so API-side prompt cache can stay hot instead of rewriting the prefix on every turn. Operators should see reason=restart only for real session identity changes, not after every captured message. Message-tool sends after a captured turn still cannot use a stale capture key.

Evidence

Pre-fix reproduction (regression test captured before the production edit): reuses a captured Claude live process and capture key across resume turns failed on main with expected "vi.fn()" to be called once, but got 2 times — the finally block killed the child, so the second resume turn spawned again.

Post-fix:

  • Same test: one spawn, same capture key, no reason=restart.
  • Identity-change path still restarts and still logs cleanup failures.
  • Grant fence: same process-stable key, deactivate of turn 1 before activate of turn 2, process not cancelled.
  • Drain timeout still closes with reason=mcp-capture-rotation and fails closed (CLI message tool call remained in flight after exit).
  • Plugin-approval block path no longer kills the live process.

Commands (worktree, Node 25.9 via /usr/bin/node):

/usr/bin/node scripts/run-vitest.mjs src/agents/cli-runner/claude-live-process.test.ts src/agents/cli-runner/claude-live-process-capture.test.ts src/agents/cli-runner/claude-live-process-approval.test.ts src/agents/cli-runner/claude-live-registry.test.ts src/agents/cli-runner/claude-live-session.test.ts src/agents/cli-runner/execute.supervisor-capture.test.ts src/agents/cli-runner.spawn.test.ts
# 182 tests passed (66 + 116)

PATH="/usr/bin:$PATH" /usr/bin/node scripts/check-changed.mjs -- src/agents/cli-runner/claude-live-session.ts src/agents/cli-runner/execute-tool-tracking.ts src/agents/cli-runner/claude-live-process.test.ts src/agents/cli-runner/claude-live-process-capture.test.ts src/agents/cli-runner/claude-live-process-approval.test.ts src/gateway/mcp-http.loopback-runtime.ts
# passed

Autoreview: python3 .agents/skills/autoreview/scripts/autoreview --engine claude --mode local --thinking max (claude-fable-5). Result: autoreview clean: no accepted/actionable findings reported.

Production LOC (git diff --numstat origin/main...HEAD): claude-live-session.ts +5/−10, execute-tool-tracking.ts +3/−1 comments, mcp-http.loopback-runtime.ts comment rewrite. Net production ≈ −3. Tests: new claude-live-process-capture.test.ts (+255) after splitting off the capture lifetime cases so claude-live-process.test.ts stays under the 1000-line cap.

Live Telegram/Gateway proof was not run: this worktree must not touch the operator gateway, ~/.openclaw, or the main checkout. Owner-boundary tests inject spawn, grant activate/deactivate, and in-flight MCP drain in the original execution order.

Head: 565510b98bd553e18cb40a8a8455edabeed004ac.

MCP delivery capture no longer kills the warm Claude process after every
turn. Capture-key admission is fenced by grant activate/deactivate so
prompt-cache continuity can survive across messages.

Co-authored-by: Cursor <[email protected]>
@clawsweeper

clawsweeper Bot commented Aug 18, 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 gateway Gateway runtime agents Agent runtime and tooling size: M labels Aug 18, 2026
@VACInc
VACInc marked this pull request as ready for review August 18, 2026 19:33
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. 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 Aug 18, 2026
@clawsweeper

clawsweeper Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 18, 2026, 3:44 PM ET / 19:44 UTC.

ClawSweeper review

What this changes

The PR keeps Claude CLI child processes alive across captured turns to preserve prompt-cache state.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 7 items remain

Keep open: normal captured Claude runs still restart because each outer run has a newly minted loopback token in the live-session fingerprint, so the PR does not deliver its intended warm-process cache reuse.

Priority: P2
Reviewed head: 565510b98bd553e18cb40a8a8455edabeed004ac

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The optimization has useful intent, but its tests omit the production credential lifecycle that prevents it from working.
Proof confidence 🧂 unranked krab (1/6) Needs real behavior proof before merge: The added proof uses mocked processes and grant-capture callbacks; it does not show an after-fix Gateway run with two real prepared captured turns. 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 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The added proof uses mocked processes and grant-capture callbacks; it does not show an after-fix Gateway run with two real prepared captured turns. 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 5 items Per-run loopback token: Preparation mints a loopback client grant and injects its token as OPENCLAW_MCP_TOKEN for the generated MCP configuration.
Fingerprint prevents reuse: The Claude live-session fingerprint hashes every execution-environment value, including the newly minted loopback token.
Existing restart behavior: A retained session whose fingerprint changes is closed before the next turn; this prevents stale-token use but also prevents the proposed reuse.
Findings 1 actionable finding [P2] Keep per-run grants out of an ineffective warm-session path
Security None None.

Live Verification

Command: pnpm openclaw --help

Result: PASS (completed)

pnpm openclaw --help
runner@runnervmzvulz:/tmp/clawsweeper-live-proof-125972-jW8QmJ/target$ pnpm openclaw --help
$ node scripts/run-node.mjs --help
pnpm openclaw --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 400.66 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 100.64 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

[tsdown-build] invocation 2/2 finished in 13.8s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 10 phases completed in 4174ms (slowest: built plugin control-plane loads 3429ms)

OpenClaw 2026.8.1 (565510b) — All your chats, one OpenClaw.

Usage: openclaw [options] [command]

Options:
  --container ‹name›   Run the CLI inside a running Podman/Docker container named ‹name› (default: env OPENCLAW_CONTAINER)
  --dev                Dev profile: isolate state under ~/.openclaw-dev, default gateway port 19001, and shift derived ports (browser/canvas)
  -h, --help           Display help for command
  --log-level ‹level›  Global log level override for file + console
… output truncated …

Assertions:

  • PASS expect_output: Usage: openclaw [options] [command]

How this fits together

Claude CLI runs receive generated MCP configuration plus a loopback grant for tool calls. The Gateway validates that grant before captured tool activity can reach delivery.

flowchart LR
  A[Prepared Claude run] --> B[Loopback grant]
  A --> C[Generated MCP config]
  C --> D[Claude child process]
  B --> E[Live-session fingerprint]
  D --> F[Captured tool call]
  F --> G[Gateway authorization]
  G --> H[Message delivery]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The added proof uses mocked processes and grant-capture callbacks; it does not show an after-fix Gateway run with two real prepared captured turns. 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 per-run grants out of an ineffective warm-session path (P2) - Each normal captured run mints a distinct OPENCLAW_MCP_TOKEN, and buildClaudeLiveFingerprint hashes every environment value. The next captured run therefore reaches the fingerprint-mismatch restart path before this retained child can process a turn, so the process never preserves the cache state this change intends to reuse. The new test uses empty prepared environments and bypasses that lifecycle. Restore shutdown, or make MCP configuration and authorization session-owned with a boundary test covering two real prepared runs.
  • Resolve merge risk (P1) - Merging this leaves the claimed cache-reuse improvement absent for normal captured runs, while retaining an idle child until its next fingerprint-driven restart.
  • Complete next step (P2) - The contributor must either retain the existing lifecycle or prove a coherent session-level authorization design; the current test does not cover the real path.
  • Improve patch quality - Restore the existing shutdown or implement session-owned MCP authorization.
  • Improve patch quality - Add a two-run regression with distinct prepared grants and outer cleanup.
  • Improve patch quality - Provide redacted after-fix Gateway evidence showing cache reuse across the second captured turn.

Findings

  • [P2] Keep per-run grants out of an ineffective warm-session path — src/agents/cli-runner/claude-live-session.ts:565
Agent review details

Security

None.

PR surface

Source -3, Tests +129. Total +126 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 3 9 12 -3
Tests 3 256 127 +129
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 265 139 +126

Review metrics

Metric Value Why it matters
Production versus test delta production -3, tests +129 The added test coverage omits the production path that mints distinct grants and hashes their environment values.

Stored data model

Persistent data-model change detected: serialized state: src/agents/cli-runner/claude-live-process-capture.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Restore the captured-session shutdown (recommended)
    Keep the existing lifecycle until a session-owned grant design can preserve reuse without bypassing per-turn authority.
  2. Pause the optimization
    Defer the warm-process change if the required grant and MCP-config lifecycle redesign is out of scope.

Technical review

Best possible solution:

Restore captured-session shutdown unless MCP configuration and grant ownership move coherently to the session with a tested per-turn authorization handoff.

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

Yes from source: two normal prepared captured runs mint different OPENCLAW_MCP_TOKEN values, and the second token changes the live-session fingerprint before reuse.

Is this the best way to solve the issue?

No; merely retaining the child cannot preserve reuse while the process fingerprint includes per-run credentials and those credentials are intentionally revoked after each outer run.

Full review comments:

  • [P2] Keep per-run grants out of an ineffective warm-session path — src/agents/cli-runner/claude-live-session.ts:565
    Each normal captured run mints a distinct OPENCLAW_MCP_TOKEN, and buildClaudeLiveFingerprint hashes every environment value. The next captured run therefore reaches the fingerprint-mismatch restart path before this retained child can process a turn, so the process never preserves the cache state this change intends to reuse. The new test uses empty prepared environments and bypasses that lifecycle. Restore shutdown, or make MCP configuration and authorization session-owned with a boundary test covering two real prepared runs.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: The PR’s core Claude cache-reuse improvement is ineffective on the captured execution path it changes.
  • add merge-risk: 🚨 other: The merged change can claim and retain a warm-process optimization that normal captured runs immediately defeat through their per-run environment fingerprint.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The added proof uses mocked processes and grant-capture callbacks; it does not show an after-fix Gateway run with two real prepared captured turns. 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.

Label justifications:

  • P2: The PR’s core Claude cache-reuse improvement is ineffective on the captured execution path it changes.
  • merge-risk: 🚨 other: The merged change can claim and retain a warm-process optimization that normal captured runs immediately defeat through their per-run environment fingerprint.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The added proof uses mocked processes and grant-capture callbacks; it does not show an after-fix Gateway run with two real prepared captured turns. 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

Acceptance criteria:

  • [P1] Prepare two captured Claude contexts with distinct loopback grants.
  • [P1] Complete the first outer run so its grant is revoked.
  • [P1] Verify the second turn either safely reuses a session-owned authorization path or starts a fresh child.
  • [P1] Capture redacted Gateway evidence of the observed second-turn behavior.

What I checked:

Likely related people:

  • Peter Steinberger: Current-main blame covers loopback grant preparation; history includes the major Claude live-session refactor. (role: recent area contributor; confidence: high; commits: e68e973c0527, f5aba5443734; files: src/agents/cli-runner/prepare.ts, src/agents/cli-runner/claude-live-session.ts)
  • Vito Cappello: Prior merged history covers Claude cache and live-session behavior. (role: prior feature contributor; confidence: medium; commits: 5ae8a4f4f98c; files: src/agents/cli-runner/claude-live-session.ts)
  • Ayaan Zaidi: Recent history includes Claude live-session reliability work. (role: recent area contributor; confidence: medium; commits: 342a1e70a041; files: src/agents/cli-runner/claude-live-session.ts)

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.

@VACInc

VACInc commented Aug 19, 2026

Copy link
Copy Markdown
Member Author

Superseded by #125528, which merged this branch and added the joint captured-session thinking regression. Included commit range: 565510b98bd553e18cb40a8a8455edabeed004ac^..68352458facbcd2abc68582e0be50bc9cc5dc4ca.

Please continue review on #125528.

@VACInc VACInc closed this Aug 19, 2026
@VACInc

VACInc commented Sep 7, 2026

Copy link
Copy Markdown
Member Author

Related follow-up: #140566 (“preserve resumed CLI caches across Git changes”) is now merged.

Keeping a compatible Claude process warm and preserving the request prefix when a process must resume are complementary improvements. The new fix targets the latter: it prevents Claude Code’s refreshed startup Git snapshot from rewriting the conversation prefix after workspace activity.

It does not change MCP capture/grant lifetimes, process-reuse decisions, or thinking-level transitions. It should not be read as replacing the warm-session work tracked here. Existing merged/closed status is unchanged.

Reference: #140566

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: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M 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.

1 participant