Skip to content

perf(agents): preserve prompt cache across instruction refreshes - #167698

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-prompt-cache-system-prompt-churn-20260919
Oct 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-prompt-cache-system-prompt-churn-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Skill, workspace-memory, and runtime refreshes could replace an established system prompt and discard the conversation's reusable prefix. A 24-hour production sample reported 114 stable-prompt and 105 suffix changes accompanying cache-read drops. These counts overlap with other cache-break causes.

User Impact

Native OpenAI Responses and supported direct Anthropic sessions retain their initial system prompt while receiving refreshed instructions as appended messages. Existing skill, memory, tool-policy, and permission refreshes remain effective. Route or selected personal-profile changes, reset, and compaction start a fresh series.

Why This Change Was Made

Reuse the existing transcript-backed prompt-series owner for the complete prompt, including its suffix. Restore its last rendered instructions after attempt disposal instead of requiring fresh inputs to match. The OpenAI plugin opts native Responses into this path, and its transport preserves instruction authority and position. The selected human profile joins the series identity so a shared session cannot pin the previous person's personal bootstrap. Unsupported endpoints retain their existing behavior.

No new configuration, checkpoint fields, database schema, or cache is introduced. Older checkpoints whose route/profile identity no longer matches naturally start a fresh series. Cache diagnostics name changed sections using bounded labels and hashes without logging prompt contents or arbitrary headings.

Production LOC: +102 (+82 diagnostics, +18 native policy/transport handling, +2 profile invalidation; the snapshot owner is net neutral). The requested diagnostic and instruction-authority contracts require that growth; the fresh-suffix reconstruction path and matching-input restore condition are removed.

Evidence

A 288-turn session simulating 24 hours used the production renderer, transcript checkpoints, attempt teardown/reacquisition, model boundary, and Responses payload builder. Skills and memory refreshed throughout, with a date rollover:

Measurement Before After
Stable-prompt digest changes 47 0
Suffix digest changes 1 0
Mean common request prefix on changed turns 34,355 bytes 174,363 bytes (5.08×)
Projection loop, all 288 turns 211 ms 348 ms
Sampled RSS, same process 905 MiB 914 MiB

All 47 instruction updates were appended. This trades modest projection overhead for greater cache reuse.

A native OpenAI Responses control check (gpt-5.6-luna, cold initial turns) changed the same verification instruction. Rebuilding instructions read 0 cached tokens and had 1,533 uncached input tokens. Pinning instructions and appending the update read 1,504 cached tokens, leaving 54 uncached input tokens. Both returned the updated answer. This is one cache observation; it does not establish a latency improvement (1,034 versus 1,356 ms).

The separate three-turn production-transport live proof also kept instructions identical and obeyed the updated instruction. Cache reads were 0 → 1,372 → 1,396 tokens.

Validation:

  • 326 focused and sibling tests across 18 files passed. The original cache regression fails on the pre-fix source at turn two. The personal-profile regression fails before its scope guard and passes for Alice → Bob → shared defaults.
  • Blacksmith Testbox tbx_01m4fc6bvj31j4amaspkav3a8v, profile openclaw-check: focused owner/transport/policy/diagnostic command passed in 27.22 s; sibling replay/lifecycle command passed in 40.61 s, both with --maxWorkers=1.
  • Linux rig: runtime-preparation and bootstrap-selection suites passed together (17 tests, 97.77 s wall). The relocated provider test file passed all four cases; cold worker compilation dominated its 438.88 s wall time. The two new pure policy cases took 14 and 9 ms. Existing slow transport cases were unchanged.
  • Fresh independent Codex review: scoped-clean through P2, including profile invalidation.
  • node scripts/check-changed.mjs --staged passed core types, all 27 core-test type shards, extension types/tests, and the preceding guards on the original candidate. It stopped at four inherited unused exports. The exact same production/full-tree findings reproduce on unchanged main 175146de74ad5103aa97f2a04c4d06423a84df56 with node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts: bindCliQuestionAnswerAuthority, prepareSessionEventTargetForHost, readSessionEntryCreationTransition, and RESTART_CONTINUATION_CONTEXT_PREFIX. None is in this diff.
  • Remaining changed-file lint and repository guards passed on Blacksmith Testbox tbx_01m4frgr5xe2jmskw0gxvyh64h (275.53 s, exit 0). No ignore or baseline was changed. An earlier rig typecheck was killed by global memory pressure; its successful replacement ran separately from the focused tests.
  • A rebase onto 0015e4a8f0c2 preserves upstream fresh-session diagnostic reset and tool-change attribution. The affected observability/prompt-phase suites passed 79 tests after conflict resolution, and lint passed for the conflicted files. Fresh conflict-resolution review completed scoped-clean through P2 before the rebased commit was finalized.
  • Exact-head CI run 37901709970 passed for 3d5897ed86ad6ff78bc626d55a83af0ec712f523: 486 s workflow wall time. Its 20 Node validation jobs totaled 2,970 runner-seconds, including shared setup and existing tests. The PR merged normally as a79e29ec04fc30517814ffcd28e713fe53540ed4; no admin exception or CI rerun was used.
Focused validation commands
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/session-prompt-state.test.ts \
  src/agents/embedded-agent-runner/prompt-cache-observability.test.ts \
  src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts \
  src/agents/transcript-policy.test.ts \
  packages/ai/src/transports/openai-responses-prompt-role.test.ts \
  extensions/openai/openai-provider.test.ts --maxWorkers=1

node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/session-prompt-state.cache-ttl.test.ts \
  src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-phase.test.ts \
  src/agents/embedded-agent-runner/run/attempt-prompt-submit.foreground.test.ts \
  src/agents/transcript-policy.policy.test.ts \
  extensions/openai/openai-provider.responses.test.ts \
  packages/ai/src/transports/openai-responses-async-replay.test.ts \
  packages/ai/src/transports/openai-responses-retained-compaction-replay.test.ts \
  packages/ai/src/transports/openai-responses-payload-policy.instructions.integration.test.ts \
  packages/ai/src/transports/openai-responses-steering.integration.test.ts \
  packages/ai/src/transports/openai-responses-steering.test.ts --maxWorkers=1

node scripts/run-vitest.mjs \
  src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.ts \
  src/agents/embedded-agent-runner/run/attempt-bootstrap-prepare.test.ts --maxWorkers=1

node scripts/check-changed.mjs --staged

The first combined focused invocation exposed a fixture using the older provider entrypoint; the corrected test exercises the embedded Responses transport. The policy assertion was moved from an over-cap provider test file into its existing smaller Responses sibling. The commands above, plus that relocated-file run, provide the final focused proof.

Post-deployment production events/day is not yet measured; this PR does not deploy a Gateway. Synthetic prefix bytes and the small live control are not estimates of total production token savings.

Pin the complete system prompt through the existing transcript-backed series
owner and deliver refreshed sections as appended instructions. Enable the
native OpenAI Responses path while preserving provider role compatibility.

Keep personal bootstrap scoped to the selected profile, and report bounded
section changes without retaining prompt contents in cache diagnostics.
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: anthropic extensions: openai size: L labels Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 07:54
@steipete
steipete enabled auto-merge (squash) October 9, 2026 07:59
@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The agent preserves its initial instructions for provider cache reuse and appends refreshed skills, memory, and runtime guidance without rewriting earlier requests.

Example: Instructions change from “Skill 0” to “Skill 1” between conversation turns.

  • Before: A fresh attempt can replace the saved system prompt and lose its reusable request prefix.
  • After: The original system prompt remains unchanged and “Skill 1” arrives in an appended instruction message.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful and focused, with live provider evidence, but application-level proof remains limited and one added test mirrors a policy flag.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The complete PR body reports real native Responses calls through the production transport, with unchanged initial instructions, updated answers, and increasing cache reads; the longer synthetic session separately exercises checkpoint restoration and refresh projection. Full CLI/Gateway composition is not shown. Existing checkpoint fields remain compatible, and changed route/profile identities safely start a new series without rewriting user data.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Refreshing instructions can discard reusable model input, increasing uncached tokens during an ongoing conversation.
Reason: Measured cache churn supports the value of preserving established request prefixes. The author also appears in prior merged history for the affected owners, and the implementation follows their existing design.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current-main gap through the existing prompt-series owner. No blocking correctness or security defect was found.

Priority: P2
Reviewed head: 3d5897ed86ad6ff78bc626d55a83af0ec712f523

Before merge

None.

Findings

None.

Tests

  • Low-value test extensions/openai/openai-provider.responses.test.ts: uses host-admitted prompt updates on native Responses: Remove this flag-copy test: its expected value mirrors the implementation and does not exercise instruction delivery or host admission.
  • Missing end-to-end proof: The submitted evidence does not demonstrate a full CLI or Gateway conversation refreshing skills, memory, and temporal context across attempt disposal.
Agent review details

How this fits together

The embedded agent combines workspace instructions and conversation history into model requests. Its transcript-backed prompt-series owner preserves previously sent instructions while provider transports encode subsequent updates.

flowchart TD
  A[Skills and workspace instructions] --> B[Prompt renderer]
  B --> C[Transcript-backed prompt series]
  D[Saved checkpoint and conversation] --> C
  C --> E{Route or profile changed?}
  E -->|Yes| F[Start fresh instruction series]
  E -->|No| G[Keep initial prompt and append updates]
  F --> H[Provider model request]
  G --> H
Loading

Technical review

Best possible solution:

Keep instruction refresh and invalidation in the existing transcript-backed prompt-series owner.

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

Yes: current main reconstructs the suffix and rejects checkpoint restoration when refreshed instructions differ. The submitted regression targets the second fresh attempt and is reported to fail before the fix; it was not rerun during this read-only review.

Is this the best way to solve the issue?

Yes: extending the existing prompt-series owner avoids a competing cache or refresh mechanism, and preserves explicit route, profile, reset, and compaction invalidation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduction: Reviewed the merge-base-to-head delta rather than endpoint drift; the introduced changes reuse existing checkpoint, replay-policy, and transport owners. (3d5897ed86ad)
  • Still necessary on current main: Current main still requires the saved rendered prefix to match fresh inputs and reconstructs the dynamic suffix. No intervening main changes affect the reviewed paths; the earlier Anthropic implementation does not cover this PR's complete-prompt restoration and native Responses behavior. (src/agents/embedded-agent-runner/session-prompt-state.ts:141, c4887fb7de36)
  • Existing owner and intent: History and the merged improve(anthropic): append system prompt updates and runtime context in history on Claude routes #163461 establish the transcript-backed series and appended instruction design; this PR explains extending it to complete prompts and restoration after refreshed inputs. (src/agents/embedded-agent-runner/session-prompt-state.ts:138, 46ab36a493ac)
  • Live provider evidence: The complete supplied PR body, captured with sourceRevision be6a2fde1b69fd422f782ae11aaf12ff3203237003ddf0a5f7fad5cd5aadd940, reports a native Responses control with 1,504 cached and 54 uncached input tokens while obeying updated instructions. A separate production-transport run retained identical instructions and reported cache reads of 0 → 1,372 → 1,396. These are contributor-reported live results, not reviewer executions. (3d5897ed86ad)
  • Checkpoint compatibility: Checkpoint fields and writes retain their existing format. The added profile component makes older route identities mismatch safely, causing a fresh series; reset, compaction, model-change, orphaned-update, and retirement checks remain. The profile regression covers Alice → Bob → shared defaults. (src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.ts:139, 3d5897ed86ad)
  • Instruction authority: Only typed operator messages with text-only content receive instruction roles on native Responses. Ordinary user and image messages retain user roles; host route eligibility excludes proxy, Azure, and ChatGPT-backed routes. Existing projection and restart owners create trusted markers and retire earlier prompt overrides. (packages/ai/src/transports/openai-responses-replay-messages-internal.ts:399, 3d5897ed86ad)

Likely related people:

  • Peter Steinberger: Raw commit 46ab36a adds src/agents/embedded-agent-runner/session-prompt-state.ts:142 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 46ab36a493ac; files: src/agents/embedded-agent-runner/session-prompt-state.ts)
  • Vito Cappello: Raw commit 1e7f224 adds src/agents/embedded-agent-runner/prompt-cache-observability.ts:50 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1e7f2241e0e7; files: src/agents/embedded-agent-runner/prompt-cache-observability.ts)

PR surface

Source +102, Tests +282, Docs +3. Total +387 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 130 28 +102
Tests 7 373 91 +282
Docs 3 13 10 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 516 129 +387

Review metrics

Metric Value Why it matters
Production versus tests Production +102 LOC; tests +282 LOC Production growth primarily adds bounded diagnostics and native transport handling while reusing the existing state owner.

Labels

Label changes:

  • add P2: Instruction refresh can reduce provider cache reuse and increase input costs, without evidence of an urgent availability or delivery failure.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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: Instruction refresh can reduce provider cache reuse and increase input costs, without evidence of an urgent availability or delivery failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Demonstrate instruction refresh across fresh attempts through a real CLI or Gateway conversation, with private information redacted.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 9, 2026, 4:00 AM ET / 08:00 UTC.

@steipete
steipete merged commit a79e29e into main Oct 9, 2026
199 of 202 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-cache-system-prompt-churn-20260919 branch October 9, 2026 08:03
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…nclaw#167698)

Pin the complete system prompt through the existing transcript-backed series
owner and deliver refreshed sections as appended instructions. Enable the
native OpenAI Responses path while preserving provider role compatibility.

Keep personal bootstrap scoped to the selected profile, and report bounded
section changes without retaining prompt contents in cache diagnostics.
obviyus added a commit that referenced this pull request Oct 19, 2026
## What Problem This Solves

Fixes: the provider prompt cache misses completely on session-event turns, for example the exec-exit notification after a background `exec`. On real OpenAI that turn read 0 cached tokens, and the next turn missed part of its prefix again.

The tool block changed on that turn in three ways. Each one alone breaks the cached prefix:

1. The turn builds fewer tools. It replays the producing turn's allowlist, which leaves out owner-only tools (`automations`, `conversations_*`).
2. The descriptions of `exec`, `process` and `sessions_send` change, because they name sibling tools (`applyToolAvailabilityDescriptions`) and those siblings are missing.
3. The provider-hosted `web_search` drops out of the request. The saved event allowlist holds only function tools, so the hosted tool's runtime gate saw no `web_search` entry.

## Why This Change Was Made

#167698 already pins the system prompt per session in the transcript-backed prompt series. This extends the same owner to the tool block:

- **Pin the tool list.** The session pins every tool definition it has sent (`prepareSessionToolSurface`, `session-prompt-state.ts`). A turn that builds fewer tools still sends the pinned definitions. A call to a tool this turn did not build is refused through `gateAgentToolExecution` (#175309), so authority is unchanged.
- **Pin descriptions.** Within a pin, a tool keeps its pinned description while its parameters match. A new tool or a parameter change extends the pin once.
- **When a new pin starts.** On a route or model change, compaction or reset, and when the tool policy config (`tools`, the agent's `tools`) changes, so configured removals leave the request. Only a digest of that config is stored.
- **Storage.** The pin lives in the existing `openclaw.system-prompt` checkpoint entry. Routes without in-history prompt updates write a tools-only checkpoint. No schema change.
- **Permission refresh.** It rebuilds the pinned surface from the current tool generation, so new executors replace revoked ones.
- **Hosted `web_search`.** The saved session-event allowlist keeps it when the producing turn's full conversation policy allowed it (`isConversationToolAllowed`: profile, group, sender, sandbox, subagent and runtime caps). An event turn cannot gain `web_search` that its producer did not have.
- **Compaction.** A checkpoint carries the pinned tools only when the pin's route and history match the snapshot, so compaction or a route change retires the pin, and the next attempt pins the current tools.
- **`OPENCLAW_PROMPT_CACHE_ASSERT=1`.** It now also throws on tool-block changes within a session, except a pin change the pin declared, and names the turn (trigger, provenance, reply mode).

## User Impact

Background and event turns reuse the cached prefix. No change to which tools a turn may run.

## Evidence

Real OpenAI (`gpt-6-sol`, direct to `api.openai.com`) through the Gateway and a Telegram mock-user scenario: two user turns, image generation, a subagent spawn, a background `exec`, a system event and a closing user turn. Cached share of prompt tokens per request, from the Gateway's usage records:

| Turn | Before | After |
|---|---|---|
| User turns | 94–98% | 92–98% |
| Image completion | 98% | 99% |
| Subagent completion | 98% | 98% |
| **Exec-exit event** | **0%** | **95%** (94% in a second run) |
| Turn after the event | 85% | 86% |
| Whole session | 83.1% | 87.5% |

The first request of each session and each new subagent is cold (0%) on both sides.

Hosted-search authority at the final provider request (same real-OpenAI setup, request tool lists from `OPENCLAW_DEBUG_MODEL_PAYLOAD=tools`). The producing turn starts a background `exec` that sleeps 90 s. While it sleeps, the Gateway config gets `tools.deny: ["web_search"]` (hot reload):

| Request | Tools sent | Hosted `web_search` |
|---|---|---|
| User turn and `exec` call, before the deny | 52 | sent |
| Exec-exit event, after the deny | 39 | **not sent** |
| Later user turns | 53 | not sent |

A producer that sender policy denies search (`tools.toolsBySender: {"*": {deny: ["web_search"]}}`) sends 51 tools without hosted `web_search` on every request. That includes its exec-exit event, which reads 93.5% cached.

The queued event does not keep hosted search after a revocation. The policy change also starts a new pin, which costs one cache miss, as designed. The allowed case is the exec-exit row in the cache table above: 52 tools, `web_search` sent.

- Unit tests (`session-prompt-state.test.ts` and others):
  - A background turn keeps the user turn's definitions and refuses a missing tool.
  - The pin survives a restart, a prompt-series restart during admission and a system-prompt-only checkpoint.
  - A route or policy change starts a new pin.
  - A sibling-only description change keeps the pinned text.
  - A permission refresh uses the new executors.
  - The assert admits one declared pin change.
  - The session-event allowlist keeps hosted `web_search`.

  - Compaction retires the pin instead of carrying it into the new history.
  - A checkpoint written before this change (no `tools` key) still restores the system-prompt series, and a new pin starts from it.
  - Hosted search: a producer whose policy denies `web_search` saves no `web_search` entry. A saved entry still yields to the current policy when the event turn sends its request (`resolveWebSearchToolPolicy` with `tools.deny`).

  Each test for a fix fails without that fix. The pre-change checkpoint test and the two hosted-search policy tests cover behavior that already holds.
- E2E: compaction hot-reload passes on the final head. On the previous head, background-exec restart, session resume restart, restored-requester settle, heartbeat session routing, subagent current-requester and the SQLite flip proof all pass (14/14). Earlier commits on this branch also passed the compaction hot-reload, image-generation, silent-reply, chat-tools and approval suites. One test expectation changed (`gateway-session-resume-restart`): a stale `exec` call after recovery restricted the session is still refused and its effect still never happens. The refusal now comes from the pinned gate, so the wording differs.
- Upgrade: `pnpm test:docker:published-upgrade-survivor` from the current `latest` (`[email protected]`) passes on this head (881 s, no failures). An earlier run from `[email protected]` passed as well (915 s). The lane installs the published release with seeded config, sessions and transcripts, then updates in place to this branch. The Gateway, config and stored state survive.
- Harness fix: the SQLite flip-proof helper now skips compressed (`event_zstd`) transcript rows, which the larger checkpoint entry produces.

## Merge danger

Two-way door for behavior: a revert stops pinning, and older code ignores the `tools` field in checkpoint entries. Blast radius: the tool block of every embedded-runner request, and the allowlist stored with background exec and session events.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
## What Problem This Solves

Fixes: the provider prompt cache misses completely on session-event turns, for example the exec-exit notification after a background `exec`. On real OpenAI that turn read 0 cached tokens, and the next turn missed part of its prefix again.

The tool block changed on that turn in three ways. Each one alone breaks the cached prefix:

1. The turn builds fewer tools. It replays the producing turn's allowlist, which leaves out owner-only tools (`automations`, `conversations_*`).
2. The descriptions of `exec`, `process` and `sessions_send` change, because they name sibling tools (`applyToolAvailabilityDescriptions`) and those siblings are missing.
3. The provider-hosted `web_search` drops out of the request. The saved event allowlist holds only function tools, so the hosted tool's runtime gate saw no `web_search` entry.

## Why This Change Was Made

openclaw#167698 already pins the system prompt per session in the transcript-backed prompt series. This extends the same owner to the tool block:

- **Pin the tool list.** The session pins every tool definition it has sent (`prepareSessionToolSurface`, `session-prompt-state.ts`). A turn that builds fewer tools still sends the pinned definitions. A call to a tool this turn did not build is refused through `gateAgentToolExecution` (openclaw#175309), so authority is unchanged.
- **Pin descriptions.** Within a pin, a tool keeps its pinned description while its parameters match. A new tool or a parameter change extends the pin once.
- **When a new pin starts.** On a route or model change, compaction or reset, and when the tool policy config (`tools`, the agent's `tools`) changes, so configured removals leave the request. Only a digest of that config is stored.
- **Storage.** The pin lives in the existing `openclaw.system-prompt` checkpoint entry. Routes without in-history prompt updates write a tools-only checkpoint. No schema change.
- **Permission refresh.** It rebuilds the pinned surface from the current tool generation, so new executors replace revoked ones.
- **Hosted `web_search`.** The saved session-event allowlist keeps it when the producing turn's full conversation policy allowed it (`isConversationToolAllowed`: profile, group, sender, sandbox, subagent and runtime caps). An event turn cannot gain `web_search` that its producer did not have.
- **Compaction.** A checkpoint carries the pinned tools only when the pin's route and history match the snapshot, so compaction or a route change retires the pin, and the next attempt pins the current tools.
- **`OPENCLAW_PROMPT_CACHE_ASSERT=1`.** It now also throws on tool-block changes within a session, except a pin change the pin declared, and names the turn (trigger, provenance, reply mode).

## User Impact

Background and event turns reuse the cached prefix. No change to which tools a turn may run.

## Evidence

Real OpenAI (`gpt-6-sol`, direct to `api.openai.com`) through the Gateway and a Telegram mock-user scenario: two user turns, image generation, a subagent spawn, a background `exec`, a system event and a closing user turn. Cached share of prompt tokens per request, from the Gateway's usage records:

| Turn | Before | After |
|---|---|---|
| User turns | 94–98% | 92–98% |
| Image completion | 98% | 99% |
| Subagent completion | 98% | 98% |
| **Exec-exit event** | **0%** | **95%** (94% in a second run) |
| Turn after the event | 85% | 86% |
| Whole session | 83.1% | 87.5% |

The first request of each session and each new subagent is cold (0%) on both sides.

Hosted-search authority at the final provider request (same real-OpenAI setup, request tool lists from `OPENCLAW_DEBUG_MODEL_PAYLOAD=tools`). The producing turn starts a background `exec` that sleeps 90 s. While it sleeps, the Gateway config gets `tools.deny: ["web_search"]` (hot reload):

| Request | Tools sent | Hosted `web_search` |
|---|---|---|
| User turn and `exec` call, before the deny | 52 | sent |
| Exec-exit event, after the deny | 39 | **not sent** |
| Later user turns | 53 | not sent |

A producer that sender policy denies search (`tools.toolsBySender: {"*": {deny: ["web_search"]}}`) sends 51 tools without hosted `web_search` on every request. That includes its exec-exit event, which reads 93.5% cached.

The queued event does not keep hosted search after a revocation. The policy change also starts a new pin, which costs one cache miss, as designed. The allowed case is the exec-exit row in the cache table above: 52 tools, `web_search` sent.

- Unit tests (`session-prompt-state.test.ts` and others):
  - A background turn keeps the user turn's definitions and refuses a missing tool.
  - The pin survives a restart, a prompt-series restart during admission and a system-prompt-only checkpoint.
  - A route or policy change starts a new pin.
  - A sibling-only description change keeps the pinned text.
  - A permission refresh uses the new executors.
  - The assert admits one declared pin change.
  - The session-event allowlist keeps hosted `web_search`.

  - Compaction retires the pin instead of carrying it into the new history.
  - A checkpoint written before this change (no `tools` key) still restores the system-prompt series, and a new pin starts from it.
  - Hosted search: a producer whose policy denies `web_search` saves no `web_search` entry. A saved entry still yields to the current policy when the event turn sends its request (`resolveWebSearchToolPolicy` with `tools.deny`).

  Each test for a fix fails without that fix. The pre-change checkpoint test and the two hosted-search policy tests cover behavior that already holds.
- E2E: compaction hot-reload passes on the final head. On the previous head, background-exec restart, session resume restart, restored-requester settle, heartbeat session routing, subagent current-requester and the SQLite flip proof all pass (14/14). Earlier commits on this branch also passed the compaction hot-reload, image-generation, silent-reply, chat-tools and approval suites. One test expectation changed (`gateway-session-resume-restart`): a stale `exec` call after recovery restricted the session is still refused and its effect still never happens. The refusal now comes from the pinned gate, so the wording differs.
- Upgrade: `pnpm test:docker:published-upgrade-survivor` from the current `latest` (`[email protected]`) passes on this head (881 s, no failures). An earlier run from `[email protected]` passed as well (915 s). The lane installs the published release with seeded config, sessions and transcripts, then updates in place to this branch. The Gateway, config and stored state survive.
- Harness fix: the SQLite flip-proof helper now skips compressed (`event_zstd`) transcript rows, which the larger checkpoint entry produces.

## Merge danger

Two-way door for behavior: a revert stops pinning, and older code ignores the `tools` field in checkpoint entries. Blast radius: the tool block of every embedded-runner request, and the allowlist stored with background exec and session events.

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 docs Improvements or additions to documentation extensions: anthropic extensions: openai size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant