Skip to content

fix(agents): runtime-only turns persist a fabricated user turn in session transcripts - #137273

Merged
steipete merged 4 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-124244-runtime-marker-persistence
Oct 11, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-124244-runtime-marker-persistence

Conversation

@LiuwqGit

@LiuwqGit LiuwqGit commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Related: #124244

What Problem This Solves

Runtime-only embedded turns can save Continue the OpenClaw runtime event. as human-authored text even though the user never wrote it.

User Impact

Runtime continuations are now hidden internal-system input, while genuine user messages remain visible and correctly attributed. Their original model-visible content stays in history so cold replay preserves the prefix preceding retained responses and signed thinking. Existing transcript rows are unchanged; no configuration or migration is required.

This PR covers only transcript attribution. It does not claim to resolve the issue's other timeout, duplicate-send, or restart symptoms.

Why This Change Was Made

Builds on @LiuwqGit's work in the existing session persistence guard. The guard owns one one-shot persistence policy: normal input, suppressed replay duplicate, or hidden runtime input. Submission selects runtime mode and resets unconsumed mode in finally; the guard consumes runtime attribution before write hooks so a blocked marker cannot hide later user input. Recovery/replay callers share that setter; the redundant setters are removed.

The earlier suppression-only candidate lost model history after a cold reopen. This revision addresses ClawSweeper's finding by retaining the continuation with existing internal_system provenance and display: false. It preserves the append-only replay contract from #136782 and carrier placement/role behavior from #168169 and #168546. Contributor commits remain intact; main was merged, never rebased.

Production +34/−18 (net +16); tests/support +358/−138 (net +220); test routing +2/−0; docs +7/−0. The small production increase expresses attribution and replay as valid states in the existing owner. Prompt text/token delta: 0. No new config, schema, dependency, or public SDK export.

Evidence

  • Before: main e5ee13e2d2d460c94dd4694e9df3c7da329db211, isolated Gateway, native Ollama qwen3:4b. A temporary plugin Gateway method used public api.runtime.agent.runEmbeddedAgent() with no user text and explicit runtime context. The model replied RUNTIME_EVENT_ACK; reopened SQLite attributed the marker to an ordinary user. This establishes the supported plugin-runtime entry point; no built-in channel producer is claimed.
  • Regression and cold replay: the main regression fails on the unattributed marker. The revised real SQLite tests compare the exact timestamped, serialized role/content prefix before and after a fresh AgentSession reopen across retained, transient, and native-Ollama policies. Switching runtime mode back to suppression fails that prefix comparison because the continuation disappears. Hidden metadata and normal follow-up visibility are also checked.
  • Early failure, real provider: real AgentSession auth preflight rejected before any append; activating the local provider and submitting genuine text produced RECOVERY_ACK. Reopened SQLite retained exactly the normal user input. This is session/submission-owner proof, separate from the Gateway proof.
  • Final tests: 143 passed across six files, including Anthropic transport tests; 126.07 s wall including compiler/import work. Test execution: new phase 0.285 s; extracted four-case replay file 5.525 s; submission 11.910 s; guard 0.042 s; Anthropic transport 0.241 s; existing orphan file 32.249 s. The orphan fixture's 25 database-recovery cases are unchanged except the setter cutover; its slower cross-component contract remains in the existing suite. The replay extraction keeps the original host-owned SQLite fork project and worker watch mapping, without a new serial configuration.
  • Checks: touched-source lint, core and relevant test typechecks, Markdown lint, formatting/diff checks, max-lines, line-cap, assertion-safety, timeout-race, mock-export, config-doc, and plugin-inventory checks passed. Full build passed in 207.39 s wall. Fresh isolated Codex autoreview is scoped-clean at P2 with no accepted/actionable findings.
  • Prior-head CI limitation: a5d39c5b4c62 failed collection of untouched src/gateway/talk/handlers/client-native-actions.test.ts at src/cli/cli-process-tree.test-support.ts:4 with ERR_INVALID_URL_SCHEME (job, 174 CI seconds). The helper/test match baseline main; standalone main passes on Node 26 (90.88 s wall) and Node 24 with CI=1 (139.81 s). The Linux/cache-specific cause is unresolved; passing replays are not claimed as a fix.
Focused test command
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-prompt-phase.runtime-marker.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.runtime-replay.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.test.ts \
  src/agents/embedded-agent-runner/run/attempt-session-boundary.orphan.test.ts \
  src/agents/session-tool-result-guard.test.ts \
  packages/ai/src/transports/anthropic-transport-stream.test.ts --maxWorkers=1

Gateway proof uses pnpm openclaw --profile runtime-input gateway run --port 19511, a seed via agent --session-key, gateway call runtime-input-proof.run --expect-final, and a genuine follow-up via agent. State, workspace, plugin, and transcript reads are isolated synthetic fixtures; the operator Gateway is not used.

Final live candidate 9147c3039ffdd5db6b40b090d041291a6263f388: the isolated Gateway/native Ollama run returned RUNTIME_EVENT_ACK and the genuine follow-up returned HUMAN_ACK. Reopened SQLite retained one marker with provenance.kind: internal_system and display: false; its two human entries contained only the seed and genuine follow-up. The public chat.history RPC likewise returned exactly those two visible user messages, with no marker. This preserves replay content while fixing human attribution and chat visibility.

Final review/CI: 9147c3039ffdd5db6b40b090d041291a6263f388 passed CI, including both openclaw/ci-gate signals. All 32 Node shard jobs passed (3586 aggregate CI job-seconds, including existing selected suites). ClawSweeper reviewed this exact head on 2026-10-11 and reports no findings, no before-merge items, and readiness for maintainer review. Its partial-fix rating reflects the intentionally limited Related scope.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Sep 3, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR retains synthetic runtime continuations as hidden internal-system input instead of attributing them to a human.

Example: An embedded runtime event arrives with no user text.

  • Before: The transcript presents “Continue the OpenClaw runtime event.” as an ordinary user message.
  • After: The marker remains available for model replay with internal_system provenance and display false; subsequent genuine user input remains visible.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong supplied runtime evidence and a correct focused repair; the overall tier reflects partial coverage of the linked umbrella issue, not an outstanding merge blocker.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied exact-head Gateway/native Ollama output exercises the public plugin runtime entry point, verifies retained hidden metadata after SQLite reopen, and confirms chat.history excludes the marker while a genuine follow-up remains visible; separate real-provider preflight evidence confirms normal input survives early failure.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Session history can claim that a human wrote an internal runtime continuation.
Reason: The patch restores the documented attribution contract with a focused shared-owner repair; its Related wording correctly leaves the broader issue's other symptoms outside scope.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it repairs a current-main transcript-attribution bug while preserving replay history, with no remaining actionable findings.

Priority: P2
Reviewed head: 9147c3039ffdd5db6b40b090d041291a6263f388

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded prompt phase submits user text and runtime context to AgentSession; the session persistence guard records transcript messages that later feed model replay and visible chat history.

flowchart LR
A[Runtime event] --> B[Embedded prompt phase]
B --> C[AgentSession]
C --> D[Persistence guard]
D --> E[SQLite transcript]
E --> F[Model replay]
E --> G[Chat history projection]
Loading

Technical review

Best possible solution:

Land the focused attribution repair while leaving the linked issue's separate timeout and restart symptoms tracked independently.

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

Yes: current-main source deterministically turns empty human text plus runtime fragments into an ordinarily persisted synthetic user message, corroborated by the supplied pre-fix Gateway run; this review executed no target code.

Is this the best way to solve the issue?

Yes: hidden attribution at the existing persistence guard fixes the violated contract while retaining model-visible history and clearing unused state after preflight failure.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 390f0f0acb98.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current-main defect remains: Current main submits the synthetic transcript prompt without runtime-specific attribution; runtime-context-prompt.ts selects the marker when human text is empty and runtime fragments are present. (src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts:321, 390f0f0acb98)
  • Repair stays in the existing owner: The guard consumes runtime mode before persistence hooks, retains the message with hidden internal-system metadata, and preserves ordinary replay suppression; all callers use the consolidated setter. (src/agents/session-tool-result-guard.ts:533, 9147c3039ffd)
  • Earlier replay finding resolved: The revision replaces suppression with retained attribution and compares timestamped serialized provider prefixes after a fresh SQLite-backed session reopen, including retry, retention overrides, normal follow-up, and reset. (src/agents/embedded-agent-runner/run/attempt-prompt-submit.runtime-replay.test.ts:137, 9147c3039ffd)
  • Supplied shipped-entry-point proof: The full PR body records an isolated Gateway/native Ollama qwen3:4b run on the reviewed head: RUNTIME_EVENT_ACK, then HUMAN_ACK; reopened SQLite retains one hidden internal marker, and chat.history returns only the seed and genuine follow-up. (9147c3039ffd)
  • Existing storage representation: Persisted user messages already support display false and InputProvenance; internal_system is an existing provenance kind, and the patch introduces no schema change or rewrite of existing rows. (src/sessions/user-turn-transcript.types.ts:41, 9147c3039ffd)
  • Exact-head CI and mergeability: GitHub reports the reviewed head cleanly mergeable; CI run 38117981653 and both check-run/status ci-gate signals succeeded. (9147c3039ffd)

Likely related people:

  • Peter Steinberger: Raw commit 00dce0d adds src/agents/session-tool-result-guard.ts:629 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 00dce0d12424; files: src/agents/session-tool-result-guard.ts)
  • Vincent Koc: Raw commit 9dbf8f7 adds src/agents/session-tool-result-guard.ts:647 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9dbf8f718ff8; files: src/agents/session-tool-result-guard.ts)
  • Dash: Raw commit d35c79e adds src/agents/session-tool-result-guard.ts:311 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d35c79edd63b; files: src/agents/session-tool-result-guard.ts)

PR surface

Source +16, Tests +221, Docs +7, Other +1. Total +245 across 15 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 5 34 18 +16
Tests 8 359 138 +221
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 15 401 156 +245

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +34/-18; tests/support +358/-138 The small production increase adds attribution to the existing persistence owner; coverage protects cold replay and failure cleanup while moving the existing replay table rather than duplicating it.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #124244
Summary: This PR fixes the canonical report's synthetic-turn attribution component, rather than its entire timeout and restart umbrella.

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 repair addresses incorrect session attribution through a supported embedded-runtime entry point without changing configuration or transport behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-04T02:48:03.554Z sha c1acfb2d6aa5f8bbaf955825023edb8d430ec610 :: blocked before merge. :: none
  • reviewed 2026-09-23T04:53:06.488Z sha c1acfb2d6aa5f8bbaf955825023edb8d430ec610 :: needs changes before merge. :: none
  • reviewed 2026-10-07T23:00:41.599Z sha c1acfb2d6aa5f8bbaf955825023edb8d430ec610 :: blocked before merge. :: none
  • reviewed 2026-10-07T23:08:11.746Z sha c1acfb2d6aa5f8bbaf955825023edb8d430ec610 :: blocked before merge. :: none
  • reviewed 2026-10-10T01:36:55.210Z sha 9f00d5017d97776a70678b53bacb2b9d21aec4c7 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-10T04:45:34.278Z sha 6002464 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T05:24:22.473Z sha a5d39c5 :: needs changes before merge. :: [P1] Preserve runtime-only model history across session reopen
  • reviewed 2026-10-11T06:35:27.379Z sha 9147c30 :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 2:50 AM ET / 06:50 UTC (Revision 12).

@LiuwqGit
LiuwqGit force-pushed the feat/issue-124244-runtime-marker-persistence branch from d1f1748 to 6f12149 Compare September 3, 2026 13:06
@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 3, 2026
@LiuwqGit
LiuwqGit force-pushed the feat/issue-124244-runtime-marker-persistence branch from 6f12149 to c1acfb2 Compare September 3, 2026 13:26
@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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 3, 2026
@vincentkoc vincentkoc self-assigned this Sep 9, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. and removed P1 High-priority user-facing bug, regression, or broken workflow. labels Sep 23, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@LiuwqGit

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (d810d753e31) and reconciled with main's existing suppression mechanism, per the clawsweeper review: the guard's setNextUserMessagePersistenceSuppression setter is now reused directly (no new guard API), and the arm/disarm is absorbed into submitEmbeddedAttemptPrompt's existing cleanup finally. Net production change is now +17 lines (was +49/-25). New committed end-to-end regression test fails on unpatched main (marker persisted as a user turn) and passes with the fix; validate.sh plus the agents-root/agents-other type shards are green. CI lanes re-run on Actions.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor

@vincentkoc — coordinating on the transcript-attribution portion of #124244 only. I preserved @LiuwqGit's commit, merged main, consolidated the existing persistence guard API, and added live native Ollama before/after plus early-failure cleanup evidence to the PR body. The timeout/restart symptoms remain outside this PR's claim.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 11, 2026
Keep runtime continuation messages replayable with internal-system provenance and hidden display instead of dropping their model-visible prefix. Reuse the existing guard as the one-shot persistence policy owner; reset pending mode after prompt preflight and consume it before write hooks.

Preserve append-only history through timestamped cold SQLite replay, test blocked-write and preflight cleanup, and move the replay table to its existing host-owned SQLite test lane. Related: openclaw#124244.
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L and removed size: M labels Oct 11, 2026
@steipete

Copy link
Copy Markdown
Contributor

Addressed the cold-reopen prefix finding in 9147c30. The existing guard now retains runtime input as hidden internal-system content instead of dropping it. The timestamped serialized-prefix regression fails under the prior suppression behavior and passes after cold SQLite reopen; the new exact-head Ollama/Gateway proof also verifies visible chat history. Details and the prior CI collection limitation are in the updated body.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@steipete
steipete merged commit 6476fe2 into openclaw:main Oct 11, 2026
176 of 178 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…sion transcripts (openclaw#137273)

Retain runtime-only continuations as hidden internal_system input in the existing persistence guard. Genuine user messages remain visible and correctly attributed, while cold replay preserves the model-visible prefix preceding retained responses and signed thinking. Reset unconsumed runtime mode after early submission failures.

Related: openclaw#124244. This fixes only transcript attribution; timeout, duplicate-send, and restart symptoms remain outside this PR's scope.

Validated by 143 focused tests, exact-head CI, and an isolated Gateway using native Ollama qwen3:4b: reopened SQLite and chat.history retain genuine user input without showing runtime markers as human-authored text. Cold-reopen prefix and early-failure cleanup regressions pass. Autoreview and the completed ClawSweeper review report no actionable findings.

Thanks @LiuwqGit for the original fix.

Co-authored-by: LiuwqGit <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
obviyus added a commit that referenced this pull request Oct 19, 2026
## What Problem This Solves

Fixes: after a provider rate limit (HTTP 429) or another transient failure, the retry and the next turn resend the whole conversation and miss the prompt cache.

## User Impact

User impact: sessions that hit a rate limit keep their prompt cache on the retry and on the following turns, so retries cost fewer uncached input tokens and answer sooner. Internal retry prompts stay hidden from the transcript, as before. There is no configuration, schema or migration change.

## Why This Change Was Made

A transient retry continues the turn with an internal prompt ("Continue the current task…"). That prompt was sent to the model but deliberately not saved. The turn-scoped runtime context sent right after it *was* saved. So the transcript kept the runtime context without the prompt in front of it. The retry and the next run then replayed a different history than the model had already seen: a role change at the old prompt's position. On OpenAI Responses that also drops `previous_response_id` and resends the full input.

Internal prompts now take the same path as runtime-only prompts (#137273): submission saves them as hidden `internal_system` input (`display: false`). Because an internal prompt has no transcript recorder to capture a model-facing projection, it is submitted and saved as the exact text the model receives (`modelPrompt`, or hook prepend + prompt + append). Replay then sends the same bytes. One helper, `resolveModelPromptText`, now owns that text for both normal and internal prompts.

This keeps #122908's guarantee: internal recovery prompts never appear as operator-authored messages.

## Evidence

- **Production pattern (OpenAI Responses Gateway, 4.3 h, logs only):** 227 user-turn `historyRewrite` cache drops. 205 of them were inside a run that had just received `429 rate_limit_exceeded` (tokens per minute). In 215 the model, route and cache key were unchanged, so the cache was lost only because the replayed history changed. Median cached tokens kept after a drop: 12%.
- **Embedded runner, 4 routes** (`src/agents/embedded-agent-runner.prompt-cache.test.ts`, extended with a rate-limited tool continuation and a following turn). It runs through `runEmbeddedAgent` with the durable transcript and byte-level provider prefix checks:
  - `main`: **4 failed** (OpenAI Responses, Chat Completions, Anthropic Messages, Anthropic in-history), each `prefix changed … path=$.role` on the turn after the retry.
  - This branch: **4 passed**.
- **Real Gateway E2E** (`test/e2e/qa-lab/runtime/gateway-rate-limit-prompt-cache.e2e.test.ts`): `chat.send` runs through a QA-lab Gateway, with the mock OpenAI provider returning one 429 on the tool continuation, then an ordinary second turn.
  - `main`: **failed**, `request 4 breaks request 3 prefix at input[4]: was user/message, now assistant/message`.
  - This branch: **passed**.
  - `gateway-rpc-chat.e2e.test.ts`: 9 of 9 passed.
  - Mock provider suite: 189 of 189 passed.
- **Related suites:** 59 files cover submit, LLM boundary, retries, model fallback, settled-turn finalization and the worker runtime. All pass, except one worker background-exec timing test (`worker.runtime.test.ts > stops registered background execs after anchor`, `ENOENT exec.pid`). It failed once under heavy host load and passed 71/71 when its file was rerun alone.
- `pnpm check:changed`: format, typecheck and lint pass for the changed files. Remaining failures (`max-lines suppression ratchet`, `core tsgo graph boundary`, `dead export scan`) are in files this PR does not touch and are already on `main`.
- **Not covered:** the WebSocket Responses transport, Codex-native turns, and a live provider check of `cached_tokens`.

No overlap with Pash/Sarah changes.

**Merge danger:** two-way door. Reverting restores the old behavior. New transcripts gain one hidden `internal_system` user row per internal retry prompt; older builds already read such rows (runtime-only turns write them today). **Blast radius:** embedded runs that retry with an internal prompt (transient provider errors, outer model fallback after dispatch, plugin-runtime refresh, compaction and settled-turn continuations), on all providers. If it is wrong, the model would see an extra hidden continuation prompt in replayed history.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
## What Problem This Solves

Fixes: after a provider rate limit (HTTP 429) or another transient failure, the retry and the next turn resend the whole conversation and miss the prompt cache.

## User Impact

User impact: sessions that hit a rate limit keep their prompt cache on the retry and on the following turns, so retries cost fewer uncached input tokens and answer sooner. Internal retry prompts stay hidden from the transcript, as before. There is no configuration, schema or migration change.

## Why This Change Was Made

A transient retry continues the turn with an internal prompt ("Continue the current task…"). That prompt was sent to the model but deliberately not saved. The turn-scoped runtime context sent right after it *was* saved. So the transcript kept the runtime context without the prompt in front of it. The retry and the next run then replayed a different history than the model had already seen: a role change at the old prompt's position. On OpenAI Responses that also drops `previous_response_id` and resends the full input.

Internal prompts now take the same path as runtime-only prompts (openclaw#137273): submission saves them as hidden `internal_system` input (`display: false`). Because an internal prompt has no transcript recorder to capture a model-facing projection, it is submitted and saved as the exact text the model receives (`modelPrompt`, or hook prepend + prompt + append). Replay then sends the same bytes. One helper, `resolveModelPromptText`, now owns that text for both normal and internal prompts.

This keeps openclaw#122908's guarantee: internal recovery prompts never appear as operator-authored messages.

## Evidence

- **Production pattern (OpenAI Responses Gateway, 4.3 h, logs only):** 227 user-turn `historyRewrite` cache drops. 205 of them were inside a run that had just received `429 rate_limit_exceeded` (tokens per minute). In 215 the model, route and cache key were unchanged, so the cache was lost only because the replayed history changed. Median cached tokens kept after a drop: 12%.
- **Embedded runner, 4 routes** (`src/agents/embedded-agent-runner.prompt-cache.test.ts`, extended with a rate-limited tool continuation and a following turn). It runs through `runEmbeddedAgent` with the durable transcript and byte-level provider prefix checks:
  - `main`: **4 failed** (OpenAI Responses, Chat Completions, Anthropic Messages, Anthropic in-history), each `prefix changed … path=$.role` on the turn after the retry.
  - This branch: **4 passed**.
- **Real Gateway E2E** (`test/e2e/qa-lab/runtime/gateway-rate-limit-prompt-cache.e2e.test.ts`): `chat.send` runs through a QA-lab Gateway, with the mock OpenAI provider returning one 429 on the tool continuation, then an ordinary second turn.
  - `main`: **failed**, `request 4 breaks request 3 prefix at input[4]: was user/message, now assistant/message`.
  - This branch: **passed**.
  - `gateway-rpc-chat.e2e.test.ts`: 9 of 9 passed.
  - Mock provider suite: 189 of 189 passed.
- **Related suites:** 59 files cover submit, LLM boundary, retries, model fallback, settled-turn finalization and the worker runtime. All pass, except one worker background-exec timing test (`worker.runtime.test.ts > stops registered background execs after anchor`, `ENOENT exec.pid`). It failed once under heavy host load and passed 71/71 when its file was rerun alone.
- `pnpm check:changed`: format, typecheck and lint pass for the changed files. Remaining failures (`max-lines suppression ratchet`, `core tsgo graph boundary`, `dead export scan`) are in files this PR does not touch and are already on `main`.
- **Not covered:** the WebSocket Responses transport, Codex-native turns, and a live provider check of `cached_tokens`.

No overlap with Pash/Sarah changes.

**Merge danger:** two-way door. Reverting restores the old behavior. New transcripts gain one hidden `internal_system` user row per internal retry prompt; older builds already read such rows (runtime-only turns write them today). **Blast radius:** embedded runs that retry with an internal prompt (transient provider errors, outer model fallback after dispatch, plugin-runtime refresh, compaction and settled-turn continuations), on all providers. If it is wrong, the model would see an extra hidden continuation prompt in replayed history.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Oct 20, 2026
Co-authored-by: LiuwqGit <[email protected]>

Co-authored-by: Peter Steinberger <[email protected]>

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: L stale Marked as stale due to inactivity status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants