Repository navigation
fix(ai): stop serializing runtime context as user turns and preserve prompt cache - #141585
salad-maker wants to merge 44 commits into
Conversation
(cherry picked from commit a3c3c31)
Cut from main 37a5c5b with the native locale refresh (openclaw#136680) cherry-picked. Aligns every version location and the version-owned generated metadata via pnpm release:prepare and release:prep. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The generation fixture emitted index.js without its package.json. Since 696eb5d (openclaw#136399), bundled artifact selection follows emitted package metadata so stale JS/CJS/MJS neighbors cannot replace the declared output. The real build already writes this metadata; the fixture missed that contract. Repair createSpeechFixture in the generation test by declaring ./index.js beside the built entry. Preserve every built/source, generation isolation, no-rediscovery, and no-re-registration assertion. Production LOC delta: 0. Proof: CI=true NODE_OPTIONS=--max-old-space-size=8192 OPENCLAW_VITEST_MAX_WORKERS=2 OPENCLAW_VITEST_SHARD_NAME=agentic-plugins OPENCLAW_TEST_PROJECTS_PARALLEL=2 pnpm test -- test/vitest/vitest.plugins.config.ts -- Before: 5 capability failures, 4694 passed, 1 skipped. After: all 9 generation cases pass; 4698 passed, 1 skipped, and one separate 120s native SDK bridge timeout (that test took 108s before the patch). pnpm test src/plugins/capability-provider-runtime: 75 passed. pnpm check:changed passed; independent Codex review clean through P2. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 58a94ab)
Windows release checks pass drive-qualified archive paths to GNU tar, which treats their colon as a remote host. The shared fixture registry then stalls before readiness or silently loses package dependencies. Make the registry's manifest reader pass the archive basename with its parent as cwd, matching the existing prerelease artifact validator. The owning surface is release/E2E tooling, before installer or update dispatch. Proof: the real registry regression fails on the old reader under GNU tar 1.35 and passes with the repair; 191 focused tests cover registry behavior, artifact identity, and cross-OS harness contracts. All ten 2026.9.1 release companions served exact metadata and tarball bytes in local GNU tar proof. pnpm check:changed and independent Codex autoreview passed. Native Windows end-to-end validation still needs the three CI lanes rerun. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 1fbd62d)
The binding source-test image installed only the root project. With pnpm's isolated linker, private packages reached through source aliases had no package-local dependency links, so all three suites failed to import mdast-util-from-markdown from markdown-core. Remove the root-only install filter in the owning E2E Dockerfile so pnpm creates the complete workspace graph. Keep the frozen lockfile, isolated linker, and disabled lifecycle scripts. Update the existing helper guard. Proof: the unmodified Docker lane and native Markdown import reproduced ERR_MODULE_NOT_FOUND. Rebuilding the corrected image passes the import, workspace/plugin symlink probes, and all three focused binding tests. pnpm test test/scripts/docker-build-helper.test.ts passes 273 tests with two existing skips; pnpm check:changed and fresh Codex autoreview pass. Other sampled release Docker failures have independent plugin/update causes and are not covered by this image repair. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 1fa94d9)
The installed 2026.8.2 updater refuses the release smoke before package mutation or candidate handoff. Current main has the same defect: strict systemd command inspection cannot distinguish a missing manager from an uninspectable existing service. Let the native service-state owner record affirmative manager/unit absence, then require strict Gateway lock inspection and a free configured port at update preflight. Preserve unknown-state refusal and report skipped restart when nothing is running. Lock discovery retains its existing contract. Use the shipped baseline's documented --no-restart path only after proving the dedicated smoke container idle, then repeat the candidate update with default restart policy. Join the heartbeat timer exposed by that idle check. Document the one-time 2026.8.2 upgrade workaround. Proof: original baseline and packed-main Docker runs refused with exit 1; managerless and strict-lock regressions fail before the fix. Final focused suites pass 532 tests; the full update CLI suite passes 370 with 1 skipped. Final Docker baseline/manual plus candidate/default updates and doctor steps pass; pnpm check:changed passes. Independent review is clean through P2. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 245e18edf13d084ef4d0ce4c6f3f1486b73f7b1f)
Prepared registry merging kept upstream latest tags during candidate upgrade, so the survivor installed 2026.8.2 plugins despite serving 2026.9.1 artifacts. The registry helper now distinguishes published baseline tags from candidate package tags while retaining older dependency versions and fixture identities. Owner: prepared npm registry harness. Product runtime is unchanged; this repairs false stable-release upgrade failures for WhatsApp and Matrix. Proof: stable registry regression failed twice before the repair; all 15 registry helper and 37 plugin selection tests pass. The original 2026.9.1 candidate now passes the published 2026.8.2 survivor in local Docker. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 13246c2)
The nested synthetic registry replaced only one npm environment spelling, then setup discarded both instead of restoring the parent prepared registry. This caused a synthetic-package 404 and, once repaired, an unpublished core dependency ETARGET. Set both spellings and scope fixture setup to a subshell whose cleanup owns only the temporary server; preserve parent artifact state. Owner: npm fixture lifecycle and corrupt-plugin scenario. Product runtime is unchanged; release validation now exercises real corrupt-plugin tolerance. Proof: real npm regression fails before the repair and passes afterward. Docker reproduces both failures, then passes the full 2026.8.2 to unchanged 2026.9.1 candidate upgrade while preserving the plugin policy assertions. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 023c6ed)
Companion provenance inspection ran after the harness restored deliberately invalid legacy Discord configuration, so validation aborted before update. Keep inspection within the existing parked-config lifetime and restore the exact authored bytes after success or failure. Existing Doctor migrations remain responsible for the actual upgrade. Owner: upgrade-survivor fixture preparation. Product runtime is unchanged; release validation can reach the migration it is intended to exercise. Proof: the original candidate reproduces the pre-update Docker failure; two new lifecycle cases fail before the repair and all three pass afterward, with the existing registry-order helper case also passing. Full Docker survivor now passes migration, state survival, and Gateway readiness/RPC against the same original release candidate. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit db064aa)
Update reconciliation reused cached filesystem facts across package installation. A repaired missing payload still appeared absent, causing strict package-owner resolution to reject its runtime child list; replaced metadata could likewise retain retired children. Give cohort snapshots and post-install CLI reconciliation fresh operation caches. Preserve the authoritative owner check and retained runtime cache generations instead of invalidating a running gateway or adding fallbacks. Proof: missing/replaced real-filesystem regressions fail before this change; 67 focused cohort, package-policy, and plugin CLI tests pass. The original 2026.9.1 package fails the plugin-update Docker lane at missing-payload-accepted; the same release with this repair passes consent, repair, and unchanged checks. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit e55f6cf0bd23dd206f7dd770cf7443cd35766f07)
The runtime-plugin sweep invoked demo-npm after uninstall --keep-files and reinstall. Reinstall intentionally retains the explicit disabled marker, so command registration was correctly absent on that second invocation. Assert the reinstalled disabled state, then explicitly enable the fixture through the existing capability-consent helper before checking its CLI. Keep command registration and operator uninstall intent unchanged. Proof: the full Docker plugins lane fails before and passes after this harness change using the identical 2026.9.1 package and registry snapshot. The stateful sweep regression rejects command execution until re-enabled; all 23 package-consent compatibility tests pass. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 1c50920b3538b3f6a6a9d951262c2ebdef7fd503)
Root cause: the composed Gateway fixture bypassed required service methods through a context cast after execution-mode projection became mandatory. Owner: the App SDK E2E worker-service fixture now satisfies the complete request-facing contract and asserts supported execution modes. Proof: the original E2E failed 3/3 before and passed 3/3 after; environment owner tests pass (33 tests). Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 781d95537879194e83ccc58acd56234bdb6c3f4c)
Root cause: a reasonless skipped update is a failed update, so the old fixture exited before reaching its intended database compatibility gate. Owner: the schema-preflight fixture now declares the supported already-current outcome and preserves the schema-refusal assertion. Proof: the original E2E failed 3/3 before and passed 3/3 after; doctor-update owner tests pass (35 tests). No schema or production behavior changes. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit d39fa7bcc9dd03f6627dc6dcb6e72b8352dd31b8)
Root cause: requester and lifecycle fixtures returned text without the terminal send receipt required for external completion delivery, and observed RPC calls before their delivery state had committed. Owner: Gateway-result fixtures now provide confirmed receipts; scenarios wait on committed cleanup and release gated work even on assertion failure. Proof: the rejected requester wake failed 3/3 before and passed 3/3 after. Receipt repairs also resolved four sibling lifecycle failures. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit bd463c64e541527d694fcfab2e173053e776fffb)
Root cause: four retry-grace scenarios emitted 1970 timestamps under the current fake clock, so the 30-minute delivery deadline had already expired. Owner: each event producer now records Date.now(); grace advances and observable delivery assertions remain unchanged. Proof: all four failed 3/3 with stale timestamps; the corrected sibling suite passes all 14 tests in the final 22-test Gateway E2E run. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit 6e611dc93c3a67c491d3fe3c5b004c437de79bd9)
Root cause: the wake read route metadata only from its scheduling child, so a rerouted sibling disappeared from the parent's consolidated context. Owner: the requester settle-wake formatter now reuses the current-child selection, deduplicates and sorts route notices, and caps the aggregate at 1024 characters while preserving local and shared-channel visibility. Proof: the original visible-wake assertion still failed after fixture-only repairs and passes after this change. All four reported E2E failures pass 3/3; 39 wake owner tests cover sibling notices, stale owners and the bound. Production growth is 17 lines for bounded, deterministic batch aggregation. Co-Authored-By: Claude Fable 5.1 <[email protected]> (cherry picked from commit cab74190c5d3ecfe529e586df05a312183c1ac9e)
The successful announce fixture supplied only aggregate message-tool evidence, which no longer proves a committed final reply to the source conversation. Supply the receipt owned by the embedded runner without changing delivery policy or requester-wake sibling rerouting. Proof: the format suite failed 21 of 87 tests at both c92d0ae and a41af7e; all 87 pass with the corrected fixture. (cherry picked from commit 8229b8fcb61fa3a4e5b0c80acff087547a7904d4)
Inventory callers forced full discovery on every browse while trying to refresh auth-stale content. Give the prepared catalog owner a distinct stale refresh intent, preserve explicit forced refresh, and leave ordinary turn reads on their existing facts. Apply the policy to commands, CLI, and RPC. Correct the Ollama fixture response contract and await full catalog readiness. Verify discovered-only models survive callbacks and RPC while discovery is unavailable, and verify explicit refresh still reaches the provider. Proof: before the fix, the real Gateway made 8 discovery calls after a 3-call warmup, and the owner policy regressions failed. Prepared catalog and auth reload owner tests now pass (43 tests). (cherry picked from commit 1dfddb6e8fa7f57fcc60c4f01384b679e88ad77a)
The Docker scenario treated workspaceAccess=none as a read-only private workspace. The sandbox mount owner intentionally provides private writable storage while hiding the host and agent workspaces. Assert a private write/read succeeds and the same-named host sentinel stays unchanged. Keep read-only write rejection and read-write host persistence. Use a unique temporary workspace in the owner test so ambient /tmp skills cannot add unexpected mounts. Proof: OrbStack Docker reproduced the old assertion on successful exit zero; the complete none/read-only/read-write scenario now passes. (cherry picked from commit 85079b8ca7571f48537ef3b0ce5d393880b8b0c7)
The cancellation fixture hardcoded a root node_modules adapter path, but acpx owns that dependency. This caused deterministic MODULE_NOT_FOUND startup failures in both release validation runs, not an agent startup flake. Remove the override so the canonical plugin launcher resolves its adapter; retain the synthetic Codex app-server process through CODEX_PATH. Proof: the real installed adapter process passes cancellation authorization, rejects stale replacements without interrupting them, and preserves queued successors when the preceding run is cancelled. (cherry picked from commit 1e15a1d9ce4cb7ff9d1364ea8b4fe2528ef81c55)
Doctor imported the retained 10,000-row legacy host event tail through 10,000 standalone writes, each repeating expiry and retention scans. Prepare bounded 500-row batches before synchronous transactions. Share the canonical register path, maintain transaction-local retention counts, and refresh them on expiry or clock rollback. Per-row savepoints preserve the successful prefix on row failures; preparation failures flush their valid prefix. Preserve source ages, TTLs, ordering, limits, sibling state, and idempotent resume without changing the schema. The oversized-log test fell from 53.508s to 2.274s on the first paired run; subsequent runs took 1.447s and 1.647s. The full memory suite passed 1,422 tests; shared-store/database and Matrix doctor tests passed 95 and 20. requires maintainer approval for the transaction-boundary change (cherry picked from commit 7eccf12)
The catalog worker reconstructed an authoritative plugin registry with only augmentation and harness owners, so runtime catalog discovery lost provider names and reasoning metadata. Plan discovery through the canonical provider scope and materialize its owners after auth refresh using captured metadata. Keep the startup generation immutable and preserve lightweight and empty discovery scopes. Shared planning absorbs the owner selection instead of adding a registry fallback. Proof: both original ClawRouter cases fail on release 730dc39 and main eea96a3. All three repaired cases, including late durable auth, and 116 owner/sibling tests pass. Combined catalog, retry, abort and Telegram release proof passes 13 tests. (cherry picked from commit 608583c)
The fixtures still expected the retired 10s/20s backoff and advanced past a model after one HTTP 500, although the retry owner allows three transient retries with jittered 1s/2s/4s delays. Fix the random source and script persistent errors that exhaust that existing budget. Preserve exact delay, profile order, fallback winner and exhaustion prose assertions. No runtime retry policy changes. Proof: the same three tests fail on release 730dc39 and main eea96a3; all eight repaired fault-sequence tests pass, including the combined patched-release run. (cherry picked from commit 3ca630b)
The cold Gateway fixture expected a failed/blocked result after Stop, contradicting the existing authoritative cancellation repair. Assert the exact timeout/rpc/aborted wire payload and the canonical cancelled task. Keep provider connection closure and exactly one request checks. Owner: Gateway agent execution and task lifecycle. No product changes. Proof: the identical assertion fails on release 730dc39 and main eea96a3. The strengthened built-Gateway test passes on both patched main and release, including its first chat RPC and provider cancellation. (cherry picked from commit 897187f)
Failure handling read error text from successful current-attempt assistants, allowing stale text to replace an actual timeout or trigger a thinking retry after a successful reply. Normalize the failed assistant once at the failure owner for classification, retry decisions, profile health and failure copy. Keep structured terminal replay-safety checks and provider-start evidence independent of that text selection. Proof: full-entry regressions reproduce misleading HTTP 500 timeout copy and an unnecessary second attempt before the fix. Six context tests and 21 assistant-failure owner tests pass after the repair. (cherry picked from commit d330e36)
The failover owner reconstructed HTTP status from its routing reason, turning an observed 500 into 408 and mislabeling the final reply as a timeout. Preserve the canonical assistant failure signal status before using a synthesized status for failures without one. Apply the same rule to profile-rotation exhaustion, model fallback and surfaced failures. The Telegram proof expects the existing safe detailed copy and rejects raw provider details. Document status versus retry reason. Proof: six status cases fail before the fix; 82 owner tests pass after. Both baseline Gateway runs reproduce 17 requests and the wrong 408 reply. The patched release Telegram flow passes with exact 500 copy and the raw-error privacy canary excluded. (cherry picked from commit 32e2a90)
Dependency GuardThis PR changes dependency-related files. Maintainers should confirm these changes are intentional. Changed files:
Maintainer follow-up:
|
Dependency graph changes are blockedOpenClaw does not accept dependency graph changes through PRs unless a repository admin or security explicitly authorizes the current head SHA. Dependency updates are generated internally by maintainers so external PRs cannot change the resolved graph. Detected dependency graph changes:
If this PR intentionally needs a dependency graph change, ask a repository admin or member of The action will approve the current head SHA ( |
|
Codex review: needs real behavior proof before merge. Reviewed September 7, 2026, 5:35 PM ET / 21:35 UTC. ClawSweeper reviewWhat this changesThe branch moves Anthropic runtime metadata into system blocks, changes OpenAI Responses metadata to instruction roles, updates notice stripping, and carries release-branch changes. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 9 items remain Keep open: the branch contains useful, distinct work, but its Anthropic cache premise is incorrect and the provider-role change conflicts with a recently merged compatibility decision. The related cache PR covers only part of this proposal. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw adds runtime metadata to incoming requests before its provider adapters construct model messages. These adapters determine message roles, retained-history replay, and prompt-cache boundaries. flowchart LR
A[Incoming user request] --> C[Runtime context assembly]
B[Conversation history] --> C
C --> D[Provider message conversion]
D --> E[Anthropic system and messages]
D --> F[OpenAI Responses input]
E --> G[Model response and cache usage]
F --> G
Decision needed
Why: The proposed role change departs from an explicit recent compatibility decision; choosing a new retained-session contract requires maintainer intent. Before merge
Findings
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Reuse current provenance projection and shared provider conversion, preserving retained prefixes while fixing transient cache anchors without moving volatile context ahead of conversation history. Do we have a high-confidence way to reproduce the issue? Yes, from source: consecutive Anthropic requests with unchanged history and different carrier text diverge inside the system prefix before every message cache marker. No runtime reproduction was executed during this read-only review. Is this the best way to solve the issue? No. The proposed system-tail placement defeats cross-turn conversation caching; current provenance projection and lifecycle-qualified cache handling provide a safer foundation, while broader role migration remains unresolved. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 0994c66c963e. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
Summary
Resolves multiple coupled issues where OpenClaw-generated runtime context (timestamps, channel metadata, session state) is serialized into provider conversation messages as a
userturn.Attributing runtime metadata to the user creates three distinct failure modes:
messages, every turn perturbed the message prefix or captured the moving cache breakpoint, constantly busting the prompt cache ([Bug]: 2026.9.2 Anthropic cache_control can attach to relocating runtime-context carrier (opt-out removed in #136782) #140607).What This PR Changes
1. Anthropic: Partition carriers to uncached trailing system blocks
partitionAnthropicRuntimeContextCarriersto split carrier messages out of the conversation before conversion in bothconvertMessagesandconvertAnthropicMessages.systemtext blocks placed afterbuildAnthropicSystemBlocks(...)/applyAnthropicPayloadPolicyToParams(...)with nocache_control.2. OpenAI Responses: Align carrier role with system prompt
developerwhere supported, otherwisesystem) instead ofuser.3. Notice Cleanup & Stripping Parity
This context is runtime-generated, not user-authored.LEGACY_OPENCLAW_RUNTIME_CONTEXT_NOTICEandOPENCLAW_RUNTIME_CONTEXT_NOTICESso stored session transcripts and legacy event headers continue to strip cleanly on display sanitization.Fixes / References
Verification
packages/aiandsrc/agents).oxlint(0 warnings, 0 errors),oxfmt, andtsgo:coreclean.cache_control: { type: "ephemeral" })cache_control: { type: "ephemeral" })cache_control: null)