Skip to content

fix(agents): stop tool discovery from breaking prompt caches - #114572

Merged
steipete merged 1 commit into
mainfrom
codex/agent-loop-kv-cache-stability
Jul 27, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/agent-loop-kv-cache-stability

Conversation

@steipete

@steipete steipete commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor
Additional instructions

Maintainer edits are enabled for this maintainer-owned branch.

What Problem This Solves

Fixes an issue where users running multi-turn agents with Tool Search, changing plugin discovery order, Anthropic, or Gemini would unexpectedly lose provider prompt-cache reuse even when their trusted tools and stable instructions were unchanged. Cache-break diagnostics could also incorrectly blame dynamic per-turn instructions or miss actual tool-schema changes.

Why This Change Was Made

Give directory mode one deterministic, automatically included trusted capability directory; expose its stable search controls, core coding primitives, direct-only tools, and explicitly policy-required trusted message delivery. Delete turn-specific schema guesses and their duplicated hydration heuristics in both the embedded runner and agent harness. Canonicalize provider-visible tool declarations through one shared ASCII-stable ordering for OpenAI, Anthropic, direct Gemini, and managed Gemini; keep Anthropic's cache breakpoint and Gemini's managed-cache identity stable. Order plugin prompt guidance by plugin and command ownership. Fingerprint only the cacheable system prefix and bounded, provider-visible tool descriptor/schema digests, and do no fingerprinting when diagnostics are disabled. Preserve MCP/client trust boundaries and existing direct client-tool execution.

No config keys, environment variables, runtime defaults, migration, or protocol versions are added or changed. Tool Search remains opt-in; when enabled, its capability directory is included automatically and stays stable across turns.

User Impact

Agents can discover available trusted capabilities without sacrificing prompt KV-cache hits. Identical tool sets produce identical OpenAI, Anthropic, and Gemini request prefixes regardless of plugin/tool discovery order; repeated Gemini turns reuse existing managed cached content. Operators receive accurate cache-break diagnostics without storing prompt, tool-description, or schema contents and without adding hot-path work to ordinary runs.

Evidence

  • Linux Blacksmith Testbox: 841 passing tests across 20 focused files and six Vitest shards, including complete Tool Search discovery/ranking/runtime coverage, the embedded and harness paths, system-prompt/full-loop cache stability, required direct message delivery, collision/MCP boundaries, plugin guidance, managed Google cache reuse, direct Gemini wire payloads, OpenAI providers, and Anthropic request payloads/cache breakpoints.
  • Regression proves reordered Anthropic tools produce byte-identical request tools with the same final cache_control breakpoint.
  • Regression proves reordered Gemini tools create one managed cached-content entry and reuse it without an additional cache request.
  • Regression proves dynamic prompt suffixes do not produce cache-break false positives and same-name schema changes do produce tools diagnostics.
  • Regression proves wide, hostile, circular, unreadable, and insertion-reordered schemas remain bounded; wide descriptor getters are never evaluated.
  • Fresh structured Codex autoreview: clean, no accepted/actionable findings; the two initial hot-path/boundedness findings were fixed and the entire regression matrix was rerun.
  • Existing OpenAI behavior is preserved; public provider Plugin SDK export and boundary contracts have been checked.
  • Upstream Codex cache/deferred-tool contract personally verified in codex-rs/core/src/client.rs, codex-rs/core/src/tools/handlers/tool_search_spec.rs, and codex-rs/protocol/src/dynamic_tools.rs.

Maintainer decision and upgrade behavior

The repository maintainer explicitly requested this exact product decision: “If tool search is enabled we should automatically give it the directory,” followed by “review the whole system for kv friendliness - full agent loop” and “fix all of that, refactor generously and PR test land.” Existing opted-in directory-mode configurations therefore intentionally move to one automatically provided, stable capability directory rather than prompt-selected directly hydrated schemas. Preserving the previous per-prompt hydration would change the provider-visible tool prefix on every request and directly violate the approved KV-cache requirement. Core file and shell coding primitives, required message delivery, direct-only tools, configured client tools, and MCP/trust boundaries remain directly available where their contracts require it. Tool Search remains opt-in; no configuration defaults, keys, migration, or protocol versions change.

Real gateway behavior proof

The documented, user-facing command was executed on a real Linux Blacksmith Testbox against the actual gateway, QA Lab, and mock OpenAI provider:

$ pnpm openclaw qa suite --provider-mode mock-openai --scenario tool-search-gateway-e2e
[qa-suite] lab ready: http://127.0.0.1:40715
[qa-suite] provider ready: http://127.0.0.1:33737
[qa-suite] gateway ready: http://127.0.0.1:32779
[qa-suite] scenario start (1/1): tool-search-gateway-e2e
[qa-suite] scenario pass (1/1): tool-search-gateway-e2e
[qa-suite] run complete: passed=1 failed=0 skipped=0 total=1

The scenario verifies that 36 installed plugin-owned tools remain behind the stable compact bridge, the target capability is automatically visible in the bounded directory, the target plugin actually executes, and the provider payload is smaller than directly exposing all tool schemas.

Complete build and validation

  • Packaged Linux pnpm build passes, including the Control UI and all 143 public plugin SDK subpaths.
  • All 841 cross-provider/agent-loop and workflow-guard Linux regressions, full documentation validation, production and export dead-code scans, and the independent whole-branch review pass.
  • During validation, GitHub exposed an unrelated rate-limited OpenGrep installer. The same SHA-256-pinned release fix was subsequently landed directly on main; this PR rebases onto and reuses that upstream solution unchanged instead of adding a duplicate security action, workflow change, or CI guard.
  • Both MCP metadata and bundled MCP anti-impersonation regressions pass while legitimate core coding and trusted delivery tools remain directly visible.

Current-main compatibility

Rebased onto current main and retained its newly landed core-coding visibility contract: genuine core file and shell primitives remain directly callable in Tool Search directory mode, but plugin tools that reuse core names remain deferred and prompt-selected hydration is still removed. Both the directory and agent-harness regressions cover identical visible coding tools across unrelated user prompts. The public documentation describes the stable coding, client, direct-only, and policy-required tool surface explicitly.

MCP trust-boundary hardening

A fresh whole-branch review identified and verified the policy-delivery spoofing edge case. Directory mode now promotes explicitly required names only when their canonical catalog provenance is trusted OpenClaw, and core coding primitives only when they are core-owned. Uniquely named MCP tools cannot impersonate message, file, or shell tools; ambiguous names remain deferred. Separate regressions prove both explicit MCP metadata and bundle-mcp lookalikes are excluded, while legitimate plugin-owned message delivery and stable core coding tools remain directly visible.

Final lean product-only SHA d954a465b52: all 841 Linux provider, runtime, hostile-schema, MCP-boundary, and upstream workflow-guard regressions pass; the documented real gateway scenario was rerun and passes on this exact head, and fresh whole-branch autoreview reports zero findings.

Prototype-safe cache diagnostics

Schema fingerprint normalization uses null-prototype records, preserving hostile but valid own JSON-schema keys such as __proto__ without prototype pollution. Regression tests prove distinct __proto__ schemas produce distinct fingerprints and absent fields cannot collide; depth, width, node, getter, and string bounds remain intact.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: google size: XL maintainer Maintainer-authored PR labels Jul 27, 2026
@steipete
steipete force-pushed the codex/agent-loop-kv-cache-stability branch from 14b4b53 to 9434063 Compare July 27, 2026 12:39
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 27, 2026, 9:49 AM ET / 13:49 UTC.

ClawSweeper review

What this changes

The branch makes Tool Search directory mode use a stable directly callable tool surface, sorts provider-visible tools deterministically for prompt-cache reuse, and improves cache-break diagnostics across agent and provider paths.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This PR has a coherent cache-stability implementation, passing CI evidence, and sufficient real gateway proof. It must remain open for maintainer review because its intentional directory-mode behavior change can alter which plugin schemas existing opted-in users receive directly, and the item carries the protected maintainer label.

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

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong real behavior and focused regression evidence support a coherent patch; merge readiness is limited by an intentional compatibility decision that requires maintainer acceptance.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides an after-fix gateway QA Lab run on the exact head that exercises Tool Search directory behavior, plugin execution, and the compact provider payload; the successful real-behavior proof check corroborates it.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides an after-fix gateway QA Lab run on the exact head that exercises Tool Search directory behavior, plugin execution, and the compact provider payload; the successful real-behavior proof check corroborates it.
Evidence reviewed 5 items Directory-mode behavior: The branch removes prompt-specific schema hydration and passes only policy-required direct names into directory compaction, so the provider-visible tool set no longer depends on the current user prompt.
Provider ordering invariant: A shared ASCII-stable sorter is used for OpenAI-compatible, Anthropic, and Google tool payload construction; focused tests cover reordered Anthropic and Gemini declarations.
Real behavior proof: The PR body includes an after-fix gateway QA Lab run that passed tool-search-gateway-e2e, showing the compact directory, target plugin execution, and a smaller provider payload in a real gateway setup.
Findings None None.
Security None None.

How this fits together

Tool Search compacts a large catalog of agent tools into a directory plus a small direct surface before agent requests reach OpenAI, Anthropic, or Gemini. This PR makes that provider-visible prefix deterministic so cache identity and diagnostics remain stable across plugin discovery order and unrelated user prompts.

flowchart LR
  A[Plugin and core tools] --> B[Tool Search catalog]
  B --> C[Stable direct tool surface]
  B --> D[Capability directory]
  C --> E[Provider request builder]
  D --> E
  E --> F[Prompt cache identity]
  F --> G[Agent response and tool execution]
Loading

Decision needed

Question Recommendation
Should existing Tool Search directory-mode users intentionally move from prompt-selected direct plugin schemas to the PR’s stable directory/search/describe/call workflow in exchange for deterministic provider prompt-cache reuse? Confirm stable directory mode: Accept the documented directory-mode upgrade behavior so provider-visible tool prefixes remain deterministic across turns and discovery orders.

Why: The code and proof support the cache-stability invariant, but choosing the upgrade behavior for already opted-in directory-mode users is a product compatibility decision rather than a mechanical correctness question.

Before merge

  • Resolve merge risk (P1) - Existing users who opted into Tool Search directory mode may no longer receive prompt-selected plugin schemas directly; their agent may need the stable search, describe, or call path after upgrade. The PR presents this as intentional for cache stability, but it is still a user-visible compatibility decision that requires maintainer confirmation.
Agent review details

Security

None.

PR surface

Source -225, Tests +312, Docs +2. Total +89 across 28 files.

View PR surface stats
Area Files Added Removed Net
Source 17 217 442 -225
Tests 10 517 205 +312
Docs 1 16 14 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 28 750 661 +89

Review metrics

Metric Value Why it matters
Directory-mode compatibility path 1 existing mode behavior changed; 0 config keys, defaults, migrations, or protocol versions added The merge decision is about the changed direct-tool exposure for existing opted-in users, not a new configuration rollout.

Stored data model

Persistent data-model change detected: persistent cache schema: packages/ai/src/providers/anthropic-tool-projection.ts, persistent cache schema: packages/ai/src/providers/anthropic.test.ts, persistent cache schema: packages/ai/src/providers/openai-responses-tools.ts, persistent cache schema: packages/ai/src/transports/openai-transport-shared.ts, persistent cache schema: src/agents/embedded-agent-runner/prompt-cache-observability.test.ts, persistent cache schema: src/agents/embedded-agent-runner/run/attempt-execution-settle.ts, and 4 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Accept the documented directory-mode tradeoff (recommended)
    A maintainer can approve the stable directory/search/describe/call contract for opted-in users, with the stated direct-tool exceptions retained.
  2. Pause until compatibility direction is explicit
    Keep the PR open if maintainers want a different upgrade path for users who relied on prompt-selected direct plugin schemas.

Technical review

Best possible solution:

Keep Tool Search opt-in, retain the stable capability directory and explicitly trusted direct tools, and land only after a maintainer confirms that replacing prompt-selected direct plugin schemas is the intended upgrade behavior.

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

Yes, at source-and-proof level: the PR supplies a real gateway QA scenario and focused cross-provider regressions for reordered tools and directory mode, although this review could not independently rerun them in the read-only environment.

Is this the best way to solve the issue?

Unclear pending maintainer direction: canonical ordering and a stable directory are a coherent fix for prompt caches, but maintainers must confirm that the direct-schema compatibility tradeoff is the intended solution for existing directory-mode users.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 96a7a21d3130.

Labels

Label changes:

  • remove merge-risk: 🚨 automation: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.
  • remove merge-risk: 🚨 security-boundary: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.

Label justifications:

  • P1: The PR targets multi-turn agent workflows across major providers, where unstable prompt prefixes can prevent expected cache reuse and increase real-user runtime cost or latency.
  • merge-risk: 🚨 compatibility: Directory mode intentionally replaces prompt-selected direct plugin schemas with a stable deferred-tool workflow for existing opted-in configurations.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides an after-fix gateway QA Lab run on the exact head that exercises Tool Search directory behavior, plugin execution, and the compact provider payload; the successful real-behavior proof check corroborates it.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides an after-fix gateway QA Lab run on the exact head that exercises Tool Search directory behavior, plugin execution, and the compact provider payload; the successful real-behavior proof check corroborates it.

Evidence

What I checked:

  • Directory-mode behavior: The branch removes prompt-specific schema hydration and passes only policy-required direct names into directory compaction, so the provider-visible tool set no longer depends on the current user prompt. (src/agents/embedded-agent-runner/run/attempt-tool-catalog.ts:95, d954a465b52e)
  • Provider ordering invariant: A shared ASCII-stable sorter is used for OpenAI-compatible, Anthropic, and Google tool payload construction; focused tests cover reordered Anthropic and Gemini declarations. (packages/ai/src/utils/prompt-cache-stability.ts:9, d954a465b52e)
  • Real behavior proof: The PR body includes an after-fix gateway QA Lab run that passed tool-search-gateway-e2e, showing the compact directory, target plugin execution, and a smaller provider payload in a real gateway setup. (d954a465b52e)
  • Review continuity: The previous completed ClawSweeper cycle found no remaining line-level defect after the earlier direct-tool compatibility finding was addressed; its remaining note was a maintainer confirmation of the intentional upgrade tradeoff. (b9e49f3acaf7)
  • Protected review state: The supplied timeline and current labels include maintainer; repository policy requires explicit maintainer handling rather than automatic cleanup or closure. (AGENTS.md:1, 96a7a21d3130)

Likely related people:

  • steipete: Authored the reviewed cache-stability implementation and its focused cross-provider, Tool Search, and diagnostic coverage; maintainer review should include the person most able to explain the intended invariant. (role: recent area contributor; confidence: medium; commits: d954a465b52e; files: src/agents/tool-search-directory.ts, src/agents/embedded-agent-runner/prompt-cache-observability.ts, packages/ai/src/utils/prompt-cache-stability.ts)

Rank-up moves

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

  • Obtain explicit maintainer confirmation of the directory-mode upgrade behavior before merging.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-07-27T12:44:43.225Z sha 9434063f11a4ccfdf0965558567697bcfd60315a :: needs real behavior proof before merge. :: [P1] Preserve the shipped directory-mode tool surface
  • reviewed 2026-07-27T12:56:03.064Z sha e3e65f1772982a262073cf9a4e8abe3b26e2ea45 :: found issues before merge. :: [P1] Preserve directory-mode direct-tool compatibility
  • reviewed 2026-07-27T13:08:46.011Z sha cb52d7e59a7ba3a775b4d141a8a2413d8abaa338 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-27T13:31:00.878Z sha b9e49f3acaf7fed45c5ea84de78edbc1e689dfde :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/agent-loop-kv-cache-stability branch from 9434063 to e3e65f1 Compare July 27, 2026 12:51
@openclaw-barnacle openclaw-barnacle Bot added the security Security documentation label Jul 27, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 27, 2026
@steipete
steipete force-pushed the codex/agent-loop-kv-cache-stability branch from e3e65f1 to cb52d7e Compare July 27, 2026 13:03
@clawsweeper clawsweeper Bot added 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 27, 2026
@steipete
steipete force-pushed the codex/agent-loop-kv-cache-stability branch 2 times, most recently from 5146988 to b9e49f3 Compare July 27, 2026 13:24
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. labels Jul 27, 2026
@steipete
steipete force-pushed the codex/agent-loop-kv-cache-stability branch from b9e49f3 to b2f60ca Compare July 27, 2026 13:36
@openclaw-barnacle openclaw-barnacle Bot removed the security Security documentation label Jul 27, 2026
@steipete
steipete force-pushed the codex/agent-loop-kv-cache-stability branch from b2f60ca to d954a46 Compare July 27, 2026 13:40
@clawsweeper clawsweeper Bot removed merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Jul 27, 2026
@steipete
steipete merged commit 17ed69e into main Jul 27, 2026
135 of 137 checks passed
@steipete
steipete deleted the codex/agent-loop-kv-cache-stability branch July 27, 2026 13:58
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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: google maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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