Skip to content

fix(agents): keep projected prompt updates out of later user turns - #201843

Merged
obviyus merged 3 commits into
mainfrom
fix/silent-turn-update-merge
Nov 20, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/silent-turn-update-merge

Conversation

@obviyus

@obviyus obviyus commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

What was wrong

Some providers cannot accept mid-conversation system messages (inHistorySystemUpdates is false), such as custom OpenAI-compatible Chat Completions endpoints and Claude behind a non-native Responses proxy. On those routes, OpenClaw sends prompt updates as plain user messages. If a turn ends silently (like NO_REPLY after editing AGENTS.md, or a silent background exec wake), no assistant reply follows the update, so the next turn merged the new user message into the previous prompt update and broke the prompt cache.

Example

You edit AGENTS.md, a silent NO_REPLY turn runs, and then you send a normal message:

  • Before: the new user message merged into the earlier prompt update (rewriting message 6), breaking the prefix cache (cached 29495 / uncached 1207).
  • Now: the prompt update stays separate, history stays append-only, and the cache keeps hitting (cached 29865 / uncached 568).

The fix

  • Tag user-role prompt updates with an internal symbol (PROJECTED_PROMPT_UPDATE) in src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts when inHistorySystemUpdates is false.
  • Update canMergeUser (src/agents/embedded-agent-helpers/turns.ts) to refuse merging across that marker.
  • Use a symbol key instead of synthetic so it never serializes into provider requests, worker messages, or transcripts, and does not change ChatGPT V2 compaction provenance (retainUserProvenance).
  • Leave routes with native in-history system updates (native OpenAI Responses, direct Anthropic) unchanged. Production diff: +8 / -2 lines in 2 files.

Proof

Isolated scratch Gateways on merge base 1579eb4 vs head 53c326c, custom OpenAI-compatible Chat Completions route oaic (gpt-5.6-sol, rerun 2026-11-20):

Journey (next user turn) Base (1579eb4) Head (53c326c)
Silent NO_REPLY after AGENTS.md edit REWRITE at msg 6; cached 29495 / uncached 1207 Append-only; cached 29865 / uncached 568
Silent exec wake with ## Tooling update REWRITE at msg 13; cached 30897 / uncached 5130 Append-only; cached 33027 / uncached 2731
  • No-regression routes: Native OpenAI Responses (gpt-6.2-astra) and Claude proxy (claude-opus-5-5) stayed append-only with identical layouts and no marker in request bodies.
  • UI and side effects: Control UI renders the same chat history on base and head with no leaked prompt-update bubbles. Concurrent ordinary chat (3/3 turns) and /compact ("Compacted (31k → 1.4k)") worked normally; every journey turn returned status: ok.
  • Tests and review: attempt.silent-prompt-update.test.ts passes 8/8 on head (the 4 silent-turn cases fail on base). Local ClawSweeper (gpt-6.1-sol, normal speed) on 53c326c: review_status: complete, "patch is correct", 0 findings. All required PR CI checks pass on 53c326c.
Full test details

Why not synthetic

At least one route has inHistorySystemUpdates false and also reads synthetic on user messages. The ChatGPT Codex backend (provider: "openai", api: "openai-chatgpt-responses", chatgpt.com) is not a native Responses endpoint (packages/ai/src/transports/openai-responses-endpoint.ts:21-25 needs api: "openai-responses" on api.openai.com), so its prompt updates are projected as plain user messages. The same backend is the only one eligible for ChatGPT V2 compaction (src/agents/embedded-agent-runner/run/chatgpt-v2-compaction.ts:35-55, usesNativeOpenAICodexResponsesBackend). During V2 compaction it sets retainUserProvenance (packages/ai/src/providers/openai-chatgpt-responses.ts:221-223 → openai-chatgpt-responses-request.ts:118-124). Then openai-responses-replay-messages-internal.ts:441-448 tags non-synthetic user input as retained, and chatgpt-v2-compaction.ts:180-185 checks non-synthetic user input before persistence. A synthetic update would drop out of the V2 retained input on that route, which changes behavior. The symbol changes nothing there.

Scope and limits

  • Accepted gap: Bedrock Converse. It requires strict role alternation, so the stream boundary calls mergeConsecutiveUserMessages with preserveContextBoundaries: false for bedrock-converse-stream (attempt-tool-call-replay-sanitization.ts:382) and never consults canMergeUser. A silent turn rewrites the prefix there with or without an update. This PR does not change Bedrock.
  • One-time cache miss on upgrade: the marker also stops an update from merging backward into a user message directly before it in the same turn. Where history was sent as [user + update], the first request after the upgrade sends [user, update]. After that request, history is append-only again.
  • Longer runs of consecutive user-role messages: after a silent turn a request can now contain, for example, user, carrier, update, user, carrier in a row (main merged the update with the next user). Carriers already produce consecutive user-role messages on every turn on these routes, so this is not a new failure class.
  • Google Gemini routes do not merge user turns (validateAnthropicTurns is false), so this bug does not occur there.
  • The OpenAI provider plugin's own Chat Completions policy does not merge user turns either. The bug occurs on custom and plugin-owned OpenAI-compatible Chat Completions routes that use the strict OpenAI-compatible replay policy.
  • This supersedes the closed fix(agents): keep silent replies in replay so the session prefix stays append-only #201654 (silent replies in replay) for the routes above.

Which route merges

The original capture and the gate below use the same config: provider id oaic (a custom provider, no owning plugin, plugins disabled), api: "openai-completions", model gpt-5.6-sol, base URL pointing to a local logging proxy in front of the OpenAI API.

  • No plugin owns oaic, so resolveTranscriptPolicy uses buildUnownedProviderTransportReplayFallback (src/agents/transcript-policy.ts:161). That fallback sets validateAnthropicTurns: true for openai-completions (transcript-policy.ts:79,105).
  • With that flag, the stream wrapper merges consecutive user messages (src/agents/embedded-agent-runner/run/attempt-tool-call-replay-sanitization.ts:378-383, the same line 381 on 8a23d7c). canMergeUser (src/agents/embedded-agent-helpers/turns.ts:433) decides which messages may merge.
  • The OpenAI plugin's own policy sets validateAnthropicTurns: false for every API (extensions/openai/replay-policy.ts:18, same on 8a23d7c), so provider: "openai" with Chat Completions never reaches this merge.

Tests (attempt.silent-prompt-update.test.ts)

The test runs the real boundary projection, the real stream sanitization wrapper with the resolved transcript policy, and the real transport for each route (streamOpenAICompletions / streamOpenAIResponses). It captures the live payload object in onPayload, before serialization, so the key check sees symbol keys too.

Test Merge base 1579eb4 Head
custom Chat Completions, silent NO_REPLY after AGENTS.md edit red green
custom Chat Completions, silent exec wake with tooling update red green
Claude through custom Responses proxy, silent NO_REPLY after AGENTS.md edit red green
Claude through custom Responses proxy, silent exec wake with tooling update red green
both routes: update before a visible reply (request unchanged) green green
both routes: unmarked consecutive user text still merges (marker absent = main) green green

E2E (exact head 53c326c, rerun 2026-11-20)

Two isolated scratch Gateways from source: merge base 1579eb4 and head 53c326c. Real custom Chat Completions route oaic (openai-completions, gpt-5.6-sol) through a logging proxy that saves each request body and the provider usage. Both Gateways ran the same script. An ordinary chat ran concurrently with the journeys.

Silent NO_REPLY turn after an AGENTS.md edit, then user turns, /compact, and one more user turn:

Request Base: layout vs previous Base cached / uncached Head: layout vs previous Head cached / uncached
silent turn (update is last) append-only 29495 / 646 append-only 29222 / 646
next user turn REWRITE at msg 6 29495 / 1207 append-only 29865 / 568
following user turn append-only 30699 / 576 append-only 30430 / 576
first turn after /compact rewrite (compaction, expected) 0 / 31085 rewrite (compaction, expected) 0 / 30812

Silent exec-completion wake that carries a ## Tooling update, then a user turn:

Request Base: layout vs previous Base cached / uncached Head: layout vs previous Head cached / uncached
wake turn (update is last) append-only 30897 / 2408 append-only 30621 / 2409
next user turn REWRITE at msg 13 30897 / 5130 append-only 33027 / 2731

Side effects:

  • Ordinary chat, 3 turns: every reply arrives on base and head; every request is append-only (head cached / uncached: 29226 / 583, 29806 / 583).
  • /compact: works the same on base and head ("Compacted (31k → 1.4k)"). The next turn replies normally. The post-compaction request is the one rewrite that compaction is allowed to make, on both sides.
  • Every turn of every journey returned status: ok on both Gateways.

Earlier real Gateway run, custom Chat Completions oaic (gpt-5.6-sol)

An unrelated chat ran 6 turns concurrently on each Gateway (6/6 ok).

Journey 1: turn 1, then a NO_REPLY turn after an AGENTS.md edit, then two user turns.

Request Main Head
silent turn append-only append-only
next user turn REWRITE at message 6 (update merged with the new user text); cached 29457, uncached 1205 append-only; cached 29850, uncached 568
following turn append-only append-only

Journey 2: background exec, then a silent exec-completion wake that carries a ## Tooling update, then a user turn.

Request Main Head
wake turn append-only append-only
next user turn REWRITE at message 13; cached 30860, uncached 5129 append-only; cached 33013, uncached 2731

No-regression routes (same two journeys, main vs head, concurrent chat active)

Native OpenAI Responses (gpt-6.2-astra, inHistorySystemUpdates on) and Claude (claude-opus-5-5) through an Anthropic-compatible proxy (anthropic-messages, no stream merge). Request layouts come from the cache trace (stream:context fingerprints); cache numbers from cache:result. The proxy captured the Claude request bodies; no body contains the marker.

Route / journey Main Head
Responses, NO_REPLY after AGENTS.md edit 4 requests, all append-only, layouts uu → uuauuu → uuauuuuu → uuauuuuuauu same layouts, all append-only
Responses, silent exec wake 6 requests, all append-only same layouts, all append-only
Claude proxy, NO_REPLY after AGENTS.md edit 4 requests, all append-only; last turn cacheRead 72882, cacheWrite 925 same layouts, all append-only; cacheRead 72771, cacheWrite 925
Claude proxy, silent exec wake 6 requests, all append-only; last turn cacheWrite 8052 same layouts, all append-only; cacheWrite 8080

Responses cache numbers differ by at most 3 tokens per request (timestamp text). Concurrent chat: 6/6 turns ok in every run.

Gates (head 53c326c)

Gate Result
ocx test on the new test file 8/8 pass on head; on the merge base the 4 silent-turn cases fail and the 4 controls pass
ocx test sanitization, LLM boundary, cache stability, transcript policy, prefix stability suites pass
oxfmt (changed files) pass
oxlint (changed files) pass
pnpm tsgo:core pass
pnpm check:test-types 7 errors, all in test/scripts/release-* files that this PR does not touch; none in changed files
Local ClawSweeper (gpt-6.1-sol, normal speed) complete, "patch is correct", 0 findings

UI screenshots (Control UI of each scratch Gateway, chat history after the journeys)

Head and base render the same history. No "System prompt update" bubble or other prompt-update text appears in any session on head (checked in the rendered chat log text as well). The silent NO_REPLY turn shows only the user message, as on base.

Head, NO_REPLY journey with /compact:

Head: NO_REPLY journey with compact

Base, same journey:

Base: NO_REPLY journey with compact

Head, silent exec wake journey:

Head: silent exec wake journey

Base, same journey:

Base: silent exec wake journey

@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 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. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 19, 2026
@obviyus
obviyus marked this pull request as ready for review November 19, 2026 14:16
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR prevents projected prompt updates from merging with later user messages on affected provider routes.

Example: A custom Chat Completions session receives an AGENTS.md update, finishes silently, then receives “Reply with exactly: OK three”.

  • Before: The next request merges that text into the previously sent prompt update, changing the cached prefix.
  • After: The update remains a separate message and the next request preserves the earlier prefix.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-consistent repair with supplied end-to-end evidence and no correctness findings; some regression cases duplicate the same boundary.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied live results exercise isolated Gateways with a real custom Chat Completions provider through a request-capturing proxy, showing stable prefixes after both silent instruction-update and exec-wake turns on head; native Responses and Anthropic runs provide controls.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After a silent turn carrying a prompt update, a later user turn can rewrite previously sent history and lose prompt-cache reuse.
Reason: The maintainer-authored direction restores the documented prefix-stability contract with a narrow repair and explicitly bounds the unchanged Bedrock case.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR repairs a current prompt-prefix defect with a focused change; no introduced correctness or security bug was found.

Priority: P2
Reviewed head: 53c326c7e3f65c2333f7f1955e9d6c021513ba65

Before merge

None.

Findings

None.

Tests

  • Low-value test src/agents/embedded-agent-runner/run/attempt.silent-prompt-update.test.ts: Consolidate the two silentTurns fixtures into one regression per transport: both construct the same user/carrier/prompt-update sequence and differ only in text, so the exec-wake variant exercises no distinct completion boundary.
Agent review details

How this fits together

The embedded runner projects transcript messages into model history, then shared replay sanitization prepares that history for provider transports.

flowchart LR
  A[Transcript messages] --> B[Boundary projection]
  B --> C[Projected update marker]
  C --> D[Replay turn merging]
  D --> E[Transport conversion]
  E --> F[Provider request]
Loading

Technical review

Best possible solution:

Keep the projection-only marker and let the existing merge owner preserve the update boundary without changing transcript storage or provider semantics.

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

Current-main source establishes the projection-to-merge failure path, and the supplied Gateway results report both silent-turn reproductions; this review did not execute them.

Is this the best way to solve the issue?

The fix restores the append-only prefix invariant at the existing projection and merge owners, avoiding the broader silent-reply retention approach and preserving synthetic-user semantics.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Prompt-update projection keeps the original intent (46ab36a: Append prompt updates in history on capable routes while preserving fallback behavior; subsequent projection memoization preserved provider-facing bytes.)
  • Fallback runtime-context projection keeps the original intent (825f8fa: Preserve runtime-context envelopes when falling back to routes without native in-history system updates.)
  • Context-preserving user-turn merge keeps the original intent (d67c3c8: Keep carriers, operator updates and synthetic context separate from ordinary user text outside Bedrock; the later compaction refactor carried that rule into the shared adapter.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduction: The merge-base-to-head diff adds a projection-only symbol and checks it in the existing user-merge owner; the remaining changes provide transport-boundary regression coverage. (src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts:95, 53c326c7e3f6)
  • Current-main defect: Current main projects fallback prompt updates as unmarked user messages, while canMergeUser excludes runtime carriers, operator messages and synthetic messages but accepts these updates. (src/agents/embedded-agent-helpers/turns.ts:430, 41bdde2111dd)
  • Affected routes verified: The unowned-provider fallback enables user-turn merging for Chat Completions and Claude through Responses; the stream wrapper preserves context boundaries except on Bedrock Converse. (src/agents/transcript-policy.ts:105, 53c326c7e3f6)
  • Supplied Gateway proof: The full live PR body reports isolated Gateway runs through custom provider oaic and a logging proxy: main rewrites message 6 after the silent instruction-update turn and message 13 after the silent exec wake; head preserves both prefixes and reports lower uncached input. (53c326c7e3f6)
  • Maintainer-accepted limits: The collaborator-authored body explicitly accepts unchanged Bedrock behavior and a one-time cache miss where an existing update previously merged backward into a user message. (53c326c7e3f6)
  • Earlier proposal distinguished: The author closed fix(agents): keep silent replies in replay so the session prefix stays append-only #201654 because retaining silent replies broadly lacked demonstrated benefit on the tested non-Bedrock routes; this PR instead demonstrates the projected-update failure on a custom merging route.

PR surface

Source +8, Tests +148. Total +156 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 2 10 2 +8
Tests 1 148 0 +148
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 158 2 +156

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 P2: The demonstrated defect reduces prompt-cache reuse and increases input processing cost on a limited set of merging provider routes.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: The demonstrated defect reduces prompt-cache reuse and increases input processing cost on a limited set of merging provider routes.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

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

Workflow

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

Reviewed November 19, 2026, 9:30 AM ET / 14:30 UTC.

obviyus added a commit that referenced this pull request Nov 19, 2026
@obviyus
obviyus merged commit ced3bf6 into main Nov 20, 2026
220 checks passed
@obviyus
obviyus deleted the fix/silent-turn-update-merge branch November 20, 2026 04:53
@obviyus

obviyus commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in ced3bf6. On routes that project system prompt updates as user messages, a silent turn left the update as the last message and the next user message merged into it, rewriting history the provider had already cached. Projected updates now carry an in-memory marker that blocks the merge. Exact-head E2E on a custom Chat Completions route: the next user turn went from 1207 to 568 uncached tokens (NO_REPLY after an AGENTS.md edit) and from 5130 to 2731 (silent exec wake), with history append-only throughout.

obviyus added a commit that referenced this pull request Nov 20, 2026
…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 | ![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 `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]>
obviyus added a commit that referenced this pull request Nov 20, 2026
obviyus added a commit that referenced this pull request Nov 20, 2026
The cron reply merge (#201838) and the Chat Completions silent-turn merge
(#201843) are fixed on main, and the skills-after-reload rebuild no longer
occurs on Anthropic seeds 1 and 6.

Co-authored-by: obviyus <[email protected]>
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…penclaw#201843)

## Problem

Some routes cannot send a system prompt update as a system message (`inHistorySystemUpdates` is false). Examples: custom OpenAI-compatible Chat Completions providers, and Claude through a non-native Responses proxy. On these routes, the boundary projects the update as a plain `{ role: "user" }` message. The update is the last message of its turn.

When that turn ends silent (a `NO_REPLY` turn after an `AGENTS.md` edit, or a silent exec wake that carries a `## Tooling` update), no assistant message follows the update. On the next turn, the stream boundary merges the new user message into the update (`mergeConsecutiveUserMessages`). `canMergeUser` refuses carriers, operator messages and synthetic messages, but not this projected update. The result: a message that the provider already received is rewritten, and the prompt cache misses from that point.

## Fix

- When `inHistorySystemUpdates` is false, the projection puts a symbol-keyed marker (`PROJECTED_PROMPT_UPDATE`) on the projected update message.
- `canMergeUser` refuses to merge across that marker.
- A symbol key is not in `JSON.stringify` or structured clone output, so the marker never reaches a provider request, the worker protocol or the transcript. Only `canMergeUser` reads it.
- Why not `synthetic`: at least one route has `inHistorySystemUpdates` false and also reads `synthetic` on user messages. The ChatGPT Codex backend (`provider: "openai"`, `api: "openai-chatgpt-responses"`, `chatgpt.com`) is not a native Responses endpoint (`packages/ai/src/transports/openai-responses-endpoint.ts:21-25` needs `api: "openai-responses"` on `api.openai.com`), so its prompt updates are projected as plain user messages. The same backend is the only one eligible for ChatGPT V2 compaction (`src/agents/embedded-agent-runner/run/chatgpt-v2-compaction.ts:35-55`, `usesNativeOpenAICodexResponsesBackend`). During V2 compaction it sets `retainUserProvenance` (`packages/ai/src/providers/openai-chatgpt-responses.ts:221-223` → `openai-chatgpt-responses-request.ts:118-124`). Then `openai-responses-replay-messages-internal.ts:441-448` tags non-synthetic user input as retained, and `chatgpt-v2-compaction.ts:180-185` checks non-synthetic user input before persistence. A `synthetic` update would drop out of the V2 retained input on that route, which changes behavior. The symbol changes nothing there.
- Routes with `inHistorySystemUpdates` (native OpenAI Responses, direct Anthropic) are unchanged: they keep `operatorMessage` and never get the marker.

Production diff: 8 added, 2 removed lines in 2 files.

## Scope and limits

- Accepted gap: Bedrock Converse. It requires strict role alternation, so the stream boundary calls `mergeConsecutiveUserMessages` with `preserveContextBoundaries: false` for `bedrock-converse-stream` (`attempt-tool-call-replay-sanitization.ts:382`) and never consults `canMergeUser`. A silent turn rewrites the prefix there with or without an update. This PR does not change Bedrock.
- One-time cache miss on upgrade: the marker also stops an update from merging backward into a user message directly before it in the same turn. Where history was sent as `[user + update]`, the first request after the upgrade sends `[user, update]`. After that request, history is append-only again.
- Longer runs of consecutive user-role messages: after a silent turn a request can now contain, for example, user, carrier, update, user, carrier in a row (main merged the update with the next user). Carriers already produce consecutive user-role messages on every turn on these routes, so this is not a new failure class.
- Google Gemini routes do not merge user turns (`validateAnthropicTurns` is false), so this bug does not occur there.
- The OpenAI provider plugin's own Chat Completions policy does not merge user turns either. The bug occurs on custom and plugin-owned OpenAI-compatible Chat Completions routes that use the strict OpenAI-compatible replay policy.
- This supersedes the closed openclaw#201654 (silent replies in replay) for the routes above.

## Evidence

### Tests (`attempt.silent-prompt-update.test.ts`)

The test runs the real boundary projection, the real stream sanitization wrapper with the resolved transcript policy, and the real transport for each route (`streamOpenAICompletions` / `streamOpenAIResponses`). It captures the live payload object in `onPayload`, before serialization, so the key check sees symbol keys too.

| Test | Merge base `0f19e40` | Head |
|---|---|---|
| custom Chat Completions, silent `NO_REPLY` after `AGENTS.md` edit | red | green |
| custom Chat Completions, silent exec wake with tooling update | red | green |
| Claude through custom Responses proxy, silent `NO_REPLY` after `AGENTS.md` edit | red | green |
| Claude through custom Responses proxy, silent exec wake with tooling update | red | green |
| both routes: update before a visible reply (request unchanged) | green | green |
| both routes: unmarked consecutive user text still merges (marker absent = main) | green | green |

### Which route merges

The original capture and the gate below use the same config: provider id `oaic` (a custom provider, no owning plugin, plugins disabled), `api: "openai-completions"`, model `gpt-5.6-sol`, base URL pointing to a local logging proxy in front of the OpenAI API.

- No plugin owns `oaic`, so `resolveTranscriptPolicy` uses `buildUnownedProviderTransportReplayFallback` (`src/agents/transcript-policy.ts:161`). That fallback sets `validateAnthropicTurns: true` for `openai-completions` (`transcript-policy.ts:79,105`).
- With that flag, the stream wrapper merges consecutive user messages (`src/agents/embedded-agent-runner/run/attempt-tool-call-replay-sanitization.ts:378-383`, the same line 381 on `db32b2b`). `canMergeUser` (`src/agents/embedded-agent-helpers/turns.ts:433`) decides which messages may merge.
- The OpenAI plugin's own policy sets `validateAnthropicTurns: false` for every API (`extensions/openai/replay-policy.ts:18`, same on `db32b2b`), so `provider: "openai"` with Chat Completions never reaches this merge.

### Real Gateway, custom Chat Completions provider `oaic` (`gpt-5.6-sol`)

Isolated scratch Gateways (main = merge base, head = this branch), a logging proxy that captures each request body, provider cache numbers from the response `usage`. An unrelated chat ran 6 turns concurrently on each Gateway (6/6 ok).

Journey 1: turn 1, then a `NO_REPLY` turn after an `AGENTS.md` edit, then two user turns.

| Request | Main | Head |
|---|---|---|
| silent turn | append-only | append-only |
| next user turn | **REWRITE at message 6** (update merged with the new user text); cached 29457, uncached 1205 | append-only; cached 29850, uncached 568 |
| following turn | append-only | append-only |

Journey 2: background exec, then a silent exec-completion wake that carries a `## Tooling` update, then a user turn.

| Request | Main | Head |
|---|---|---|
| wake turn | append-only | append-only |
| next user turn | **REWRITE at message 13**; cached 30860, uncached 5129 | append-only; cached 33013, uncached 2731 |

### No-regression routes (same two journeys, main vs head, concurrent chat active)

Native OpenAI Responses (`gpt-6.2-astra`, `inHistorySystemUpdates` on) and Claude (`claude-opus-5-5`) through an Anthropic-compatible proxy (`anthropic-messages`, no stream merge). Request layouts come from the cache trace (`stream:context` fingerprints); cache numbers from `cache:result`. The proxy captured the Claude request bodies; no body contains the marker.

| Route / journey | Main | Head |
|---|---|---|
| Responses, `NO_REPLY` after `AGENTS.md` edit | 4 requests, all append-only, layouts `uu → uuauuu → uuauuuuu → uuauuuuuauu` | same layouts, all append-only |
| Responses, silent exec wake | 6 requests, all append-only | same layouts, all append-only |
| Claude proxy, `NO_REPLY` after `AGENTS.md` edit | 4 requests, all append-only; last turn cacheRead 72882, cacheWrite 925 | same layouts, all append-only; cacheRead 72771, cacheWrite 925 |
| Claude proxy, silent exec wake | 6 requests, all append-only; last turn cacheWrite 8052 | same layouts, all append-only; cacheWrite 8080 |

Responses cache numbers differ by at most 3 tokens per request (timestamp text). Concurrent chat: 6/6 turns ok in every run.

### Gates (head `53c326c`)

| Gate | Result |
|---|---|
| `ocx test` on the new test file | 8/8 pass on head; on the merge base the 4 silent-turn cases fail and the 4 controls pass |
| `ocx test` sanitization, LLM boundary, cache stability, transcript policy, prefix stability suites | pass |
| oxfmt (changed files) | pass |
| oxlint (changed files) | pass |
| `pnpm tsgo:core` | pass |
| `pnpm check:test-types` | 7 errors, all in `test/scripts/release-*` files that this PR does not touch; none in changed files |
| Local ClawSweeper (`gpt-6.1-sol`, normal speed) | complete, "patch is correct", 0 findings |



## E2E (exact head `53c326c`, rerun 2026-11-20)

Two isolated scratch Gateways from source: merge base `0f19e40` and head `53c326c`. Real custom Chat Completions route `oaic` (`openai-completions`, `gpt-5.6-sol`) through a logging proxy that saves each request body and the provider `usage`. Both Gateways ran the same script. An ordinary chat ran concurrently with the journeys.

### Silent `NO_REPLY` turn after an `AGENTS.md` edit, then user turns, `/compact`, and one more user turn

| Request | Base: layout vs previous | Base cached / uncached | Head: layout vs previous | Head cached / uncached |
|---|---|---|---|---|
| silent turn (update is last) | append-only | 29495 / 646 | append-only | 29222 / 646 |
| next user turn | **REWRITE at msg 6** | 29495 / **1207** | append-only | 29865 / **568** |
| following user turn | append-only | 30699 / 576 | append-only | 30430 / 576 |
| first turn after `/compact` | rewrite (compaction, expected) | 0 / 31085 | rewrite (compaction, expected) | 0 / 30812 |

### Silent exec-completion wake that carries a `## Tooling` update, then a user turn

| Request | Base: layout vs previous | Base cached / uncached | Head: layout vs previous | Head cached / uncached |
|---|---|---|---|---|
| wake turn (update is last) | append-only | 30897 / 2408 | append-only | 30621 / 2409 |
| next user turn | **REWRITE at msg 13** | 30897 / **5130** | append-only | 33027 / **2731** |

On base the next user message merges into the projected update, so the provider cache stops at that message. On head, history stays append-only and the cache continues to the end of the earlier request.

### Side effects

- Ordinary chat, 3 turns: every reply arrives on base and head; every request is append-only (head cached / uncached: 29226 / 583, 29806 / 583).
- `/compact`: works the same on base and head ("Compacted (31k → 1.4k)"). The next turn replies normally. The post-compaction request is the one rewrite that compaction is allowed to make, on both sides.
- Every turn of every journey returned `status: ok` on both Gateways.

### UI (Control UI of each scratch Gateway, chat history after the journeys)

Head and base render the same history. No "System prompt update" bubble or other prompt-update text appears in any session on head (checked in the rendered chat log text as well). The silent `NO_REPLY` turn shows only the user message, as on base.

Head, `NO_REPLY` journey with `/compact`:

![Head: NO_REPLY journey with compact](https://github.com/user-attachments/assets/2313c741-a82a-41e6-900c-4762e0516bb8)

Base, same journey:

![Base: NO_REPLY journey with compact](https://github.com/user-attachments/assets/3c15a26c-d4b9-48c0-9836-4dbbe924aca2)

Head, silent exec wake journey:

![Head: silent exec wake journey](https://github.com/user-attachments/assets/77426d6e-8d20-439a-bfbe-2f8bec1118e5)

Base, same journey:

![Base: silent exec wake journey](https://github.com/user-attachments/assets/792c5ff5-64de-404d-881e-527ec24abf9b)

### Review and CI on this head

- Local ClawSweeper on `53c326c`: `review_status: complete`, "patch is correct", 0 findings.
- PR CI on `53c326c`: all required checks pass.

Co-authored-by: Ayaan Zaidi <[email protected]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant