Skip to content

fix(agents): freeze a prompt series' tool set at its first request - #201710

Merged
obviyus merged 42 commits into
mainfrom
fix/session-tool-surface-fixed
Nov 20, 2026
Merged

obviyus merged 42 commits into
mainfrom
fix/session-tool-surface-fixed

Conversation

@obviyus

@obviyus obviyus commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

Tool definitions sit at the very front of every model request, so any change to the tool list invalidates the entire prompt cache. Previously, the tool list changed whenever turn authority changed—such as a cron starting a chat before a user turn, a run with toolsAllow, a guest and owner taking turns in the same group chat, or an MCP server connecting mid-session. Freezing the list without changing how tools are built would have permanently dropped tools for later turns.

Example

A shared-session cron runs with toolsAllow: ["read"], and then the owner sends a message asking to run exec:

  • Before: the cron sent 4 tools and the owner's turn sent 14 tools, wiping out the cache on OpenAI (read 0 / uncached 19,340) and causing a large cache write on Claude (read 9,554 / write 21,734).
  • Now: both turns send the same 14 tools and the cron turn blocks exec at execution time, keeping the cache warm for the owner (OpenAI: read 13,582 / uncached 4,968; Claude: read 21,976 / write 7,856).

The fix

  • Freeze the series tool list (session-prompt-state.ts, prepareSessionToolSurface): on a fixed Tool Search listing, the first request of a prompt series pins the tool set and definitions. Isolated one-shot cron sessions (isCronRunSessionKey) keep main's narrowed list because they do not share a series.
  • Move the deferred MCP directory out of tool_search (buildToolSchemaDirectoryPrompt): append the sanitized MCP directory to the system prompt's ### Deferred Tool Schemas section so MCP changes arrive as appended prompt updates instead of rewriting tool definitions.
  • Gate core/plugin tools at execution instead of omitting them (resolveTurnToolSurface): always list message and core/plugin tools regardless of reply mode, toolsAllow, or group/sender policy, and refuse disallowed calls at execution (including blocking execution preparers, dispatch_action rewraps, delegation, capture, and prompt guidance via applyPromptBuildToolsAllow).
  • Keep scope tight: MCP/LSP startup and discovery, toolSearch: false, and custom selectors stay unchanged from main. Production diff vs 3da2118: +290 / -205 (net +85), plus docs in docs/reference/prompt-caching.md, docs/tools/tool-search.md, and docs/concepts/experimental-features.md.

Proof

Isolated scratch Gateways on merge base 3da2118f243c vs head 45ef8f8c583f (OpenAI Responses and Claude via Anthropic-messages proxy, visibleReplies: "message_tool", Tool Search on):

Journey Route Base (3da2118f243c) Head (45ef8f8c583f)
J1: cron starts chat, then user Claude 2 tool lists; read 9,668 / write 16,952 (total write 42,138) 1 tool list; read 23,965 / write 3,168 (total write 28,339)
J1: cron starts chat, then user OpenAI 2 tool lists; read 0 / uncached 17,007 1 tool list; read 15,667 / uncached 1,972
J2: shared cron (toolsAllow: ["read"]), then owner exec OpenAI 4 → 14 tools; owner read 0 / uncached 19,340 (session 27,413) 14 tools; owner read 13,582 / uncached 4,968 (session 18,934)
J2: shared cron (toolsAllow: ["read"]), then owner exec Claude 4 → 14 tools; owner read 9,554 / write 21,734 (session 32,060) 14 tools; owner read 21,976 / write 7,856 (session 20,066)
J2i: isolated cron (toolsAllow: ["read"]) OpenAI / Claude 4 tools; input 6,110 / 9,206 4 tools; input 6,145 / 9,260 (narrowed list kept)
J11: group guest (denied exec), then owner OpenAI / Claude 2 lists (9 → 14); 1 full miss; uncached/write 39,422 / 62,158 1 list (14); 0 misses; uncached/write 25,740 / 29,511
  • UI and side effects: Control UI shows visible refusals for blocked cron/guest exec calls and normal replies across J1, J2, J11, and J2i. Disallowed tools never executed; allowed read and owner exec worked on both arms. Existing sessions re-pin once after upgrade (one-time miss), then hit cache on subsequent cron/owner turns.
  • Tests and review: Execution-based refusal-equivalence tests confirm identical callable sets across direct, preparer, and dispatch_action paths; Gate C randomized seeds pass 60/60. Local ClawSweeper (gpt-6.1-sol, normal) on 45ef8f8c583f: patch is correct, no findings (exit 0).
Full test details

Size, isolated crons, and scope notes

  • 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
  • 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.

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 and Fable D findings (53145b8)

  • Exceptions (behavior unchanged): execution gating and guidance filtering 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: per-turn lists equal between arms). Out of scope (follow-up): other trigger-dependent definition text, e.g. the message description's action list.
  • M1 (owner turns lose tools after a narrowed turn): fixed by execution gating.
  • m2 (rewrap could bypass the gate): fixed; 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; a fork sends the source's list unchanged.
  • 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 dropping listed-but-refused tools from callableToolNames.

E2E notes and UI screenshots (45ef8f8c583f vs 3da2118f243c)

OpenAI: read = cached_tokens, uncached = input − cached. Claude: read = cache_read_input_tokens, uncached = input_tokens, plus write = cache_creation_input_tokens.

  • J2 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.
  • J11 group result: guest exec on head refused with "exec is outside the tools this run allows. Do not retry exec." (base: not listed, model says 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 hello-j1 and second-j1, 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. The live operator Gateway was untouched during the runs (its pid and config unchanged).

Control UI of the head and base scratch Gateways after the journeys (chat area cropped):

base head
J2 base J2 head J2
J11 group base group head group
J1 (OpenAI) base J1 head J1

Unit and refusal-equivalence 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 fix(agents): keep the prompt series when the bounded window drops an old compaction #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). 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 three paths agree for every tool. Also covers an MCP-only allowlist listing the full set (red on 390da1c), sender allow/deny policies including an MCP tool, refused tools never delegated or captured, and only-refused-tools failing loudly (green on main and head, red on 390da1c).
  • 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.
  • 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).

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 at 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. 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 3da2118 then head d827cceb 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.

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)

Gate C, gates, test lines, review, and risks

  • Gate C (append-only journeys from test(prompt-cache): extend the prefix journey with cron, steer, overflow and a concurrent chat on five transports #201723): stability journeys: head 5/5 pass, main 5/5 pass. 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.
  • 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). An earlier P2 at 9543fde3 (sender change dropping a direct-only tool such as computer from a frozen group listing) is fixed: 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 fix(agents): keep projected prompt updates out of later user turns #201843.
    • MCP names and sanitized descriptions now enter the system prompt's deferred-tool section instead of the tool_search description.

A turn that built a tool the session pin lacked extended the pin and changed the
provider tool list. A series started by a scheduled turn (no message tool) lost its
whole cached prefix on the next user turn, which builds `message`. The session prompt
owner now keeps the series' first tool set and every definition, whatever starts a
later turn. Tools a turn did not build stay listed and refuse their calls; tools the
pin lacks wait for the next series. The GitHub publication listing owner still
replaces its own definition on refresh, and MCP configuration joins the tool policy
digest so a configured server change stays a rebuild point.

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

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Nov 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR freezes each prompt series’ initial tool definitions while preserving explicit configuration and publication-listing refreshes.

Example: A cron turn starts a chat with seven tools, and a later user turn builds message.

  • Before: The list grows to eight tools and the supplied run reads zero cached tokens.
  • After: The list stays at seven tools and reads 8,907 cached tokens, but message remains unavailable until a rebuild.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The cache effect has shipped-entry-point evidence, but the concrete reply-delivery regression makes this head unready.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied head-specific isolated Gateway output exercises alternating cron and user turns through a real provider route and shows the initial seven-tool list retained with cache reuse until compaction.
Patch quality 🧂 unranked krab (1/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Alternating scheduled and user turns can invalidate an otherwise reusable provider prefix, increasing uncached inference work.
Reason: The maintainer-authored direction addresses a demonstrated cache defect with the existing owner, although its explicitly unresolved reply-path consequence blocks this implementation.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this draft open: the cache improvement is useful, but freezing a cron-started tool list can remove a later turn’s required reply path.

Priority: P1
Reviewed head: 96c939b795ee64493578e1243983e846380b3fe4
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should cache stability come from trigger-independent tool construction or an exception admitting a required message tool?
  • Recommendation: Stabilize tool construction: Build the advertised surface from session facts across triggers so the initial pin includes the required capabilities.
  • Why: The collaborator-authored PR establishes the cache-repair direction, but explicitly pauses the draft for this narrower choice because unconditional freezing can prevent replies.

Before merge

  • Preserve message when a later turn requires tool-only delivery (P1) - If a cron turn establishes a pin without message, this loop permanently excludes a message tool built by a later user turn until compaction or another rebuild. This is more than delayed optional capability: resolveOptionalToolRegistrationPolicy explicitly includes message for message_tool_only turns, and dispatch-from-config.finalize.ts suppresses their missing-reply fallback. With direct tools, the later turn therefore loses its required reply path. Preserve that capability by stabilizing initial tool construction or admitting the required delivery tool rather than dropping it here.

Findings

  • [P1] Preserve message when a later turn requires tool-only delivery — src/agents/embedded-agent-runner/session-prompt-state.ts:350-353

Tests

  • Low-value test src/agents/embedded-agent-runner/session-prompt-state.test.ts: The added “starts a pin when neither the session state nor the checkpoint has one” case repeats initial legacy-checkpoint admission already covered nearby and restored-pin retention covered by the updated restoration test; consolidate these assertions.
Agent review details

How this fits together

The embedded runner combines current executable tools with transcript-backed prompt checkpoints to produce the tool definitions sent to the model.

flowchart LR
  A[Turn and session facts] --> B[Tool construction]
  B --> C[Session tool pin]
  D[Transcript checkpoint] --> C
  C --> E[Provider request]
  E --> F[Tool execution gates]
Loading

Technical review

Best possible solution:

Make the initial advertised surface independent of the triggering turn while preserving current execution gates and required reply tools.

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

Current main extends a pin when a later turn builds another tool, matching the supplied Gateway trace; source inspection also establishes the introduced missing-reply path without running target code.

Is this the best way to solve the issue?

The existing pin owner is the right location for definition retention, but freezing a trigger-dependent initial inventory sacrifices required capabilities instead of correcting their construction.

Full review comments:

  • [P1] Preserve message when a later turn requires tool-only delivery — src/agents/embedded-agent-runner/session-prompt-state.ts:350-353
    If a cron turn establishes a pin without message, this loop permanently excludes a message tool built by a later user turn until compaction or another rebuild. This is more than delayed optional capability: resolveOptionalToolRegistrationPolicy explicitly includes message for message_tool_only turns, and dispatch-from-config.finalize.ts suppresses their missing-reply fallback. With direct tools, the later turn therefore loses its required reply path. Preserve that capability by stabilizing initial tool construction or admitting the required delivery tool rather than dropping it here.
    Confidence: 0.99
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • New-tool and changed-schema admission changes intended behavior with a stated reason (1f7b2f1: Retain previously advertised tools across restricted turns while allowing new tools and parameter changes to extend the pin once.)
  • Computer-definition retention keeps the original intent (3bffe4f: Keep computer definitions stable while live capabilities and authority govern execution.)
  • GitHub publication-listing ownership keeps the original intent (dcac946: Let authoritative publication configuration determine its listing without asynchronous discovery rewriting an established definition.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 1f7b2f1 adds src/agents/embedded-agent-runner/session-prompt-state.ts:90 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1f7b2f1c6f00; files: src/agents/embedded-agent-runner/session-prompt-state.ts)
  • Peter Steinberger: Raw commit b9308ff adds src/agents/embedded-agent-runner/session-prompt-state.ts:132 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b9308ff8d8f7; files: src/agents/embedded-agent-runner/session-prompt-state.ts)

PR surface

Source -8, Tests -20, Docs +2. Total -26 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 23 31 -8
Tests 1 38 58 -20
Docs 1 7 5 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 68 94 -26

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P1: The introduced behavior can prevent a later user turn from replying when its delivery mode requires message.
  • add merge-risk: 🚨 message-delivery: A cron-started pin can exclude message even when a later turn requires it, while automatic fallback delivery is suppressed.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🐚 platinum hermit and patch quality is 🧂 unranked krab.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: The introduced behavior can prevent a later user turn from replying when its delivery mode requires message.
  • merge-risk: 🚨 message-delivery: A cron-started pin can exclude message even when a later turn requires it, while automatic fallback delivery is suppressed.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🐚 platinum hermit and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 19, 2026, 3:12 AM ET / 08:12 UTC.

…cution

The frozen series pin made a turn's omissions permanent: a series a cron turn
started had no `message`, and the MCP directory in the `tool_search` definition
still changed with the connected servers.

With Tool Search on, every turn now builds the same listing:
- `message` is always listed; a turn whose delivery or tool policy does not
  allow it refuses the call visibly through the turn-authority owner.
- A cron run's toolsAllow keeps the listing and refuses calls outside it; the
  callable set is unchanged.
- The MCP directory moves into the system prompt's deferred-tool section, whose
  changes the prompt owner already sends as appended prompt updates.

Tool Search off, directory mode and include/exclude selections keep the earlier
filtering.

Co-authored-by: obviyus <[email protected]>
obviyus and others added 4 commits November 19, 2026 15:21
…per turn

With Tool Search off, in directory mode, or with include/exclude selectors,
`message` and a scheduled toolsAllow still filter the list per turn. A frozen
pin there kept a later turn's required `message` unavailable until a rebuild.
Those surfaces now admit a tool the pin lacks once; pinned definitions stay
frozen. Fixed-listing surfaces keep the full freeze.

Co-authored-by: obviyus <[email protected]>
A tool a scheduled allowlist refuses keeps its plugin and MCP metadata, so the
catalog still classifies an MCP tool as MCP instead of a native tool.

Co-authored-by: obviyus <[email protected]>
…upgrade

Surfaces that still filter per turn (Tool Search off, directory mode, selectors)
admit changed tool schemas as well as new tools, as before. A pin written before
the fixed listing may lack tools it now lists, so the tool policy digest gains a
marker and each session starts one new pin after the upgrade.

Co-authored-by: obviyus <[email protected]>
obviyus and others added 4 commits November 19, 2026 18:13
With a fixed listing, a cron turn whose message tool reports no route no longer
drops message from the model surface; the series pin then keeps it for later
user turns. The call itself still fails visibly on that turn.

Co-authored-by: obviyus <[email protected]>
…thing

An allowlist that matches no tool keeps the narrowed list, so the run fails with
"No callable tools remain" as on main instead of running with every tool refused.

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

obviyus commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the red checks on head 45ef8f8 are inherited from main, not caused by this PR.

  • build-artifacts: ui/src/e2e/template-chat-review.e2e.test.ts (":32 hydrates…" and ":261 keeps inline review category rows…") times out. The same two tests fail in build-artifacts on main CI run 44660938439 at 1ade2b7 (job 136039206369), and on unrelated PR runs 44663114959 (job 136046454800) and 44664080293 (job 136049851927). This PR changes no ui/ or Template file. The test update is test: follow Template previews into the review dialog #202198.
  • check-docs: markdownlint MD001/MD024 in docs/releases/2026.11.5.md. The same job fails on unrelated PR runs 44666643767, 44666146482, 44665828253, 44665523432 and 44665230283. This PR changes no docs/releases/ file.
  • openclaw/ci-gate: the aggregate of the two checks above.

Every other check passes. Exact-head local review: "patch is correct", 0 findings. Exact-head real-Gateway E2E is in the PR body.

@obviyus
obviyus merged commit 4639df3 into main Nov 20, 2026
128 of 132 checks passed
@obviyus
obviyus deleted the fix/session-tool-surface-fixed branch November 20, 2026 04:53
@obviyus

obviyus commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 4639df3 with the maintainer override above for two reds inherited from main. Cron runs, event turns, group guests and run allowlists changed a session's tool list, so the next turn missed the prompt cache. A session now keeps one tool list built from session facts, and per-turn authority refuses calls instead of removing tools; isolated cron sessions keep their narrowed list. Exact-head E2E: J2 owner turn after a read-only cron went from 0 to 13,582 cached tokens (OpenAI), J11 group guest-then-owner dropped from 2 tool lists and a cache miss to 1 list and 0 misses, and refused calls stayed visibly refused.

obviyus added a commit that referenced this pull request Nov 20, 2026
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 20, 2026
…ed tool listing

Upstream openclaw#201710 (4639df3) pins a prompt series' tool list at its
first request and, on a fixed listing (Tool Search on, the default), no
longer admits tools a later turn builds. The fork built the continuation
tools only on turns that may continue: memory turns, cron-runner jobs
(scheduled, hook and join-intro turns) and compaction got none. A series
that started on such a turn then sent no continue_work or
continue_delegate to the provider for every later user turn of that
series.

On a fixed listing, a turn that may not continue now builds the same
tools with the inventory callbacks and gates their calls through
gateAgentToolExecution, with the refusal text upstream's pin uses for an
unbuilt pinned tool. That is the AGENTS.md prompt-prefix rule (per-turn
authority gates calls) and what openclaw#201710 does for message. Without a fixed
listing, those turns still build none.

Pin in upstream's session-tool-listing.test.ts: a cron-runner turn and a
user turn build the same definitions; continue_work is callable on the
user turn and refused on the cron turn. RED with the production change
reverted (the cron turn built 13 tools, the user turn 15), GREEN with it.
31 suites that build or pin continuation tools (registration, tool
surface, prefix stability, turn authority, scheduled allowlists, session
prompt state, cron tool policy): 471/471 on Bun and on Node 24; tsgo core
rc 0.

Refs openclaw#129388
obviyus added a commit that referenced this pull request Nov 20, 2026
…low and a concurrent chat on five transports (#201723)

## What was wrong

The prompt-cache journey is the CI check that each provider request in a chat extends the previous request byte for byte, except where a rebuild is expected. It skipped four triggers that real chats hit: a scheduled job that comes due in the chat, a user message steered into a running tool call, tool results that fill the context window, and an unrelated chat that compacts while this one runs. It also covered only three transports. A break in any of those paths could land without CI noticing.

**Example:** a scheduled job sent its reply to the model twice on every route. On Chat Completions and Gemini the copy merged into the next tool-call message, which rewrote history and lost the cache from that point on. Fixed in #201838. This journey would have caught it.

## Fix

- Adds the cron, steer, tool-result overflow and concurrent-compaction steps to the stability journey. It now runs on five transports: Anthropic, Responses, Chat Completions, Gemini and Bedrock.
- Adds a seeded randomized journey: 15 turn kinds on five transports, plus a variant with Tool Search turned off.
- Lists the breaks main still has, each with its owner. Entries expire: when a fix lands, the journey fails until its entry is removed. Each entry checks the whole request, so a known change cannot hide a second one.
- Rebuild steps are excused only when the rebuild actually happened. A compaction must put its new summary into the next request, and a model switch must make the next request come from the selected model.
- The steer step holds the tool open until the Gateway reports that the run has taken the steer. Before, it slept for a fixed 3 s.

## Numbers

| | main (before this PR) | this PR |
|---|---|---|
| Triggers covered | ordinary turns, tools, compaction | + cron, steer, tool-result overflow, concurrent compaction, cron-first chat, 15-kind randomized journey |
| Transports | 3 | 5 |
| Stability journey | n/a | 5/5 |
| Randomized journey (default seeds, 6 files) + negative controls | n/a | 12/12 + 5/5 |
| Anthropic and Tool Search off, seeds 1 and 6 | n/a | 2/2 and 2/2 |

<details><summary>Breaks still on main (accepted entries)</summary>

| Where | Change | Owner |
|---|---|---|
| Gemini, tool-result overflow (other chat) | the pre-request pressure check trims tool results that were already sent | #199530 |
| Bedrock, randomized | a dropped silent reply merges the user turns around it | accepted gap (#201654 closed) |
| Tool Search off, randomized | a provider switch adds `skills_read`/`skills_search` on turns started by a subagent completion or inter-session message | #201710 / documented exception of the opt-out surface |

Removed because their owners landed: the cron reply twice (#201838), the Chat Completions silent-turn merge (#201843), the cron-first `message` growth (#201710), and the skills rebuild after `config.patch` (issue #202150, which no longer reproduces on Anthropic seeds 1 and 6).
Bedrock refuses `cron.add` for AWS-SDK auth by design, and the journey expects that refusal.
</details>

<details><summary>Steer signal</summary>

- The steer is sent with `queueMode: "steer"`, as the chat composer sends it. The test waits for `sessions.changed` with reason `agent.input.steering`, which the Gateway emits when the active run accepts the steer into its queue. The tool is released only after that event.
- On all five transports the event arrives about 200-260 ms after the send is acknowledged, while the tool is still held.
- Negative control: releasing right after the acknowledgment lost the race on Gemini (1/5). The steered input became a separate turn.
- A default `chat.send` steer exposes nothing before release. Its pending input stays `queued` with no `steerNow`, and `agent.input.steering` only fires when the tool ends. So the step uses the composer's steer path.
</details>

<details><summary>Rebuild evidence checks</summary>

- Compaction: the fake numbers each compaction summary. The step needs a new summary, and the turn after it must contain that summary.
- Model switch: the alternate provider has its own model id. Every request after the switch must name exactly the selected model, read from the request body or the URL (Gemini, Bedrock), and at least one request must arrive.
- Teeth: with `sessions.compact` turned into a no-op, all 10 randomized seeds failed. With `sessions.patch` pinned to the first model, all 10 failed too.
</details>

<details><summary>Cron-first red on base</summary>

On the parent of #201710 with this PR's test files (no entry), the cron-first step fails on Anthropic and Responses at the owner turn's tool list (`at: 1, change: tools`). On main the step passes.
</details>

<details><summary>Harness fixes</summary>

- Each seed uses its own session keys. A retained subagent from the previous seed made every turn fail with `Retained subagent payload is unavailable`.
- After a silent reply, the fake acts only on the newest step marker, because main drops silent replies from replay.
- Every request is assigned to its session by its runtime line. A request from an unexpected session fails the journey.
- The Advisor fork check is dropped. Forks never arrived in earlier runs. When they did arrive, their requests differed from the parent's on all transports, which needs its own investigation.
</details>

<details><summary>Gates</summary>

- `ocx test` from source with an in-process Gateway and fake provider endpoints: 5 stability files, 6 randomized files and the known-breaks unit, 17/17. Anthropic and Tool Search off at seeds 1 and 6, 2/2 each. A second stability pass, 5/5.
- `pnpm tsgo:test:root`, oxfmt and oxlint on the changed files, and the test-lines ratchet all pass.
- Local review on this head: patch is correct, no findings.
</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 20, 2026
…ect in a series a user turn started

🌊's design GO for openclaw#201710 (msg 1573401437864591373): a stable listing
plus a per-turn call gate. e7796dc pinned only cron -> user. This pins
user -> cron, in upstream's session-tool-listing harness with
continuation on and request_compaction allowed: the cron turn sends the
user turn's list (continue_work, continue_delegate and dispatch_action
stay listed) and refuses every continuation effect, with the reason:
- direct calls to continue_work and continue_delegate return the gated
  refusal "<name> is not available in this turn. Do not retry <name>.";
- through Tool Search, dispatch_action on the deferred request_compaction
  returns that refusal, and dispatch_action on the direct-only tools is
  refused as "already available directly";
- no wake is scheduled (the runner's requestContinuation), no delegate
  is written or staged (enqueuePendingDelegate,
  stagePostCompactionCustodyDelegate), no compaction is requested
  (triggerCompaction).
The same calls on the user turn reach requestContinuation and
triggerCompaction, so those spies see the effect when it is allowed.

Revert proof against e7796dc's repair (openclaw-tools.continuation.ts
and openclaw-tools.continuation-run.ts at e7796dc^): RED, with
"Unknown tool id: request_compaction. Did you mean ... Use tool_search
to find a tool" from dispatch_action. The cron turn built no
continuation tools, so its catalog lost the deferred tool and the model
was sent searching for it. Direct calls are refused either way:
upstream's pin refuses a pinned tool the turn did not build with the
same text (session-prompt-state.ts refusePinnedTool). GREEN with the
repair, 7/7 on Bun and Node 24.

Refs openclaw#129388
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 20, 2026
…ion tool on any turn

Second gap in the openclaw#201710 checklist (🌊's design GO, msg
1573401437864591373): with agents.defaults.continuation.enabled false,
no continuation tool definition is sent on any turn, including a fixed
listing's first, pinning request. The config alone decides: the turns
pass live runner callbacks and allow continue_work, continue_delegate
and request_compaction by name. Two series, one pinned by a user turn
(then cron-runner, exec wake, subagent announce, steer and allowlisted
turns) and one pinned by a cron-runner turn: every turn's built and sent
lists hold none, and Tool Search's dispatch_action answers "Unknown
tool id: request_compaction".

Revert proof: e7796dc's repair does not apply here. It reordered the
config check ahead of the cron-turn gate, so the disabled path is the
same before and after it; this pin is green with that repair reverted.
Mutation control instead: with the config check removed from
createOpenClawContinuationTools, the pin is RED (the first turn lists
continue_delegate and continue_work). GREEN at the head, 8/8 on Bun and
Node 24.

Refs openclaw#129388
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 20, 2026
…ow-up

Brings the reviewed fix-2 chain (b6c8b1f .. 451bf1e, on dc11bf4)
into the absorb result, per 🩸's GO: the continuation surface trimmed
from the plugin SDK declarations (the tracer on a private
official-plugin subpath, binding and run-hook types de-duplicated into
ContinuationRunToolOptions), the declaration ratchet raised by the
measured continuation delta, and its variance and off-by-one pins.

One conflict, src/agents/openclaw-tools.continuation.ts, between the
absorb's openclaw#201710 per-turn call gate (e7796dc: on a fixed listing a
turn that may not continue builds the tools with the inventory callbacks
and gates their calls) and fix-2's removal of the local
Pick<OpenClawToolsOptions, ...> in favor of ContinuationRunToolOptions.
Both survive: the parameter is ContinuationRunToolOptions plus upstream's
fixedToolListing, picked from OpenClawToolsOptions (its owner since
openclaw#201710), and the gate is unchanged. The restart-custody test support
merged cleanly: fix-2's module-private RequesterMessage beside Task A's
removeChildSession helper.

Refs openclaw#129388
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 20, 2026
check-test-lines-ratchet against upstream 1129d4c at the combined
head: net +113,955 against the 400-line allowance and 113,471 lines of
fork allocation credit, 84 over. The absorb head 8ba4ee8 was 281
under; this lane adds +365 net (measured per file, the ratchet's own
semantics): Task A's lineage-missing pins +191, Task B's openclaw#201710
checklist pins +126, and fix-2b's measured ratchet record and preflight
fixture +48. The record states the exact measured net, per change, as
the fork's other continuation records do. Pending review; no approval
claimed.

Refs openclaw#129388
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…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 | ![base J2](https://github.com/user-attachments/assets/0f47c723-4506-4dd3-ba92-9aa3e0631c20) | ![head J2](https://github.com/user-attachments/assets/8c2b3d6a-7fa8-4ec6-8dff-dff1daf8df80) |
| J11 group | ![base group](https://github.com/user-attachments/assets/d20693da-356d-444e-be9b-2ff611cb25a2) | ![head group](https://github.com/user-attachments/assets/b75a98e0-7a4c-4c0b-b622-59bb418ad99f) |
| J1 (OpenAI) | ![base J1](https://github.com/user-attachments/assets/2e158b3a-4702-4478-8ee6-b093d3cb99ac) | ![head J1](https://github.com/user-attachments/assets/a8083c98-89db-44a9-a156-cea6d802ba3c) |

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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…low and a concurrent chat on five transports (openclaw#201723)

## What was wrong

The prompt-cache journey is the CI check that each provider request in a chat extends the previous request byte for byte, except where a rebuild is expected. It skipped four triggers that real chats hit: a scheduled job that comes due in the chat, a user message steered into a running tool call, tool results that fill the context window, and an unrelated chat that compacts while this one runs. It also covered only three transports. A break in any of those paths could land without CI noticing.

**Example:** a scheduled job sent its reply to the model twice on every route. On Chat Completions and Gemini the copy merged into the next tool-call message, which rewrote history and lost the cache from that point on. Fixed in openclaw#201838. This journey would have caught it.

## Fix

- Adds the cron, steer, tool-result overflow and concurrent-compaction steps to the stability journey. It now runs on five transports: Anthropic, Responses, Chat Completions, Gemini and Bedrock.
- Adds a seeded randomized journey: 15 turn kinds on five transports, plus a variant with Tool Search turned off.
- Lists the breaks main still has, each with its owner. Entries expire: when a fix lands, the journey fails until its entry is removed. Each entry checks the whole request, so a known change cannot hide a second one.
- Rebuild steps are excused only when the rebuild actually happened. A compaction must put its new summary into the next request, and a model switch must make the next request come from the selected model.
- The steer step holds the tool open until the Gateway reports that the run has taken the steer. Before, it slept for a fixed 3 s.

## Numbers

| | main (before this PR) | this PR |
|---|---|---|
| Triggers covered | ordinary turns, tools, compaction | + cron, steer, tool-result overflow, concurrent compaction, cron-first chat, 15-kind randomized journey |
| Transports | 3 | 5 |
| Stability journey | n/a | 5/5 |
| Randomized journey (default seeds, 6 files) + negative controls | n/a | 12/12 + 5/5 |
| Anthropic and Tool Search off, seeds 1 and 6 | n/a | 2/2 and 2/2 |

<details><summary>Breaks still on main (accepted entries)</summary>

| Where | Change | Owner |
|---|---|---|
| Gemini, tool-result overflow (other chat) | the pre-request pressure check trims tool results that were already sent | openclaw#199530 |
| Bedrock, randomized | a dropped silent reply merges the user turns around it | accepted gap (openclaw#201654 closed) |
| Tool Search off, randomized | a provider switch adds `skills_read`/`skills_search` on turns started by a subagent completion or inter-session message | openclaw#201710 / documented exception of the opt-out surface |

Removed because their owners landed: the cron reply twice (openclaw#201838), the Chat Completions silent-turn merge (openclaw#201843), the cron-first `message` growth (openclaw#201710), and the skills rebuild after `config.patch` (issue openclaw#202150, which no longer reproduces on Anthropic seeds 1 and 6).
Bedrock refuses `cron.add` for AWS-SDK auth by design, and the journey expects that refusal.
</details>

<details><summary>Steer signal</summary>

- The steer is sent with `queueMode: "steer"`, as the chat composer sends it. The test waits for `sessions.changed` with reason `agent.input.steering`, which the Gateway emits when the active run accepts the steer into its queue. The tool is released only after that event.
- On all five transports the event arrives about 200-260 ms after the send is acknowledged, while the tool is still held.
- Negative control: releasing right after the acknowledgment lost the race on Gemini (1/5). The steered input became a separate turn.
- A default `chat.send` steer exposes nothing before release. Its pending input stays `queued` with no `steerNow`, and `agent.input.steering` only fires when the tool ends. So the step uses the composer's steer path.
</details>

<details><summary>Rebuild evidence checks</summary>

- Compaction: the fake numbers each compaction summary. The step needs a new summary, and the turn after it must contain that summary.
- Model switch: the alternate provider has its own model id. Every request after the switch must name exactly the selected model, read from the request body or the URL (Gemini, Bedrock), and at least one request must arrive.
- Teeth: with `sessions.compact` turned into a no-op, all 10 randomized seeds failed. With `sessions.patch` pinned to the first model, all 10 failed too.
</details>

<details><summary>Cron-first red on base</summary>

On the parent of openclaw#201710 with this PR's test files (no entry), the cron-first step fails on Anthropic and Responses at the owner turn's tool list (`at: 1, change: tools`). On main the step passes.
</details>

<details><summary>Harness fixes</summary>

- Each seed uses its own session keys. A retained subagent from the previous seed made every turn fail with `Retained subagent payload is unavailable`.
- After a silent reply, the fake acts only on the newest step marker, because main drops silent replies from replay.
- Every request is assigned to its session by its runtime line. A request from an unexpected session fails the journey.
- The Advisor fork check is dropped. Forks never arrived in earlier runs. When they did arrive, their requests differed from the parent's on all transports, which needs its own investigation.
</details>

<details><summary>Gates</summary>

- `ocx test` from source with an in-process Gateway and fake provider endpoints: 5 stability files, 6 randomized files and the known-breaks unit, 17/17. Anthropic and Tool Search off at seeds 1 and 6, 2/2 each. A second stability pass, 5/5.
- `pnpm tsgo:test:root`, oxfmt and oxlint on the changed files, and the test-lines ratchet all pass.
- Local review on this head: patch is correct, no findings.
</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 26, 2026
…rk and continue_delegate

With Tool Search on (the default when tools.toolSearch is unset),
request_compaction was the one continuation tool still cataloged:
callable only through dispatch_action and absent from the provider's
direct tool list, while continue_work and continue_delegate are
catalogMode "direct-only". Mark it the same way, so it reaches the
provider as a direct tool under Tool Search, the directory, Code Mode
and the Codex dynamic catalog (which routes direct-only tools to its
direct namespace).

Availability is unchanged: createOpenClawContinuationTools decides
whether the tool exists, and a turn's tool policy still removes it. On a
fixed listing (openclaw#201710), a cron-runner turn keeps listing it and refuses
the direct call with the same gate as the other two; the listing pin
says so instead of reaching the refusal through dispatch_action.

Tests: the tool-surface suite covers all three tools, including that a
refused dispatch never evaluates the guard or triggers compaction (RED
on a329243: 6 direct names, expected 7). Record
continuation-direct-only 118 -> 136: +22 tool-surface, -4 listing pin.
Measured net, not a cap. Pending review; no approval claimed.

Refs #1575, openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 26, 2026
…d minimal prompts teach the wake

A cron job whose sessionTarget is main or session:<key> (a room
heartbeat) runs as a reply turn of that session: the reply pipeline
passes continueWorkOpts, settles continue_work elections and drains
delegates after the turn. withContinuationOpts still stripped every
continuation tool from it because it matched any cron/event run with a
job id, so a heartbeat whose toolsAllow lists continue_work could never
arm its next turn. The gate now refuses only cron-runner runs whose host
passes no continueWorkOpts: detached isolated and current jobs, hooks,
join intros and cron trigger scripts, which nothing services. On
a329243 only the reply pipeline passes continueWorkOpts with a cron
trigger and job id; the isolated executor, hooks, join intros and
trigger scripts pass none.

On a fixed tool listing (openclaw#201710) the refusal holds for those detached
turns: they list the series' continuation tools and refuse the calls.
The two listing pins now model that host (no runner callbacks), and the
user-then-cron pin adds that a cron turn whose host services the
callbacks reaches them on the same listing.

Minimal prompts (cron, toolsAllow-capped and sub-agent runs) rendered
only "## Chain Delegation". When a turn control is callable they now
carry the same "### How you wake" lines as the full prompt, from one
helper, ahead of the chain-hop section; parameter tables stay out.

Tests: a session:<key> scheduled turn through the real reply execution
and production run-param builder gets continue_work, continue_delegate
and request_compaction (RED on 0587a9a: none); the detached cron and
event executor test still strips them; the minimal prompt carries the
full prompt's wake block byte for byte and omits it when no control is
callable. Record continuation-room-session-cron: 100. Measured net, not
a cap. Pending review; no approval claimed.

Refs #1575, openclaw#129388

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. security-sensitive-changed size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant