Skip to content

fix(agents): move the model-context history window only at compaction - #203536

Merged
obviyus merged 1 commit into
mainfrom
fix/stable-history-window
Nov 22, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/stable-history-window

Conversation

@obviyus

@obviyus obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it.

What Problem This Solves

Each attempt (a new turn, a subagent settle, sessions_send, a retry) loads history through selectBoundedModelRequests with a byte cap of contextTokenBudget × 8. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes history_changed/history_shorter, and the full replay hits only instructions and tools.

The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts.

On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are request=1, the first request of an attempt.

Why This Change Was Made

Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction.

  • resolveEmbeddedSessionContextLimits returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires.
  • Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt.
  • The contextTokenBudget plumbing that existed only for this cap is removed (prepareRecoverySession, readCompactionTranscriptBytes, readPreflightTranscriptContextMessages).
  • Unchanged: selectBoundedModelRequests and its fallbacks (quarter-cap steps, fix: next turn starts blank when the previous turn exceeds the byte cap #191146 trailing prompt, fix: keep a sub-agent's task when a retry reloads oversized history #201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps toolResultOverflow: "omit" (fix(agents): keep the turn's request in a bounded summary view after large tool results #184704). With the larger guard, it keeps every result body in every case that fit before.
  • Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing).

Accepted edge cases, without code:

  • A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps.
  • On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact.
  • Plugin harnesses that use resolveAgentHarnessHistoryLimits (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up.

Evidence

Regression step on every transport. The step is in the prefix-stability journey (test/prompt-cache-prefix-stability.test-support.ts). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one.

  • Base 8d1e59c2fddc: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two message 0 breaks each.
  • This head: green on all 5.
  • Mutation: the head with the old budget × 8 cap restored is red again.

Scratch Gateway E2E. Native https://api.openai.com/v1, openai/gpt-6.2-astra, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and response.completed usage were captured.

req base status base input / cached head status head input / cached
1-6 first, then continued 17096/0 … 18214/18099 same same
7 (turn 3, request=1) history_shorter, msg 1 moved, 10 items sent in full 17959 / 16430 continued, 2 items sent 18853 / 18211
8-10 continued … 18853/18738 continued … 19747/19632
11 (turn 5, request=1) history_shorter, msg 1 moved, 13 items sent in full 18598 / 16430 continued, 2 items sent 20386 / 19744
12 continued 19237/18030 continued 21025/19818

16430 is the instructions+tools prefix alone. Base logged historyRewrite(message 0 (user) differs ...) twice, and head logged it zero times.

Tests: the touched test files and every test file that imports a changed source (31 files), pnpm check:changed, oxfmt and oxlint.

What Changes for Users

Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently.

Merge danger

Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it.

Co-authored-by: obviyus [email protected]

Attempts hydrated history through a contextTokenBudget x 8 byte cut. Opaque
replay bytes reach it far below the token budget, so each new attempt dropped
the oldest turns, broke the prompt-cache prefix and hid history from the
compaction estimate. The hydration cap is now a fixed 16 MiB memory guard;
token compaction is the only step that shortens model-visible history.

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

clawsweeper Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Nov 22, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 22, 2026
@clawsweeper

clawsweeper Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces the embedded runtime’s token-scaled history byte cap with a fixed 16 MiB guard and adds screenshot-heavy prefix-stability coverage.

Example: A 64,000-token session reads four screenshots and continues across new attempts.

  • Before: The supplied Gateway capture shows request 7 restarting history with history_shorter and 16,430 cached tokens.
  • After: The corresponding request continues with two new items and 18,211 cached tokens.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with live Gateway evidence on one native transport and production-path regression coverage across five transports.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied isolated Gateway run exercises screenshot reads and subsequent attempts through the native Responses API, recording preserved continuation and cached-token usage; five-transport regression controls support that result.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Long sessions silently lose older model-visible history between attempts, breaking prompt-cache reuse before token compaction is needed.
Reason: The collaborator-authored direction restores the documented stable-context invariant within the retained resource guard.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current history-replay defect with a focused shared-owner change and relevant live evidence; no actionable introduced bug was found.

Priority: P2
Reviewed head: 1713700022eb0bcdc9c81db7b3684c178fca0d03

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded runner loads saved transcript history through a shared bounded selector before preparing provider requests; token compaction summarizes history when context pressure requires it.

flowchart TD
  A[Saved transcript] --> B[Shared history guard]
  B --> C[Embedded attempt]
  C --> D[Provider request]
  D --> A
  C --> E[Token compaction]
  E --> A
Loading

Technical review

Best possible solution:

Land the shared-limit repair once the existing head CI gate passes.

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

Current-main source confirms the premature byte-window path, and the PR supplies matching base/head Gateway observations and regression controls; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change is a small repair at the existing hydration owner, preserves established selector safeguards, and explicitly documents the exceptional guard behavior.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared attempt and recovery hydration limit changes intended behavior with a stated reason (06c345f: Bound recovery to the same canonical window as ordinary attempts to prevent retained-archive amplification.)
  • Chunked history selection keeps the original intent (c16bff1: Preserve local prompt-cache prefixes between byte-cap steps while retaining hard resource bounds.)
  • Settled-finalization omission policy keeps the original intent (5a8be2a: Prefer preserving the original task over large result bodies in the separately keyed finalizer.)
  • Bounded preflight transcript accounting keeps the original intent (33e7baf: Estimate missing usage from the runtime’s bounded context without rescanning the entire saved conversation.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 336bc3c adds test/prompt-cache-prefix-stability.test-support.ts:2 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 336bc3cb723f; files: test/prompt-cache-prefix-stability.test-support.ts)
  • Peter Steinberger: Raw commit b296e41 adds src/agents/compaction-transcript-bytes.ts:18 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b296e41b8f46; files: src/agents/compaction-transcript-bytes.ts)
  • Sukhdeep: Raw commit 5a8be2a adds src/agents/embedded-agent-runner/run/session-context-limits.ts:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 5a8be2a1eb7b; files: src/agents/embedded-agent-runner/run/session-context-limits.ts)
  • Vito Cappello: Raw commit 06c345f adds src/agents/embedded-agent-runner/run/session-context-limits.ts:5 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 06c345ffb7bb; files: src/agents/embedded-agent-runner/run/session-context-limits.ts)

PR surface

Source -6, Tests +61, Docs -3. Total +52 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 15 21 -6
Tests 2 105 44 +61
Docs 1 21 24 -3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 141 89 +52

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 test changes Production +15/-21 lines; tests +105/-44 lines. Production removes obsolete budget plumbing; test growth adds the screenshot regression to an existing Gateway journey.

Labels

Label changes:

  • add P2: Premature history clipping loses useful context and provider cache reuse in screenshot-heavy or opaque-history sessions.
  • 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 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Premature history clipping loses useful context and provider cache reuse in screenshot-heavy or opaque-history sessions.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 execution lanes are retired.

Reviewed November 22, 2026, 11:10 AM ET / 16:10 UTC.

@obviyus
obviyus merged commit 6198f78 into main Nov 22, 2026
141 checks passed
@obviyus
obviyus deleted the fix/stable-history-window branch November 22, 2026 16:16
@obviyus

obviyus commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 6198f78. Bug: every new attempt reloaded history through a contextTokenBudget x 8 byte cut, so opaque-heavy sessions lost their oldest turns and their prompt cache on each request=1. Fix: hydration uses a fixed 16 MiB memory guard, and token compaction is the only step that shortens history. Proof: the new prefix-journey step is red on base and green on head on all 5 transports, and red again when the old cap is restored. Scratch Gateway, native OpenAI Responses: base had 2 history_shorter replays (cached 16430 = instructions+tools only); head had 12/12 requests continued.

obviyus added a commit that referenced this pull request Nov 22, 2026
Result: plugin harnesses (Codex app-server, Agents API, Muse) now read session history with the same guard as the embedded runner. Their history keeps everything since the latest compaction and only grows between compactions. Follow-up to #203536.

## What Problem This Solves

`resolveAgentHarnessHistoryLimits` (Plugin SDK) still computed its own byte cap: `contextTokenBudget × 8`. Each Codex hook/continuity read, Agents API prompt-hook read and Muse session transfer therefore cut the oldest turns once history passed 8 bytes per budget token. Reasoning, images and tool payloads reach that size far below the token budget. Each new attempt reread and cut the history again, so it was rewritten outside compaction. This is the same class #203536 fixed for the embedded runner.

## Why This Change Was Made

- `resolveAgentHarnessHistoryLimits` now returns `resolveEmbeddedSessionContextLimits({})` (16 MiB / 10,000 events) plus its existing `toolResultOverflow: "omit"`. There is one owner for the bound, and the duplicate budget-based computation is gone.
- The export keeps its name and signature. Its `contextTokenBudget` argument is still accepted, but it is **deprecated and ignored** (documented in the doc comment and in `docs/plugins/sdk-agent-harness/attempt-runtime.md`).
- Bundled callers stop passing it. Codex drops the `contextTokenBudget` argument from `readCodexMirroredSessionHistoryMessages` / `readMirroredSessionHistoryMessages`. Agents API drops the limits from its history-reuse scope key: the limits are now constant, so a budget change no longer forces a fresh read. Muse calls it with no argument.
- No schema, protocol or dependency change.

Tests that asserted the removed budget cut are deleted or rewritten:
- Codex `session-history.test.ts`: the budget-128 cut and budget-512 omission tests are replaced by the regression test below.
- `run-attempt.bounded-continuity.test.ts`: the "assistant-only bounded suffix" case is kept. Its user turn is now larger than the 16 MiB guard, so it still covers the fallback past the guard.
- Agents API: the "new budget" retry case is removed, and the pinned `maxBytes: 256_000` assertion is removed.

## Evidence

Regression test through the Codex harness history consumer (`readCodexMirroredSessionHistoryMessages`): 1.3 MB of history, which is past the old default-budget cut and far below compaction. Two consecutive reads with a new turn appended between them.
- Base `2754763da236`: red, `expected … to have a length of 43 but got 25` (the oldest turns were cut).
- Head: green. All 43 messages are returned, and the second read extends the first one exactly.
- Mutation: head with the harness cap set back to `128_000 × 8` is red again (the same 25-message cut).

Tests: the touched test files plus every test file that imports a changed source (25 files), oxfmt/oxlint on the changed files, and `pnpm check:changed`.

## What Changes for Users

Codex, Agents API and Muse sessions with reasoning, screenshots or large tool output keep their whole history (and the provider cache prefix) until compaction. Before, old turns dropped silently on each attempt.

## Merge danger

Two-way door. A revert restores the budget-based cut. Third-party plugins that pass a budget get the shared guard; their call still compiles.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…openclaw#203536)

Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it.

## What Problem This Solves

Each attempt (a new turn, a subagent settle, `sessions_send`, a retry) loads history through `selectBoundedModelRequests` with a byte cap of `contextTokenBudget × 8`. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes `history_changed`/`history_shorter`, and the full replay hits only instructions and tools.

The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts.

On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are `request=1`, the first request of an attempt.

## Why This Change Was Made

Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction.

- `resolveEmbeddedSessionContextLimits` returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires.
- Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt.
- The `contextTokenBudget` plumbing that existed only for this cap is removed (`prepareRecoverySession`, `readCompactionTranscriptBytes`, `readPreflightTranscriptContextMessages`).
- Unchanged: `selectBoundedModelRequests` and its fallbacks (quarter-cap steps, openclaw#191146 trailing prompt, openclaw#201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps `toolResultOverflow: "omit"` (openclaw#184704). With the larger guard, it keeps every result body in every case that fit before.
- Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing).

Accepted edge cases, without code:
- A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps.
- On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact.
- Plugin harnesses that use `resolveAgentHarnessHistoryLimits` (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up.

## Evidence

**Regression step on every transport.** The step is in the prefix-stability journey (`test/prompt-cache-prefix-stability.test-support.ts`). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one.
- Base `735a7475c1fb`: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two `message 0` breaks each.
- This head: green on all 5.
- Mutation: the head with the old `budget × 8` cap restored is red again.

**Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and `response.completed` usage were captured.

| req | base status | base input / cached | head status | head input / cached |
|---|---|---|---|---|
| 1-6 | first, then `continued` | 17096/0 … 18214/18099 | same | same |
| 7 (turn 3, request=1) | `history_shorter`, msg 1 moved, 10 items sent in full | 17959 / **16430** | `continued`, 2 items sent | 18853 / 18211 |
| 8-10 | `continued` | … 18853/18738 | `continued` | … 19747/19632 |
| 11 (turn 5, request=1) | `history_shorter`, msg 1 moved, 13 items sent in full | 18598 / **16430** | `continued`, 2 items sent | 20386 / 19744 |
| 12 | `continued` | 19237/18030 | `continued` | 21025/19818 |

16430 is the instructions+tools prefix alone. Base logged `historyRewrite(message 0 (user) differs ...)` twice, and head logged it zero times.

Tests: the touched test files and every test file that imports a changed source (31 files), `pnpm check:changed`, oxfmt and oxlint.

## What Changes for Users

Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently.

## Merge danger

Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
Result: plugin harnesses (Codex app-server, Agents API, Muse) now read session history with the same guard as the embedded runner. Their history keeps everything since the latest compaction and only grows between compactions. Follow-up to openclaw#203536.

## What Problem This Solves

`resolveAgentHarnessHistoryLimits` (Plugin SDK) still computed its own byte cap: `contextTokenBudget × 8`. Each Codex hook/continuity read, Agents API prompt-hook read and Muse session transfer therefore cut the oldest turns once history passed 8 bytes per budget token. Reasoning, images and tool payloads reach that size far below the token budget. Each new attempt reread and cut the history again, so it was rewritten outside compaction. This is the same class openclaw#203536 fixed for the embedded runner.

## Why This Change Was Made

- `resolveAgentHarnessHistoryLimits` now returns `resolveEmbeddedSessionContextLimits({})` (16 MiB / 10,000 events) plus its existing `toolResultOverflow: "omit"`. There is one owner for the bound, and the duplicate budget-based computation is gone.
- The export keeps its name and signature. Its `contextTokenBudget` argument is still accepted, but it is **deprecated and ignored** (documented in the doc comment and in `docs/plugins/sdk-agent-harness/attempt-runtime.md`).
- Bundled callers stop passing it. Codex drops the `contextTokenBudget` argument from `readCodexMirroredSessionHistoryMessages` / `readMirroredSessionHistoryMessages`. Agents API drops the limits from its history-reuse scope key: the limits are now constant, so a budget change no longer forces a fresh read. Muse calls it with no argument.
- No schema, protocol or dependency change.

Tests that asserted the removed budget cut are deleted or rewritten:
- Codex `session-history.test.ts`: the budget-128 cut and budget-512 omission tests are replaced by the regression test below.
- `run-attempt.bounded-continuity.test.ts`: the "assistant-only bounded suffix" case is kept. Its user turn is now larger than the 16 MiB guard, so it still covers the fallback past the guard.
- Agents API: the "new budget" retry case is removed, and the pinned `maxBytes: 256_000` assertion is removed.

## Evidence

Regression test through the Codex harness history consumer (`readCodexMirroredSessionHistoryMessages`): 1.3 MB of history, which is past the old default-budget cut and far below compaction. Two consecutive reads with a new turn appended between them.
- Base `319099fbfe2d`: red, `expected … to have a length of 43 but got 25` (the oldest turns were cut).
- Head: green. All 43 messages are returned, and the second read extends the first one exactly.
- Mutation: head with the harness cap set back to `128_000 × 8` is red again (the same 25-message cut).

Tests: the touched test files plus every test file that imports a changed source (25 files), oxfmt/oxlint on the changed files, and `pnpm check:changed`.

## What Changes for Users

Codex, Agents API and Muse sessions with reasoning, screenshots or large tool output keep their whole history (and the provider cache prefix) until compaction. Before, old turns dropped silently on each attempt.

## Merge danger

Two-way door. A revert restores the budget-based cut. Third-party plugins that pass a budget get the shared guard; their call still compiles.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 23, 2026
…204028)

Result: the settled-turn finalizer again builds its summary request within eight bytes per context token, so a screenshot-heavy cut-off turn sends a bounded request with the user's request in view. Scheduled `main` CI has been red on `settled-turn-finalization.incomplete.test.ts` since #203536, and this change fixes it. Normal attempts keep the #203536 behavior: all history since the latest compaction, with no per-attempt slide.

## What Problem This Solves

#203536 changed `resolveEmbeddedSessionContextLimits` to a fixed 16 MiB guard for every operation. The settled-tool finalizer (#178300, #184704) also takes its bound from that owner. It answers for its turn alone under its own cache key, and it relied on the old `contextTokenBudget × 8` bound to replace screenshot bodies with short notices before it dropped the turn's request. At 16 MiB the omission never fired, so the finalizer sent every screenshot body.

Measured in the failing test (10 screenshots, 64k context window, bound 524,288 B):

| Build | Finalizer request | Tool-result bodies |
|---|---|---|
| `6198f78b^` | 472,487 B | 4 of 10 replaced by notices (77,339 B → 429 B each) |
| `6198f78b` (#203536) | **780,415 B** | all 10 kept, 77,339 B each |
| this head | 472,487 B | 4 of 10 replaced by notices |

## Why This Change Was Made

- The fix is in the existing owner, `resolveEmbeddedSessionContextLimits`, which already special-cased the finalizer. For `operation: "settled-tool-finalization"`, it returns `min(16 MiB, max(1 KiB, contextTokenBudget × 8))` with `toolResultOverflow: "omit"`. Every other operation keeps the fixed 16 MiB guard.
- The finalizer's cut cannot break an append-only prefix, because it is a separately keyed side request. Normal attempts, recovery and compaction reads are unchanged.
- The 512 KiB test limit is unchanged.
- The `attempt-history-prepare.test.ts` budget case that #203536 deleted is restored. It covers the finalizer omitting a body under a small budget.
- Docs: `docs/concepts/compaction.md` names the finalizer as the one exception to the history guard.

## Evidence

- `settled-turn-finalization.incomplete.test.ts`: passes on `6198f78b^`, fails on `6198f78b` (`expected 780415 to be less than 524288`) and fails on `main`. It passes on this head. The request sizes in the table came from a temporary per-message size log in scratch copies; the log is not committed.
- #203536's prefix-journey step (screenshot chat) passes on all 5 transports on this head.
- The targeted tests pass: every test file that imports `session-context-limits` or one of its callers. `pnpm check:changed` and oxfmt/oxlint pass on the changed files.

## Merge danger

Two-way door. The change touches only the finalizer's bound. A revert restores the oversized finalizer request.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…1766)

(cherry picked from commit 9156690)

Release adaptation: Keep the stable full-prefix test. Exercise in-budget and omitted tool results using stable’s 16 MiB cap; stable no longer sizes this context from contextTokenBudget.

Companion audit: #204028, #203901, #202306 and #203536 are separate finalizer-budget, custody, project-transfer and context-window changes; not dependencies of the timestamp guard.

Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 24, 2026
…penclaw#204028)

Result: the settled-turn finalizer again builds its summary request within eight bytes per context token, so a screenshot-heavy cut-off turn sends a bounded request with the user's request in view. Scheduled `main` CI has been red on `settled-turn-finalization.incomplete.test.ts` since openclaw#203536, and this change fixes it. Normal attempts keep the openclaw#203536 behavior: all history since the latest compaction, with no per-attempt slide.

## What Problem This Solves

openclaw#203536 changed `resolveEmbeddedSessionContextLimits` to a fixed 16 MiB guard for every operation. The settled-tool finalizer (openclaw#178300, openclaw#184704) also takes its bound from that owner. It answers for its turn alone under its own cache key, and it relied on the old `contextTokenBudget × 8` bound to replace screenshot bodies with short notices before it dropped the turn's request. At 16 MiB the omission never fired, so the finalizer sent every screenshot body.

Measured in the failing test (10 screenshots, 64k context window, bound 524,288 B):

| Build | Finalizer request | Tool-result bodies |
|---|---|---|
| `d67eac7f^` | 472,487 B | 4 of 10 replaced by notices (77,339 B → 429 B each) |
| `d67eac7f` (openclaw#203536) | **780,415 B** | all 10 kept, 77,339 B each |
| this head | 472,487 B | 4 of 10 replaced by notices |

## Why This Change Was Made

- The fix is in the existing owner, `resolveEmbeddedSessionContextLimits`, which already special-cased the finalizer. For `operation: "settled-tool-finalization"`, it returns `min(16 MiB, max(1 KiB, contextTokenBudget × 8))` with `toolResultOverflow: "omit"`. Every other operation keeps the fixed 16 MiB guard.
- The finalizer's cut cannot break an append-only prefix, because it is a separately keyed side request. Normal attempts, recovery and compaction reads are unchanged.
- The 512 KiB test limit is unchanged.
- The `attempt-history-prepare.test.ts` budget case that openclaw#203536 deleted is restored. It covers the finalizer omitting a body under a small budget.
- Docs: `docs/concepts/compaction.md` names the finalizer as the one exception to the history guard.

## Evidence

- `settled-turn-finalization.incomplete.test.ts`: passes on `d67eac7f^`, fails on `d67eac7f` (`expected 780415 to be less than 524288`) and fails on `main`. It passes on this head. The request sizes in the table came from a temporary per-message size log in scratch copies; the log is not committed.
- openclaw#203536's prefix-journey step (screenshot chat) passes on all 5 transports on this head.
- The targeted tests pass: every test file that imports `session-context-limits` or one of its callers. `pnpm check:changed` and oxfmt/oxlint pass on the changed files.

## Merge danger

Two-way door. The change touches only the finalizer's bound. A revert restores the oversized finalizer request.

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 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. size: S 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