Repository navigation
fix(agents): keep every session prefix append-only on every route - #198100
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
The session system-prompt pin and its appended prompt-update deltas ran only where the transcript policy allowed it (native OpenAI Responses, then every Anthropic Messages route). Chat Completions, Google, Bedrock and every other transport re-rendered the system prompt each attempt, and routes without append-only runtime context stripped the previous turn's carrier, which also changed how that turn's user message was merged. Both rewrote the cached prefix on ordinary user turns, exec wakes, inter-session input and subagent completions. Every session now pins its system prompt on every route; later changes go out as an in-history system message where the route accepts one, otherwise as the existing user-role note. The pinnedSystemPrompt policy flag is gone, and so is the tool-pin-only checkpoint path. Runtime-context carriers stay in history on every route. The series rebuilds only for a new session (/new, /reset), an explicit compaction, or a model or provider switch; the code and docs list these points. The prompt-cache tracker now asserts on system-prompt prefix and suffix changes as well as history and tools, unless the series declared a rebuild. The test suite runs with OPENCLAW_PROMPT_CACHE_ASSERT=1 by default; the two observability suites that change prefixes on purpose opt out. Production logs one warning per session and changed component. A Gateway e2e drives one session through a user turn, an exec wake, a subagent settle, sessions_send, a skill add, a workspace file edit and a compaction against fake anthropic-messages and openai-completions providers. Each provider request must extend the previous one; the only break is at the compaction. Co-authored-by: obviyus <[email protected]>
0941836 to
9195d14
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR extends embedded-session prompt pinning across provider routes, retains runtime context by default, and detects unexpected prefix changes. Example: An ongoing gpt-5.4-mini Chat Completions session receives an AGENTS.md edit adding “Prefer bullets.”
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR remains useful work beyond current main, with no actionable introduced defect found; the latest-stable upgrade evidence resolves the previous compatibility hold. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe embedded Gateway runner combines rendered instructions, provider replay policy, tools, and transcript history into provider requests, while the existing session checkpoint preserves admitted prompt and tool definitions. flowchart LR
A[User and internal turns] --> B[Embedded runner]
C[Provider replay policy] --> B
D[Transcript checkpoint] --> E[Session prompt owner]
B --> E
E --> F[Provider request]
F --> G[Prefix diagnostics]
Technical reviewBest possible solution: Use the existing session prompt owner and combined checkpoint across embedded routes while preserving provider opt-outs and the documented rebuild boundaries. Do we have a high-confidence way to reproduce the issue? Current-main route gating explains why ordinary instruction refreshes replace prompts on Chat Completions and other unpinned routes; supplied real Gateway captures demonstrate the resulting prefix breaks, and no target code was executed during this review. Is this the best way to solve the issue? The patch uses the established prompt-series owner, removes its superseded tool-only persistence path, and preserves plugin authority rather than adding another cache or configuration option. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 73f9a8904411. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -11, Tests +393, Docs +45, Other +32. Total +459 across 31 files. Added test files: 3. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (6 earlier review cycles)
Reviewed November 13, 2026, 2:10 AM ET / 07:10 UTC (Revision 7). |
Gateway state is process-wide; the second route in one file failed before any provider request. One file per route keeps each journey isolated. Co-authored-by: obviyus <[email protected]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
The suite-wide prefix assertion surfaced three suites. Request admission and cache-observation tests change prefixes deliberately. The borrowed settled-finalization suite observes its revoked finalization request against the conversation baseline; it keeps the warning path and the gap is noted for follow-up. Also type the optional prompt commit and a Bedrock base URL in the runtime-preparation tests. Co-authored-by: obviyus <[email protected]>
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
## What Problem This Solves Every chat turn on the embedded runtime adds a hidden runtime-context block to the conversation, with state snapshots: active exec sessions, active subagents, media-generation tasks, approved executables and the current date. Since #198100 these blocks stay in history on every route, so the model keeps seeing every earlier copy. The snapshots were re-sent on every turn even when nothing had changed, so each turn added the same 715–1,066 bytes again. By turn 8 of a plain chat, these repeated snapshots were 49–75% of the message history. They cost context on every later request. ## User Impact Long sessions keep less repeated state in context. A chat turn where nothing changed adds no snapshot bytes. The model still sees the current state: a snapshot is sent again as soon as it changes (for example, when an exec session ends it gets "No active exec-tool sessions"), and after compaction, on a fresh session, or on a route that clears turn-scoped updates, every snapshot is sent in full. Earlier history stays byte-for-byte unchanged, so prompt caching behaves the same. No config, schema or stored-format change. ## Why This Change Was Made - `buildRuntimeFactsContext` now owns one rule: send a snapshot only if it differs from the latest copy the request already carries. A snapshot the request does not carry counts as unknown and is sent in full, including its empty form. - Snapshot identity comes from the headings each producer renders, exported next to the producer. No new stored field: the latest copy is read from the stored carrier, either from its producer fragments or from a projected system update. - The diff base is what the request really sends. Routes that do not retain carriers send no earlier copies. The route that clears turn-scoped system updates (`clear_at: "next_user_message"` on Anthropic) drops those copies. That route fact moves into one function in `transcript-policy.ts`, which both callers use. - `includeEmptySnapshots` is no longer derived from `appendOnlyRuntimeContext` in the embedded path. The CLI runner, the worker launch descriptor and the Codex app-server turn context have the same repetition with different owners; they are not changed here. - I did not make snapshots transient (sent with the current request only and never stored). Prefix-binding Claude models bind each thinking block to the exact prefix before it (#136782), so removing or moving an earlier carrier breaks reasoning replay. It would also undo the append-only contract from #198100. - Related direction: #172313 moves generated inbound metadata out of the system prompt into turn carriers. This change keeps those carriers from re-recording unchanged state. ## Evidence - **Regression test, red on main and green here:** `attempt-prompt-context.test.ts` "does not replay unchanged state snapshots into the next turn's history". On main the turn-2 carrier repeats the temporal, subagent and exec snapshots. - **New tests for the edge cases:** - a retry within one turn adds no second copy; - the first turn after compaction sends every snapshot, empty forms included; - a route that clears turn-scoped updates gets the snapshots again, and a route that keeps them does not; - the reader handles both stored carrier forms (`runtime-facts-prompt.test.ts`). - **Touched and consumer tests green:** prompt context, runtime facts, internal runtime context, media hint cache boundary, `agent-tools.prefix-stability`, subagent active context and catch-up, transcript policy, context advancement, tool-result truncation, runtime marker. `pnpm check:changed` green after one assertion-ratchet fix. - **History bytes per turn, main vs this branch.** Built product (`openclaw agent --local` and a scratch Gateway), 8-turn chat and 8-turn code task, isolated state, provider requests recorded at a TLS proxy. Message bytes of each turn's first request: | Route | Surface | Turn 8 main → branch | Change | |---|---|---|---| | Anthropic Messages (fake provider) | `--local` chat | 7,544 → 2,364 B | −69% | | Anthropic Messages (fake provider) | Gateway chat | 10,942 → 6,511 B | −40% | | Anthropic Messages (fake provider) | `--local` code | 12,741 → 7,561 B | −41% | | Anthropic Messages (fake provider) | Gateway code | 16,133 → 11,702 B | −27% | | OpenAI gpt-5.4-mini, Completions route (served via Responses) | `--local` chat | 10,113 → 4,402 B | −56% | | OpenAI gpt-5.4-mini, Completions route | Gateway chat | 13,365 → 8,842 B | −34% | | OpenAI gpt-5.4-mini, Completions route | `--local` code | 14,378 → 9,489 B | −34% | | OpenAI gpt-5.4-mini, Completions route | Gateway code | 18,157 → 12,938 B | −29% | | OpenAI gpt-5.4-mini, Responses (embedded) | `--local` code | 35,330 → 21,837 B | −38% | | OpenAI gpt-5.4-mini, Responses (embedded) | `--local` chat | carriers 5,680 → 710 B (total varies with encrypted reasoning) | | | OpenAI gpt-5.4-mini, Responses (embedded) | Gateway (`previous_response_id`) | per-turn carrier delta 1,013 → 380 B | | - **Prefix stability:** byte-prefix breaks were 0 on main and 0 on this branch for every full-request pair on all routes above. Real OpenAI cache loss per session was unchanged within noise (for example 820 → 844 and 2,147 → 1,882 tokens). - The remaining Gateway carrier bytes per turn are the per-turn deferred-tool grant and the inbound sender block, which this change does not touch. - **Not measured:** real Anthropic routes with in-history system updates (direct API-key prefix-binding models). They are covered by the cleared-route test only. Co-authored-by: Ayaan Zaidi <[email protected]>
…law#206766) ## What Problem This Solves Every chat turn on the embedded runtime adds a hidden runtime-context block to the conversation, with state snapshots: active exec sessions, active subagents, media-generation tasks, approved executables and the current date. Since openclaw#198100 these blocks stay in history on every route, so the model keeps seeing every earlier copy. The snapshots were re-sent on every turn even when nothing had changed, so each turn added the same 715–1,066 bytes again. By turn 8 of a plain chat, these repeated snapshots were 49–75% of the message history. They cost context on every later request. ## User Impact Long sessions keep less repeated state in context. A chat turn where nothing changed adds no snapshot bytes. The model still sees the current state: a snapshot is sent again as soon as it changes (for example, when an exec session ends it gets "No active exec-tool sessions"), and after compaction, on a fresh session, or on a route that clears turn-scoped updates, every snapshot is sent in full. Earlier history stays byte-for-byte unchanged, so prompt caching behaves the same. No config, schema or stored-format change. ## Why This Change Was Made - `buildRuntimeFactsContext` now owns one rule: send a snapshot only if it differs from the latest copy the request already carries. A snapshot the request does not carry counts as unknown and is sent in full, including its empty form. - Snapshot identity comes from the headings each producer renders, exported next to the producer. No new stored field: the latest copy is read from the stored carrier, either from its producer fragments or from a projected system update. - The diff base is what the request really sends. Routes that do not retain carriers send no earlier copies. The route that clears turn-scoped system updates (`clear_at: "next_user_message"` on Anthropic) drops those copies. That route fact moves into one function in `transcript-policy.ts`, which both callers use. - `includeEmptySnapshots` is no longer derived from `appendOnlyRuntimeContext` in the embedded path. The CLI runner, the worker launch descriptor and the Codex app-server turn context have the same repetition with different owners; they are not changed here. - I did not make snapshots transient (sent with the current request only and never stored). Prefix-binding Claude models bind each thinking block to the exact prefix before it (openclaw#136782), so removing or moving an earlier carrier breaks reasoning replay. It would also undo the append-only contract from openclaw#198100. - Related direction: openclaw#172313 moves generated inbound metadata out of the system prompt into turn carriers. This change keeps those carriers from re-recording unchanged state. ## Evidence - **Regression test, red on main and green here:** `attempt-prompt-context.test.ts` "does not replay unchanged state snapshots into the next turn's history". On main the turn-2 carrier repeats the temporal, subagent and exec snapshots. - **New tests for the edge cases:** - a retry within one turn adds no second copy; - the first turn after compaction sends every snapshot, empty forms included; - a route that clears turn-scoped updates gets the snapshots again, and a route that keeps them does not; - the reader handles both stored carrier forms (`runtime-facts-prompt.test.ts`). - **Touched and consumer tests green:** prompt context, runtime facts, internal runtime context, media hint cache boundary, `agent-tools.prefix-stability`, subagent active context and catch-up, transcript policy, context advancement, tool-result truncation, runtime marker. `pnpm check:changed` green after one assertion-ratchet fix. - **History bytes per turn, main vs this branch.** Built product (`openclaw agent --local` and a scratch Gateway), 8-turn chat and 8-turn code task, isolated state, provider requests recorded at a TLS proxy. Message bytes of each turn's first request: | Route | Surface | Turn 8 main → branch | Change | |---|---|---|---| | Anthropic Messages (fake provider) | `--local` chat | 7,544 → 2,364 B | −69% | | Anthropic Messages (fake provider) | Gateway chat | 10,942 → 6,511 B | −40% | | Anthropic Messages (fake provider) | `--local` code | 12,741 → 7,561 B | −41% | | Anthropic Messages (fake provider) | Gateway code | 16,133 → 11,702 B | −27% | | OpenAI gpt-5.4-mini, Completions route (served via Responses) | `--local` chat | 10,113 → 4,402 B | −56% | | OpenAI gpt-5.4-mini, Completions route | Gateway chat | 13,365 → 8,842 B | −34% | | OpenAI gpt-5.4-mini, Completions route | `--local` code | 14,378 → 9,489 B | −34% | | OpenAI gpt-5.4-mini, Completions route | Gateway code | 18,157 → 12,938 B | −29% | | OpenAI gpt-5.4-mini, Responses (embedded) | `--local` code | 35,330 → 21,837 B | −38% | | OpenAI gpt-5.4-mini, Responses (embedded) | `--local` chat | carriers 5,680 → 710 B (total varies with encrypted reasoning) | | | OpenAI gpt-5.4-mini, Responses (embedded) | Gateway (`previous_response_id`) | per-turn carrier delta 1,013 → 380 B | | - **Prefix stability:** byte-prefix breaks were 0 on main and 0 on this branch for every full-request pair on all routes above. Real OpenAI cache loss per session was unchanged within noise (for example 820 → 844 and 2,147 → 1,882 tokens). - The remaining Gateway carrier bytes per turn are the per-turn deferred-tool grant and the inbound sender block, which this change does not touch. - **Not measured:** real Anthropic routes with in-history system updates (direct API-key prefix-binding models). They are covered by the cleared-route test only. Co-authored-by: Ayaan Zaidi <[email protected]>
What
Make "the session prefix never changes mid-session" a guarantee for every provider route, not a per-route option.
Builds on #197925, which pinned the system prompt on every Anthropic Messages route.
pinnedSystemPrompttranscript-policy flag from fix(agents): pin the session system prompt on every Anthropic Messages route #197925 is removed.prepareSessionSystemPromptnow runs for every route: Chat Completions, Google, Bedrock and any other transport. Later changes go out as appended deltas: an in-history system message where the route accepts one (inHistorySystemUpdates), otherwise the existing user-role note. The tool-pin-only checkpoint path (persistSessionToolSurface) is removed because every session now writes the combined checkpoint.appendOnlyRuntimeContextstripped the previous turn's carrier. On Anthropic Messages that also changed how that turn's user message merged with the carrier. Both rewrote earlier messages on every turn. The new e2e found this.falseper model.appendOnlyRuntimeContext: false, as Gemini's managed explicit caching does. That is also the documented workaround in [Bug]: Claude 5.x via third-party Anthropic-compatible proxy answers the runtime-context carrier instead of the user message (consecutive user turns on non-directanthropic-messagesroutes) #186434 for proxies that answer a trailing carrier.prepareSessionSystemPromptand indocs/reference/prompt-caching.md#session-prefix-stability):/new,/reset);/compactand/neware the operator refresh points. There is no separate refresh command.systemPromptandsystemPromptSuffixchanges, as well as history and tools. Only a declared series rebuild is exempt.test/setup.shared.tsturns onOPENCLAW_PROMPT_CACHE_ASSERT=1for the whole test suite. The two observability suites that change prefixes on purpose opt out explicitly.[prompt-cache] prefix changed within session outside a rebuild point: <component>(...)warning per session and component.test/prompt-cache-prefix-stability.{anthropic,openai-completions}.e2e.test.ts). One session goes through a user turn, an exec completion wake, a subagent settle,sessions_sendfrom another session, a skill add, a workspaceAGENTS.mdedit andsessions.compact. It runs against fakeanthropic-messagesandopenai-completionsproviders. Every provider request must extend the previous one byte for byte (cache markers ignored; a string equals a single text block). The only allowed break is at the compaction. Each route has its own e2e file, because Gateway state is process-wide. Both pass.anthropic-messages.Upgrade behavior
openclaw.system-promptcustom transcript entry. A session that has no checkpoint starts its series on its first turn after the upgrade. That turn sends the freshly rendered prompt, the same request it sends today.latest) created a session with two turns.openclaw doctor --fix, this branch's build resumed it. The first turn sent the stored history (8 messages) and replied normally; 14,848 input tokens were still cached across the upgrade.openclaw doctor --fixfirst, which newermainrequires independently of this PR.Real-route proof
The same journey runs on one target session through a real Gateway: user, exec wake,
sessions_send, skill add, workspace edit, subagent settle, final user. A logging proxy records each provider request and its usage. Before ismainbefore #197925. After is this change on top of #197925's head, measured before the rebase onto currentmain.Anthropic Messages through a custom base URL proxy (Claude Opus 5.5,
cacheRetention: short), target-session requests:OpenAI Chat Completions (
openai-completions, gpt-5.4-mini, automatic prompt caching), target-session requests:The remaining break is an edge case. The exec-wake reply was silent, so replay has no assistant message after that turn. This route merges consecutive user turns, so the next turn's input merged into that turn's trailing prompt-update note. Routes that merge consecutive user turns (strict Chat Completions compatibility, Google, Bedrock) can break once in this way. It happens only when a silent turn also carried a prompt update.
Not covered
prompt-updateentry through the worker transcript-commit path. That is a follow-up.anthropic-messagesroutes) #186434) keep the old transient behavior. Those routes break the previous turn's tail once per turn, as before. The docs list this as an exception.settled-turn-finalization.borrowed.test.tskeeps the warning path, and a comment names the gap. Request-admission and cache-observation suites change prefixes on purpose and opt out the same way.attempt-session-runtime-prepare.test.ts; their delta note uses the same user-role shape that runtime-context carriers already use on those routes.