Repository navigation
fix(agents): keep the prompt series when the bounded window drops an old compaction - #201655
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: blocked before merge. What this changesPreserve prompt-series identity across bounded history reloads by recovering it from checkpoints matched to the transcript boundary count. Example: After compaction, prompt checkpoints push the compaction entry outside a 192 KB transcript window.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain Keep open: this PR addresses a current prompt-cache defect, but its new mock factories fail the repository’s export ratchet. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe embedded runner reads transcript history and saved prompt checkpoints to select the system prompt and tool definitions sent to providers; background forks consume the same history-identity resolver. flowchart LR
A[Transcript storage] --> B[Bounded history window]
A --> C[Boundary count]
B --> D[History identity resolver]
C --> D
D --> E[Prompt and tool checkpoint owner]
E --> F[Provider request]
D --> G[Background session fork]
Technical reviewBest possible solution: Keep the shared checkpoint-based resolver, repair the new mocks, and retain focused cross-run coverage with verified upgrade compatibility. Do we have a high-confidence way to reproduce the issue? Current-main source shows the cross-attempt null fallback, and the PR supplies matching real-Gateway before/after output; this review executed no target code. Is this the best way to solve the issue? The shared resolver repairs the existing owner and checks checkpoint freshness against an authoritative count; the focused hydration regression is useful, while the additional 30-turn journey does not exercise boundary omission. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c6f10e80c474. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceAcceptance criteria:
What I checked:
Likely related people:
PR surfaceSource +44, Tests +285. Total +329 across 6 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. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 19, 2026, 1:30 AM ET / 06:30 UTC. |
…201710) > **Size:** production code vs `main` (base `3da2118`, excluding tests and docs) is +290 / -205 (net +85). Not net negative: the growth is the execution-gate conversion itself (build the session's full list, then gate by turn policy in assembly and the message policy), keeping refused tools out of delegation, capture, guidance and the preparer path, the run-policy mark that keeps the empty-allowlist error identical to `main`, and the opt-out admission path `toolSearch: false` still needs. 27 added lines are a move (`session-prompt-delta.ts`) forced by the line-cap ratchet. > > **Isolated crons keep main's narrowed list.** A session whose key is an isolated cron run (`agent:<id>:cron:<job>:run:<runId>`, one run per session, `isCronRunSessionKey`) has no series to share, so it keeps the listing narrowed to its allowlist, as on `main`. Every other session, including a cron that runs in a shared session, keeps the fixed listing. Call gates apply everywhere. First request of an isolated cron with `toolsAllow: ["read"]` (tools / input tokens; Claude input = uncached + cache read + cache write): > > | | main `3da2118` | `a5d2e08` (fixed listing everywhere) | this head | > |---|---|---|---| > | OpenAI | 4 / 6,128 | 14 / 12,368 | 4 / 6,114 | > | Claude | 4 / 9,206 | 14 / 20,121 | 4 / 9,258 | > > A cron that runs in a named shared session (journey J2) still sends the fixed list (14 tools), which is what keeps that session's later turns on one cached prefix. > > **Scope:** this PR covers core and plugin tools. MCP and LSP keep `main`'s behavior exactly: their runtimes start only when the run's allowlist permits it, and sender/group denies still apply at MCP discovery. Because MCP tools sit in the deferred catalog, an MCP-only-allowlist cron after `/compact` (J12) no longer narrows the pinned tool list on this head; what remains (the deferred directory following the allowlist, sender denies dropping an MCP server, and starting MCP/LSP from the pin) is the follow-up: pin-owned MCP/LSP listing with a lazy runtime start. ## Problem The session prompt owner pins the tool definitions of a prompt series. A turn that built a tool the pin lacked extended the pin, so the provider tool list changed. Tools sit at the front of the request, so the whole cached prefix missed. The list changed with turn authority: - A chat whose series starts on a cron turn has no `message` tool under the `coding` profile. The next user turn in `message_tool_only` delivery builds `message`, the pin grows, and that request reads 0 cached tokens. - A run's `toolsAllow` (cron, queued follow-ups, cross-session events) narrows the list. A subagent child's spawn turn (`disableMessageTool`) lists no `message` while its follow-up turns do. - Group `tools` / `toolsBySender` policy narrows the list per sender, so a guest and an owner in one group chat send different lists. - The deferred MCP directory sat in the `tool_search` definition, so an MCP server that connected later changed a tool definition. Freezing the pin alone made the first turn's omissions permanent (an owner turn after a narrowed turn silently lost tools). This PR makes the list independent of turn authority and gates calls at execution instead. ## Solution 1. **Freeze** (`session-prompt-state.ts`, `prepareSessionToolSurface`): on a fixed listing the series' first request pins the tool set and every definition. A pinned tool a turn did not build stays listed and refuses its call. The tool policy digest's inputs changed (it now includes `config.mcp`), so every session starts one new pin after upgrade. 2. **MCP directory out of `tool_search`**: `buildToolSchemaDirectoryPrompt` appends the bounded, sanitized MCP directory to the system prompt's `### Deferred Tool Schemas` section. An MCP server that connects, disconnects or changes its tools reaches the model as an appended prompt-update note, never as a definition change. 3. **`message` always listed, gated at execution**: on a fixed listing the assembly builds `message` regardless of reply mode; `resolveTurnToolSurface` refuses it on a turn that cannot send ("message cannot send on this turn: ... Do not retry message."). 4. **Every run allowlist and group/sender policy is an execution gate** (core and plugin tools): on a fixed listing, `toolsAllow` on any trigger and the group `tools` / `toolsBySender` policy no longer narrow construction. `resolveTurnToolSurface` refuses the tools the turn's policy omits ("`<tool>` is outside the tools this run allows. Do not retry `<tool>`."), marks them unavailable and as run-policy refusals, and never hands them the source's execution preparer, so direct calls, the agent loop's preparer path and a `dispatch_action` rewrap all refuse. Turn authority, child inheritance, cron-creator capture and the catalog restriction read the same policy, so the callable set is unchanged (table below). An allowlist that leaves nothing callable still fails with "No callable tools remain", as on `main`. 5. **Guidance follows callable tools** (m6): `applyPromptBuildToolsAllow` drops listed-but-refused tools from `callableToolNames`, so a turn that cannot send is not told to "use the message tool". 6. **Docs**: `docs/reference/prompt-caching.md`, `docs/tools/tool-search.md`, `docs/concepts/experimental-features.md`. ### Authority recheck at `390da1c` (fixed in this head) - **A1** (allowlists narrowing the list): for core and plugin tools, the allowlist no longer narrows construction on a fixed listing. The attempt-level filter is skipped (the assembly's turn policy already refuses what the allowlist omits, so the old attempt-level gate was redundant and is deleted). The MCP part (J12) is out of scope; see Scope. - **A2** (refused copies carried the source's execution preparer): `copyAgentToolMetadata` no longer copies the preparer onto a target that refuses execution (the turn-policy refusal in `resolveTurnToolSurface`, including the scoped-reads split). Ring-zero tools: a ring-zero harness run has no Tool Search controls, so it is never a fixed listing and the allowlist still removes them, as on `main` (test). - **m-a**: a tool built after the session pin is logged (`tools built after the session pin wait for the next prompt series`). - **m-b / 1b** (fixed for plugins): on a fixed listing, plugin construction keeps every grant plus the default plugin tools and uses a denylist without sender, group and run denies; those refuse at execution. Children still inherit the full denylist. The MCP part (a sender deny dropping a whole MCP server at discovery) is out of scope. - **1a** (fixed): `progress_card` is built whatever the run allowlist names and refused by the turn policy. `show_widget` keeps its admission rule (a scheduled run gets it only when its allowlist names it); that rule grants a capability rather than narrowing one, and changing it would remove widget authoring from such runs. Documented, not changed. - **1c**: the bundle pass (MCP/LSP) is back to `main`, except that tools the turn refuses are not delegated or captured. - **1d** (fixed): the scoped-reads split is marked before its metadata copy, so it never inherits the source's preparer (test red before the fix). - **1e** (fixed): the built-after-pin log fires once per series and tool set. - **m4a** (accepted): a completion handoff on a fixed listing does not mark run-allowlist refusals, so they can hide an allowlist that matched nothing (`main` removed them). - **m3** (accepted): a grant that only a guest's `allow` names builds that optional plugin tool on the guest's turn only. Plugin tools are catalog entries, so the pin holds; the cost is one prompt-update note per sender flip. Same class as the `show_widget` rule. - **m6** (accepted): a refused call still runs plugin `before_tool_call` hooks; the refusal happens after them and authority is unaffected. - **m5c**: the fixed listing has no unit test of the MCP call lifecycle; the real-route journeys (J5, J12) cover it. A cataloged client tool in the restored empty-allowlist error is also not unit-tested here. - **`fixedToolListing` kept**: Copilot (`tool-bridge.ts`), Codex (`dynamic-tool-build.ts`) and agentsapi pass a run allowlist into OpenClaw tool construction; I did not verify that each of them removes `progress_card` later, so the registration flag stays. - **structured_output** (documented): swarm collectors re-add `structured_output` after policy, so it stays callable under a `toolsAllow` that omits it. `main` removed it. Benign: it only records the collector's own result. - **Restored error** (fixed): "No callable tools remain" now matches `main` exactly except for tools a run allowlist or sender/group policy refuses (these were absent on `main`). Owner-only tools and cataloged client tools count as before (test: an allowlist naming an owner-only tool on a non-owner turn does not error, on `main` and head). - **MCP/LSP startup**: unchanged from `main` (out of scope). Auth prompts: starting the MCP runtime only reads credential status; sign-in starts only when a connect tool is called from an untainted owner direct chat, so a cron start raises no prompt. - **m-c**: the empty-allowlist error counts only callable tools, so a sender `allow` typo or a `toolsAllow` that names only refused tools fails with "No callable tools remain", as on `main` (same test green on both). - **m-d**: guidance drops cataloged tools the turn refuses, not only direct ones. ### Exceptions (behavior unchanged) Items 3-5 apply only when Tool Search lists a fixed set (`listsFixedToolSet`: controls enabled, `mode: "tools"`, no `include`/`exclude`). Otherwise (`tools.toolSearch` off, `disableToolSearch` runs, memory flush, Code Mode, selectors, `mode: "directory"`) filtering and pin admission stay as on `main` (gate A J8 below: per-turn lists equal between arms). Out of scope (follow-up): other trigger-dependent definition text, e.g. the `message` description's action list (see Risks). ### Fable D findings at `53145b8` - **M1** (owner turns lose tools after a narrowed turn): fixed by item 4. - **m2** (rewrap could bypass the gate): fixed; the production-path test "keeps a run allowlist refusal through a catalog rewrap" calls through a `dispatch_action` rewrap and gets the refusal. - **M3** (fork mismatch): gone with item 4; a fork sends the source's list unchanged (test below). - **m4** (history growth): after the split the MCP directory flips again on allowlisted turns, as on `main`: an allowlist naming no MCP server starts no MCP runtime, so a prompt-update note goes out on the cron turn and another on the next user turn. The cache is kept (notes append); the follow-up removes the flip. - **m5** (fork before the first post-upgrade turn): accepted edge case. `readSessionForkPin` ignores the policy digest, so such a fork sends the old pin plus `message` once (one miss); the source re-pins on its own next turn. Test: "lets a fork that runs before the first post-upgrade turn add message once". - **m6**: fixed by item 5. ## E2E on this head (`45ef8f8c583f`, base = merge base `3da2118f243c`) Isolated scratch Gateways (own state dir, random port, `env -i`) from source copies of each commit, real provider routes (OpenAI Responses and Claude via an Anthropic-messages proxy), a logging proxy recording provider usage per request. Both arms ran the same journeys with the same config (`visibleReplies: "message_tool"`, Tool Search on), with an unrelated chat running turns and `sessions.compact` throughout. OpenAI: `read` = `cached_tokens`, uncached = input − cached. Claude: `read` = `cache_read_input_tokens`, uncached = `input_tokens`, plus `write` = `cache_creation_input_tokens`. **J1: cron starts a chat, then the user** (cron request, then user turns) | route | arm | tool lists in the chat | cron→user request | session total | |---|---|---|---|---| | Claude | base | 2 (cron A, user B) | read 9,668 / write 16,952 | write 42,138 | | Claude | head | 1 | read 23,965 / write 3,168 | write 28,339 | | OpenAI | base | 2 | read 0 / uncached 17,007 | both user turns stopped by the model's `message` loop (below) | | OpenAI | head | 1 for the turns (see note) | read 15,667 / uncached 1,972 | `hello-j1` and `second-j1` delivered | **J2: shared-session cron with `toolsAllow: ["read"]`, then the owner asks for `exec`** | route | arm | cron listing | owner turn after the cron | session uncached (OpenAI) / write (Claude) | |---|---|---|---|---| | OpenAI | base | 4 tools | 14 tools, read 0 / uncached 19,340 | 27,413 | | OpenAI | head | 14 tools (fixed) | same list, read 13,582 / uncached 4,968 | 18,934 | | Claude | base | 4 tools | 14 tools, read 9,554 / write 21,734 | 32,060 | | Claude | head | 14 tools (fixed) | same list, read 21,976 / write 7,856 | 20,066 | Cron result on head (both routes): `exec` refused visibly ("exec is outside the tools this run allows. Do not retry exec."), `read` returned `gate-file-contents-7731`, `exec` did not run. Base: the model reports exec unavailable (not listed). The owner's later `exec` ran on both arms. **J2i: isolated cron with `toolsAllow: ["read"]`** keeps the narrowed listing, matching base: 4 tools on both arms; first request input OpenAI 6,110 (base) vs 6,145 (head), Claude 9,206 vs 9,260 total. **J11: one group, guest denied `exec` (sender policy), then owner** | route | arm | tool lists in the group | requests with read 0 after the first | uncached (OpenAI) / write (Claude) | |---|---|---|---|---| | OpenAI | base | 2 (guest 9 tools, owner 14) | 1 (owner's first turn) | 39,422 | | OpenAI | head | 1 (14) | 0 | 25,740 | | Claude | base | 2 (9, 14) | 1 | 62,158 | | Claude | head | 1 (14) | 0 | 29,511 | Guest `exec` on head: refused with "exec is outside the tools this run allows. Do not retry exec." (base: not listed, the model says it is unavailable). Guest `read` worked and both owner `exec` calls ran on both arms. **Side effects.** Every journey's replies arrived on head (J1 user replies, J2 cron + owner, J11 five group replies, J2i cron `ok`); refused tools stayed refused and never executed. The OpenAI model on this route sometimes fills every optional `message` field (a `gatewayUrl`, a made-up target) and loops; this happened on **both** arms (base: both J1 user turns and one unrelated-chat turn stopped by the 20-repeat guard; head: three unrelated-chat turns stopped the same way, and J1's first reply was kept private, then delivered by the stranded-reply retry). The stranded-reply retry runs with `toolsAllow: ["message"]` (`stranded-reply-recovery.ts`, unchanged by this PR), so it sends a message-only list and misses the cache once (OpenAI uncached 9,207) on both arms; not changed here, noted as a follow-up. **UI** (Control UI of the head and base scratch Gateways, after the journeys; chat area cropped): the J2 chat shows the cron's visible refusal, the J11 group shows the guest's refusal, J1 renders both delivered replies. | | base | head | |---|---|---| | J2 |  |  | | J11 group |  |  | | J1 (OpenAI) |  |  | The live operator Gateway was untouched during the runs (its pid and config unchanged). ## Evidence ### Tests (red on merge base `3da2118f243c`, green on this head) - `src/agents/session-tool-listing.test.ts`: one tool list across user, cron, exec-wake, subagent, steer and allowlisted turns, checked on each turn's own built list and on the sent list; one list for every sender of a group chat; a fork sends the source's list unchanged; a cron turn after `/compact` re-pins the owner turn's list (green on main too: this fixture does not reproduce the #201655 4-vs-3 case); a later user turn sends with `message` in a cron-started series. - `attempt-tool-prepare.scheduled-tools-allow.test.ts` (real `prepareEmbeddedAttemptToolBase`): refusal-equivalence table "allows exactly the calls main allowed" for cron/user/event `toolsAllow`, group guest sender and group owner sender; one tool set for every group sender with the guest refused through `dispatch_action`; refusal kept through a catalog rewrap; an allowlist matching nothing still fails (green on main and head). - `agent-tools.turn-authority.test.ts`: a turn-policy refusal and the scoped-reads split never carry the source's preparer (red on `390da1c` / before the fix). - `attempt-prompt-tool-policy.test.ts`: "leaves a listed tool the turn refuses out of the callable guidance" (main: `['message','read']`, head: `['read']`). - `attempt-session-runtime-prepare.test.ts`: production `admitNewTools` wiring (inverting it fails 2 tests). `session-prompt-state.test.ts`: one new pin after an upgrade changes the policy digest. ### Execution-based refusal equivalence `attempt.configured-mcp-lifecycle.test.ts` now runs its cataloged case with an `include` selector: the fixed listing builds every core tool, which that harness does not mock. The fixed-listing MCP path is covered by the real-route journeys (J5, J12, J13). `attempt-tool-prepare.scheduled-tools-allow.test.ts` builds tools through the production tool base, bundle pass (a mocked bundle MCP server) and catalog, then executes every listed tool through the direct path, the preparer the agent loop prefers, and a `dispatch_action` rewrap. The callable tables (cron/user/event `toolsAllow`, group guest, group owner) pass unchanged on `main` and on this head; the three paths agree for every tool. New: an MCP-only allowlist lists the full set (red on `390da1c`), sender `allow`/`deny` policies including an MCP tool, a refused tool is never delegated or captured, and only-refused-tools fails loudly (green on `main` and head, red on `390da1c`). A tool counts as callable only when a call with schema-valid placeholder arguments passes every gate, starts the tool's implementation and does not come back refused; exceptions and timeouts before the implementation starts count as not callable. ### Callable set, base vs head (`toolsAllow: ["read", "group:web", "sessions_*", "message"]`; group deny `exec, process, write, edit, apply_patch` for the guest) | case | callable on base and head | listed on head | |---|---|---| | cron / user / event `toolsAllow` | dispatch_action, message, read, sessions_create, sessions_history, sessions_list, sessions_search, sessions_send, sessions_spawn, sessions_yield, tool_describe, tool_search, web_fetch | full session list (39), the rest refused | | group guest | guest set (identical on base and head) | full session list (40), denied tools refused | | group owner | guest set + apply_patch, automations, conversations_*, edit, exec, gateway, plugins, portal, process, terminal, write | same list as the guest | ### Gate A at earlier heads (`c1160ede` / `6bbc29a2`), for history Base `3da2118`. OpenAI `gpt-6.2-astra` and cliproxy `claude-opus-5-5`. Raw results in `/tmp/pcr/gate201710/`. | journey | main | head | |---|---|---| | J1 cron starts chat, then user | list changes 2x (OpenAI incl. a message-only list), cache misses | one list, cache hits; user reply via `message` | | J2 cron `toolsAllow: ["read"]` | list 4 tools on the cron turn, 14 on the user turn (miss) | 14 throughout; `exec` refused visibly, `read` works, later user `exec` works; cache hits | | J3 reset, cron first, user | reply arrives | reply arrives; new list only at the reset (new session) | | J4 turn that may not send calls `message` | OpenAI: no refusal | OpenAI: visible refusal, nothing delivered. Claude: same as main on both arms (model replied without the message call) | | J5 MCP connect mid-chat | directory in `tool_search` | list unchanged; directory change arrives as an appended note; `dispatch_action` -> `mcp:beta:beta__beta_probe` returns `probe-ok-beta` with a cache hit (OpenAI read 30,770 / 30,949) | | J6 computer without a node | one list; call fails visibly | same | | J7 exec wake, subagent, steer | list changes (OpenAI D->B->E->D) | one list; wake, child result and steer all delivered | | J8 `toolSearch: false` | per-turn lists | identical to main on both routes | | J9 regression set | ok (OpenAI after-reset turn errored once) | ok | | J10 owner turns, `/compact`, cron, owner | one list (no 4-vs-3 repro on this config) | one list (14) before and after; cron after compaction keeps it; next owner turn cache hit | | J11 group: guest denied exec, owner | guest pins 9 tools, owner turn 14 with a miss, a prompt-update note per sender flip | one list (14) for both senders, every request a cache hit (Claude reads 23,881 -> 31,107), guest `exec` refused ("exec is outside the tools this run allows"), guest `read` and owner `exec` work | ### Gate A on this head (`d827cceb`, main `3da2118`), proxy-log excerpts, redacted Isolated scratch Gateways (`env -i`, random ports, isolated state), a concurrent second chat running turns and `sessions.compact`. Each cell: the session's tool sets in order (a letter per distinct tool-definition hash), then per request `tool count/cached input tokens`. | journey | route | main | head | |---|---|---|---| | J1 cron starts chat, then user | OpenAI | `B>A`: 14/0 **14/0** 14/16362 14/16587 | `B`: 14/0 14/14440 14/14762 14/15070 14/17039 | | | Claude | `B>A`: 14/0 **14/9668** 14/26625 | `B`: 14/0 14/23920 14/27152 | | J2 cron `toolsAllow: ["read"]`, then user `exec` | OpenAI | `C>D`: **4**/0 4/6485 **14/0** 14/19323 | `B`: 14/0 14/13046 14/13163 14/13500 14/18458; `exec` refused, `read` ok, user `exec` ok | | | Claude | `C>D`: **4**/0 4/9786 4/10049 **14/9554** 14/31223 | `B`: 14/9951 14/21608 14/21904 14/29747 | | J3 reset, cron first, user | both | new set at the reset, then back | new set only at the reset (new session) | | J4 cannot-send cron calls `message` | OpenAI | no refusal | refused: "message cannot send on this turn: its reply delivery or tool policy does not allow the message tool. Do not retry message." | | J7 exec wake, subagent, steer | OpenAI | `A>F>A` | `A` | | J10 owner, `/compact`, cron, owner | Claude | `A`: 14/9668 14/23800 14/9668 14/25198 14/26268 | `A`: 14/9554 14/23780 14/9554 14/25189 14/26302 (the 9,554 row is the cron right after compaction: history rewritten, tools kept) | | J11 group: guest denied `exec`, then owner | OpenAI | `H>I`: **9**/0 9/12866 9/13418 **14/0** 14/19652 | `E`: 14/0 14/14300 14/17481 14/17525 14/20649; guest `exec` refused ("exec is outside the tools this run allows. Do not retry exec."), guest `read` and owner `exec` ok | | | Claude | `G>H`: **9**/0 **14/0** 14/28797 14/28928 | `E`: 14/9942 14/23774 14/28261 14/28369 | | J12 owner, `/compact`, cron `toolsAllow: ["alpha__alpha_probe"]`, owner | Claude | `A>I>A`: 14/9668 14/23800 **3/0** 3/6670 3/7224 **14/9668** | `A`: 14/9554 14/23780 14/9554 14/22377 14/22989 14/23317; cron calls `alpha_probe` via `dispatch_action`, its `exec` is refused, owner `exec` ok | J12 passes on head because MCP tools live in the deferred catalog, not the tool list: the core list no longer follows the allowlist. What stays as on `main` is the MCP runtime start rule (an allowlist that names no MCP server does not start MCP, so the deferred directory changes through an appended note) and MCP discovery honoring sender/group denies. Earlier runs (J5 MCP connect mid-chat, J6 computer, J8 `toolSearch: false`, J9 regression set) are unchanged by the split and were green at `c1160ede`. Pre-existing on both arms: gpt-6.2 fills `channel`/`target` on WebChat `message` calls and loops on the rejection; `chat.abort` leaves the run status `error`; a `sessions.compact` during an active run is rejected ("has an active run; retry after it finishes"). ### Existing-session upgrade (one session, main then head on the same state dir) Isolated scratch Gateway (`env -i`, random port, isolated state dir, 250k context so compaction cannot mask the measurement), cliproxy `claude-opus-5-5`. Main `3da2118` builds the session with four owner turns (reply, `read`, `exec`, reply) and stops. Head `d827cceb` starts on the same state dir: one owner turn, a cron with `toolsAllow: ["read"]`, an owner `exec` turn, a last reply. | arm | turn | tools | cached / written | |---|---|---|---| | main | owner reply | 14 | 9,668 / 15,865 | | main | owner `read` (+ follow-up) | 14 | 25,533 / 1,148; 26,681 / 84 | | main | owner `exec` (+ follow-up) | 14 | 26,765 / 1,158; 27,923 / 104 | | main | owner reply | 14 | 28,027 / 1,152 | | head | first turn after the upgrade: **the one re-pin** | 14 | 9,554 / 20,755 (only the system prefix is cached) | | head | cron `toolsAllow: ["read"]`: `read` ok, `exec` refused ("exec is outside the tools this run allows") | 14 | 30,309 / 6,865; 37,174 / 302 (hits) | | head | owner `exec`: runs | 14 | 37,476 / 9,278; 46,754 / 161 (hits) | | head | last reply | 14 | 46,915 / 1,153 (hit) | One miss on the first head turn, then cache hits on the cron and owner turns. ### Gate C (append-only journeys from #201723) Stability journeys: head 5/5 pass, main 5/5 pass (they do not separate the arms). Randomized seeds 1-10 on head: 60/60 pass (anthropic-messages, openai-responses, openai-completions, google, bedrock, and the Tool Search opt-out surface). ### Gates - `pnpm tsgo:core`: pass. oxlint, oxfmt on changed files, `git diff --check`: clean. - Production code vs `main` (excluding tests and docs): +290 / -205 (net +85); see the size note at the top. ### Test lines Net test lines +994 against the 400 allowance. Duplicate tests were removed first (the scheduled-run table duplicate, the separate catalog-rewrap test, the sender-deny MCP case, the bundle MCP fixture, and the duplicate group-sender listing test). The remaining 594 lines are recorded in `config/test-lines-allocations/201710-session-tool-listing.txt`: refusal equivalence against `main` executed through the production tool base, bundle pass and catalog for five policy shapes across the direct, preparer and `dispatch_action` paths, plus series listing, fork and upgrade pin cases. ### Local ClawSweeper (gpt-6.1-sol, normal) Head `45ef8f8c583f`: patch is correct, no findings (exit 0). The local review reads only the committed range and its tests; the real-route journeys above are outside its inputs. An earlier P2 at `9543fde3` (sender change dropping a direct-only tool such as `computer` from a frozen group listing) is fixed by item 4: every sender builds the same list. ## Risks - `message` and allowlist-refused tools are listed (and refused visibly) on turns that cannot use them. Each costs one definition. - The `message` definition's action list still depends on the turn that starts the series (a cron-started WebChat series pins "Supports actions: send" without `react`). The pin keeps it stable; `react` is not advertised in that series until a rebuild point. Main would extend the pin (a miss) instead. Follow-up. - Upgrade: every existing session re-pins once on its first turn after the upgrade (the toolPolicy digest changes), costing one cache miss per session. This is the same accepted one-time cost as #201843. - MCP names and sanitized descriptions now enter the system prompt's deferred-tool section instead of the `tool_search` description. Co-authored-by: Ayaan Zaidi <[email protected]>
…arts after compaction The series is keyed on its history: the newest compaction or reset. A bounded transcript reload can start after that entry. The id then read as null, the series restarted as a new history and the whole system prompt was re-rendered mid-session (seen after a workspace file edit, once the session outgrew the window). The newest prompt checkpoint in the window was written in that history and records its id, so the series now reads it there. History-id resolution moves to its own module. Co-authored-by: obviyus <[email protected]>
… boundary A bounded window can start after the newest compaction. The newest prompt checkpoint then names the history, but a checkpoint written before a later compaction still carries the earlier history. That pinned a system prompt from before the compaction and lost the prompt updates the compaction summarized. Each checkpoint now records the transcript boundary count. A checkpoint is evidence of the current history only when its count matches the session manager's count; otherwise the history is unknown and the series restarts once. Null stays valid only for a session that never compacted or reset. The session fork pin resolves its history with the same resolver. Co-authored-by: obviyus <[email protected]>
…n in the prefix journey Co-authored-by: obviyus <[email protected]>
…old compaction OpenClaw-Publication: 650c2283-6d98-83fb-aa93-9135a86a193d
The boundary count changes only at a compaction or reset on the active path, so a checkpoint that recorded `unknown:N` at count N belongs to the same history. A legacy series restarts at most twice: once to the unknown history, then once more when the boundary fits a window. Cover rewind before the last compaction, an edit of an earlier message, reset, two sessions with the same count, and the two-restart upgrade path through the real SQLite hydration. Pass the boundary count in the bounded window unit test as production does. Drop the journey step: it passed on the merge base, so it could not catch the defect. Co-authored-by: obviyus <[email protected]>
A checkpoint that records the transcript's boundary count was written in the current history, so its id now names the history even when the boundary is back in the window. Before, an evicted checkpoint led to an unknown:N restart, and the returning boundary restarted the series again. A restored legacy checkpoint now keeps its persisted (missing) count, so the next persist writes the count instead of leaving it absent forever. Tests now push the boundary out of the window so they reach the count rule: eviction, legacy count, the legacy null restart (now once), and the active-path count after a rewind. Remove the edit and reset tests, which could not fail with the count rule removed, and reduce the two-session test to the unknown:<count> shape it checks. Revert the fork resolver change: the fork view carries no checkpoint data, so it was a no-op. Co-authored-by: obviyus <[email protected]>
…and compaction cases Co-authored-by: obviyus <[email protected]>
… path after a rewind Co-authored-by: obviyus <[email protected]>
… duplicate cases Use the real payload log, cache trace, tool-result projection, context guards and settle tracker; annotate the two isolation mocks. Fold the unknown-id shape check into the rewind case and drop the unit legacy-null case the SQLite test covers. Co-authored-by: obviyus <[email protected]>
…undary journey only main grew session-accessor.sqlite-bounded-context.test.ts past the line cap; the rewind case in attempt-session-runtime-prepare.history-boundary.test.ts reads the same SQLite bounded context and asserts the active-path count. Co-authored-by: obviyus <[email protected]>
dd58eb1 to
7a698fb
Compare
A pinned prompt series carries every System prompt update since its history began, each repeating the whole changed section. Compaction summarized them all and could exhaust the summary output budget. Compaction starts a new prompt history whose restart renders every section current, so the summarizer reads none of them. Co-authored-by: obviyus <[email protected]>
…p spread Co-authored-by: obviyus <[email protected]>
|
Landed as ee1140e (squash) at head dfb4d5b. The prompt series now survives a compaction scrolling out of the bounded transcript window, and compaction no longer summarizes superseded prompt updates. Proof: real-Gateway E2E on base vs head (OpenAI request 13 went from 0 to 12336 cached tokens, history restarts without a compaction went from 2-3 to 0, every turn answered after a Gateway restart), clean local review, green CI. checks-fast-baseline-ratchets lost its hosted runner once and passed on a rerun. |
…penclaw#201710) > **Size:** production code vs `main` (base `cbc12e7`, excluding tests and docs) is +290 / -205 (net +85). Not net negative: the growth is the execution-gate conversion itself (build the session's full list, then gate by turn policy in assembly and the message policy), keeping refused tools out of delegation, capture, guidance and the preparer path, the run-policy mark that keeps the empty-allowlist error identical to `main`, and the opt-out admission path `toolSearch: false` still needs. 27 added lines are a move (`session-prompt-delta.ts`) forced by the line-cap ratchet. > > **Isolated crons keep main's narrowed list.** A session whose key is an isolated cron run (`agent:<id>:cron:<job>:run:<runId>`, one run per session, `isCronRunSessionKey`) has no series to share, so it keeps the listing narrowed to its allowlist, as on `main`. Every other session, including a cron that runs in a shared session, keeps the fixed listing. Call gates apply everywhere. First request of an isolated cron with `toolsAllow: ["read"]` (tools / input tokens; Claude input = uncached + cache read + cache write): > > | | main `cbc12e7` | `a5d2e08` (fixed listing everywhere) | this head | > |---|---|---|---| > | OpenAI | 4 / 6,128 | 14 / 12,368 | 4 / 6,114 | > | Claude | 4 / 9,206 | 14 / 20,121 | 4 / 9,258 | > > A cron that runs in a named shared session (journey J2) still sends the fixed list (14 tools), which is what keeps that session's later turns on one cached prefix. > > **Scope:** this PR covers core and plugin tools. MCP and LSP keep `main`'s behavior exactly: their runtimes start only when the run's allowlist permits it, and sender/group denies still apply at MCP discovery. Because MCP tools sit in the deferred catalog, an MCP-only-allowlist cron after `/compact` (J12) no longer narrows the pinned tool list on this head; what remains (the deferred directory following the allowlist, sender denies dropping an MCP server, and starting MCP/LSP from the pin) is the follow-up: pin-owned MCP/LSP listing with a lazy runtime start. ## Problem The session prompt owner pins the tool definitions of a prompt series. A turn that built a tool the pin lacked extended the pin, so the provider tool list changed. Tools sit at the front of the request, so the whole cached prefix missed. The list changed with turn authority: - A chat whose series starts on a cron turn has no `message` tool under the `coding` profile. The next user turn in `message_tool_only` delivery builds `message`, the pin grows, and that request reads 0 cached tokens. - A run's `toolsAllow` (cron, queued follow-ups, cross-session events) narrows the list. A subagent child's spawn turn (`disableMessageTool`) lists no `message` while its follow-up turns do. - Group `tools` / `toolsBySender` policy narrows the list per sender, so a guest and an owner in one group chat send different lists. - The deferred MCP directory sat in the `tool_search` definition, so an MCP server that connected later changed a tool definition. Freezing the pin alone made the first turn's omissions permanent (an owner turn after a narrowed turn silently lost tools). This PR makes the list independent of turn authority and gates calls at execution instead. ## Solution 1. **Freeze** (`session-prompt-state.ts`, `prepareSessionToolSurface`): on a fixed listing the series' first request pins the tool set and every definition. A pinned tool a turn did not build stays listed and refuses its call. The tool policy digest's inputs changed (it now includes `config.mcp`), so every session starts one new pin after upgrade. 2. **MCP directory out of `tool_search`**: `buildToolSchemaDirectoryPrompt` appends the bounded, sanitized MCP directory to the system prompt's `### Deferred Tool Schemas` section. An MCP server that connects, disconnects or changes its tools reaches the model as an appended prompt-update note, never as a definition change. 3. **`message` always listed, gated at execution**: on a fixed listing the assembly builds `message` regardless of reply mode; `resolveTurnToolSurface` refuses it on a turn that cannot send ("message cannot send on this turn: ... Do not retry message."). 4. **Every run allowlist and group/sender policy is an execution gate** (core and plugin tools): on a fixed listing, `toolsAllow` on any trigger and the group `tools` / `toolsBySender` policy no longer narrow construction. `resolveTurnToolSurface` refuses the tools the turn's policy omits ("`<tool>` is outside the tools this run allows. Do not retry `<tool>`."), marks them unavailable and as run-policy refusals, and never hands them the source's execution preparer, so direct calls, the agent loop's preparer path and a `dispatch_action` rewrap all refuse. Turn authority, child inheritance, cron-creator capture and the catalog restriction read the same policy, so the callable set is unchanged (table below). An allowlist that leaves nothing callable still fails with "No callable tools remain", as on `main`. 5. **Guidance follows callable tools** (m6): `applyPromptBuildToolsAllow` drops listed-but-refused tools from `callableToolNames`, so a turn that cannot send is not told to "use the message tool". 6. **Docs**: `docs/reference/prompt-caching.md`, `docs/tools/tool-search.md`, `docs/concepts/experimental-features.md`. ### Authority recheck at `390da1c` (fixed in this head) - **A1** (allowlists narrowing the list): for core and plugin tools, the allowlist no longer narrows construction on a fixed listing. The attempt-level filter is skipped (the assembly's turn policy already refuses what the allowlist omits, so the old attempt-level gate was redundant and is deleted). The MCP part (J12) is out of scope; see Scope. - **A2** (refused copies carried the source's execution preparer): `copyAgentToolMetadata` no longer copies the preparer onto a target that refuses execution (the turn-policy refusal in `resolveTurnToolSurface`, including the scoped-reads split). Ring-zero tools: a ring-zero harness run has no Tool Search controls, so it is never a fixed listing and the allowlist still removes them, as on `main` (test). - **m-a**: a tool built after the session pin is logged (`tools built after the session pin wait for the next prompt series`). - **m-b / 1b** (fixed for plugins): on a fixed listing, plugin construction keeps every grant plus the default plugin tools and uses a denylist without sender, group and run denies; those refuse at execution. Children still inherit the full denylist. The MCP part (a sender deny dropping a whole MCP server at discovery) is out of scope. - **1a** (fixed): `progress_card` is built whatever the run allowlist names and refused by the turn policy. `show_widget` keeps its admission rule (a scheduled run gets it only when its allowlist names it); that rule grants a capability rather than narrowing one, and changing it would remove widget authoring from such runs. Documented, not changed. - **1c**: the bundle pass (MCP/LSP) is back to `main`, except that tools the turn refuses are not delegated or captured. - **1d** (fixed): the scoped-reads split is marked before its metadata copy, so it never inherits the source's preparer (test red before the fix). - **1e** (fixed): the built-after-pin log fires once per series and tool set. - **m4a** (accepted): a completion handoff on a fixed listing does not mark run-allowlist refusals, so they can hide an allowlist that matched nothing (`main` removed them). - **m3** (accepted): a grant that only a guest's `allow` names builds that optional plugin tool on the guest's turn only. Plugin tools are catalog entries, so the pin holds; the cost is one prompt-update note per sender flip. Same class as the `show_widget` rule. - **m6** (accepted): a refused call still runs plugin `before_tool_call` hooks; the refusal happens after them and authority is unaffected. - **m5c**: the fixed listing has no unit test of the MCP call lifecycle; the real-route journeys (J5, J12) cover it. A cataloged client tool in the restored empty-allowlist error is also not unit-tested here. - **`fixedToolListing` kept**: Copilot (`tool-bridge.ts`), Codex (`dynamic-tool-build.ts`) and agentsapi pass a run allowlist into OpenClaw tool construction; I did not verify that each of them removes `progress_card` later, so the registration flag stays. - **structured_output** (documented): swarm collectors re-add `structured_output` after policy, so it stays callable under a `toolsAllow` that omits it. `main` removed it. Benign: it only records the collector's own result. - **Restored error** (fixed): "No callable tools remain" now matches `main` exactly except for tools a run allowlist or sender/group policy refuses (these were absent on `main`). Owner-only tools and cataloged client tools count as before (test: an allowlist naming an owner-only tool on a non-owner turn does not error, on `main` and head). - **MCP/LSP startup**: unchanged from `main` (out of scope). Auth prompts: starting the MCP runtime only reads credential status; sign-in starts only when a connect tool is called from an untainted owner direct chat, so a cron start raises no prompt. - **m-c**: the empty-allowlist error counts only callable tools, so a sender `allow` typo or a `toolsAllow` that names only refused tools fails with "No callable tools remain", as on `main` (same test green on both). - **m-d**: guidance drops cataloged tools the turn refuses, not only direct ones. ### Exceptions (behavior unchanged) Items 3-5 apply only when Tool Search lists a fixed set (`listsFixedToolSet`: controls enabled, `mode: "tools"`, no `include`/`exclude`). Otherwise (`tools.toolSearch` off, `disableToolSearch` runs, memory flush, Code Mode, selectors, `mode: "directory"`) filtering and pin admission stay as on `main` (gate A J8 below: per-turn lists equal between arms). Out of scope (follow-up): other trigger-dependent definition text, e.g. the `message` description's action list (see Risks). ### Fable D findings at `53145b8` - **M1** (owner turns lose tools after a narrowed turn): fixed by item 4. - **m2** (rewrap could bypass the gate): fixed; the production-path test "keeps a run allowlist refusal through a catalog rewrap" calls through a `dispatch_action` rewrap and gets the refusal. - **M3** (fork mismatch): gone with item 4; a fork sends the source's list unchanged (test below). - **m4** (history growth): after the split the MCP directory flips again on allowlisted turns, as on `main`: an allowlist naming no MCP server starts no MCP runtime, so a prompt-update note goes out on the cron turn and another on the next user turn. The cache is kept (notes append); the follow-up removes the flip. - **m5** (fork before the first post-upgrade turn): accepted edge case. `readSessionForkPin` ignores the policy digest, so such a fork sends the old pin plus `message` once (one miss); the source re-pins on its own next turn. Test: "lets a fork that runs before the first post-upgrade turn add message once". - **m6**: fixed by item 5. ## E2E on this head (`45ef8f8c583f`, base = merge base `cbc12e7178f8`) Isolated scratch Gateways (own state dir, random port, `env -i`) from source copies of each commit, real provider routes (OpenAI Responses and Claude via an Anthropic-messages proxy), a logging proxy recording provider usage per request. Both arms ran the same journeys with the same config (`visibleReplies: "message_tool"`, Tool Search on), with an unrelated chat running turns and `sessions.compact` throughout. OpenAI: `read` = `cached_tokens`, uncached = input − cached. Claude: `read` = `cache_read_input_tokens`, uncached = `input_tokens`, plus `write` = `cache_creation_input_tokens`. **J1: cron starts a chat, then the user** (cron request, then user turns) | route | arm | tool lists in the chat | cron→user request | session total | |---|---|---|---|---| | Claude | base | 2 (cron A, user B) | read 9,668 / write 16,952 | write 42,138 | | Claude | head | 1 | read 23,965 / write 3,168 | write 28,339 | | OpenAI | base | 2 | read 0 / uncached 17,007 | both user turns stopped by the model's `message` loop (below) | | OpenAI | head | 1 for the turns (see note) | read 15,667 / uncached 1,972 | `hello-j1` and `second-j1` delivered | **J2: shared-session cron with `toolsAllow: ["read"]`, then the owner asks for `exec`** | route | arm | cron listing | owner turn after the cron | session uncached (OpenAI) / write (Claude) | |---|---|---|---|---| | OpenAI | base | 4 tools | 14 tools, read 0 / uncached 19,340 | 27,413 | | OpenAI | head | 14 tools (fixed) | same list, read 13,582 / uncached 4,968 | 18,934 | | Claude | base | 4 tools | 14 tools, read 9,554 / write 21,734 | 32,060 | | Claude | head | 14 tools (fixed) | same list, read 21,976 / write 7,856 | 20,066 | Cron result on head (both routes): `exec` refused visibly ("exec is outside the tools this run allows. Do not retry exec."), `read` returned `gate-file-contents-7731`, `exec` did not run. Base: the model reports exec unavailable (not listed). The owner's later `exec` ran on both arms. **J2i: isolated cron with `toolsAllow: ["read"]`** keeps the narrowed listing, matching base: 4 tools on both arms; first request input OpenAI 6,110 (base) vs 6,145 (head), Claude 9,206 vs 9,260 total. **J11: one group, guest denied `exec` (sender policy), then owner** | route | arm | tool lists in the group | requests with read 0 after the first | uncached (OpenAI) / write (Claude) | |---|---|---|---|---| | OpenAI | base | 2 (guest 9 tools, owner 14) | 1 (owner's first turn) | 39,422 | | OpenAI | head | 1 (14) | 0 | 25,740 | | Claude | base | 2 (9, 14) | 1 | 62,158 | | Claude | head | 1 (14) | 0 | 29,511 | Guest `exec` on head: refused with "exec is outside the tools this run allows. Do not retry exec." (base: not listed, the model says it is unavailable). Guest `read` worked and both owner `exec` calls ran on both arms. **Side effects.** Every journey's replies arrived on head (J1 user replies, J2 cron + owner, J11 five group replies, J2i cron `ok`); refused tools stayed refused and never executed. The OpenAI model on this route sometimes fills every optional `message` field (a `gatewayUrl`, a made-up target) and loops; this happened on **both** arms (base: both J1 user turns and one unrelated-chat turn stopped by the 20-repeat guard; head: three unrelated-chat turns stopped the same way, and J1's first reply was kept private, then delivered by the stranded-reply retry). The stranded-reply retry runs with `toolsAllow: ["message"]` (`stranded-reply-recovery.ts`, unchanged by this PR), so it sends a message-only list and misses the cache once (OpenAI uncached 9,207) on both arms; not changed here, noted as a follow-up. **UI** (Control UI of the head and base scratch Gateways, after the journeys; chat area cropped): the J2 chat shows the cron's visible refusal, the J11 group shows the guest's refusal, J1 renders both delivered replies. | | base | head | |---|---|---| | J2 |  |  | | J11 group |  |  | | J1 (OpenAI) |  |  | The live operator Gateway was untouched during the runs (its pid and config unchanged). ## Evidence ### Tests (red on merge base `cbc12e7178f8`, green on this head) - `src/agents/session-tool-listing.test.ts`: one tool list across user, cron, exec-wake, subagent, steer and allowlisted turns, checked on each turn's own built list and on the sent list; one list for every sender of a group chat; a fork sends the source's list unchanged; a cron turn after `/compact` re-pins the owner turn's list (green on main too: this fixture does not reproduce the openclaw#201655 4-vs-3 case); a later user turn sends with `message` in a cron-started series. - `attempt-tool-prepare.scheduled-tools-allow.test.ts` (real `prepareEmbeddedAttemptToolBase`): refusal-equivalence table "allows exactly the calls main allowed" for cron/user/event `toolsAllow`, group guest sender and group owner sender; one tool set for every group sender with the guest refused through `dispatch_action`; refusal kept through a catalog rewrap; an allowlist matching nothing still fails (green on main and head). - `agent-tools.turn-authority.test.ts`: a turn-policy refusal and the scoped-reads split never carry the source's preparer (red on `390da1c` / before the fix). - `attempt-prompt-tool-policy.test.ts`: "leaves a listed tool the turn refuses out of the callable guidance" (main: `['message','read']`, head: `['read']`). - `attempt-session-runtime-prepare.test.ts`: production `admitNewTools` wiring (inverting it fails 2 tests). `session-prompt-state.test.ts`: one new pin after an upgrade changes the policy digest. ### Execution-based refusal equivalence `attempt.configured-mcp-lifecycle.test.ts` now runs its cataloged case with an `include` selector: the fixed listing builds every core tool, which that harness does not mock. The fixed-listing MCP path is covered by the real-route journeys (J5, J12, J13). `attempt-tool-prepare.scheduled-tools-allow.test.ts` builds tools through the production tool base, bundle pass (a mocked bundle MCP server) and catalog, then executes every listed tool through the direct path, the preparer the agent loop prefers, and a `dispatch_action` rewrap. The callable tables (cron/user/event `toolsAllow`, group guest, group owner) pass unchanged on `main` and on this head; the three paths agree for every tool. New: an MCP-only allowlist lists the full set (red on `390da1c`), sender `allow`/`deny` policies including an MCP tool, a refused tool is never delegated or captured, and only-refused-tools fails loudly (green on `main` and head, red on `390da1c`). A tool counts as callable only when a call with schema-valid placeholder arguments passes every gate, starts the tool's implementation and does not come back refused; exceptions and timeouts before the implementation starts count as not callable. ### Callable set, base vs head (`toolsAllow: ["read", "group:web", "sessions_*", "message"]`; group deny `exec, process, write, edit, apply_patch` for the guest) | case | callable on base and head | listed on head | |---|---|---| | cron / user / event `toolsAllow` | dispatch_action, message, read, sessions_create, sessions_history, sessions_list, sessions_search, sessions_send, sessions_spawn, sessions_yield, tool_describe, tool_search, web_fetch | full session list (39), the rest refused | | group guest | guest set (identical on base and head) | full session list (40), denied tools refused | | group owner | guest set + apply_patch, automations, conversations_*, edit, exec, gateway, plugins, portal, process, terminal, write | same list as the guest | ### Gate A at earlier heads (`c1160ede` / `6bbc29a2`), for history Base `cbc12e7`. OpenAI `gpt-6.2-astra` and cliproxy `claude-opus-5-5`. Raw results in `/tmp/pcr/gate201710/`. | journey | main | head | |---|---|---| | J1 cron starts chat, then user | list changes 2x (OpenAI incl. a message-only list), cache misses | one list, cache hits; user reply via `message` | | J2 cron `toolsAllow: ["read"]` | list 4 tools on the cron turn, 14 on the user turn (miss) | 14 throughout; `exec` refused visibly, `read` works, later user `exec` works; cache hits | | J3 reset, cron first, user | reply arrives | reply arrives; new list only at the reset (new session) | | J4 turn that may not send calls `message` | OpenAI: no refusal | OpenAI: visible refusal, nothing delivered. Claude: same as main on both arms (model replied without the message call) | | J5 MCP connect mid-chat | directory in `tool_search` | list unchanged; directory change arrives as an appended note; `dispatch_action` -> `mcp:beta:beta__beta_probe` returns `probe-ok-beta` with a cache hit (OpenAI read 30,770 / 30,949) | | J6 computer without a node | one list; call fails visibly | same | | J7 exec wake, subagent, steer | list changes (OpenAI D->B->E->D) | one list; wake, child result and steer all delivered | | J8 `toolSearch: false` | per-turn lists | identical to main on both routes | | J9 regression set | ok (OpenAI after-reset turn errored once) | ok | | J10 owner turns, `/compact`, cron, owner | one list (no 4-vs-3 repro on this config) | one list (14) before and after; cron after compaction keeps it; next owner turn cache hit | | J11 group: guest denied exec, owner | guest pins 9 tools, owner turn 14 with a miss, a prompt-update note per sender flip | one list (14) for both senders, every request a cache hit (Claude reads 23,881 -> 31,107), guest `exec` refused ("exec is outside the tools this run allows"), guest `read` and owner `exec` work | ### Gate A on this head (`d827cceb`, main `cbc12e7`), proxy-log excerpts, redacted Isolated scratch Gateways (`env -i`, random ports, isolated state), a concurrent second chat running turns and `sessions.compact`. Each cell: the session's tool sets in order (a letter per distinct tool-definition hash), then per request `tool count/cached input tokens`. | journey | route | main | head | |---|---|---|---| | J1 cron starts chat, then user | OpenAI | `B>A`: 14/0 **14/0** 14/16362 14/16587 | `B`: 14/0 14/14440 14/14762 14/15070 14/17039 | | | Claude | `B>A`: 14/0 **14/9668** 14/26625 | `B`: 14/0 14/23920 14/27152 | | J2 cron `toolsAllow: ["read"]`, then user `exec` | OpenAI | `C>D`: **4**/0 4/6485 **14/0** 14/19323 | `B`: 14/0 14/13046 14/13163 14/13500 14/18458; `exec` refused, `read` ok, user `exec` ok | | | Claude | `C>D`: **4**/0 4/9786 4/10049 **14/9554** 14/31223 | `B`: 14/9951 14/21608 14/21904 14/29747 | | J3 reset, cron first, user | both | new set at the reset, then back | new set only at the reset (new session) | | J4 cannot-send cron calls `message` | OpenAI | no refusal | refused: "message cannot send on this turn: its reply delivery or tool policy does not allow the message tool. Do not retry message." | | J7 exec wake, subagent, steer | OpenAI | `A>F>A` | `A` | | J10 owner, `/compact`, cron, owner | Claude | `A`: 14/9668 14/23800 14/9668 14/25198 14/26268 | `A`: 14/9554 14/23780 14/9554 14/25189 14/26302 (the 9,554 row is the cron right after compaction: history rewritten, tools kept) | | J11 group: guest denied `exec`, then owner | OpenAI | `H>I`: **9**/0 9/12866 9/13418 **14/0** 14/19652 | `E`: 14/0 14/14300 14/17481 14/17525 14/20649; guest `exec` refused ("exec is outside the tools this run allows. Do not retry exec."), guest `read` and owner `exec` ok | | | Claude | `G>H`: **9**/0 **14/0** 14/28797 14/28928 | `E`: 14/9942 14/23774 14/28261 14/28369 | | J12 owner, `/compact`, cron `toolsAllow: ["alpha__alpha_probe"]`, owner | Claude | `A>I>A`: 14/9668 14/23800 **3/0** 3/6670 3/7224 **14/9668** | `A`: 14/9554 14/23780 14/9554 14/22377 14/22989 14/23317; cron calls `alpha_probe` via `dispatch_action`, its `exec` is refused, owner `exec` ok | J12 passes on head because MCP tools live in the deferred catalog, not the tool list: the core list no longer follows the allowlist. What stays as on `main` is the MCP runtime start rule (an allowlist that names no MCP server does not start MCP, so the deferred directory changes through an appended note) and MCP discovery honoring sender/group denies. Earlier runs (J5 MCP connect mid-chat, J6 computer, J8 `toolSearch: false`, J9 regression set) are unchanged by the split and were green at `c1160ede`. Pre-existing on both arms: gpt-6.2 fills `channel`/`target` on WebChat `message` calls and loops on the rejection; `chat.abort` leaves the run status `error`; a `sessions.compact` during an active run is rejected ("has an active run; retry after it finishes"). ### Existing-session upgrade (one session, main then head on the same state dir) Isolated scratch Gateway (`env -i`, random port, isolated state dir, 250k context so compaction cannot mask the measurement), cliproxy `claude-opus-5-5`. Main `cbc12e7` builds the session with four owner turns (reply, `read`, `exec`, reply) and stops. Head `d827cceb` starts on the same state dir: one owner turn, a cron with `toolsAllow: ["read"]`, an owner `exec` turn, a last reply. | arm | turn | tools | cached / written | |---|---|---|---| | main | owner reply | 14 | 9,668 / 15,865 | | main | owner `read` (+ follow-up) | 14 | 25,533 / 1,148; 26,681 / 84 | | main | owner `exec` (+ follow-up) | 14 | 26,765 / 1,158; 27,923 / 104 | | main | owner reply | 14 | 28,027 / 1,152 | | head | first turn after the upgrade: **the one re-pin** | 14 | 9,554 / 20,755 (only the system prefix is cached) | | head | cron `toolsAllow: ["read"]`: `read` ok, `exec` refused ("exec is outside the tools this run allows") | 14 | 30,309 / 6,865; 37,174 / 302 (hits) | | head | owner `exec`: runs | 14 | 37,476 / 9,278; 46,754 / 161 (hits) | | head | last reply | 14 | 46,915 / 1,153 (hit) | One miss on the first head turn, then cache hits on the cron and owner turns. ### Gate C (append-only journeys from openclaw#201723) Stability journeys: head 5/5 pass, main 5/5 pass (they do not separate the arms). Randomized seeds 1-10 on head: 60/60 pass (anthropic-messages, openai-responses, openai-completions, google, bedrock, and the Tool Search opt-out surface). ### Gates - `pnpm tsgo:core`: pass. oxlint, oxfmt on changed files, `git diff --check`: clean. - Production code vs `main` (excluding tests and docs): +290 / -205 (net +85); see the size note at the top. ### Test lines Net test lines +994 against the 400 allowance. Duplicate tests were removed first (the scheduled-run table duplicate, the separate catalog-rewrap test, the sender-deny MCP case, the bundle MCP fixture, and the duplicate group-sender listing test). The remaining 594 lines are recorded in `config/test-lines-allocations/201710-session-tool-listing.txt`: refusal equivalence against `main` executed through the production tool base, bundle pass and catalog for five policy shapes across the direct, preparer and `dispatch_action` paths, plus series listing, fork and upgrade pin cases. ### Local ClawSweeper (gpt-6.1-sol, normal) Head `45ef8f8c583f`: patch is correct, no findings (exit 0). The local review reads only the committed range and its tests; the real-route journeys above are outside its inputs. An earlier P2 at `9543fde3` (sender change dropping a direct-only tool such as `computer` from a frozen group listing) is fixed by item 4: every sender builds the same list. ## Risks - `message` and allowlist-refused tools are listed (and refused visibly) on turns that cannot use them. Each costs one definition. - The `message` definition's action list still depends on the turn that starts the series (a cron-started WebChat series pins "Supports actions: send" without `react`). The pin keeps it stable; `react` is not advertised in that series until a rebuild point. Main would extend the pin (a miss) instead. Follow-up. - Upgrade: every existing session re-pins once on its first turn after the upgrade (the toolPolicy digest changes), costing one cache miss per session. This is the same accepted one-time cost as openclaw#201843. - MCP names and sanitized descriptions now enter the system prompt's deferred-tool section instead of the `tool_search` description. Co-authored-by: Ayaan Zaidi <[email protected]>
…old compaction (openclaw#201655) ## What was wrong OpenClaw ties a session's system prompt series to the newest compaction or reset in its hydrated transcript window. When a chat grew long after a compaction, that compaction fell out of the bounded window, causing the history ID to flip to `null`, restart the prompt series (`restarted:history`), and miss the entire provider cache. Compaction summaries were also re-reading every accumulated `System prompt update` message even though compaction starts a fresh prompt series. ## Example You compact a chat, then edit `AGENTS.md` several times with follow-up turns until the compaction scrolls out of the bounded transcript window: - **Before:** the next turn stopped seeing the compaction, triggered `restarted:history`, and missed the cache (OpenAI: **0 / 11096**; Claude: **1394 / 16782**). - **Now:** the latest prompt checkpoint identifies the current history using its boundary count, so the series stays pinned and hits cache (OpenAI: **12336 / 484**; Claude: **18263 / 988**). ## The fix - Use the newest `openclaw.system-prompt` checkpoint in the window to name the history when the compaction boundary has scrolled out of view (`session-prompt-history-id.ts`, `session-prompt-state.ts`, porting the first commit with its original author). - Record `sessionManager.getBoundaryCount()` on each checkpoint so a stale checkpoint from before a later compaction or reset cannot spoof the current history. When neither a visible boundary nor a matching checkpoint is in view, use `unknown:<boundaryCount>` so the series restarts at most once. - Exclude `System prompt update` messages from compaction summary input (`src/agents/compaction-planning.ts`), since compaction starts a new series with fresh rendered sections. - Production diff vs main: +102 / -34 (compaction change: +33 / -14). Existing compacted sessions without a boundary count restart at most once after deploy if the compaction is already out of window. ## Proof Isolated scratch Gateways on merge base `9b8aa3dc4914` vs head `af7ee63f5b61` (final head `dfb4d5bce649` only reshapes a test fixture; OpenAI Responses `gpt-6.2-astra`, `contextTokens: 24000`, `maxTokens: 2048`, numbers are `cacheRead / cacheWrite`): | Metric (long workspace rules, 2 runs per side) | Base (`9b8aa3dc4914`) | Head (`af7ee63f5b61`) | |---|---|---| | Req 13/14 after window drops compaction | `restarted:history`, **0 / 11096** (run 2); **0 / 11459** at req 14 (run 1) | pinned, **12336 / 484** (run 2); **12332 / 484** (run 1) | | History restarts without a compaction | 2 and 3 | **0** and **0** | | Live prompt updates at compaction (peak) | 34 KB | 88 KB in history, none in summary input | Earlier real-route run (`3df7c5332e81` / re-run `3677e9f`) on cliproxy Claude (`claude-opus-5-5`, `contextTokens: 30000`): req 15 went from `restarted:history` (**1394 / 16782**) on base to pinned (**18263 / 988**) on head (1 → 0 uncompacted restarts). - **UI and side effects:** Control UI on the head scratch Gateway renders history across both compactions and answers every turn after Gateway restart (screenshots in PR comments). Concurrent chat (`gate-other`), short-rules control, cron/tool/session paths, and upgrade from legacy checkpoints all passed. - **Tests and gates:** `attempt-session-runtime-prepare.history-boundary.test.ts`, `prepared-compaction-plan.test.ts`, `session-prompt-state.test.ts`, `pnpm tsgo:core`, `pnpm check:test-types`, oxlint, oxfmt, and all baseline ratchets pass. <details><summary>Full test details</summary> ### Boundary-count and upgrade details - A checkpoint is evidence of the current history only when its recorded `sessionManager.getBoundaryCount()` matches the current count. A checkpoint whose count matches names the history even when the boundary is also in the window. Otherwise the visible boundary names it; with neither, the history is `unknown:<boundaryCount>`. - `null` stays valid only for a session that never compacted or reset. A restored checkpoint without a count is rewritten with the count on the next persist. - Existing checkpoints do not record a boundary count. In a session that has compacted, the first run after deploy whose window does not contain the compaction restarts the series once. A legacy checkpoint read while the compaction is in the window is rewritten with the count instead. Never-compacted sessions are not affected. - Provider requests outside compaction are unchanged. ### E2E details (`af7ee63f5b61` vs merge base `9b8aa3dc4914`; `dfb4d5bce649` only reshapes a test fixture) Isolated scratch Gateways from source (`env -i`, own state, random ports), same driver on both sides, OpenAI Responses (`gpt-6.2-astra`, `contextTokens: 24000`, `maxTokens: 2048`). Journey `gate-h`: three story turns, `/compact` asking for a very long summary, then workspace `AGENTS.md` edits each followed by a follow-up turn (the history after the compaction outgrows the bounded window), then a **Gateway restart** on the same state and three more edit/follow-up pairs. An unrelated chat (`gate-other`) runs ordinary turns and `/compact` every second turn throughout. - **Automatic compaction after the restart:** base run 2 had 1 failed attempt then succeeded, and one turn failed ("Couldn't finish this reply"). Head run 2 had 2 failed attempts then succeeded, and every turn answered; head run 1 answered every turn. - Before the compaction change (head `dd58eb1`, two runs), the same journey failed automatic compaction three times in a row after the restart and the last turn failed in both runs. The remaining failed attempts on both sides are `summary truncated at the output token limit` and come from the journey itself: the `/compact` message asks for "at least 3000 words" and stays in the history the next automatic compaction summarizes. With a plain `/compact`, base and head match request for request and both compact twice without a failure. - **Short workspace rules (control, 9 edits):** neither window loses the compaction, so both sides stay pinned and match (req 22: 14398 / 664 head, 14336 / 662 base); both compact automatically after the restart and every turn answers. - **Side effects:** - Ordinary chat (`gate-other`): every turn and every `/compact` returned `ok` on both sides in all runs. - Cron, tool and session paths (run on head `dd58eb1`, unchanged by the compaction commit except the summary input): cron starting a chat, exec background wake, subagent completion, steer, `sessions_send`, cron surviving new/reset/edited chats, Stop and reset gave identical results on base and head, then a Gateway restart. ### Earlier real-route run (`3df7c5332e81` vs merge base; re-run on `3677e9f`) On `3677e9f`: OpenAI requests 13/15 pinned at 9474/484 and 12048/484, 0 history restarts without a compaction; Claude request 15 pinned at 18150/988, only restart at a real compaction with `boundaryCount: 2`. OpenAI Responses (`gpt-6.2-astra`, minimal tool profile, `contextTokens: 24000`): | Request | Base series, cacheRead / cacheWrite | Head series, cacheRead / cacheWrite | |---|---|---| | 13 | `restarted:history` (historyId -> null), **2700 / 3876** | pinned, 9432 / 484 | | 15 | pinned, 7061 / 484 | pinned, 12005 / 484 | | 16 | `restarted:history` (flips back), 7545 / 485 | real automatic compaction (allowed rebuild) | | History restarts without a compaction | 2 | 0 | cliproxy Claude (`claude-opus-5-5`, `contextTokens: 30000`): | Request | Base series, cacheRead / cacheWrite | Head series, cacheRead / cacheWrite | |---|---|---| | 15 | `restarted:history` (historyId -> null), **1394 / 16782** | pinned, 18263 / 988 | | 20/21 | restart at a real automatic compaction | restart at a real automatic compaction (checkpoint `boundaryCount: 2`) | | History restarts without a compaction | 1 | 0 | ### Upgrade test (one state dir: base then head, OpenAI route) - Target chat: one `restarted:history` on the first turn after the upgrade, then pinned through 6 edit/follow-up pairs (cacheRead 2432 -> 10213); `/compact` on head restarts once and writes `boundaryCount: 2`; later checkpoints stay pinned at count 2. - Never-compacted chat: pinned across the upgrade (legacy checkpoint `historyId: null`, then `boundaryCount: 0`). - Unrelated chat: restarts only at its own compactions (counts 2-5 recorded). - Cron created on base: still enabled on head and fired on schedule in the target chat; with the scratch model at `maxTokens: 2048`, that turn failed in automatic compaction (summary output budget exhausted); the merge base fails the same way on the same setup. With `maxTokens: 8192` the cron turn passes on head, the target chat restarts once after the upgrade and then stays pinned (cacheRead 2297 -> 10078), and `/compact` restarts once with `boundaryCount: 3`. ### Unit and integration tests (merge base vs head) - `attempt-session-runtime-prepare.history-boundary.test.ts` (real SQLite hydration, one bounded view per run; every case pushes the boundary out of the window so it reaches the count rule): - three runs whose byte window includes, then drops, then includes an old compaction keep one series (base: `restarted:history` on run 2); - eviction: the newest checkpoint leaves the window with the compaction, the series restarts once as `unknown:1`, then stays pinned when the boundary returns beside that checkpoint (previous head `3df7c53`: second restart); - a legacy checkpoint that names the visible boundary is rewritten with the count and stays pinned when the boundary leaves (previous head: two restarts); - a legacy checkpoint with `historyId: null` restarts once, then stays pinned (base: pinned on the wrong history); - rewind to a checkpoint written at count 1 (stored as `unknown:1`, `boundaryCount: 1`) past a later compaction: the series stays pinned to that checkpoint (fails if the count were store-wide); - a counted reset restarts the series although the window holds a checkpoint of the earlier history (fails if resets were not counted); - a visible compaction after a counted checkpoint restarts the series (fails if any counted checkpoint outranked the visible boundary). - Each of the last three cases was checked with a local mutation of the behavior it guards (store-wide count, uncounted reset, checkpoint always outranking the boundary): each fails under its mutation and passes after revert. - `prepared-compaction-plan.test.ts`: prompt updates between turns are left out of the summary selection, the turns stay (red on `7a698fb`: the updates were selected). - The rewind case reads the same SQLite bounded context through `SessionManager.openBoundedAsync`; the separate SQLite reader case was dropped after main grew that file past the line cap. - `session-prompt-state.test.ts`: - a checkpoint that predates a compaction outside the window restarts the series, and the request carries the re-rendered prompt (base: pinned); - a never-compacted session stays pinned (passes on both); - the ported unit test for a window that starts after the compaction, now passing the boundary count as production does (base: restart). - The earlier prefix-stability journey step was removed: it passed on the merge base, so it could not catch this defect. ### Follow-ups (not blockers) and gates - A session fork loses its pinned prefix while the source series is `unknown:N` (the fork view carries no checkpoint data); this costs cache until the next compaction. - `removeTrailingEntries` can delete a boundary through the plugin compatibility surface; core does not reach that path today. - A legacy session gets one extra checkpoint append after the upgrade, when its count is first written. - Gates on `af7ee63`, plus lint, format, the touched test and test-lines on `dfb4d5b`: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on touched files, the baseline ratchets (mock-exports, test-lines +400 of 400, line-cap, max-lines, database-worker), the focused tests above, the prompt-cache prefix-stability suites, and the compaction, safeguard and memory-flush tests. </details> <!-- openclaw-publication:650c2283-6d98-83fb-aa93-9135a86a193d --> Co-authored-by: Ayaan Zaidi <[email protected]>
…old compaction (#201655) OpenClaw ties a session's system prompt series to the newest compaction or reset in its hydrated transcript window. When a chat grew long after a compaction, that compaction fell out of the bounded window, causing the history ID to flip to `null`, restart the prompt series (`restarted:history`), and miss the entire provider cache. Compaction summaries were also re-reading every accumulated `System prompt update` message even though compaction starts a fresh prompt series. You compact a chat, then edit `AGENTS.md` several times with follow-up turns until the compaction scrolls out of the bounded transcript window: - **Before:** the next turn stopped seeing the compaction, triggered `restarted:history`, and missed the cache (OpenAI: **0 / 11096**; Claude: **1394 / 16782**). - **Now:** the latest prompt checkpoint identifies the current history using its boundary count, so the series stays pinned and hits cache (OpenAI: **12336 / 484**; Claude: **18263 / 988**). - Use the newest `openclaw.system-prompt` checkpoint in the window to name the history when the compaction boundary has scrolled out of view (`session-prompt-history-id.ts`, `session-prompt-state.ts`, porting the first commit with its original author). - Record `sessionManager.getBoundaryCount()` on each checkpoint so a stale checkpoint from before a later compaction or reset cannot spoof the current history. When neither a visible boundary nor a matching checkpoint is in view, use `unknown:<boundaryCount>` so the series restarts at most once. - Exclude `System prompt update` messages from compaction summary input (`src/agents/compaction-planning.ts`), since compaction starts a new series with fresh rendered sections. - Production diff vs main: +102 / -34 (compaction change: +33 / -14). Existing compacted sessions without a boundary count restart at most once after deploy if the compaction is already out of window. Isolated scratch Gateways on merge base `b4ddf4b30fc5` vs head `af7ee63f5b61` (final head `dfb4d5bce649` only reshapes a test fixture; OpenAI Responses `gpt-6.2-astra`, `contextTokens: 24000`, `maxTokens: 2048`, numbers are `cacheRead / cacheWrite`): | Metric (long workspace rules, 2 runs per side) | Base (`b4ddf4b30fc5`) | Head (`af7ee63f5b61`) | |---|---|---| | Req 13/14 after window drops compaction | `restarted:history`, **0 / 11096** (run 2); **0 / 11459** at req 14 (run 1) | pinned, **12336 / 484** (run 2); **12332 / 484** (run 1) | | History restarts without a compaction | 2 and 3 | **0** and **0** | | Live prompt updates at compaction (peak) | 34 KB | 88 KB in history, none in summary input | Earlier real-route run (`3df7c5332e81` / re-run `3677e9f`) on cliproxy Claude (`claude-opus-5-5`, `contextTokens: 30000`): req 15 went from `restarted:history` (**1394 / 16782**) on base to pinned (**18263 / 988**) on head (1 → 0 uncompacted restarts). - **UI and side effects:** Control UI on the head scratch Gateway renders history across both compactions and answers every turn after Gateway restart (screenshots in PR comments). Concurrent chat (`gate-other`), short-rules control, cron/tool/session paths, and upgrade from legacy checkpoints all passed. - **Tests and gates:** `attempt-session-runtime-prepare.history-boundary.test.ts`, `prepared-compaction-plan.test.ts`, `session-prompt-state.test.ts`, `pnpm tsgo:core`, `pnpm check:test-types`, oxlint, oxfmt, and all baseline ratchets pass. <details><summary>Full test details</summary> - A checkpoint is evidence of the current history only when its recorded `sessionManager.getBoundaryCount()` matches the current count. A checkpoint whose count matches names the history even when the boundary is also in the window. Otherwise the visible boundary names it; with neither, the history is `unknown:<boundaryCount>`. - `null` stays valid only for a session that never compacted or reset. A restored checkpoint without a count is rewritten with the count on the next persist. - Existing checkpoints do not record a boundary count. In a session that has compacted, the first run after deploy whose window does not contain the compaction restarts the series once. A legacy checkpoint read while the compaction is in the window is rewritten with the count instead. Never-compacted sessions are not affected. - Provider requests outside compaction are unchanged. Isolated scratch Gateways from source (`env -i`, own state, random ports), same driver on both sides, OpenAI Responses (`gpt-6.2-astra`, `contextTokens: 24000`, `maxTokens: 2048`). Journey `gate-h`: three story turns, `/compact` asking for a very long summary, then workspace `AGENTS.md` edits each followed by a follow-up turn (the history after the compaction outgrows the bounded window), then a **Gateway restart** on the same state and three more edit/follow-up pairs. An unrelated chat (`gate-other`) runs ordinary turns and `/compact` every second turn throughout. - **Automatic compaction after the restart:** base run 2 had 1 failed attempt then succeeded, and one turn failed ("Couldn't finish this reply"). Head run 2 had 2 failed attempts then succeeded, and every turn answered; head run 1 answered every turn. - Before the compaction change (head `dd58eb1`, two runs), the same journey failed automatic compaction three times in a row after the restart and the last turn failed in both runs. The remaining failed attempts on both sides are `summary truncated at the output token limit` and come from the journey itself: the `/compact` message asks for "at least 3000 words" and stays in the history the next automatic compaction summarizes. With a plain `/compact`, base and head match request for request and both compact twice without a failure. - **Short workspace rules (control, 9 edits):** neither window loses the compaction, so both sides stay pinned and match (req 22: 14398 / 664 head, 14336 / 662 base); both compact automatically after the restart and every turn answers. - **Side effects:** - Ordinary chat (`gate-other`): every turn and every `/compact` returned `ok` on both sides in all runs. - Cron, tool and session paths (run on head `dd58eb1`, unchanged by the compaction commit except the summary input): cron starting a chat, exec background wake, subagent completion, steer, `sessions_send`, cron surviving new/reset/edited chats, Stop and reset gave identical results on base and head, then a Gateway restart. On `3677e9f`: OpenAI requests 13/15 pinned at 9474/484 and 12048/484, 0 history restarts without a compaction; Claude request 15 pinned at 18150/988, only restart at a real compaction with `boundaryCount: 2`. OpenAI Responses (`gpt-6.2-astra`, minimal tool profile, `contextTokens: 24000`): | Request | Base series, cacheRead / cacheWrite | Head series, cacheRead / cacheWrite | |---|---|---| | 13 | `restarted:history` (historyId -> null), **2700 / 3876** | pinned, 9432 / 484 | | 15 | pinned, 7061 / 484 | pinned, 12005 / 484 | | 16 | `restarted:history` (flips back), 7545 / 485 | real automatic compaction (allowed rebuild) | | History restarts without a compaction | 2 | 0 | cliproxy Claude (`claude-opus-5-5`, `contextTokens: 30000`): | Request | Base series, cacheRead / cacheWrite | Head series, cacheRead / cacheWrite | |---|---|---| | 15 | `restarted:history` (historyId -> null), **1394 / 16782** | pinned, 18263 / 988 | | 20/21 | restart at a real automatic compaction | restart at a real automatic compaction (checkpoint `boundaryCount: 2`) | | History restarts without a compaction | 1 | 0 | - Target chat: one `restarted:history` on the first turn after the upgrade, then pinned through 6 edit/follow-up pairs (cacheRead 2432 -> 10213); `/compact` on head restarts once and writes `boundaryCount: 2`; later checkpoints stay pinned at count 2. - Never-compacted chat: pinned across the upgrade (legacy checkpoint `historyId: null`, then `boundaryCount: 0`). - Unrelated chat: restarts only at its own compactions (counts 2-5 recorded). - Cron created on base: still enabled on head and fired on schedule in the target chat; with the scratch model at `maxTokens: 2048`, that turn failed in automatic compaction (summary output budget exhausted); the merge base fails the same way on the same setup. With `maxTokens: 8192` the cron turn passes on head, the target chat restarts once after the upgrade and then stays pinned (cacheRead 2297 -> 10078), and `/compact` restarts once with `boundaryCount: 3`. - `attempt-session-runtime-prepare.history-boundary.test.ts` (real SQLite hydration, one bounded view per run; every case pushes the boundary out of the window so it reaches the count rule): - three runs whose byte window includes, then drops, then includes an old compaction keep one series (base: `restarted:history` on run 2); - eviction: the newest checkpoint leaves the window with the compaction, the series restarts once as `unknown:1`, then stays pinned when the boundary returns beside that checkpoint (previous head `3df7c53`: second restart); - a legacy checkpoint that names the visible boundary is rewritten with the count and stays pinned when the boundary leaves (previous head: two restarts); - a legacy checkpoint with `historyId: null` restarts once, then stays pinned (base: pinned on the wrong history); - rewind to a checkpoint written at count 1 (stored as `unknown:1`, `boundaryCount: 1`) past a later compaction: the series stays pinned to that checkpoint (fails if the count were store-wide); - a counted reset restarts the series although the window holds a checkpoint of the earlier history (fails if resets were not counted); - a visible compaction after a counted checkpoint restarts the series (fails if any counted checkpoint outranked the visible boundary). - Each of the last three cases was checked with a local mutation of the behavior it guards (store-wide count, uncounted reset, checkpoint always outranking the boundary): each fails under its mutation and passes after revert. - `prepared-compaction-plan.test.ts`: prompt updates between turns are left out of the summary selection, the turns stay (red on `7a698fb`: the updates were selected). - The rewind case reads the same SQLite bounded context through `SessionManager.openBoundedAsync`; the separate SQLite reader case was dropped after main grew that file past the line cap. - `session-prompt-state.test.ts`: - a checkpoint that predates a compaction outside the window restarts the series, and the request carries the re-rendered prompt (base: pinned); - a never-compacted session stays pinned (passes on both); - the ported unit test for a window that starts after the compaction, now passing the boundary count as production does (base: restart). - The earlier prefix-stability journey step was removed: it passed on the merge base, so it could not catch this defect. - A session fork loses its pinned prefix while the source series is `unknown:N` (the fork view carries no checkpoint data); this costs cache until the next compaction. - `removeTrailingEntries` can delete a boundary through the plugin compatibility surface; core does not reach that path today. - A legacy session gets one extra checkpoint append after the upgrade, when its count is first written. - Gates on `af7ee63`, plus lint, format, the touched test and test-lines on `dfb4d5b`: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on touched files, the baseline ratchets (mock-exports, test-lines +400 of 400, line-cap, max-lines, database-worker), the focused tests above, the prompt-cache prefix-stability suites, and the compaction, safeguard and memory-flush tests. </details> <!-- openclaw-publication:650c2283-6d98-83fb-aa93-9135a86a193d --> Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit ee1140e) Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 30aca27a4c6dbf29377f968a61b888fe01f8bad3) (cherry picked from commit 8c84653a2e13efe5f3975e78b86a22a8379eafa1)





What was wrong
OpenClaw ties a session's system prompt series to the newest compaction or reset in its hydrated transcript window. When a chat grew long after a compaction, that compaction fell out of the bounded window, causing the history ID to flip to
null, restart the prompt series (restarted:history), and miss the entire provider cache. Compaction summaries were also re-reading every accumulatedSystem prompt updatemessage even though compaction starts a fresh prompt series.Example
You compact a chat, then edit
AGENTS.mdseveral times with follow-up turns until the compaction scrolls out of the bounded transcript window:restarted:history, and missed the cache (OpenAI: 0 / 11096; Claude: 1394 / 16782).The fix
openclaw.system-promptcheckpoint in the window to name the history when the compaction boundary has scrolled out of view (session-prompt-history-id.ts,session-prompt-state.ts, porting the first commit with its original author).sessionManager.getBoundaryCount()on each checkpoint so a stale checkpoint from before a later compaction or reset cannot spoof the current history. When neither a visible boundary nor a matching checkpoint is in view, useunknown:<boundaryCount>so the series restarts at most once.System prompt updatemessages from compaction summary input (src/agents/compaction-planning.ts), since compaction starts a new series with fresh rendered sections.Proof
Isolated scratch Gateways on merge base
b4ddf4b30fc5vs headaf7ee63f5b61(final headdfb4d5bce649only reshapes a test fixture; OpenAI Responsesgpt-6.2-astra,contextTokens: 24000,maxTokens: 2048, numbers arecacheRead / cacheWrite):b4ddf4b30fc5)af7ee63f5b61)restarted:history, 0 / 11096 (run 2); 0 / 11459 at req 14 (run 1)Earlier real-route run (
3df7c5332e81/ re-run3677e9f) on cliproxy Claude (claude-opus-5-5,contextTokens: 30000): req 15 went fromrestarted:history(1394 / 16782) on base to pinned (18263 / 988) on head (1 → 0 uncompacted restarts).gate-other), short-rules control, cron/tool/session paths, and upgrade from legacy checkpoints all passed.attempt-session-runtime-prepare.history-boundary.test.ts,prepared-compaction-plan.test.ts,session-prompt-state.test.ts,pnpm tsgo:core,pnpm check:test-types, oxlint, oxfmt, and all baseline ratchets pass.Full test details
Boundary-count and upgrade details
sessionManager.getBoundaryCount()matches the current count. A checkpoint whose count matches names the history even when the boundary is also in the window. Otherwise the visible boundary names it; with neither, the history isunknown:<boundaryCount>.nullstays valid only for a session that never compacted or reset. A restored checkpoint without a count is rewritten with the count on the next persist.E2E details (
af7ee63f5b61vs merge baseb4ddf4b30fc5;dfb4d5bce649only reshapes a test fixture)Isolated scratch Gateways from source (
env -i, own state, random ports), same driver on both sides, OpenAI Responses (gpt-6.2-astra,contextTokens: 24000,maxTokens: 2048). Journeygate-h: three story turns,/compactasking for a very long summary, then workspaceAGENTS.mdedits each followed by a follow-up turn (the history after the compaction outgrows the bounded window), then a Gateway restart on the same state and three more edit/follow-up pairs. An unrelated chat (gate-other) runs ordinary turns and/compactevery second turn throughout.dd58eb1, two runs), the same journey failed automatic compaction three times in a row after the restart and the last turn failed in both runs. The remaining failed attempts on both sides aresummary truncated at the output token limitand come from the journey itself: the/compactmessage asks for "at least 3000 words" and stays in the history the next automatic compaction summarizes. With a plain/compact, base and head match request for request and both compact twice without a failure.gate-other): every turn and every/compactreturnedokon both sides in all runs.dd58eb1, unchanged by the compaction commit except the summary input): cron starting a chat, exec background wake, subagent completion, steer,sessions_send, cron surviving new/reset/edited chats, Stop and reset gave identical results on base and head, then a Gateway restart.Earlier real-route run (
3df7c5332e81vs merge base; re-run on3677e9f)On
3677e9f: OpenAI requests 13/15 pinned at 9474/484 and 12048/484, 0 history restarts without a compaction; Claude request 15 pinned at 18150/988, only restart at a real compaction withboundaryCount: 2.OpenAI Responses (
gpt-6.2-astra, minimal tool profile,contextTokens: 24000):restarted:history(historyId -> null), 2700 / 3876restarted:history(flips back), 7545 / 485cliproxy Claude (
claude-opus-5-5,contextTokens: 30000):restarted:history(historyId -> null), 1394 / 16782boundaryCount: 2)Upgrade test (one state dir: base then head, OpenAI route)
restarted:historyon the first turn after the upgrade, then pinned through 6 edit/follow-up pairs (cacheRead 2432 -> 10213);/compacton head restarts once and writesboundaryCount: 2; later checkpoints stay pinned at count 2.historyId: null, thenboundaryCount: 0).maxTokens: 2048, that turn failed in automatic compaction (summary output budget exhausted); the merge base fails the same way on the same setup. WithmaxTokens: 8192the cron turn passes on head, the target chat restarts once after the upgrade and then stays pinned (cacheRead 2297 -> 10078), and/compactrestarts once withboundaryCount: 3.Unit and integration tests (merge base vs head)
attempt-session-runtime-prepare.history-boundary.test.ts(real SQLite hydration, one bounded view per run; every case pushes the boundary out of the window so it reaches the count rule):restarted:historyon run 2);unknown:1, then stays pinned when the boundary returns beside that checkpoint (previous head3df7c53: second restart);historyId: nullrestarts once, then stays pinned (base: pinned on the wrong history);unknown:1,boundaryCount: 1) past a later compaction: the series stays pinned to that checkpoint (fails if the count were store-wide);prepared-compaction-plan.test.ts: prompt updates between turns are left out of the summary selection, the turns stay (red on7a698fb: the updates were selected).SessionManager.openBoundedAsync; the separate SQLite reader case was dropped after main grew that file past the line cap.session-prompt-state.test.ts:Follow-ups (not blockers) and gates
unknown:N(the fork view carries no checkpoint data); this costs cache until the next compaction.removeTrailingEntriescan delete a boundary through the plugin compatibility surface; core does not reach that path today.af7ee63, plus lint, format, the touched test and test-lines ondfb4d5b:pnpm tsgo:core,pnpm check:test-types, oxlint and oxfmt on touched files, the baseline ratchets (mock-exports, test-lines +400 of 400, line-cap, max-lines, database-worker), the focused tests above, the prompt-cache prefix-stability suites, and the compaction, safeguard and memory-flush tests.