Repository navigation
feat(agents): compact from the warm prompt cache on every route - #204111
Conversation
Automatic request-boundary compaction now sends its summary request as the session's next normal request plus one appended summarize instruction, so it reads the warm prompt cache instead of paying for a cold summarizer request. - Generalized the ChatGPT V2 boundary into request-boundary-compaction with a native-checkpoint and a text variant chosen by capability. - The text variant runs session threshold compaction whose first history summary (core path or safeguard attempt 0) comes from the warm request; failures fall back to the client compactor once and write nothing. - The appended item carries cacheCheckpoint: false, so Anthropic and Chat Completions place no cache marker on it. - Reply-level token maintenance that still fits defers to the boundary. Co-authored-by: obviyus <[email protected]>
Co-authored-by: obviyus <[email protected]>
|
🦞👀 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. |
The warm boundary runs the internal compaction hooks and post-compaction memory sync that reply-level compaction ran before deferring to it, and marks its session events as hook-handled so plugin hooks do not run twice. Co-authored-by: obviyus <[email protected]>
|
Codex review: needs changes before merge. What this changesThis PR extends warm-cache automatic compaction from native ChatGPT sessions to other built-in provider routes. Example: Automatic compaction on Anthropic Sonnet 4.6 with a 24,000-token context budget.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Needs changes before merge - 2 items remain Keep open: this useful, maintainer-directed feature still has a definite fixture type error and affected lifecycle tests that assume the previous compaction owner. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe embedded agent runner checks context pressure before provider requests, asks the session compaction owner to save a summary, and resumes inference from the compacted transcript. flowchart TD
A[Prepared agent request] --> B[Context pressure boundary]
B --> C[Native ChatGPT checkpoint]
B --> D[Warm text summary]
D --> E[Session compaction writer]
C --> F[Compacted transcript]
E --> F
F --> G[Resumed agent request]
Technical reviewBest possible solution: Keep the shared request boundary and existing session writer, repair the affected test fixtures, and validate the changed default on an upgraded session. Do we have a high-confidence way to reproduce the issue? The baseline's native-only eligibility and separate summarizer request establish the cache-reuse gap in source; the new fixture's missing required fields and affected CI assertions are independently inspectable without executing target code. Is this the best way to solve the issue? Reusing the prepared provider request and authoritative session compaction writer is a coherent, focused design; the retained manual, recovery, and configured-owner paths have explicit contracts. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d595ba38e95b. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +287, Tests +378, Docs +41, Other 0. Total +706 across 29 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 23, 2026, 11:09 AM ET / 16:09 UTC. |
ChatGPT sign-in regression E2E (base
|
| Base | Head | |
|---|---|---|
| Mechanism (turn 5) | V2 compaction_trigger appended to the full request (tools kept) |
same |
| First compaction request R / W / U / O | 25,344 / 0 / 280 / 709 | 25,600 / 0 / 245 / 657 |
| Prior prompt (cached) | 25,489 (20,224) | 25,710 (20,480) |
| Read ÷ prior prompt | 99.4% | 99.6% |
| Second V2 compaction (turn 9) R / W / U / O | 25,984 / 0 / 319 / 655 | 26,112 / 0 / 256 / 733 |
| Fact from before the cut | not answered: my harness's 600 s cap killed the fact turn mid-request; I did not rerun it, to keep the credential use under 30 min | ✓ ORCHID-COPPER-731 |
Fallback rows (the session grows through large user messages; V2 keeps user text word for word, so it refuses before it sends anything, on both sides alike):
| Window | Base | Head | Fact base / head |
|---|---|---|---|
| 64k | V2 refused ("retained window exceeds the next request budget") → client summarizer 0 / 0 / 32,879 / 455; prior prompt 36,652 | same refusal → 0 / 0 / 32,879 / 455; prior prompt 36,668 | ✓ / ✓ |
| 24k | same refusal → deterministic overflow cut, no summary request | same | ✓ / ✓ |
ChatGPT reports cache_write_tokens as 0 throughout.
Verdict: no regression. ChatGPT V2 compaction behaves the same on base and head: warm (99.4% vs 99.6% of the prior prompt read from cache) and with the same fallbacks.
Credential handling: one OAuth profile was read from a private openclaw backup sqlite create --global snapshot and imported into scratch with doctor --fix. No refresh happened: the live profile still has status ok, the same expiresAt and about 111 h left. All scratch copies (snapshot, export file, scratch state DBs) are deleted. The live Gateway pid and the live config/.bak hashes are unchanged. Total use of the credential: 15:51–16:21 UTC.
Fitting reply-level maintenance now waits for the attempt's request boundary; the preflight heartbeat cases use a prompt over the window, and the warm boundary fixture supplies complete hook context. Co-authored-by: obviyus <[email protected]>
|
Landed in e5dcfa0. Automatic request-boundary compaction now sends its summary as the session's next normal request plus one unmarked summarize item, so it reads the warm prompt cache on every built-in route (ChatGPT sign-in keeps its native V2 checkpoint). Real-route proof: the compaction request read 99.5–99.99% of the prior prompt from cache on Anthropic direct, OpenAI API key and cliproxy Claude, versus 0 on the base; the fact from before the cut was answered on both sides. Manual |
Related: #204111 ## What Problem This Solves Automatic compaction started at two different points. Client maintenance started at 75% of the context window. Since #204111, the request-boundary compaction (ChatGPT V2 checkpoint and the warm text summary on every other route) started at 90%, a side effect of reusing the V2 trigger. No measurement supported 90%. At 90%, the warm summary request (the full window plus an appended instruction and the summary output, thinking included) can run out of room on ~200k windows and silently fall back to the cold summarizer. ## User Impact All built-in routes now compact at the same point: the smaller of 80% of the window and the window minus the compaction reserve. On a 200k window, compaction starts at 160,000 tokens. - ChatGPT V2 and the warm text route move from 90% to 80% (180,000 → 160,000 on 200k). The summary request keeps 20% headroom. - Client maintenance moves from 75% to 80% (150,000 → 160,000 on 200k; 750,000 → 800,000 on 1M). - The reserve cap is unchanged. Manual `/compact`, overflow recovery and native Codex / Claude CLI policies are unchanged. Request shape is unchanged. ## Why This Change Was Made `resolveCompactionThreshold` already owns the client trigger. It now uses 0.8, and the request-boundary soft trigger calls it (capped by the reserve-based prompt budget, as before) instead of keeping its own `0.9`. One trigger, one owner. Docs that stated 75% or 90% now state 80%, with recomputed examples. ## Evidence - New test (`request-boundary-compaction.chatgpt-v2.test.ts`, both `native-checkpoint` and `text` variants): on a 200k window the client threshold is 160,000, the boundary sends no compaction request at 159,000, and sends one at 160,000. - Red on base (`0828443372be`): the client threshold is 150,000; with that assertion removed, both variants send no request at 160,000 (base triggers at 180,000). - Green on this branch. - Updated threshold tables in the agent-core `shouldCompact` test, `setup.test.ts` and the refusal compaction test (now derived from the owner, not a hard-coded ratio). - Targeted local run: the touched tests plus every test file that imports a changed source. ## Merge danger Two-way door: a revert restores 75% / 90%. No stored state, config or contract changes. Blast radius: when every built-in agent session compacts (slightly later for client maintenance, earlier for ChatGPT V2 and warm text compaction). Co-authored-by: Ayaan Zaidi <[email protected]>
…and transport owners (#204292) ## Result Pull request CI now selects every test whose runtime imports reach a changed file under `src/agents/`, `src/auto-reply/reply/agent-runner*`, `packages/agent-core/src/harness/compaction/` or `packages/ai/src/transports/`, directly or transitively. Replaying the file lists of #204111 and #204180 now selects the four tests that first failed on scheduled `main` (#204252). **Cost, read this first:** for these owners the transitive closure covers almost the whole runtime suite. A PR that touches them now runs a full-suite-sized Node plan, about 21x to 105x the previous predicted test time. Exact numbers are below. The plan stays inside the existing row cap and per-job time objective. Nothing is capped or dropped. Closes #204252. ## Why the tests were missed PR CI uses `selectionMode: "aggressive"` (`scripts/ci-build-manifest.mjs`). In `resolveBoundedChangedTestTargetPlan`, aggressive mode walks reverse imports to **depth 2**, and only to **depth 1** when the changed module has 20 or more direct importers (the hub cutoff). There are no owner-list routes for these files and no shard owner list filters them. The tests are simply too far away: | Changed owner | Import distance to the missed tests | |---|---| | `src/auto-reply/reply/agent-runner-memory.ts` | 3 (agent-runner tests) | | `src/agents/compaction.ts` | 5 (agent-runner), 7 (prompt-cache) | | `src/agents/embedded-agent-runner/run/request-boundary-compaction.ts` | 5 (agent-runner), 10 (prompt-cache) | | `src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts` | 7 (prompt-cache), 9 (agent-runner) | | `packages/ai/src/transports/anthropic-messages.ts` | 6 (prompt-cache), 8 (agent-runner) | | `packages/agent-core/src/harness/compaction/summarization-completion.ts` | 6-7 | `session-context-accounting.gateway.integration.test.ts` is not reached within 10 imports of any compaction owner. It is reached only through the full closure, which runs through the Gateway into the runner. ## Fix The PR plan owner (`resolveChangedNodeTestTargets`) passes `transitiveOwners` to the bounded target walk. For a changed file that matches, the walk has no depth limit and no hub cutoff. All other paths keep the two-import walk. `docs/ci/scope-and-routing/node-test-lanes.md` describes the rule. ## Selection growth (replayed through the PR planner, hybrid backend, 130-row cap) | Replay | Before: tests / jobs / predicted test-seconds (max job) | After | |---|---|---| | #204111 (31 files) | 300 / 14 / 1,767 s (228 s) | 12,562 / 131 / 36,859 s (469 s) | | #204180 (9 files) | 22 / 5 / 351 s (140 s) | 12,405 / 131 / 36,673 s (468 s) | - The closure is nearly the whole runtime inventory. An unbounded walk from `request-boundary-compaction.ts` alone reaches 12,397 test files. - 48 of the last 200 first-parent commits on `main` (24%) touch these owners. At the replayed size, each PR push of that kind adds about 35,000 predicted test-seconds. - Shard budget: the plans stay at the compact Node row cap (130 rows plus one dist row) and below the 480-second per-job objective (max 469 s). They use the full PR row envelope that the registration budget already allows, so concurrent PRs of this kind compete for the same rows. - I tested no smaller rule that still selects the four tests. A walk depth of 10 already selects 2,401-7,129 tests (13,797-26,905 s) and still misses the Gateway integration test. ## Evidence - New test in `test/scripts/ci-changed-node-test-plan.integration.test.ts`. For 7 changed owners from #204111 and #204180, it asserts that the plan selects the four named tests and **every** test in the owner's unbounded runtime-import closure. It fails on `main` and passes on this head. - Replay script results above, on `main` and on this head. - One existing fixture expectation changed: `ci-changed-node-test-plan.selection.test.ts` used a `src/agents/example` source to pin the depth-two stop; it now expects the distant consumer. - Planner and workflow tests (13 files, 1,573 tests): all pass except `ci-changed-node-test-plan.test.ts` "retains precise process ownership (github)", which fails the same way on `main` (`expected 120 to be less than or equal to 60`). It is not caused by this change. - `pnpm check:changed`: pass. - CI on the head: green except 3 checks that fail the same way on scheduled main at the base (see the Maintainer override comment). Local ClawSweeper: patch is correct, no findings. Co-authored-by: Ayaan Zaidi <[email protected]>
…nd a declared behavior set (#204346) ## Result PR CI for agent, compaction, prompt and transport owners goes from a full-suite plan back to a bounded one, about 13x smaller. It still selects the four tests that #204252 was about. | Replay (PR planner, hybrid, 130-row cap) | Before (#204292) | After | |---|---|---| | #204111 (31 files) | 12,562 tests / 131 jobs / 36,859 s | **967 tests / 21 jobs / 2,881 s** (max job 271 s) | | #204180 (9 files) | 12,405 / 131 / 36,673 s | **302 / 14 / 1,393 s** (max job 250 s) | Both replays select `embedded-agent-runner.prompt-cache.test.ts`, `agent-runner-required-maintenance.pending-input.test.ts`, `agent-runner-compaction-fallback.test.ts` and `session-context-accounting.gateway.integration.test.ts`. ## Change For a changed source file under `src/agents/`, `src/auto-reply/reply/agent-runner*`, `packages/agent-core/src/harness/compaction/` or `packages/ai/src/transports/`, the aggressive PR plan now selects: 1. the normal two-import walk, as for every other file; 2. every transitive importer test **in the changed file's own directory**. A file directly in a package root (for example `src/agents/compaction.ts`) skips this step, because that directory is the whole package (1,795 tests for `src/agents/`); 3. a **declared behavior set**: every `*prompt-cache*` and `*compaction*` test under `src/` and `packages/` (118 files), plus `agent-runner-required-maintenance.pending-input.test.ts` and `session-context-accounting.gateway.integration.test.ts`. A test-only edit under these owners runs itself and does not pull in the declared set. Full mode (manual and hourly) is unchanged and still walks every importer. ## Decision recorded The follow-up asked for "importers within the same package". With the package root as the scope, #204111 selects 2,424 tests / 7,519 s, which misses the target of about 1,200 tests / 3,700 s. I used the changed file's directory instead, which meets the target. Coverage given up: cross-directory transitive importers, outside the declared set, of a file under these owners. The hourly full plan still runs them. This is reversible: widening the scope is a one-line change. | Variant | #204111 | #204180 | |---|---|---| | Declared set only | 369 / 1,888 s | 135 / 1,035 s | | **Same directory + declared (this PR)** | **967 / 2,881 s** | **302 / 1,393 s** | | Same package root + declared | 2,424 / 7,519 s | 308 / 1,393 s | | #204292 (unbounded) | 12,562 / 36,859 s | 12,405 / 36,673 s | ## Evidence - `ci-changed-node-test-plan.integration.test.ts`: for 7 owners from #204111 and #204180, the plan selects the four named tests and every same-directory importer test. - `ci-changed-node-test-plan.selection.test.ts`: the fixture case again expects the two-import stop for a distant consumer in another directory (the pre-#204292 expectation). - Planner, project and workflow tests (11 files): 1,322 passed. `pnpm check:changed`: pass. ## Coverage decision and closing loop - The maintainer accepted the same-directory scope as the coverage contract for these owners. The local review asked for this decision. - **Closing loop:** when a scheduled red traces to a green PR through a cross-directory importer, the fix PR adds that importer test to the owner's declared set. The declared sets grow only from real misses. - **Measurement:** 24 h after merge, compare agent-core PR rows and wall time with the #204292 numbers above. Co-authored-by: Ayaan Zaidi <[email protected]>
…claw#204111) ## Problem Automatic compaction builds its own summary request: the client summarizer sends `SUMMARIZATION_SYSTEM_PROMPT`, no tools and one `<conversation>` sample; OpenAI/xAI API keys use `/responses/compact`. Neither shares a prefix with the session's prompt cache, so every compaction pays full uncached input. Only native ChatGPT sign-in (V2 `compaction_trigger`) reused the warm prefix. ## Solution One request-boundary compaction for every built-in route, chosen by capability: - `chatgpt-v2-compaction.ts` → `request-boundary-compaction.ts`. It keeps the shared trigger (smaller of reserve budget and 90% of the window), the `compact_only` fallback and the `failed` latch, and selects a variant: `native-checkpoint` (ChatGPT V2, unchanged) or `text` (every other route). - The `text` variant runs the session's threshold compaction (`agentSessionRunWarmCompaction`). Its first history summary is the session's next normal request — same system, tools, `tool_choice`, `max_tokens`, thinking, cache key, every earlier message — plus one appended user item with the existing summary instructions (`prepareCompactionSummaryRequest`, plain prompt, no `<previous-summary>`: the request already holds it). - Default mode: the core path uses it through `compactFromSource` with no turn-prefix request (split turn: one request, empty `latestContext`). - Safeguard mode (the default for new configs): it is attempt 0 of the safeguard; the quality audit still runs and corrective retries use the existing bounded summarizer. - A tool call, a non-`stop` stop reason (`length`, `error`) or empty text rejects the warm summary: nothing is written (safeguard returns a plain cancel, no attempt row), the boundary raises `compact_only`, and the client compactor runs once. - After commit the attempt stops at the settled boundary with a maintenance precheck; the run retries from the compacted transcript (existing "compaction already happened in this attempt" recovery branch), so the loop never keeps the stale uncompacted context. - The appended item carries `cacheCheckpoint: false` (new optional `UserMessage` field); Anthropic Messages and Chat Completions place no cache marker on it, so history markers stay where the previous request put them. - Reply-level token maintenance that still fits the window defers to the boundary (`defersTokenCompactionToRequestBoundary`, generalized from the ChatGPT-only check). Required compaction (prompt does not fit), byte-triggered compaction, configured context engines, `compaction.model`, `compaction.provider`, CLI/Codex runtimes and memory-flush turns keep their existing owners. Out of scope (later PRs): manual `/compact`, overflow recovery, removing `/responses/compact` / `params.responsesCompactEndpoint` (shipped config key; needs xAI and quality evidence). Decisions recorded (defaults taken without asking): - `compaction.model` excludes the warm path whenever set (existing predicate), not only when it differs from the session model. - Context-engine ownership is not known before the attempt; reply-level maintenance keeps running for sessions with a non-legacy `plugins.slots.contextEngine`. - Trigger is the shared V2 soft trigger, so text compaction fires later than the old 75% client threshold; the hard window guard is unchanged. - Quality: sold as cost parity plus full-history input, not better summaries (probe: 52.1% vs 53.1% on 48 questions). ## Impact Users on Anthropic, OpenAI API key, cliproxy and other routes: automatic compaction reads the warm prompt cache instead of a cold summarizer request. No new config, prompt or wait. ## Evidence Tests (red on base: the module and behavior do not exist there): - `request-boundary-compaction.test.ts`: anthropic-messages attempt above the trigger sends a request equal to the uncompacted request (system, tools, params, all messages and markers) plus one unmarked user item; commit keeps summary + tail from `firstKeptEntryId` with the pending request once; split turn sends one summary request; `tool` and `length` replies write nothing, raise `compact_only`. - `compaction-safeguard.degraded-fallback.test.ts`: warm summary is attempt 0 (no `<previous-summary>`, no `<conversation>`), corrective retry stays bounded; warm failure cancels without a recorded failure. - V2 boundary suite, runreplyagent ownership cases, agent-runner-memory suite, prefix-stability: green. Real-route E2E (isolated scratch Gateway; forced 24k `contextTokens`, safeguard mode): First automatic compaction request per route. R/W/U/O = provider cacheRead / cacheWrite / uncached input / output. "Prior prompt" is the previous normal request's input tokens on that side. | Route / window | Base R/W/U/O | Head R/W/U/O | Head read ÷ prior prompt | Fact before cut answered (base/head) | |---|---|---|---|---| | Anthropic direct API key, Sonnet 4.6 / 24k | 0 / 8,442 / 3 / 380 (client safeguard) | **12,213** / 7,760 / 477 / 427 | 12,213 / 12,216 = 99.98% | ✓ / ✓ | | OpenAI API key, GPT-5-mini / 24k | 0 / 0 / 22,042 / 1,583 (`/responses/compact`) | **10,112** / 0 / 6,920 / 3,343 | 10,112 / 10,164 = 99.5% | ✓ / ✓ | | cliproxy Claude, Sonnet 4.6 / 40k | 0 / 16,232 / 3 / 471 (client safeguard) | **20,420** / 8,234 / 3 / 572 | 20,420 / 20,423 = 99.99% | ✓ / ✓ | | ChatGPT sign-in (regression) | not run: no usable native credential | not run | — | — | Head cacheWrite is the turn appended since the previous request (the history marker writes it, as a normal request would); the appended instruction itself carries no marker. On cliproxy at a 24k cap the resumed head session had already passed the window, so the hard guard used the existing deterministic fallback with no summary request; the matched 40k run (base and head with identical settings) is the proof row. Head warm requests kept all tools and the normal system prompt. Total paid E2E spend ≤ $3.80. Local review fixes: - Warm compaction consults the shared context-pressure owner first, so a run that declined maintenance sends its request instead of compacting again. - The warm boundary runs the internal `session:compact:before/after` hooks and post-compaction memory sync (`postIndexSync`) that reply-level compaction ran, and marks its session events hook-handled so plugin hooks run once. `pnpm check:changed`: green except `dead export scan` (`scripts/lib/docker-e2e-watchdog.mjs: parseTimeoutMs`, a file this PR does not touch) and one lint error in a new test, fixed. Accepted change, recorded: fitting token maintenance after a delivered reply (idle session maintenance) also defers to the next attempt's boundary, as ChatGPT V2 sessions already did, so those sessions now compact warm inside the next turn once it reaches the boundary trigger instead of with a cold request at the old client threshold. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: openclaw#204111 ## What Problem This Solves Automatic compaction started at two different points. Client maintenance started at 75% of the context window. Since openclaw#204111, the request-boundary compaction (ChatGPT V2 checkpoint and the warm text summary on every other route) started at 90%, a side effect of reusing the V2 trigger. No measurement supported 90%. At 90%, the warm summary request (the full window plus an appended instruction and the summary output, thinking included) can run out of room on ~200k windows and silently fall back to the cold summarizer. ## User Impact All built-in routes now compact at the same point: the smaller of 80% of the window and the window minus the compaction reserve. On a 200k window, compaction starts at 160,000 tokens. - ChatGPT V2 and the warm text route move from 90% to 80% (180,000 → 160,000 on 200k). The summary request keeps 20% headroom. - Client maintenance moves from 75% to 80% (150,000 → 160,000 on 200k; 750,000 → 800,000 on 1M). - The reserve cap is unchanged. Manual `/compact`, overflow recovery and native Codex / Claude CLI policies are unchanged. Request shape is unchanged. ## Why This Change Was Made `resolveCompactionThreshold` already owns the client trigger. It now uses 0.8, and the request-boundary soft trigger calls it (capped by the reserve-based prompt budget, as before) instead of keeping its own `0.9`. One trigger, one owner. Docs that stated 75% or 90% now state 80%, with recomputed examples. ## Evidence - New test (`request-boundary-compaction.chatgpt-v2.test.ts`, both `native-checkpoint` and `text` variants): on a 200k window the client threshold is 160,000, the boundary sends no compaction request at 159,000, and sends one at 160,000. - Red on base (`6d8b616e5305`): the client threshold is 150,000; with that assertion removed, both variants send no request at 160,000 (base triggers at 180,000). - Green on this branch. - Updated threshold tables in the agent-core `shouldCompact` test, `setup.test.ts` and the refusal compaction test (now derived from the owner, not a hard-coded ratio). - Targeted local run: the touched tests plus every test file that imports a changed source. ## Merge danger Two-way door: a revert restores 75% / 90%. No stored state, config or contract changes. Blast radius: when every built-in agent session compacts (slightly later for client maintenance, earlier for ChatGPT V2 and warm text compaction). Co-authored-by: Ayaan Zaidi <[email protected]>
…and transport owners (openclaw#204292) ## Result Pull request CI now selects every test whose runtime imports reach a changed file under `src/agents/`, `src/auto-reply/reply/agent-runner*`, `packages/agent-core/src/harness/compaction/` or `packages/ai/src/transports/`, directly or transitively. Replaying the file lists of openclaw#204111 and openclaw#204180 now selects the four tests that first failed on scheduled `main` (openclaw#204252). **Cost, read this first:** for these owners the transitive closure covers almost the whole runtime suite. A PR that touches them now runs a full-suite-sized Node plan, about 21x to 105x the previous predicted test time. Exact numbers are below. The plan stays inside the existing row cap and per-job time objective. Nothing is capped or dropped. Closes openclaw#204252. ## Why the tests were missed PR CI uses `selectionMode: "aggressive"` (`scripts/ci-build-manifest.mjs`). In `resolveBoundedChangedTestTargetPlan`, aggressive mode walks reverse imports to **depth 2**, and only to **depth 1** when the changed module has 20 or more direct importers (the hub cutoff). There are no owner-list routes for these files and no shard owner list filters them. The tests are simply too far away: | Changed owner | Import distance to the missed tests | |---|---| | `src/auto-reply/reply/agent-runner-memory.ts` | 3 (agent-runner tests) | | `src/agents/compaction.ts` | 5 (agent-runner), 7 (prompt-cache) | | `src/agents/embedded-agent-runner/run/request-boundary-compaction.ts` | 5 (agent-runner), 10 (prompt-cache) | | `src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts` | 7 (prompt-cache), 9 (agent-runner) | | `packages/ai/src/transports/anthropic-messages.ts` | 6 (prompt-cache), 8 (agent-runner) | | `packages/agent-core/src/harness/compaction/summarization-completion.ts` | 6-7 | `session-context-accounting.gateway.integration.test.ts` is not reached within 10 imports of any compaction owner. It is reached only through the full closure, which runs through the Gateway into the runner. ## Fix The PR plan owner (`resolveChangedNodeTestTargets`) passes `transitiveOwners` to the bounded target walk. For a changed file that matches, the walk has no depth limit and no hub cutoff. All other paths keep the two-import walk. `docs/ci/scope-and-routing/node-test-lanes.md` describes the rule. ## Selection growth (replayed through the PR planner, hybrid backend, 130-row cap) | Replay | Before: tests / jobs / predicted test-seconds (max job) | After | |---|---|---| | openclaw#204111 (31 files) | 300 / 14 / 1,767 s (228 s) | 12,562 / 131 / 36,859 s (469 s) | | openclaw#204180 (9 files) | 22 / 5 / 351 s (140 s) | 12,405 / 131 / 36,673 s (468 s) | - The closure is nearly the whole runtime inventory. An unbounded walk from `request-boundary-compaction.ts` alone reaches 12,397 test files. - 48 of the last 200 first-parent commits on `main` (24%) touch these owners. At the replayed size, each PR push of that kind adds about 35,000 predicted test-seconds. - Shard budget: the plans stay at the compact Node row cap (130 rows plus one dist row) and below the 480-second per-job objective (max 469 s). They use the full PR row envelope that the registration budget already allows, so concurrent PRs of this kind compete for the same rows. - I tested no smaller rule that still selects the four tests. A walk depth of 10 already selects 2,401-7,129 tests (13,797-26,905 s) and still misses the Gateway integration test. ## Evidence - New test in `test/scripts/ci-changed-node-test-plan.integration.test.ts`. For 7 changed owners from openclaw#204111 and openclaw#204180, it asserts that the plan selects the four named tests and **every** test in the owner's unbounded runtime-import closure. It fails on `main` and passes on this head. - Replay script results above, on `main` and on this head. - One existing fixture expectation changed: `ci-changed-node-test-plan.selection.test.ts` used a `src/agents/example` source to pin the depth-two stop; it now expects the distant consumer. - Planner and workflow tests (13 files, 1,573 tests): all pass except `ci-changed-node-test-plan.test.ts` "retains precise process ownership (github)", which fails the same way on `main` (`expected 120 to be less than or equal to 60`). It is not caused by this change. - `pnpm check:changed`: pass. - CI on the head: green except 3 checks that fail the same way on scheduled main at the base (see the Maintainer override comment). Local ClawSweeper: patch is correct, no findings. Co-authored-by: Ayaan Zaidi <[email protected]>
…nd a declared behavior set (openclaw#204346) ## Result PR CI for agent, compaction, prompt and transport owners goes from a full-suite plan back to a bounded one, about 13x smaller. It still selects the four tests that openclaw#204252 was about. | Replay (PR planner, hybrid, 130-row cap) | Before (openclaw#204292) | After | |---|---|---| | openclaw#204111 (31 files) | 12,562 tests / 131 jobs / 36,859 s | **967 tests / 21 jobs / 2,881 s** (max job 271 s) | | openclaw#204180 (9 files) | 12,405 / 131 / 36,673 s | **302 / 14 / 1,393 s** (max job 250 s) | Both replays select `embedded-agent-runner.prompt-cache.test.ts`, `agent-runner-required-maintenance.pending-input.test.ts`, `agent-runner-compaction-fallback.test.ts` and `session-context-accounting.gateway.integration.test.ts`. ## Change For a changed source file under `src/agents/`, `src/auto-reply/reply/agent-runner*`, `packages/agent-core/src/harness/compaction/` or `packages/ai/src/transports/`, the aggressive PR plan now selects: 1. the normal two-import walk, as for every other file; 2. every transitive importer test **in the changed file's own directory**. A file directly in a package root (for example `src/agents/compaction.ts`) skips this step, because that directory is the whole package (1,795 tests for `src/agents/`); 3. a **declared behavior set**: every `*prompt-cache*` and `*compaction*` test under `src/` and `packages/` (118 files), plus `agent-runner-required-maintenance.pending-input.test.ts` and `session-context-accounting.gateway.integration.test.ts`. A test-only edit under these owners runs itself and does not pull in the declared set. Full mode (manual and hourly) is unchanged and still walks every importer. ## Decision recorded The follow-up asked for "importers within the same package". With the package root as the scope, openclaw#204111 selects 2,424 tests / 7,519 s, which misses the target of about 1,200 tests / 3,700 s. I used the changed file's directory instead, which meets the target. Coverage given up: cross-directory transitive importers, outside the declared set, of a file under these owners. The hourly full plan still runs them. This is reversible: widening the scope is a one-line change. | Variant | openclaw#204111 | openclaw#204180 | |---|---|---| | Declared set only | 369 / 1,888 s | 135 / 1,035 s | | **Same directory + declared (this PR)** | **967 / 2,881 s** | **302 / 1,393 s** | | Same package root + declared | 2,424 / 7,519 s | 308 / 1,393 s | | openclaw#204292 (unbounded) | 12,562 / 36,859 s | 12,405 / 36,673 s | ## Evidence - `ci-changed-node-test-plan.integration.test.ts`: for 7 owners from openclaw#204111 and openclaw#204180, the plan selects the four named tests and every same-directory importer test. - `ci-changed-node-test-plan.selection.test.ts`: the fixture case again expects the two-import stop for a distant consumer in another directory (the pre-openclaw#204292 expectation). - Planner, project and workflow tests (11 files): 1,322 passed. `pnpm check:changed`: pass. ## Coverage decision and closing loop - The maintainer accepted the same-directory scope as the coverage contract for these owners. The local review asked for this decision. - **Closing loop:** when a scheduled red traces to a green PR through a cross-directory importer, the fix PR adds that importer test to the owner's declared set. The declared sets grow only from real misses. - **Measurement:** 24 h after merge, compare agent-core PR rows and wall time with the openclaw#204292 numbers above. Co-authored-by: Ayaan Zaidi <[email protected]>
…ture (#204857) ## Problem `test/gateway-restart-resume.e2e.test.ts` "restart markers survive graceful shutdown (suspend/reopen and blocked store: false)" times out on `main`. Request-boundary compaction (#204111) now sends a warm summary request: the turn's own system prompt, tools and history, plus the checkpoint instruction. The fixture recognized summaries only by the cold summarizer's system prompt. It took the warm request for a stream turn and held it open, so the follow-up that the Gateway re-admitted after restart waited behind it until the test timeout. No input is lost. Instrumented runs show the follow-up preserved through shutdown and re-admitted after restart, on both the good and the bad base. ## Solution The fixture recognizes both summary forms by the checkpoint instruction ("Create a structured context checkpoint summary"), which both requests carry. Test change only. ## Impact The restart-resume E2E proves restart markers again instead of timing out. ## Evidence - On `main`, the case timed out at 180 s; the fake provider held the warm summary request (full history, starts with the system message) after the resumed turn's first request. - With this change, both variants pass: blocked store true 12.4 s, false 61.5 s. Co-authored-by: Ayaan Zaidi <[email protected]>
…ture (openclaw#204857) ## Problem `test/gateway-restart-resume.e2e.test.ts` "restart markers survive graceful shutdown (suspend/reopen and blocked store: false)" times out on `main`. Request-boundary compaction (openclaw#204111) now sends a warm summary request: the turn's own system prompt, tools and history, plus the checkpoint instruction. The fixture recognized summaries only by the cold summarizer's system prompt. It took the warm request for a stream turn and held it open, so the follow-up that the Gateway re-admitted after restart waited behind it until the test timeout. No input is lost. Instrumented runs show the follow-up preserved through shutdown and re-admitted after restart, on both the good and the bad base. ## Solution The fixture recognizes both summary forms by the checkpoint instruction ("Create a structured context checkpoint summary"), which both requests carry. Test change only. ## Impact The restart-resume E2E proves restart markers again instead of timing out. ## Evidence - On `main`, the case timed out at 180 s; the fake provider held the warm summary request (full history, starts with the system message) after the resumed turn's first request. - With this change, both variants pass: blocked store true 12.4 s, false 61.5 s. Co-authored-by: Ayaan Zaidi <[email protected]>
With compaction.notifyUser on, reply preflight ran the memory flush (a full model turn that can take minutes) before any notice, so the chat looked hung. Since openclaw#204111, eligible token compaction normally defers to the request boundary, which sends its own compaction notices, so this announces the flush itself instead: "Saving memory before compaction..." once the flush attempt is prepared, before its stall guard and model run. Queued follow-ups deliver it at once (preflight and completion-owning sources), and it is not observed as the follow-up's reply, so channel progress (Discord) stays open for the answer.
…204313) After mid-turn compaction, the retry that crosses the compaction boundary continued through a hidden user turn ("Continue the current task from the existing transcript…") plus a runtime carrier. That prompt was persisted. Every such retry added another hidden user turn, and the user's own question was gone from history: compaction had summarized it as part of the split turn. - The question the user asked stays in the conversation history after compaction. The next turn sees it verbatim, instead of a hidden "continue" instruction. - No hidden continuation turn is added after compaction when the user's turn can be replayed. - The next turn's request extends the retry request byte for byte, so the provider prompt cache keeps working across the turn. - **One owner decides the retry mode.** `continueFromCurrentTranscript` (`session-prompt-state.ts`) now replays a persisted keyed user turn in place unless the attempt left an unsettled tail (partial output, or an operator abort mid-flight; callers pass `unsettledTail`). The caller-chosen `replayCurrentUserTurn` option is removed. The hidden prompt stays only for non-replayable turns. - **The replayed turn is written where the model sees it.** `persistCompactedCurrentUserTurnReplay` (`pre-persisted-user-turn.ts`), called from the replay branch of `prepareEmbeddedAttemptSessionBoundary`, appends the turn after the kept tail when a compaction summarized it. The original row keeps the turn key, because the transcript identity index is unique per session. The copy uses a key derived from the turn key and the compaction entry id, so repeated retries after the same compaction write it once, and a second compaction writes one new copy. It is `display: false`, so the chat still shows the question once. - **Submission replays that row in place.** `resolveCurrentUserTurnContextKey` returns the key under which the current turn sits in live context (its own row or its replay copy). Prompt submission and the compaction budget use it, so a later retry (for example after a rate limit) reuses the copy and its carrier instead of appending the question again. - Accepted edge, no code: if the process crashes between the compaction commit and the copy's write, the restart writes no copy for that run. The question stays in the original row and in the summary. Real-API replay (gpt-4.1-mini, captured wire pair: the retry after compaction, then the first request of the next turn; fresh seed and cache key per trial). The metric that does not depend on request length is whether the next turn reuses the whole cacheable retry prefix. | Arm, trial | Retry input | Next-turn input | Next-turn cached | Next-turn uncached | New tokens in next turn | Retry prefix fully cached | Question in next-turn history | |---|---|---|---|---|---|---|---| | main, 1 | 9,071 | 9,153 | 8,960 | 193 | 82 | yes | no (hidden prompt instead) | | main, 2 | 9,073 | 9,155 | 8,960 | 195 | 82 | yes | no | | this PR, 1 | 8,995 | 9,077 | 8,832 | 245 | 82 | yes | yes | | this PR, 2 | 8,998 | 9,080 | 8,832 | 248 | 82 | yes | yes | | this PR, 3 | 8,999 | 9,081 | 8,960 | 121 | 82 | yes | yes | | this PR, 4 | 8,993 | 9,075 | 8,832 | 243 | 82 | yes | yes | | replay without persistence (rejected design) | 9,007 | 9,059 | 7,936 | 1,123 | 52 | no (breaks at the user turn) | no | - The provider caches in 128-token blocks. Next-turn uncached = the 82 new tokens (the same in both arms) + the retry's tail inside its last partial block. That tail depends only on where the retry length falls, not on changed bytes. - "Fully cached" means the next turn caches as much as resending the identical retry request. The control resend caches 8,832 for this PR's retry (8,996 tokens) and 8,960 for main's (9,072 tokens, 76 tokens longer because of the hidden prompt). The next request's input starts with the retry's full input byte for byte. Tests: - `agent-runner-compaction-fallback.test.ts` (mid-turn case) checks: - the warm summary request equals the previous request plus one instruction; - a rate-limited first retry and the second retry after the same compaction send the identical request, with the keyed turn once and no hidden prompt; - the next turn's input starts with the retry's input and holds the question once. It is red on `main` (hidden prompt) and on the previous head of this PR (the rate-limited retry), and green here. - The fixture's stale `largestPrompt < 800_000` check moves to the end of the test, unchanged, so the new assertions run first. It fails on `main` too (851,263 at the 85% trigger) and has its own owner. - `embedded-agent-runner.prompt-cache.test.ts`: the fixture window is raised so its journey stays below the compaction trigger. This test covers prefix stability; the compaction-fallback test owns the warm summary shape. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 39bdddd) Release adaptation: Preserve the stable ChatGPT V2 compaction boundary and test the cold-summary retry, without importing the warm-summary feature or its unrelated assertion. Companion audit: #204443 changes only fixture sizing; stable test retains its pre-existing budget assertion. #207519 consolidates separate output-limit tests; #208522 is separately ordered in this lane; #204111 warm summaries are not needed for the stable cold path. Co-authored-by: RomneyDa <[email protected]>
Problem
Automatic compaction builds its own summary request: the client summarizer sends
SUMMARIZATION_SYSTEM_PROMPT, no tools and one<conversation>sample; OpenAI/xAI API keys use/responses/compact. Neither shares a prefix with the session's prompt cache, so every compaction pays full uncached input. Only native ChatGPT sign-in (V2compaction_trigger) reused the warm prefix.Solution
One request-boundary compaction for every built-in route, chosen by capability:
chatgpt-v2-compaction.ts→request-boundary-compaction.ts. It keeps the shared trigger (smaller of reserve budget and 90% of the window), thecompact_onlyfallback and thefailedlatch, and selects a variant:native-checkpoint(ChatGPT V2, unchanged) ortext(every other route).textvariant runs the session's threshold compaction (agentSessionRunWarmCompaction). Its first history summary is the session's next normal request — same system, tools,tool_choice,max_tokens, thinking, cache key, every earlier message — plus one appended user item with the existing summary instructions (prepareCompactionSummaryRequest, plain prompt, no<previous-summary>: the request already holds it).compactFromSourcewith no turn-prefix request (split turn: one request, emptylatestContext).stopstop reason (length,error) or empty text rejects the warm summary: nothing is written (safeguard returns a plain cancel, no attempt row), the boundary raisescompact_only, and the client compactor runs once.cacheCheckpoint: false(new optionalUserMessagefield); Anthropic Messages and Chat Completions place no cache marker on it, so history markers stay where the previous request put them.defersTokenCompactionToRequestBoundary, generalized from the ChatGPT-only check). Required compaction (prompt does not fit), byte-triggered compaction, configured context engines,compaction.model,compaction.provider, CLI/Codex runtimes and memory-flush turns keep their existing owners.Out of scope (later PRs): manual
/compact, overflow recovery, removing/responses/compact/params.responsesCompactEndpoint(shipped config key; needs xAI and quality evidence).Decisions recorded (defaults taken without asking):
compaction.modelexcludes the warm path whenever set (existing predicate), not only when it differs from the session model.plugins.slots.contextEngine.Impact
Users on Anthropic, OpenAI API key, cliproxy and other routes: automatic compaction reads the warm prompt cache instead of a cold summarizer request. No new config, prompt or wait.
Evidence
Tests (red on base: the module and behavior do not exist there):
request-boundary-compaction.test.ts: anthropic-messages attempt above the trigger sends a request equal to the uncompacted request (system, tools, params, all messages and markers) plus one unmarked user item; commit keeps summary + tail fromfirstKeptEntryIdwith the pending request once; split turn sends one summary request;toolandlengthreplies write nothing, raisecompact_only.compaction-safeguard.degraded-fallback.test.ts: warm summary is attempt 0 (no<previous-summary>, no<conversation>), corrective retry stays bounded; warm failure cancels without a recorded failure.Real-route E2E (isolated scratch Gateway; forced 24k
contextTokens, safeguard mode):First automatic compaction request per route. R/W/U/O = provider cacheRead / cacheWrite / uncached input / output. "Prior prompt" is the previous normal request's input tokens on that side.
/responses/compact)Head cacheWrite is the turn appended since the previous request (the history marker writes it, as a normal request would); the appended instruction itself carries no marker. On cliproxy at a 24k cap the resumed head session had already passed the window, so the hard guard used the existing deterministic fallback with no summary request; the matched 40k run (base and head with identical settings) is the proof row. Head warm requests kept all tools and the normal system prompt. Total paid E2E spend ≤ $3.80.
Local review fixes:
session:compact:before/afterhooks and post-compaction memory sync (postIndexSync) that reply-level compaction ran, and marks its session events hook-handled so plugin hooks run once.pnpm check:changed: green exceptdead export scan(scripts/lib/docker-e2e-watchdog.mjs: parseTimeoutMs, a file this PR does not touch) and one lint error in a new test, fixed.Accepted change, recorded: fitting token maintenance after a delivered reply (idle session maintenance) also defers to the next attempt's boundary, as ChatGPT V2 sessions already did, so those sessions now compact warm inside the next turn once it reaches the boundary trigger instead of with a cold request at the old client threshold.