Skip to content

fix(agents): keep every session prefix append-only on every route - #198100

Merged
obviyus merged 8 commits into
mainfrom
fix/prompt-cache-universal-pin
Nov 13, 2026
Merged

obviyus merged 8 commits into
mainfrom
fix/prompt-cache-universal-pin

Conversation

@obviyus

@obviyus obviyus commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

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.

  • Every route pins the session system prompt. The pinnedSystemPrompt transcript-policy flag from fix(agents): pin the session system prompt on every Anthropic Messages route #197925 is removed. prepareSessionSystemPrompt now 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.
  • Runtime-context carriers are append-only by default on every route. Routes without appendOnlyRuntimeContext stripped 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.
  • Rebuild points are a closed list (in code on prepareSessionSystemPrompt and in docs/reference/prompt-caching.md#session-prefix-stability):
    • a new session (/new, /reset);
    • an explicit compaction;
    • a model or provider switch (API, base URL, system-message capability, or selected personal profile).
    • /compact and /new are the operator refresh points. There is no separate refresh command.
  • Enforcement.
    • The prompt-cache tracker now also asserts on systemPrompt and systemPromptSuffix changes, as well as history and tools. Only a declared series rebuild is exempt.
    • test/setup.shared.ts turns on OPENCLAW_PROMPT_CACHE_ASSERT=1 for the whole test suite. The two observability suites that change prefixes on purpose opt out explicitly.
    • Production logs one [prompt-cache] prefix changed within session outside a rebuild point: <component>(...) warning per session and component.
    • Only the immediate request-to-request difference is enforced. Changes carried as unmeasured cache evidence stay attribution data.
  • Gateway e2e (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_send from another session, a skill add, a workspace AGENTS.md edit and sessions.compact. It runs against fake anthropic-messages and openai-completions providers. 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.
    • Before the carrier fix, the same e2e found 8 breaks outside the compaction on anthropic-messages.

Upgrade behavior

  • No schema change. The series checkpoint is the existing openclaw.system-prompt custom 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.
  • On routes that previously stripped runtime-context carriers, those carriers were never stored (the runtime-replay suite covered that case). Old history therefore replays unchanged, and only new turns store their carriers.
  • Latest stable to this branch on the OpenAI Chat Completions route:
    • OpenClaw 2026.11.3 (npm latest) created a session with two turns.
    • After 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.
    • The second turn extended it with no prefix break (17,280 cached).
  • Base build to this branch, same route:
    • A session created by the base build (29 history messages) resumed on this branch's build. The state needed openclaw doctor --fix first, which newer main requires independently of this PR.
    • The first turn sent the full stored history (32 messages) and replied normally.
    • The second turn extended it with no prefix break: 23,040 of 23,905 input tokens cached.

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 is main before #197925. After is this change on top of #197925's head, measured before the rebase onto current main.

Anthropic Messages through a custom base URL proxy (Claude Opus 5.5, cacheRetention: short), target-session requests:

requests prefix breaks cache write cache read
before 11 5 (all system prompt) 149.2k 212.7k
after 11 0 77.7k 397.8k

OpenAI Chat Completions (openai-completions, gpt-5.4-mini, automatic prompt caching), target-session requests:

requests prefix breaks uncached input cached input
before 11 3 (all system prompt) 39.9k 176.1k
after 10 1 (see below) 24.9k 218.1k

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

  • Remote worker turns still render the system prompt each turn. Pinning them needs two things: the Gateway must read the session checkpoint from the worker's model-context view (it omits custom payloads), and the checkpoint must be written after the worker commits its prompt-update entry through the worker transcript-commit path. That is a follow-up.
  • Provider opt-outs from retained carriers (Gemini managed caching, or a plugin for a proxy affected by [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-direct anthropic-messages routes) #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.
  • Silent turns on merging routes: see the Chat Completions note above.
  • Settled-turn finalization after custody revocation: the suite-wide assertion found that this request is observed against the conversation's baseline. settled-turn-finalization.borrowed.test.ts keeps 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.
  • Tool additions: a tool the session has never sent still extends the tool pin once. That is one break, and the tracker declares it. Freezing additions would hide tools from a session whose first turn had a narrow tool grant.
  • I did not measure Bedrock or Google on a real route. Their pin is covered by attempt-session-runtime-prepare.test.ts; their delta note uses the same user-role shape that runtime-context carriers already use on those routes.
  • The first-to-second-turn cache miss on the proxy route with byte-identical prefixes (noted in fix(agents): pin the session system prompt on every Anthropic Messages route #197925) is unchanged. It is visible as request 2 above in both runs.

@clawsweeper

clawsweeper Bot commented Nov 13, 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 docs Improvements or additions to documentation agents Agent runtime and tooling extensions: anthropic size: XL labels Nov 13, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 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. labels Nov 13, 2026
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]>
@obviyus
obviyus force-pushed the fix/prompt-cache-universal-pin branch from 0941836 to 9195d14 Compare November 13, 2026 05:00
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.”

  • Before: The next request replaces the rendered system prompt, disrupting its cached prefix.
  • After: The system prompt stays pinned and the changed instruction arrives as an appended update.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, coherent, and supported by real-route and stable-upgrade evidence, with documented limits to the prefix guarantee.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Recorded real Gateway journeys exercise prompt refreshes and asynchronous session turns through Anthropic proxy and Chat Completions transports, with after-fix prefix and usage results; a v2026.11.3 session also resumes successfully for two turns using the existing checkpoint format.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Ordinary session activity can rewrite previously sent prompt prefixes, reducing cache reuse and increasing input costs.
Reason: The maintainer-authored change extends an existing invariant with measured real-route benefit and explicitly records its supported scope and exceptions.

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
Reviewed head: c54721cdc90e46c2962d2e63170414aa24c7cdea

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 8a328bf adds src/agents/embedded-agent-runner/session-prompt-state.ts:200 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 8a328bf86189; files: src/agents/embedded-agent-runner/session-prompt-state.ts)

PR surface

Source -11, Tests +393, Docs +45, Other +32. Total +459 across 31 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 8 243 254 -11
Tests 17 587 194 +393
Docs 2 57 12 +45
Config 0 0 0 0
Generated 0 0 0 0
Other 4 50 18 +32
Total 31 937 478 +459

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.

Review metrics

Metric Value Why it matters
Production versus regression coverage Production −21 net lines; tests and support +403 net lines The change removes the separate persistence path and adds shared Gateway coverage for distinct wake, replay, refresh, and compaction boundaries.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Repeated prefix rewrites increase provider input costs during otherwise functioning agent sessions.
  • merge-risk: 🚨 compatibility: Replay defaults and historical carrier retention change across provider routes; the maintainer-authored direction records this tradeoff, preserves explicit plugin overrides, and supplies stable-upgrade evidence.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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 execution lanes are retired.

History

Review history (6 earlier review cycles)
  • reviewed 2026-11-13T05:06:58.416Z sha 9195d14 :: blocked before merge. :: [P2] Check current snapshot differences rather than carried telemetry changes | [P3] Scope the published prefix guarantee to the implemented behavior
  • reviewed 2026-11-13T05:19:45.861Z sha 6d44d02 :: blocked before merge. :: [P2] Check immediate snapshot differences instead of carried telemetry changes | [P3] Scope the published guarantee to supported execution paths
  • reviewed 2026-11-13T05:38:47.264Z sha 4a268ea :: blocked before merge. :: [P2] Preserve the baseline owner's initialization contract
  • reviewed 2026-11-13T05:55:48.770Z sha ee7c103 :: blocked before merge. :: [P2] Preserve the baseline owner's initialization contract
  • reviewed 2026-11-13T06:22:53.659Z sha d152696 :: blocked before merge. :: [P1] Honor explicit provider replay overrides
  • reviewed 2026-11-13T06:42:10.672Z sha c54721c :: blocked before merge. :: none

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]>
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 13, 2026
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]>
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. 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 Nov 13, 2026
obviyus added a commit that referenced this pull request Nov 27, 2026
## 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…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]>
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 extensions: anthropic merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL 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.

1 participant