Repository navigation
feat(compaction): default to provider-native compaction on OpenAI and Anthropic API-key routes - #168164
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR enables provider-native compaction by default on eligible API-key routes and improves checkpoint recovery, redaction handling, and memory-flush isolation. Example: A direct Anthropic API-key session uses claude-sonnet-4-6 with a 200,000-token budget and no compaction override.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it contains useful compaction changes absent from current main, and no actionable introduced bug was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe embedded runner prepares conversation history and provider options; provider transports create compaction checkpoints, and the existing transcript owner persists or removes their replay state. flowchart TD
A[Conversation history] --> B[Embedded runner]
B --> C[Provider eligibility policy]
C --> D[OpenAI or Anthropic transport]
D --> E[Provider compaction checkpoint]
E --> F[Session transcript owner]
F --> A
Technical reviewBest possible solution: Land the reviewed default and recovery changes while preserving opt-outs, route fencing, and client-side recovery. Do we have a high-confidence way to reproduce the issue? Current-main source establishes the manual OpenAI and opt-in Anthropic behavior, while the supplied live runs demonstrate the changed API-key paths; no target code was executed during this review. Is this the best way to solve the issue? The patch extends existing eligibility, transport, and transcript owners rather than introducing a competing compaction path. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 06d231d65279. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +121, Tests +626, Docs +26. Total +773 across 40 files. Added test files: 2. View PR surface stats
Review metrics
LabelsLabel changes: No label 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 (10 earlier review cycles; latest 8 shown)
Reviewed October 10, 2026, 1:13 PM ET / 17:13 UTC (Revision 11). |
|
Owner decision (Ayaan): enable provider-native compaction by default on these routes, including server-side manual Upgrade behavior: there is no schema or stored-row change. Existing sessions keep their transcripts; new provider checkpoints are fenced by provider, model, endpoint, auth profile and session, so a checkpoint is never replayed to a different route. Coverage: "replays captured compaction after restart" reloads a persisted transcript through JSON and replays it, and a rejected Anthropic checkpoint is stripped durably so the next request sends full history. The deprecated transport exports are being restored in a follow-up commit on this PR. |
|
Proof of data-model compatibility for upgrades:
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…n-defaults # Conflicts: # src/agents/embedded-agent-runner/run/attempt-stream-custody.test.ts
|
Landed as 77e2261.
Live numbers are in the PR body: the next turn after compaction reads 88–91% of its input from cache, and recall of planted facts was 3/3 throughout. ChatGPT sign-in follows in #168401. |
… Anthropic API-key routes (openclaw#168164) Related: openclaw#168070, openclaw#168088 ## What Problem This Solves Provider-native ("server-side") compaction keeps the full conversation in a provider checkpoint. It was available but mostly off: - **OpenAI API key:** automatic compaction used `/responses/compact`, but a manual `/compact` always ran client-side summarization. - **Anthropic API key:** threshold compaction was opt-in only. Live runs also exposed three defects on these paths: - **Paid result discarded silently.** `/responses/compact` stored the system prompt inside the returned window. When transcript redaction would change that window (for example, a session key `agent:apikey:…` matched a credential pattern), OpenClaw threw away the paid result, logged it only at DEBUG, and paid again for a client summary. - **Rejected Anthropic checkpoint looped.** When Anthropic rejected a replayed compaction block, the "do not resend" marker lived only on an error output that is never persisted. Every later turn sent the same block and got another 400. - **Anthropic summarizer could call a tool.** With tools defined, Anthropic's default summarizer can call a tool instead of summarizing (documented limitation). ## Fix - **OpenAI API key** (`openai` / `openai-responses` / `api.openai.com`): - Manual `/compact` without focus text now uses `/responses/compact`, like automatic compaction. `/compact <focus>` and overflow recovery stay client-side. `params.responsesCompactEndpoint: false` disables it. - The system prompt is sent as the endpoint's `instructions` field ([API reference](https://developers.openai.com/api/reference/resources/responses/methods/compact)), not inside `input`, so checkpoints no longer store it. - A redaction pre-check on the request content skips the paid call when the stored window could not be saved. - Every skip, discard and fallback logs a WARN with its reason. - **Anthropic API key, direct `api.anthropic.com`:** - Threshold compaction is on by default for the models Anthropic documents for it. `params.anthropicServerCompaction: false` opts out; `true` still opts in other Claude models. OAuth/subscription, Bedrock, Vertex and proxies stay off. - Every compaction edit sends tool-free summarization `instructions`. - Null compaction blocks are not captured. - A rejected replayed block is durably stripped from its transcript owner, so the next turn sends full history. - **Local preflight:** the default Anthropic trigger, `max(50k, 0.7 × budget)`, sits below local preflight compaction, so Anthropic compacts first. Only an explicit opt-in holds local preflight back to the trigger, as before. - **Memory flush:** server compaction (Anthropic threshold and OpenAI inline) is always off for memory-flush runs, so memory extraction sees the unsummarized history. - **Public API:** `@openclaw/ai/transports` keeps `OpenAIResponsesCompactionRejection` as a deprecated alias of `CompactionReplayRejection`, and `resolveOpenAIResponsesCompactEndpointPlan` still accepts its old third `purpose` argument (ignored). - **Not in this PR:** ChatGPT sign-in (Codex-style remote compaction V2). It moved to openclaw#168088 after review showed the request has to be built by the normal-turn pipeline to keep the prompt cache. That route is unchanged here. ## User Impact - **Anthropic API-key users** on Claude Sonnet 4.6, Opus 4.6+, and the 5.x models get provider compaction with no extra request. The next turn reads 88–89% of its input from cache, against 44% after client compaction. - **OpenAI API-key users** get full-fidelity provider checkpoints from manual `/compact`. Next turns are smaller and 91% cached. Each manual `/compact` reads about 131k uncached input tokens, against about 7.4k for a client summary (measured below). - **Opt-out:** `params.responsesCompactEndpoint: false` (OpenAI) or `params.anthropicServerCompaction: false` (Anthropic). Existing sessions keep working; checkpoints are fenced by provider, model, endpoint, auth profile and session. ## Evidence ### Live benchmark Isolated Gateway, synthetic workspace corpus (measured before the ChatGPT code was split out; the API-key route has changed since only by an equivalent inline endpoint check), three facts planted by the user before compaction. Recall was checked on the first turn after compaction. The host was loaded (1-minute load 34–56 on 32 cores), so wall times are upper bounds. **OpenAI API key, gpt-6-astra, ~140k-token session, manual `/compact`:** | | Server (`/responses/compact`) | Client summary | |---|---:|---:| | Provider requests | 1 | 2 | | Compaction input tokens | 130,642 / 131,186 (0 cached) | 7,461 / 7,422 (0 cached) | | Compaction output tokens | 1,186 / 1,123 | 771 / 793 | | Compaction wall time (CLI) | 23.3 s / 34.0 s | 18.1 s / 17.9 s | | Checkpoint size | 14,264 / 13,176 encrypted chars | text summary | | Tokens before → after | 130.6k → 17.9k / 131.2k → 17.6k | 140.2k → 13.8k / 140.3k → 13.8k | | Next turn input, cached | 20.2k, 18.4k cached (91%) | 37.6k, 9.1k / 18.4k cached (24% / 49%) | | Recall of planted facts | 3/3, 3/3 | 3/3, 3/3 | **Anthropic API key, claude-sonnet-5-5, ~100k-token session, trigger lowered via `anthropicCompactThreshold`:** | | Server (inside the turn) | Client summary (manual) | |---|---:|---:| | Extra provider requests | 0 | 2 | | Compaction pass | 97.9k input (23.2k cache read, 74.5k cache write), ~830 output | 7.5k input, 1.6k output | | Wall time | 10.4 s / 14.2 s for compaction plus the answer | 16.1 s | | Next turn input, cache read | 24.1k / 24.4k, 21.4k read (88–89%) | 49.1k, 21.4k read (44%) | | Recall of planted facts | 3/3, 3/3 | 3/3 | **Before this fix (same OpenAI route):** a session key in the system prompt matched a redaction pattern. The paid `/responses/compact` result (130.7k input, ~18 s) was discarded at DEBUG, then 2 more client requests ran, about 37 s in total. ### Targeted live probes - **Anthropic with a tool defined** (claude-sonnet-4-6, claude-sonnet-5-5 with thinking): a summary is captured on every run. Replay shrinks the prompt from about 70–92k to about 1k tokens. Thinking blocks after the compaction block replay fine over 3 turns, with a cache read on turn 3. Seeded facts are recalled. ### Tests - Every changed test file passes. Regressions fail on the pre-fix code: - redaction skip before fetch (endpoint not called); - `instructions` request body; - durable stripping of a rejected Anthropic checkpoint (real `streamAnthropic` with a SQLite session manager); - null-block capture; - default-on Anthropic keeps the local preflight threshold. - `pnpm run tsgo:core`, `tsgo:test:src` and `tsgo:test:packages` pass. `node scripts/check-changed.mjs` passes. - External review: five rounds of an independent model review. Every finding was resolved; the ChatGPT-specific findings moved to openclaw#168088. Co-authored-by: Ayaan Zaidi <[email protected]>
… Anthropic API-key routes (#168164) Backport of 77e2261 (#168164) adapted for 2026.10.2. Adaptations for the release line: - attempt-stream.ts: 10.1 predates installStreamWrapper (#166690); keep the direct session.agent.streamFn wrapping and split the compaction-replay repair (Responses or compactionReplayEnabled) from the Responses-only message transform, as on main. - Extract supportsNativeOpenAIResponsesEndpoint/isOfficialOpenAIResponsesBaseUrl into transports/openai-responses-endpoint.ts and re-export it from @openclaw/ai/internal/openai-responses-payload-policy, matching main's layout (introduced there by #164597) without pulling that feature in. - supportsClaudeServerCompaction delegates to supportsClaudeAdaptiveThinking, which is already id-based on 10.1 (main's ById split came with #167658). - Tests: keep release-only cases (context-management preservation, xAI opt-out, release gate rows without the removed purpose argument), export createRawSseResponse from the new Anthropic transport test-support. (cherry picked from commit 77e2261)
…mpaction V2) (#168401) Closes #168088. Related: #168164. ## What Problem This Solves With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history. ## Fix - **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache. - **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt. - **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them. - **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up. - **Fixed during live testing** (each with a regression that fails on the defect): 1. V2 never ran: the compact request was checked before the async provider adapter dispatched it. 2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there. 3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped. ## User Impact ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off. ## Evidence Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds. | Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall | |---|---:|---:|---:|---:|---:| | Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 | | Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 | | Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 | Request parity, compaction request vs the preceding normal turn: | Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input | |---|---|---|---|---:| | Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% | | Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% | | Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% | The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests. **Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark. **Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover: - request parity; - failed, cancelled and incomplete terminal responses; - aborts; - duplicate or empty items; - multilingual retention; - two consecutive persisted compactions; - the async-dispatch case and replay normalization through the real `SessionManager`. Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes. ## Release-landing follow-ups (2026.10.2) - **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces: - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`. - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request. - Requests with no anchor keep the conservative estimate. - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now. - Production LOC: +45/-27. Most of that is the function split plus contract comments. - **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (#168843; same fix as #168961). - **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment). ### Unrelated failures that also happen on `main` (proof scoped to the tests involved) Both failures reproduce on a clean `origin/main` checkout at `ce5b795128e` with no PR code. Checking out commits around one change shows that both start at 5843d60 (#168539, "route transcript appends through the session actor"): | Test | `5843d60c^` | `5843d60c` | `origin/main` `ce5b795128e` | |---|---|---|---| | `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail | | `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail | - #168981 independently reports the prompt-cache failure on clean main. - #169006 (steering diagnostics) landed and did not fix the steer-fifo failures. - CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here. ### Local proof on the current head All runs below were local and focused on the touched files: - `chatgpt-v2-compaction`: 13/13. - The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`. - `agent-runner.runreplyagent.e2e`: 231/231. - The 3 repaired Gateway e2e files: all passed. - `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests. - Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`. ### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `ff6f58a8c32`) The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain: 1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`): - Fails the same way on a clean `origin/main` checkout at `ff6f58a8c32`, and passes at `bdcbb2d8870` (10/10). - `git bisect` names `e63b5a01cf26` as the first bad commit: #168992, "perf(agents): reduce repeated SQLite work during agent preparation". - This PR does not touch native harness auth. 2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout): - Also fails on the unrelated PR #169026 (CI run 38137511377). - Passes locally (2/2) on this head, on clean `origin/main` `ff6f58a8c32`, and on this branch merged with that main. - This PR touches no `extensions/codex` files. Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head. Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Dallin Romney <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
… runs (#168164) (extracted hotfix) Original subject: feat(compaction): default to provider-native compaction on OpenAI and Anthropic API-key routes (#168164). Extracted from #168164 (77e2261): took only the attempt-stream-settle.ts hunk that sets anthropicServerCompaction/responsesServerCompaction to false in the stream extra-params override when attempt.trigger === "memory", plus the two matching attempt-stream-transport.test.ts cases. On the branch OpenAI Responses inline server compaction is on by default for the openai provider and also applied to memory-flush runs, so memory extraction could see a provider summary instead of the original history. Left out the feature work (Anthropic default-on threshold compaction, manual /compact via /responses/compact, instructions field, redaction pre-check, rejected checkpoint stripping, memory-flush threshold changes): that is a feature and default change, not a hotfix. Extracted-from: 77e2261 Co-authored-by: Ayaan Zaidi <[email protected]>
Release provenance: 89329f6 -> #168587 Release provenance: e6a9022 -> #168905 Release provenance: 15f3f12 -> #162266 Release provenance: 20805b8 -> #169430 Release provenance: 568fec8 -> #169102 Release provenance: 39dba6d -> #160440 Release provenance: 5df28c7 -> #168393 Release provenance: 10bcd8e -> #168164 Release provenance: dc5f1f5 -> #168446 Release provenance: 9f1e441 -> #168044 Release provenance: 5a235fc -> #168651
) Related: #168164 ## What Problem This Solves Fixes the next user turn failing with `Session transcript projection is rebuilding` after provider-native compaction and foreground preemption of session maintenance. ## User Impact The next embedded turn waits for the session's pending transcript projection before reading its saved history. Cancellation remains respected, and detached in-memory transcripts do not wait on unrelated durable state. No configuration, schema, or persisted-format changes. ## Why This Change Was Made The session lane already waits for deferred maintenance, but that work can settle before its independently scheduled transcript projection does. Bounded history hydration then fails closed instead of serving the next turn. Join the existing projection owner at the same pre-global-lane checkpoint; do not retry inference or weaken the history guard. The fail-closed projection guard dates to `7d71d7cf6b3` (#108851), later extracted by `5621979a469`; the missing foreground barrier predates the native-default change. #168164 (`77e2261b573a`) made the API-key compaction path part of the default behavior. This patch does not change the provider's compaction policy. The accompanying request-shape investigation found **no covered-history replay bug** in the reported token growth. Original captures show zero input items before each replayed checkpoint. The mini-model requests had 6, 9, and 8 input items: one checkpoint followed by 5, 8, and 7 later items, respectively. Instructions and tools are still sent, and the model produced new reasoning/tool calls after the inline checkpoint. The docs now explain why token totals alone cannot establish replay duplication. No overlap with Pash/Sarah changes. ## Evidence ### Before Captured on `16d913005f9`, public OpenAI Responses API, API-key authentication, `gpt-5.4-mini`, 50,000-token local context and 22,000-token inline threshold. Two synthetic file reads followed immediately by recall: ```text 2026-10-12T08:59:10.261+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T08:59:16.125+05:30 [diagnostic] lane task error: lane=main durationMs=98 error="Session transcript projection is rebuilding: f126b9b2-109e-4efc-8ff5-d3e1f471ff8c" errorName=SessionTranscriptProjectionUnavailableError taskKind=turn sessionKey=agent:main:v2b-b-gpt-5.4-mini-1791775686 runId=511762d8-1d3f-4bf4-8ac3-4c740679cc52 ``` Recall CLI exited 1 before inference. Inline-request input grew through 23,318 / 25,799 / 40,603 / 52,261 tokens; explicit compaction consumed 55,953 input tokens. ### After One new isolated live campaign with the same API-key model, limits and synthetic two-file/recall flow reproduced the maintenance-preemption condition, but recall completed: ```text 2026-10-12T09:16:43.495+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T09:16:49.874+05:30 Vault code 7291-HERON, courier Isadora, city Hobart. 2026-10-12T09:16:49.876+05:30 [agents/agent-command] [agent] run 53ceae27-6416-4eb2-a68f-c90bd3942337 ended with stopReason=stop ``` Both CLI turns exited 0; recall preserved all 3 planted facts. Explicit compaction consumed 55,074 input tokens; the next user request consumed 18,422 and contained exactly `[compaction, message:user, message:developer]`, with no pre-checkpoint items. The isolated Gateway was stopped and its 0600 credential file deleted. ### Regression and checks - New regression fails before the patch with `SessionTranscriptProjectionUnavailableError: Session transcript projection is rebuilding: foreground-projection`; it passes after the patch using a real SQLite projection rebuild and bounded hydration. - `node scripts/run-vitest.mjs run src/agents/embedded-agent-runner/run-orchestrator.projection.test.ts`: 8 passed. Test execution 27.67 s; wrapper wall time 47.59 s. The added case took 3.633 s in that run. - `pnpm tsgo:core` and `pnpm tsgo:test:src`: passed. - Repository `oxfmt`, focused `oxlint`, and `git diff --check`: passed. - One `pnpm build` with the runtime-only declaration-skip flag and shared build cache: exited 0. It reported the existing advisory Control UI chat-boot request count (38 vs 35); this patch does not change UI code. **Merge risk:** two-way door; reverting restores the previous timing behavior. The blast radius is embedded durable-session startup while a transcript projection rebuild is pending. No schema or storage-format changes, no provider request changes, and no ChatGPT V2 changes. Co-authored-by: Ayaan Zaidi <[email protected]>
…mpaction V2) (openclaw#168401) Closes openclaw#168088. Related: openclaw#168164. ## What Problem This Solves With ChatGPT sign-in, every automatic compaction in OpenClaw ran a client-side summary: separate summarization requests with 0 cached tokens, and a lossy text summary in place of the conversation. Codex compacts the same route server-side ("remote compaction V2"): the next normal model request carries a trailing `{"type":"compaction_trigger"}` item, and the provider returns one opaque `compaction` item that stands in for the history. ## Fix - **Request:** automatic compaction on the ChatGPT route (preflight before a turn, and mid-turn between tool rounds) sends V2 as the next normal request, through the same attempt pipeline and native ChatGPT stream, with `compaction_trigger` appended last. Tools, instructions, parameters, cache key and the full input prefix are the turn's own, so the compaction request reads the warm prompt cache. - **Result:** exactly one non-empty `compaction` item is accepted, only after a successful terminal response and never after an abort. Collection resets for each provider attempt. - **Checkpoint:** real user messages are retained newest-first within 64k tokens, plus the item, matching Codex `compact_remote_v2.rs`. Users retained from an earlier window stay eligible, so repeated compactions keep them. - **Fallback:** every fallback to client compaction logs a WARN with its reason. Overflow recovery, `/compact <focus>` and manual `/compact` stay client-side; manual V2 needs session-writer ownership work and is a follow-up. - **Fixed during live testing** (each with a regression that fails on the defect): 1. V2 never ran: the compact request was checked before the async provider adapter dispatched it. 2. V2 ran only in the managed client; real ChatGPT turns use the native stream. V2 now runs there. 3. Replay normalization dropped the checkpoint turn as an empty failed turn, so the next request grew back to full history. It now keeps successful compaction checkpoints; error turns and suppression markers are still dropped. ## User Impact ChatGPT sign-in sessions compact server-side with no extra summarization requests. Compaction reads 87–100% of its input from cache, and later turns stay at about 14–22k input tokens instead of about 91k. `params.responsesCompactEndpoint: false` turns it off. ## Evidence Live, real ChatGPT OAuth login, `openai/gpt-6-astra`, isolated Gateway, synthetic corpus, three facts seeded before compaction. The host was loaded, so wall times are upper bounds. | Compaction | Compaction input / cached / output | Wall | Input before → after | Next user turn input / cached | Recall | |---|---:|---:|---:|---:|---:| | Preflight | 90,999 / 73,856 / 885 | 20.2 s | 90,999 → 22,308 | 22,439 / 22,144 | 3/3 | | Mid-turn, first | 91,075 / 82,560 / 575 | 12.3 s | 91,075 → 13,904 | 14,121 / 12,928 | 3/3 | | Mid-turn, second | 76,486 / 58,880 / 716 | 17.4 s | 76,486 → 14,476 | 14,709 / 14,336 | 3/3 | Request parity, compaction request vs the preceding normal turn: | Compaction | Tools | Instruction chars | Input prefix | Cached vs previous input | |---|---|---|---|---:| | Preflight | 6 → 6 | 35,857 → 35,857 | 26/26 items identical | 89.3% | | Mid-turn, first | 6 → 6 | 35,855 → 35,855 | 26/26 items identical | 99.8% | | Mid-turn, second | 6 → 6 | 35,855 → 35,855 | 39/39 items identical | 86.7% | The tool schemas, instructions, parameters and cache-key hashes were identical in all three. The final head sent exactly 3 `compaction_trigger` requests, all HTTP 200, and no client-summary requests. **Client comparison (same route, before this change):** one client compaction of a 117.9k-token session took two summary calls (9,777 input, 0 cached, 961 output, 24.4 s). The next turn read 33,967 input with 12,800 cached. Trigger points were not matched to the V2 runs, so this is a reference, not a head-to-head benchmark. **Tests:** fetch-boundary regressions across the managed and native ChatGPT streams cover: - request parity; - failed, cancelled and incomplete terminal responses; - aborts; - duplicate or empty items; - multilingual retention; - two consecutive persisted compactions; - the async-dispatch case and replay normalization through the real `SessionManager`. Negative controls fail on each defect. tsgo core/src/packages pass; `check-changed` passes. ## Release-landing follow-ups (2026.10.2) - **ClawSweeper P2 fix (budget anchor), commit e902124:** V2 used to price the outgoing request with the conservative preflight estimator. That estimator counts unchanged instructions twice, because measured usage already includes them. The V2 boundary now uses the same accounting as the mid-turn precheck it replaces: - The shared code is `resolveProjectedRequestPressure`, split out of `checkMidTurnPrecheck`. - The stream guard's request observation now returns the matching measured predecessor. The foreground request is observed before V2 decides, so both price the same anchor. A checkpoint request is then observed again as its own request. - Requests with no anchor keep the conservative estimate. - Regression test: `chatgpt-v2-compaction.test.ts` "prices a matching measured prefix once before deciding to compact". It uses the 15,000-token / 12,000-char / 24,576 numbers from `attempt-midturn-precheck.test.ts`. It fails on the previous head (the boundary throws `MidTurnPrecheckSignal`) and passes now. - Production LOC: +45/-27. Most of that is the function split plus contract comments. - **Test-only fixture fix, commit 018c9bc:** three Gateway e2e fixtures counted the labeled `OpenClaw runtime context:` carrier as a user turn: `gateway-rpc-chat`, `gateway-provider-review-product-proof` and `gateway-completion-replay`. These fail the same way on `main` (openclaw#168843; same fix as openclaw#168961). - **Rollback to v2026.10.1:** that release's replay normalization drops the empty, zero-usage V2 checkpoint carrier. The raw transcript is never rewritten, so v2026.10.1 replays the full raw history, and its own client compaction applies if that history is too large. Rollback loses no data; it just loses the provider checkpoint. The stored checkpoint format already shipped in v2026.10.1, and its reader ignores the added optional `outputTokens` (details in the compatibility comment). ### Unrelated failures that also happen on `main` (proof scoped to the tests involved) Both failures reproduce on a clean `origin/main` checkout at `02040ecbc92` with no PR code. Checking out commits around one change shows that both start at 9657a374 (openclaw#168539, "route transcript appends through the session actor"): | Test | `9657a374^` | `9657a374` | `origin/main` `02040ecbc92` | |---|---|---|---| | `src/agents/embedded-agent-runner.prompt-cache.test.ts` | 4/4 pass | 2 fail (`SqliteTranscriptMutationConflictError` from `appendSessionManagerActor`) | 2 fail | | `test/gateway-steer-fifo.e2e.test.ts` | 7/7 pass | 3 fail (1 model request where 2 are expected) | 3 fail | - openclaw#168981 independently reports the prompt-cache failure on clean main. - openclaw#169006 (steering diagnostics) landed and did not fix the steer-fifo failures. - CI selects these tests for this PR only through the shared embedded-runner files. Neither failing path is touched here. ### Local proof on the current head All runs below were local and focused on the touched files: - `chatgpt-v2-compaction`: 13/13. - The other affected `src/agents/embedded-agent-runner/run/` unit files: 208/208. These are `attempt-midturn-precheck`, `attempt-prompt-submit.*`, `attempt-stream-*`, `preemptive-compaction*`, `attempt-execution-phase`, `attempt-prompt-preflight` and `attempt-context-guards`. - `agent-runner.runreplyagent.e2e`: 231/231. - The 3 repaired Gateway e2e files: all passed. - `node scripts/check-changed.mjs -- <touched files>` exited 0. That run includes `tsgo` for core and core tests. - Codex protocol check (read directly in `../codex`): `codex-rs/core/src/compact_remote_v2_attempt.rs:70-84` and `compact_remote_v2.rs:65,398-450`. ### Unrelated failures on the current head (b3a7405, which merges `origin/main` at `3dc543d9ee8`) The two failures above (prompt-cache and steer-fifo) no longer fail on this head; main has since landed actor-append fixes. Two other unrelated failures remain: 1. **`src/agents/embedded-agent-runner/run.harness-auth-failover.test.ts`** (5 tests, `checks-node-changed-compact-large-4`): - Fails the same way on a clean `origin/main` checkout at `3dc543d9ee8`, and passes at `596e31d1764` (10/10). - `git bisect` names `70e895e21606` as the first bad commit: openclaw#168992, "perf(agents): reduce repeated SQLite work during agent preparation". - This PR does not touch native harness auth. 2. **`extensions/codex/src/app-server/run-attempt.steering-settlement.test.ts`** (`checks-node-changed-extensions-bundle-3`, 180s hook timeout): - Also fails on the unrelated PR openclaw#169026 (CI run 38137511377). - Passes locally (2/2) on this head, on clean `origin/main` `3dc543d9ee8`, and on this branch merged with that main. - This PR touches no `extensions/codex` files. Two other failures were flaky: `build-artifacts` (`sqlite-sessions-transcripts-flip-proof.built-cli`) and `gateway-completion-replay`. Each passed on rerun, and each passes locally after `pnpm build` on this head. Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Dallin Romney <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
…claw#169583) Related: openclaw#168164 ## What Problem This Solves Fixes the next user turn failing with `Session transcript projection is rebuilding` after provider-native compaction and foreground preemption of session maintenance. ## User Impact The next embedded turn waits for the session's pending transcript projection before reading its saved history. Cancellation remains respected, and detached in-memory transcripts do not wait on unrelated durable state. No configuration, schema, or persisted-format changes. ## Why This Change Was Made The session lane already waits for deferred maintenance, but that work can settle before its independently scheduled transcript projection does. Bounded history hydration then fails closed instead of serving the next turn. Join the existing projection owner at the same pre-global-lane checkpoint; do not retry inference or weaken the history guard. The fail-closed projection guard dates to `9123fde27ed` (openclaw#108851), later extracted by `e227073af94`; the missing foreground barrier predates the native-default change. openclaw#168164 (`5d2c461f092d`) made the API-key compaction path part of the default behavior. This patch does not change the provider's compaction policy. The accompanying request-shape investigation found **no covered-history replay bug** in the reported token growth. Original captures show zero input items before each replayed checkpoint. The mini-model requests had 6, 9, and 8 input items: one checkpoint followed by 5, 8, and 7 later items, respectively. Instructions and tools are still sent, and the model produced new reasoning/tool calls after the inline checkpoint. The docs now explain why token totals alone cannot establish replay duplication. No overlap with Pash/Sarah changes. ## Evidence ### Before Captured on `75b43f6d31e`, public OpenAI Responses API, API-key authentication, `gpt-5.4-mini`, 50,000-token local context and 22,000-token inline threshold. Two synthetic file reads followed immediately by recall: ```text 2026-10-12T08:59:10.261+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T08:59:16.125+05:30 [diagnostic] lane task error: lane=main durationMs=98 error="Session transcript projection is rebuilding: f126b9b2-109e-4efc-8ff5-d3e1f471ff8c" errorName=SessionTranscriptProjectionUnavailableError taskKind=turn sessionKey=agent:main:v2b-b-gpt-5.4-mini-1791775686 runId=511762d8-1d3f-4bf4-8ac3-4c740679cc52 ``` Recall CLI exited 1 before inference. Inline-request input grew through 23,318 / 25,799 / 40,603 / 52,261 tokens; explicit compaction consumed 55,953 input tokens. ### After One new isolated live campaign with the same API-key model, limits and synthetic two-file/recall flow reproduced the maintenance-preemption condition, but recall completed: ```text 2026-10-12T09:16:43.495+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T09:16:49.874+05:30 Vault code 7291-HERON, courier Isadora, city Hobart. 2026-10-12T09:16:49.876+05:30 [agents/agent-command] [agent] run 53ceae27-6416-4eb2-a68f-c90bd3942337 ended with stopReason=stop ``` Both CLI turns exited 0; recall preserved all 3 planted facts. Explicit compaction consumed 55,074 input tokens; the next user request consumed 18,422 and contained exactly `[compaction, message:user, message:developer]`, with no pre-checkpoint items. The isolated Gateway was stopped and its 0600 credential file deleted. ### Regression and checks - New regression fails before the patch with `SessionTranscriptProjectionUnavailableError: Session transcript projection is rebuilding: foreground-projection`; it passes after the patch using a real SQLite projection rebuild and bounded hydration. - `node scripts/run-vitest.mjs run src/agents/embedded-agent-runner/run-orchestrator.projection.test.ts`: 8 passed. Test execution 27.67 s; wrapper wall time 47.59 s. The added case took 3.633 s in that run. - `pnpm tsgo:core` and `pnpm tsgo:test:src`: passed. - Repository `oxfmt`, focused `oxlint`, and `git diff --check`: passed. - One `pnpm build` with the runtime-only declaration-skip flag and shared build cache: exited 0. It reported the existing advisory Control UI chat-boot request count (38 vs 35); this patch does not change UI code. **Merge risk:** two-way door; reverting restores the previous timing behavior. The blast radius is embedded durable-session startup while a transcript projection rebuild is pending. No schema or storage-format changes, no provider request changes, and no ChatGPT V2 changes. Co-authored-by: Ayaan Zaidi <[email protected]>
) Related: #168164 ## What Problem This Solves Fixes the next user turn failing with `Session transcript projection is rebuilding` after provider-native compaction and foreground preemption of session maintenance. ## User Impact The next embedded turn waits for the session's pending transcript projection before reading its saved history. Cancellation remains respected, and detached in-memory transcripts do not wait on unrelated durable state. No configuration, schema, or persisted-format changes. ## Why This Change Was Made The session lane already waits for deferred maintenance, but that work can settle before its independently scheduled transcript projection does. Bounded history hydration then fails closed instead of serving the next turn. Join the existing projection owner at the same pre-global-lane checkpoint; do not retry inference or weaken the history guard. The fail-closed projection guard dates to `7d71d7cf6b3` (#108851), later extracted by `5621979a469`; the missing foreground barrier predates the native-default change. #168164 (`77e2261b573a`) made the API-key compaction path part of the default behavior. This patch does not change the provider's compaction policy. The accompanying request-shape investigation found **no covered-history replay bug** in the reported token growth. Original captures show zero input items before each replayed checkpoint. The mini-model requests had 6, 9, and 8 input items: one checkpoint followed by 5, 8, and 7 later items, respectively. Instructions and tools are still sent, and the model produced new reasoning/tool calls after the inline checkpoint. The docs now explain why token totals alone cannot establish replay duplication. No overlap with Pash/Sarah changes. ## Evidence ### Before Captured on `16d913005f9`, public OpenAI Responses API, API-key authentication, `gpt-5.4-mini`, 50,000-token local context and 22,000-token inline threshold. Two synthetic file reads followed immediately by recall: ```text 2026-10-12T08:59:10.261+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T08:59:16.125+05:30 [diagnostic] lane task error: lane=main durationMs=98 error="Session transcript projection is rebuilding: f126b9b2-109e-4efc-8ff5-d3e1f471ff8c" errorName=SessionTranscriptProjectionUnavailableError taskKind=turn sessionKey=agent:main:v2b-b-gpt-5.4-mini-1791775686 runId=511762d8-1d3f-4bf4-8ac3-4c740679cc52 ``` Recall CLI exited 1 before inference. Inline-request input grew through 23,318 / 25,799 / 40,603 / 52,261 tokens; explicit compaction consumed 55,953 input tokens. ### After One new isolated live campaign with the same API-key model, limits and synthetic two-file/recall flow reproduced the maintenance-preemption condition, but recall completed: ```text 2026-10-12T09:16:43.495+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T09:16:49.874+05:30 Vault code 7291-HERON, courier Isadora, city Hobart. 2026-10-12T09:16:49.876+05:30 [agents/agent-command] [agent] run 53ceae27-6416-4eb2-a68f-c90bd3942337 ended with stopReason=stop ``` Both CLI turns exited 0; recall preserved all 3 planted facts. Explicit compaction consumed 55,074 input tokens; the next user request consumed 18,422 and contained exactly `[compaction, message:user, message:developer]`, with no pre-checkpoint items. The isolated Gateway was stopped and its 0600 credential file deleted. ### Regression and checks - New regression fails before the patch with `SessionTranscriptProjectionUnavailableError: Session transcript projection is rebuilding: foreground-projection`; it passes after the patch using a real SQLite projection rebuild and bounded hydration. - `node scripts/run-vitest.mjs run src/agents/embedded-agent-runner/run-orchestrator.projection.test.ts`: 8 passed. Test execution 27.67 s; wrapper wall time 47.59 s. The added case took 3.633 s in that run. - `pnpm tsgo:core` and `pnpm tsgo:test:src`: passed. - Repository `oxfmt`, focused `oxlint`, and `git diff --check`: passed. - One `pnpm build` with the runtime-only declaration-skip flag and shared build cache: exited 0. It reported the existing advisory Control UI chat-boot request count (38 vs 35); this patch does not change UI code. **Merge risk:** two-way door; reverting restores the previous timing behavior. The blast radius is embedded durable-session startup while a transcript projection rebuild is pending. No schema or storage-format changes, no provider request changes, and no ChatGPT V2 changes. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 50c3948)
) Related: #168164 ## What Problem This Solves Fixes the next user turn failing with `Session transcript projection is rebuilding` after provider-native compaction and foreground preemption of session maintenance. ## User Impact The next embedded turn waits for the session's pending transcript projection before reading its saved history. Cancellation remains respected, and detached in-memory transcripts do not wait on unrelated durable state. No configuration, schema, or persisted-format changes. ## Why This Change Was Made The session lane already waits for deferred maintenance, but that work can settle before its independently scheduled transcript projection does. Bounded history hydration then fails closed instead of serving the next turn. Join the existing projection owner at the same pre-global-lane checkpoint; do not retry inference or weaken the history guard. The fail-closed projection guard dates to `7d71d7cf6b3` (#108851), later extracted by `5621979a469`; the missing foreground barrier predates the native-default change. #168164 (`77e2261b573a`) made the API-key compaction path part of the default behavior. This patch does not change the provider's compaction policy. The accompanying request-shape investigation found **no covered-history replay bug** in the reported token growth. Original captures show zero input items before each replayed checkpoint. The mini-model requests had 6, 9, and 8 input items: one checkpoint followed by 5, 8, and 7 later items, respectively. Instructions and tools are still sent, and the model produced new reasoning/tool calls after the inline checkpoint. The docs now explain why token totals alone cannot establish replay duplication. No overlap with Pash/Sarah changes. ## Evidence ### Before Captured on `16d913005f9`, public OpenAI Responses API, API-key authentication, `gpt-5.4-mini`, 50,000-token local context and 22,000-token inline threshold. Two synthetic file reads followed immediately by recall: ```text 2026-10-12T08:59:10.261+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T08:59:16.125+05:30 [diagnostic] lane task error: lane=main durationMs=98 error="Session transcript projection is rebuilding: f126b9b2-109e-4efc-8ff5-d3e1f471ff8c" errorName=SessionTranscriptProjectionUnavailableError taskKind=turn sessionKey=agent:main:v2b-b-gpt-5.4-mini-1791775686 runId=511762d8-1d3f-4bf4-8ac3-4c740679cc52 ``` Recall CLI exited 1 before inference. Inline-request input grew through 23,318 / 25,799 / 40,603 / 52,261 tokens; explicit compaction consumed 55,953 input tokens. ### After One new isolated live campaign with the same API-key model, limits and synthetic two-file/recall flow reproduced the maintenance-preemption condition, but recall completed: ```text 2026-10-12T09:16:43.495+05:30 [agent/embedded] context-engine compaction failed errorMessage="Session maintenance yielded to a foreground turn" 2026-10-12T09:16:49.874+05:30 Vault code 7291-HERON, courier Isadora, city Hobart. 2026-10-12T09:16:49.876+05:30 [agents/agent-command] [agent] run 53ceae27-6416-4eb2-a68f-c90bd3942337 ended with stopReason=stop ``` Both CLI turns exited 0; recall preserved all 3 planted facts. Explicit compaction consumed 55,074 input tokens; the next user request consumed 18,422 and contained exactly `[compaction, message:user, message:developer]`, with no pre-checkpoint items. The isolated Gateway was stopped and its 0600 credential file deleted. ### Regression and checks - New regression fails before the patch with `SessionTranscriptProjectionUnavailableError: Session transcript projection is rebuilding: foreground-projection`; it passes after the patch using a real SQLite projection rebuild and bounded hydration. - `node scripts/run-vitest.mjs run src/agents/embedded-agent-runner/run-orchestrator.projection.test.ts`: 8 passed. Test execution 27.67 s; wrapper wall time 47.59 s. The added case took 3.633 s in that run. - `pnpm tsgo:core` and `pnpm tsgo:test:src`: passed. - Repository `oxfmt`, focused `oxlint`, and `git diff --check`: passed. - One `pnpm build` with the runtime-only declaration-skip flag and shared build cache: exited 0. It reported the existing advisory Control UI chat-boot request count (38 vs 35); this patch does not change UI code. **Merge risk:** two-way door; reverting restores the previous timing behavior. The blast radius is embedded durable-session startup while a transcript projection rebuild is pending. No schema or storage-format changes, no provider request changes, and no ChatGPT V2 changes. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 50c3948)
…orb step 24 Four conflicts: - server-endpoint-compaction: upstream openclaw#168164 made the compact-endpoint plan purpose-independent; our trigger mapping (volitional -> manual) is moot, so take upstream's call. Volitional compaction now follows the same provider-native default as manual/budget. - tsgo-core-test-shards: our four split shards plus upstream's ui-e2e-chat. - plugin-sdk-surface-report: upstream 3655/2121; ours +11/+4. Measured 3666/2125. - worker-access-inventory.md: regenerated (623 files, 2444 calls). tsgo core, core test shards, extensions, extensions projects: 0. plugin-sdk:surface:check 0; db:worker-inventory:check 0. Lockfile unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
…o "no endpoint" The step-24 absorb took upstream openclaw#168164 (77e2261), which made the compact-endpoint plan purpose-independent: manual compaction now uses the provider-native endpoint. Our test asserted volitional never calls the endpoint, which only held while manual never did. The contract is that volitional compaction follows the manual policy. Assert that directly: on both providers, volitional issues the same endpoint request (model, context, options; the per-attempt AbortSignal excepted) and the same result as manual, and manual issues exactly one request. GREEN 24/24; with the source changed to skip the endpoint for volitional only, RED 2/24; restored, GREEN 24/24. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
Related: #168164 ([default-on change](77e2261)). ## What Problem This Solves Fixes OpenAI Responses native compaction replacing the history selected by a context engine that owns compaction, including when reopening an already-checkpointed session. ## User Impact Compaction-owning engines such as Lossless keep control of their selected history. Existing sessions need no reset: stored checkpoints are bypassed for the outgoing request, not deleted. The built-in `legacy` engine keeps its defaults. Explicit `params.responsesServerCompaction: true` still opts into provider-managed history, which can take precedence over engine assembly. Anthropic behavior is unchanged. ## Why This Change Was Made Default-on Responses compaction introduced a second history owner underneath engines declaring `info.ownsCompaction`. Disabling new compaction alone is insufficient: an old checkpoint can still slice the newly assembled history. Pass the active engine information to the existing attempt-transport preparation owner. One OpenAI-only decision controls server compaction, automatic `/responses/compact` eligibility, replay eligibility, and non-mutating checkpoint removal at stream entry. On these direct API-key routes, memory-extraction turns also bypass Responses compaction/replay. Native ChatGPT V2 (`openai-chatgpt-responses`) is unchanged. No new configuration, migration, or persistent state is introduced. The existing checkpoint utilities are reused. ## Evidence Baseline: `a1506c240abaa0781b7a462c30c653d2caf14dd4`. Current head: **`b995a36552f09bf88e5b2b928f298d87cf9bf826`**. The narrowed runtime was rebuilt and tested at **`b2c27afd646c1951dfb34f3fbf81b0cd08f0b203`**; the only later changes are the two documentation corrections requested by review. Tests use the installed Lossless 1.1.1 plugin, isolated Gateway state, direct API-key authentication, and the same CLI/session flow before and after. | E2E cell | BEFORE | AFTER | | --- | --- | --- | | Owning engine, default; five turns | The same upgrade fixture emitted compaction on all five requests, persisted checkpoints, and replaced selected literal markers with opaque replay on turns 2–5. | Narrowed runtime `b2c27afd646c`: 5/5 successful turns, no native compaction or checkpoint replay; complete response-ID chains contain every selected marker, including the early marker on all five turns. | | Checkpointed-session upgrade | Five turns on the baseline produced five stored checkpoints with Lossless loaded and owning compaction. | Narrowed runtime `b2c27afd646c` on the **same state**: plugin active, engine owns compaction, 2/2 successful turns, all selected markers present in reconstructed effective input, early marker recalled both times. Stored checkpoint hashes are unchanged; no compaction/replay was sent. Answers also included the original turn tag, so exact-output-format equality is not claimed. | | Owning engine, default, repeated | Baseline checkpoint override observed in the same flow. | Pre-narrowing `5abec9c7e5a`: two independent five-turn runs preserved all selected markers through complete effective chains. | | Upgrade, repeated | Each baseline phase persisted real checkpoints. | Pre-narrowing `5abec9c7e5a`: two independent upgrades preserved selection and recalled the early marker in both post-upgrade turns. One run also returned the turn tag. | | Lossless non-append selection | Not a separate baseline claim. | Pre-narrowing `5abec9c7e5a`: five successful turns, three real Lossless summary requests, two non-append assembly changes. Both changes sent full input without `previous_response_id`; every selected marker was present. No continuation retained the old raw prefix. | | `legacy` default, two repeats | Native compaction retained; five successful turns per repeat. | Pre-narrowing `5abec9c7e5a`: native compaction retained; five successful turns per repeat. | | Owning engine with explicit opt-in, two repeats | Native compaction retained; five successful turns per repeat. | Pre-narrowing `5abec9c7e5a`: native compaction retained; five successful turns per repeat. | | Binary-swap runtime controls, two repeats each | BEFORE → BEFORE and BEFORE → current-main control. | BEFORE → candidate also passed: installed plugin loaded/active after every swap. | The narrowed-runtime core and upgrade cells exercise the exact runtime source at the current head; only documentation changed afterward. The other AFTER rows are explicitly pre-narrowing evidence; their OpenAI behavior was not changed by removing the unproven Anthropic policy. No completed compatibility cell was rerun. Effective input is reconstructed as previous effective input + previous output + request delta. Full requests start new chains. Opaque provider checkpoints are **not** treated as readable context: BEFORE proves the literal-selection override, not the contents of the encrypted summary or an unobserved recall failure. AFTER chains are complete and contain all selected markers. Marker inclusion is not a claim of byte-for-byte equality for every transport-normalized item. The earlier plugin `Unexpected token ')'` error was an external observer-fixture syntax error. Correcting its Proxy closure resolved it on all three binary-swap controls. Anthropic experiments did not prove history loss because Lossless stubbed the oversized input; those behavior/doc changes were removed rather than extending the fix speculatively. **Stored-data compatibility:** `77e2261b573` (#168164), which introduced the affected default-on provider compaction path, is not an ancestor of `v2026.10.4` (`git merge-base --is-ancestor` exits 1). That release did not write checkpoints through the affected default-on owning-engine path. This fix adds no persisted fields, schema, writer, migration, or deletion. The same-state checkpoint upgrade above covers affected main/beta sessions and verifies the original stored checkpoint hashes remain unchanged. A release-to-head run cannot qualify a default-on checkpoint path absent from that release. Focused checks on the unchanged narrowed runtime: - `node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-stream-transport.test.ts src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.ts`: **2 files, 30 tests passed**; Vitest 64.42 s, wrapper 72.59 s. The matrix covers OpenAI ownership/default/false/true/memory and unchanged Anthropic behavior. The original regression failed on the baseline. - Scoped `oxfmt` and direct `oxlint`: passed. `pnpm build`: passed (9m 36s). After the docs-only review correction, `pnpm docs:check-links` checked 15,624 internal links with zero broken links, and `git diff --check` passed. [Current-head CI passed](https://github.com/openclaw/openclaw/actions/runs/38987676167): 35 successful jobs, zero failures or cancellations. ClawSweeper is ready on `b995a36552f09bf88e5b2b928f298d87cf9bf826` with no findings. - Total OpenAI accounted input including cached input: 1,593,120; conservative reservations: 1,923,335, below the 2.5M cap. No credentials retained. Simplification: one existing decision owner and no new state/helper layer; cumulative production delta +33/−5 lines and tests +82/−1. Unproven Anthropic behavior was removed. **Merge danger:** two-way code change, with no stored-data migration or deletion. Reverting restores the old behavior but cannot recover context a provider may summarize afterward. Blast radius is embedded OpenAI Responses sessions using compaction-owning engines (and Responses memory extraction); a wrong ownership decision could omit selected history or retain stale provider history. Legacy, explicit opt-in, and non-OpenAI routes keep their existing contracts. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: openclaw#168164 ([default-on change](openclaw@5d2c461)). ## What Problem This Solves Fixes OpenAI Responses native compaction replacing the history selected by a context engine that owns compaction, including when reopening an already-checkpointed session. ## User Impact Compaction-owning engines such as Lossless keep control of their selected history. Existing sessions need no reset: stored checkpoints are bypassed for the outgoing request, not deleted. The built-in `legacy` engine keeps its defaults. Explicit `params.responsesServerCompaction: true` still opts into provider-managed history, which can take precedence over engine assembly. Anthropic behavior is unchanged. ## Why This Change Was Made Default-on Responses compaction introduced a second history owner underneath engines declaring `info.ownsCompaction`. Disabling new compaction alone is insufficient: an old checkpoint can still slice the newly assembled history. Pass the active engine information to the existing attempt-transport preparation owner. One OpenAI-only decision controls server compaction, automatic `/responses/compact` eligibility, replay eligibility, and non-mutating checkpoint removal at stream entry. On these direct API-key routes, memory-extraction turns also bypass Responses compaction/replay. Native ChatGPT V2 (`openai-chatgpt-responses`) is unchanged. No new configuration, migration, or persistent state is introduced. The existing checkpoint utilities are reused. ## Evidence Baseline: `f35c075db7aca3c2a5db177ee56ffc8dc1e6dc63`. Current head: **`b995a36552f09bf88e5b2b928f298d87cf9bf826`**. The narrowed runtime was rebuilt and tested at **`b2c27afd646c1951dfb34f3fbf81b0cd08f0b203`**; the only later changes are the two documentation corrections requested by review. Tests use the installed Lossless 1.1.1 plugin, isolated Gateway state, direct API-key authentication, and the same CLI/session flow before and after. | E2E cell | BEFORE | AFTER | | --- | --- | --- | | Owning engine, default; five turns | The same upgrade fixture emitted compaction on all five requests, persisted checkpoints, and replaced selected literal markers with opaque replay on turns 2–5. | Narrowed runtime `b2c27afd646c`: 5/5 successful turns, no native compaction or checkpoint replay; complete response-ID chains contain every selected marker, including the early marker on all five turns. | | Checkpointed-session upgrade | Five turns on the baseline produced five stored checkpoints with Lossless loaded and owning compaction. | Narrowed runtime `b2c27afd646c` on the **same state**: plugin active, engine owns compaction, 2/2 successful turns, all selected markers present in reconstructed effective input, early marker recalled both times. Stored checkpoint hashes are unchanged; no compaction/replay was sent. Answers also included the original turn tag, so exact-output-format equality is not claimed. | | Owning engine, default, repeated | Baseline checkpoint override observed in the same flow. | Pre-narrowing `5abec9c7e5a`: two independent five-turn runs preserved all selected markers through complete effective chains. | | Upgrade, repeated | Each baseline phase persisted real checkpoints. | Pre-narrowing `5abec9c7e5a`: two independent upgrades preserved selection and recalled the early marker in both post-upgrade turns. One run also returned the turn tag. | | Lossless non-append selection | Not a separate baseline claim. | Pre-narrowing `5abec9c7e5a`: five successful turns, three real Lossless summary requests, two non-append assembly changes. Both changes sent full input without `previous_response_id`; every selected marker was present. No continuation retained the old raw prefix. | | `legacy` default, two repeats | Native compaction retained; five successful turns per repeat. | Pre-narrowing `5abec9c7e5a`: native compaction retained; five successful turns per repeat. | | Owning engine with explicit opt-in, two repeats | Native compaction retained; five successful turns per repeat. | Pre-narrowing `5abec9c7e5a`: native compaction retained; five successful turns per repeat. | | Binary-swap runtime controls, two repeats each | BEFORE → BEFORE and BEFORE → current-main control. | BEFORE → candidate also passed: installed plugin loaded/active after every swap. | The narrowed-runtime core and upgrade cells exercise the exact runtime source at the current head; only documentation changed afterward. The other AFTER rows are explicitly pre-narrowing evidence; their OpenAI behavior was not changed by removing the unproven Anthropic policy. No completed compatibility cell was rerun. Effective input is reconstructed as previous effective input + previous output + request delta. Full requests start new chains. Opaque provider checkpoints are **not** treated as readable context: BEFORE proves the literal-selection override, not the contents of the encrypted summary or an unobserved recall failure. AFTER chains are complete and contain all selected markers. Marker inclusion is not a claim of byte-for-byte equality for every transport-normalized item. The earlier plugin `Unexpected token ')'` error was an external observer-fixture syntax error. Correcting its Proxy closure resolved it on all three binary-swap controls. Anthropic experiments did not prove history loss because Lossless stubbed the oversized input; those behavior/doc changes were removed rather than extending the fix speculatively. **Stored-data compatibility:** `5d2c461f092` (openclaw#168164), which introduced the affected default-on provider compaction path, is not an ancestor of `v2026.10.4` (`git merge-base --is-ancestor` exits 1). That release did not write checkpoints through the affected default-on owning-engine path. This fix adds no persisted fields, schema, writer, migration, or deletion. The same-state checkpoint upgrade above covers affected main/beta sessions and verifies the original stored checkpoint hashes remain unchanged. A release-to-head run cannot qualify a default-on checkpoint path absent from that release. Focused checks on the unchanged narrowed runtime: - `node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt-stream-transport.test.ts src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.ts`: **2 files, 30 tests passed**; Vitest 64.42 s, wrapper 72.59 s. The matrix covers OpenAI ownership/default/false/true/memory and unchanged Anthropic behavior. The original regression failed on the baseline. - Scoped `oxfmt` and direct `oxlint`: passed. `pnpm build`: passed (9m 36s). After the docs-only review correction, `pnpm docs:check-links` checked 15,624 internal links with zero broken links, and `git diff --check` passed. [Current-head CI passed](https://github.com/openclaw/openclaw/actions/runs/38987676167): 35 successful jobs, zero failures or cancellations. ClawSweeper is ready on `b995a36552f09bf88e5b2b928f298d87cf9bf826` with no findings. - Total OpenAI accounted input including cached input: 1,593,120; conservative reservations: 1,923,335, below the 2.5M cap. No credentials retained. Simplification: one existing decision owner and no new state/helper layer; cumulative production delta +33/−5 lines and tests +82/−1. Unproven Anthropic behavior was removed. **Merge danger:** two-way code change, with no stored-data migration or deletion. Reverting restores the old behavior but cannot recover context a provider may summarize afterward. Blast radius is embedded OpenAI Responses sessions using compaction-owning engines (and Responses memory extraction); a wrong ownership decision could omit selected history or retain stale provider history. Legacy, explicit opt-in, and non-OpenAI routes keep their existing contracts. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #168070, #168088
What Problem This Solves
Provider-native ("server-side") compaction keeps the full conversation in a provider checkpoint. It was available but mostly off:
/responses/compact, but a manual/compactalways ran client-side summarization.Live runs also exposed three defects on these paths:
/responses/compactstored the system prompt inside the returned window. When transcript redaction would change that window (for example, a session keyagent:apikey:…matched a credential pattern), OpenClaw threw away the paid result, logged it only at DEBUG, and paid again for a client summary.Fix
openai/openai-responses/api.openai.com):/compactwithout focus text now uses/responses/compact, like automatic compaction./compact <focus>and overflow recovery stay client-side.params.responsesCompactEndpoint: falsedisables it.instructionsfield (API reference), not insideinput, so checkpoints no longer store it.api.anthropic.com:params.anthropicServerCompaction: falseopts out;truestill opts in other Claude models. OAuth/subscription, Bedrock, Vertex and proxies stay off.instructions.max(50k, 0.7 × budget), sits below local preflight compaction, so Anthropic compacts first. Only an explicit opt-in holds local preflight back to the trigger, as before.@openclaw/ai/transportskeepsOpenAIResponsesCompactionRejectionas a deprecated alias ofCompactionReplayRejection, andresolveOpenAIResponsesCompactEndpointPlanstill accepts its old thirdpurposeargument (ignored).User Impact
/compact. Next turns are smaller and 91% cached. Each manual/compactreads about 131k uncached input tokens, against about 7.4k for a client summary (measured below).params.responsesCompactEndpoint: false(OpenAI) orparams.anthropicServerCompaction: false(Anthropic). Existing sessions keep working; checkpoints are fenced by provider, model, endpoint, auth profile and session.Evidence
Live benchmark
Isolated Gateway, synthetic workspace corpus (measured before the ChatGPT code was split out; the API-key route has changed since only by an equivalent inline endpoint check), three facts planted by the user before compaction. Recall was checked on the first turn after compaction. The host was loaded (1-minute load 34–56 on 32 cores), so wall times are upper bounds.
OpenAI API key, gpt-6-astra, ~140k-token session, manual
/compact:/responses/compact)Anthropic API key, claude-sonnet-5-5, ~100k-token session, trigger lowered via
anthropicCompactThreshold:Before this fix (same OpenAI route): a session key in the system prompt matched a redaction pattern. The paid
/responses/compactresult (130.7k input, ~18 s) was discarded at DEBUG, then 2 more client requests ran, about 37 s in total.Targeted live probes
Tests
instructionsrequest body;streamAnthropicwith a SQLite session manager);pnpm run tsgo:core,tsgo:test:srcandtsgo:test:packagespass.node scripts/check-changed.mjspasses.