Repository navigation
perf(agents): keep enriched user prompt history stable - #167938
Conversation
Capture a versioned model prompt projection on the canonical user turn before provider dispatch. Replay the recorded, redacted text while preserving the original display content, exact turn ownership, and late-media boundaries. Remove transient prompt substitution and historical metadata stripping. Add bounded field-level cache diagnostics and request-prefix regressions across steering, compaction, and reopened sessions.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThe agent stores each user turn’s enriched model-facing text so later requests preserve earlier context while displayed chat history keeps the original text. Example: Send “original turn 1” with a model-prompt replacement, then send another turn.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR addresses a concrete prompt-history defect still present on current main. The earlier compatibility concern is resolved by the released reader contract and mixed-session replay evidence; no actionable patch defect was found. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe embedded agent runner combines user input and plugin-provided context before sending conversation history to a model provider. The transcript recorder stores canonical user messages in SQLite, and the model boundary prepares their replay text. flowchart TD
A[User input and plugin context] --> B[Embedded agent runner]
B --> C[Canonical transcript recorder]
C --> D[SQLite user turn with optional recorded prompt]
D --> E[Model boundary replay]
E --> F[Provider request with stable history]
D --> G[Chat history with original user text]
Technical reviewBest possible solution: Keep immutable enriched text with its canonical user turn and use the existing transcript owner for capture and replay. Do we have a high-confidence way to reproduce the issue? Yes, through the current-main temporary enrichment path and the linked report’s consecutive provider requests. The PR records a failing base serialized-prefix regression; this read-only review did not execute tests. Is this the best way to solve the issue? Yes. Capturing text through the existing transcript owner preserves hook semantics and replay identity without introducing a parallel carrier, table, or configuration option. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 7cf743ec145a. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +218, Tests +593, Docs +29, Other 0. Total +840 across 24 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 9, 2026, 4:31 PM ET / 20:31 UTC (Revision 2). |
|
Landed as The lane-caused CI fixture failure is fixed in The other failure is independently reproduced on untouched main For the compatibility review request, the changed contract is the optional transcript field, not a database-version or installer migration. The PR now cites the released v2026.9.9 reader's loose user-message schema and arbitrary metadata contract. The real SQLite/Responses regression keeps an unprojected turn beside projected turns, reopens the session, compares full serialized prefixes, and verifies that the unprojected turn remains unprojected. Absent fields retain the existing path; unsupported present versions fail explicitly. The documented downgrade limitation is loss of enriched-prefix continuity on older readers, not loss of original transcript content. A full v2026.9.9 installer-upgrade run was not performed and is not claimed. I am treating the optional-field compatibility contract as covered by the released reader inspection and persisted mixed-session replay; the unchanged installer/SQL migration matrix is outside this repair's required proof. The independent code reviews found no actionable P0–P2 defects. |
* perf(agents): keep enriched user prompt history stable Capture a versioned model prompt projection on the canonical user turn before provider dispatch. Replay the recorded, redacted text while preserving the original display content, exact turn ownership, and late-media boundaries. Remove transient prompt substitution and historical metadata stripping. Add bounded field-level cache diagnostics and request-prefix regressions across steering, compaction, and reopened sessions. * test(agents): keep prompt fixture turns independent
Capture a versioned model prompt projection on the canonical user turn before provider dispatch. Replay the recorded, redacted text while preserving the original display content, exact turn ownership, and late-media boundaries. Remove transient prompt substitution and historical inbound-metadata stripping so a turn keeps its first model-facing bytes when it becomes history. Backport of 6461c18 (#167938) adapted for 2026.10.2: - capture uses the release line's rewriteTranscriptMessageAtAnchor with an inline active-row check (main's rewritePreparedTranscriptMessageAtAnchor is not on this line); a replaced anchor rejects with the writer-claim error - the prompt phase wraps capture in the owned transcript lane only, because the release line's anchored rewrite takes its own agent-database admission - bounded field-level prompt-cache diagnostics from the PR are not included - base-only steering/timestamp tests updated to the new replay semantics
…ted dispatch A model-fallback retry (and any re-prompt of an already dispatched turn) can change the model prompt, e.g. the "[Retry after the previous model attempt failed or timed out]" marker. When the user turn had already been sent to a provider without a recorded projection, #167938's capture then rejected with "Model prompt projection must be captured before provider dispatch", so the fallback attempt never reached its provider and the run ended in error (sessions_spawn child ladders, cron/subagent fallbacks). Keep such text request-local instead: the canonical transcript keeps the bytes first sent, and the runtime view is not mutated. Turns that were not yet dispatched still freeze their projection before the first request. Fix for e02e615 (#167938 backport) on 2026.10.2.
#167938 freezes a user turn's first model-facing text as a projection and replays it as history. For inter-session input (e.g. a sessions_send follow-up) the stored transcript text carries the "[Inter-session message] sourceSession=... sourceTool=..." safety envelope, while the active request moves that envelope into a transient runtime-context carrier and sends only the routed body. Capturing the body as the projection meant that once the turn became history the envelope disappeared from the model's view, so a child resumed after a Gateway restart no longer saw that the earlier message came from another session rather than its user. When the prompt does not contain the whole stored inter-session text, keep the replacement request-local so history replays the stored, provenance-annotated text. Comparing the full stored text (not the body's prefix) also covers forwarded bodies that carry their own envelope. Other enriched prompts still freeze their first projection.
…ory (#169130) * fix(agents): keep inter-session provenance in replayed history #167938 freezes a user turn's first model-facing text as a projection and replays it as history. For inter-session input (e.g. a sessions_send follow-up) the stored transcript text carries the "[Inter-session message] sourceSession=... sourceTool=..." safety envelope, while the active request moves that envelope into a transient runtime-context carrier and sends only the routed body. Capturing the body as the projection meant that once the turn became history the envelope disappeared from the model's view, so a child resumed after a Gateway restart no longer saw that the earlier message came from another session rather than its user. When the prompt does not contain the whole stored inter-session text, keep the replacement request-local so history replays the stored, provenance-annotated text. Comparing the full stored text (not the body's prefix) also covers forwarded bodies that carry their own envelope. Other enriched prompts still freeze their first projection. * fix(agents): redact request-local inter-session prompts before dispatch Keeping an inter-session replacement request-local skipped the recorder's capture, which is also where configured and registered-secret redaction is applied before the first provider dispatch. Route request-local text through the same capture with a requestLocal option: it is redacted exactly like a durable projection but the stored user record is left unchanged.
Related: #168843 ## What Problem This Solves Fixes duplicate user turns in `chat.history` when a message starts with an inline directive such as `/think high` and continues with an ordinary prompt. ## User Impact One `chat.send` produces one user-history entry, preserving the original prompt and its whitespace. Standalone slash commands, native command errors, and their delivered replies keep their existing history behavior. Existing transcripts are not rewritten. ## Why This Change Was Made Regression introduced by #169026 (`289d859c2babddd9f5aee9dda96fbb94c5107f70`): command mirroring classified a delivered inline acknowledgement by the inbound message's `/` prefix. The normal user-turn owner had already persisted `<run>:user`; command mirroring then persisted the same input again under `command-input:[channel,account,conversation,run]`, with array content instead of string content. The inline-reply producer now records private `inlineCommandReply` metadata. Both block and final transcript-mirror admission honor that ownership fact instead of creating another command exchange. There is no content-based dedupe or text-parser heuristic. A focused suite protects producer metadata and both delivery paths; its existing producer case moved out of an oversized suite without removing assertions. No overlap with Pash/Sarah changes. ## Evidence - Before: the whitespace Gateway RPC test failed on main-based `ed1bc51edb0`, expecting one user message and receiving two identical prompts (string and text-block-array shapes). The two persisted identities were traced to normal turn admission and the command mirror introduced by #169026. - After: `preserves model-input whitespace independently from canonical chat history` passed through the real Gateway and mock provider (two turns, exact whitespace assertions, one history entry per turn). The temporary fixture from #168961 was used, with its replay assertion adjusted to the stable model-prompt projection introduced by #167938; none of those fixture changes are in this PR. - The other eight `gateway-rpc-chat.e2e.test.ts` cases passed in the full-file run. - Four focused unit suites passed: 202 tests, including producer metadata, block/final mirror exclusion, and existing standalone command coverage. - Runtime build, `tsgo:core`, formatting, line-cap growth ratchet, and oxlint on the other four changed files passed. The initial raw oxlint invocation reported the pre-existing over-cap `dispatch-from-config.choose-route.ts`; this file has no counted-line growth. - Independent source review: no remaining findings. Merge danger: **two-way door**. Reverting restores the old inline-acknowledgement mirroring behavior. No schema, stored-data migration, or configuration changes; the blast radius is transcript mirroring of inline command acknowledgements. Co-authored-by: Ayaan Zaidi <[email protected]>
#167938 replays the recorded model-prompt projection, so the consumed /think directive is absent from the second turn's replay of the first, as it was from the original request.
…ory (openclaw#169130) * fix(agents): keep inter-session provenance in replayed history openclaw#167938 freezes a user turn's first model-facing text as a projection and replays it as history. For inter-session input (e.g. a sessions_send follow-up) the stored transcript text carries the "[Inter-session message] sourceSession=... sourceTool=..." safety envelope, while the active request moves that envelope into a transient runtime-context carrier and sends only the routed body. Capturing the body as the projection meant that once the turn became history the envelope disappeared from the model's view, so a child resumed after a Gateway restart no longer saw that the earlier message came from another session rather than its user. When the prompt does not contain the whole stored inter-session text, keep the replacement request-local so history replays the stored, provenance-annotated text. Comparing the full stored text (not the body's prefix) also covers forwarded bodies that carry their own envelope. Other enriched prompts still freeze their first projection. * fix(agents): redact request-local inter-session prompts before dispatch Keeping an inter-session replacement request-local skipped the recorder's capture, which is also where configured and registered-secret redaction is applied before the first provider dispatch. Route request-local text through the same capture with a requestLocal option: it is redacted exactly like a durable projection but the stored user record is left unchanged.
…69434) Related: openclaw#168843 ## What Problem This Solves Fixes duplicate user turns in `chat.history` when a message starts with an inline directive such as `/think high` and continues with an ordinary prompt. ## User Impact One `chat.send` produces one user-history entry, preserving the original prompt and its whitespace. Standalone slash commands, native command errors, and their delivered replies keep their existing history behavior. Existing transcripts are not rewritten. ## Why This Change Was Made Regression introduced by openclaw#169026 (`afb47c66b96d2408160ca91de63e3cd930403832`): command mirroring classified a delivered inline acknowledgement by the inbound message's `/` prefix. The normal user-turn owner had already persisted `<run>:user`; command mirroring then persisted the same input again under `command-input:[channel,account,conversation,run]`, with array content instead of string content. The inline-reply producer now records private `inlineCommandReply` metadata. Both block and final transcript-mirror admission honor that ownership fact instead of creating another command exchange. There is no content-based dedupe or text-parser heuristic. A focused suite protects producer metadata and both delivery paths; its existing producer case moved out of an oversized suite without removing assertions. No overlap with Pash/Sarah changes. ## Evidence - Before: the whitespace Gateway RPC test failed on main-based `ed1bc51edb0`, expecting one user message and receiving two identical prompts (string and text-block-array shapes). The two persisted identities were traced to normal turn admission and the command mirror introduced by openclaw#169026. - After: `preserves model-input whitespace independently from canonical chat history` passed through the real Gateway and mock provider (two turns, exact whitespace assertions, one history entry per turn). The temporary fixture from openclaw#168961 was used, with its replay assertion adjusted to the stable model-prompt projection introduced by openclaw#167938; none of those fixture changes are in this PR. - The other eight `gateway-rpc-chat.e2e.test.ts` cases passed in the full-file run. - Four focused unit suites passed: 202 tests, including producer metadata, block/final mirror exclusion, and existing standalone command coverage. - Runtime build, `tsgo:core`, formatting, line-cap growth ratchet, and oxlint on the other four changed files passed. The initial raw oxlint invocation reported the pre-existing over-cap `dispatch-from-config.choose-route.ts`; this file has no counted-line growth. - Independent source review: no remaining findings. Merge danger: **two-way door**. Reverting restores the old inline-acknowledgement mirroring behavior. No schema, stored-data migration, or configuration changes; the blast radius is transcript mirroring of inline command acknowledgements. Co-authored-by: Ayaan Zaidi <[email protected]>
…tored copy Fork-only fix for upstream openclaw#169154 on v2026.10.1. Storage redaction hints some values on its first pass and masks them on a second, so the run's copy of an admitted user turn carrying a bearer token, an env assignment, a URL password or an OAuth code could arrive one pass further than its stored copy and fail every turn with "Transcript idempotency key ... conflicts with the admitted message". Without pending-input custody, a keyed user replay now also matches the stored copy redacted once more. Upstream fixed this in openclaw#169237, which depends on openclaw#167938's prompt projection; drop this commit when the fork carries both.
…nges (#168961) Fixes Gateway regression checks that select serialized runtime-context carriers instead of the user turn when provider serialization labels both as user messages. Fixes #168843 The three Gateway fixtures filter carriers with QA Lab’s shared recognizer through its extension API. Their behavioral assertions remain intact, and the output now records the selected turn, provider review pause, and requester effect across restart. No runtime behavior changes. Maintainers can verify that these Gateway regression scenarios select the intended turn and preserve their outcomes through a provider pause and Gateway restart. - Before: base `c7a7539` reproduced the three selector failures; 8 of 11 tests passed. - After: exact head `b7b8071713d191801004668a2b63127d0001adae` passed all 11 tests against a built Gateway with local WebSocket clients and loopback Responses fixtures. - Runtime traces show one serialized carrier skipped, the review seed persisted as continuable after the provider pause, and the requester effect remained at one call and one file line after restart. ```text $ OPENCLAW_E2E_USE_PREBUILT_DIST=1 pnpm test:e2e:gateway \ test/e2e/qa-lab/runtime/gateway-rpc-chat.e2e.test.ts \ test/e2e/qa-lab/runtime/gateway-provider-review-product-proof.e2e.test.ts \ test/gateway-completion-replay.e2e.test.ts --reporter=verbose --silent=false [gateway-rpc-chat-runtime-proof] {"turn":1,"gatewayRunStatus":"ok","serializedRuntimeCarriersSkipped":1,"selectedUserTurns":1,"latestPromptSelected":true,"persistedHistoryContainsPrompt":true} [gateway-rpc-chat-runtime-proof] {"turn":2,"gatewayRunStatus":"ok","serializedRuntimeCarriersSkipped":1,"selectedUserTurns":2,"latestPromptSelected":true,"persistedHistoryContainsPrompt":true} [provider-review-runtime-proof] {"phase":"provider-review-pause","seed":"allowed","httpStatus":403,"errorCode":"misalignment_policy_violation","runtimeCarriersSkipped":1,"selectedSeed":true} [provider-review-runtime-proof] {"phase":"gateway-review-seed-paused","gatewayRunStatus":"error","reviewPersisted":true,"canContinue":true,"expectedContinuationReceived":true,"runtimeCarriersSkipped":1} [gateway-completion-replay-provider-proof] {"phase":"requester-selected","serializedRuntimeCarriersSkipped":1,"requesterTurnSelected":true} [gateway-completion-replay-runtime-proof] {"phase":"requester-effect-before-restart","requesterEffectCalls":1,"persistedEffectLines":1,"childDeliveryStatus":"suspended","childSuspendedReason":"permanent_failure"} [gateway-completion-replay-runtime-proof] {"phase":"requester-effect-after-restart","followupStatus":"ok","requesterEffectCalls":1,"persistedEffectLines":1,"effectUnchanged":true} Test Files 3 passed (3) Tests 11 passed (11) ``` <details> <summary>Reproduction proof script</summary> ```bash set -euo pipefail pnpm build:docker OPENCLAW_E2E_USE_PREBUILT_DIST=1 pnpm test:e2e:gateway \ test/e2e/qa-lab/runtime/gateway-rpc-chat.e2e.test.ts \ test/e2e/qa-lab/runtime/gateway-provider-review-product-proof.e2e.test.ts \ test/gateway-completion-replay.e2e.test.ts --reporter=verbose --silent=false ``` </details> AI-assisted: built with Codex Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 6ce48cb) Backport note (release/2026.10.5): conflicts came from main-only test edits in 52200cf. Took main's version of the two failing fixtures (gateway-provider-review-product-proof, gateway-completion-replay) and kept gateway-rpc-chat.e2e.test.ts unchanged: it passes on this branch, and main's version asserts #167938 replay behavior.
What Problem This Solves
Follow-up requests lose prompt-hook context or strip inbound metadata from an earlier user turn, rewriting the prompt prefix and reducing cache reuse.
User Impact
Enriched user prompts retain their first model-facing text across later requests and reopened sessions. The visible transcript keeps its original content. Existing transcript redaction applies before the enriched text is first sent and recorded.
The optional versioned transcript field requires no database-version bump or migration. Legacy rows retain legacy replay. Older builds can read the original transcript but cannot preserve the recorded projection's cache continuity; unsupported projection versions require a compatible build or a new session.
Compatibility evidence: v2026.9.9's user-message reader uses a loose schema, and its transcript metadata contract accepts arbitrary
__openclawfields. The SQLite/Responses regression retains an unprojected user turn beside projected turns, reopens the session, and checks the entire serialized prefix and the absence of a projection on that unprojected turn. No installer upgrade from v2026.9.9 was run; SQL migrations, settings, and updater behavior are unchanged by this diff.Why This Change Was Made
The existing user-turn recorder captures immutable projection text on the canonical user record through the transcript writer before dispatch. Replay reads that field before deterministic timestamp/sender normalization. Exact user correlation survives steering; compaction retires the projection with its source; late media stays separate. Ordinary unmodified prompts add no capture write.
This removes transient prompt substitution/restoration and historical metadata stripping. Cache diagnostics now identify bounded, allowlisted field names and content-block indexes without exposing values or arbitrary extension keys.
Production LOC: +218; the requested non-test diff is +219, including one test-routing registration. The necessary growth implements the approved immutable stored-field, redaction, version compatibility, and live-admission contracts, plus bounded field diagnostics (+88). The former temporary marker/restoration path and metadata-stripping pass are removed; no new table, sidecar, configuration, or cache owner is added.
Evidence
Initial heavy proof ran on Blacksmith Testbox (
blacksmith-testbox,openclaw-check), lease tbx_01m4grkfxns19fn62rj3h1ykve, base432ade6f500de6cdb0bcd4b0948a07bf466672f1. Source hashes were checked after sync and dependencies installed with the frozen lockfile. Testbox workflow: https://github.com/openclaw/openclaw/actions/runs/37960827896. The runner workflow was cancelled after the behavioral proof; the full changed gate continued on the authorized AWS Crabbox fallback, leasecbx_f5e6256b3064.Synthetic replay uses real session persistence and the Responses request serializer, 109 hook turns and 109 replacement turns, with a reopen halfway through each:
historyRewritediagnosticsBoth remaining diagnostics are envelope-only
idempotencyKeychanges on reopen; their provider bytes are identical. Durable capture adds roughly 6.2 ms per enriched request in this fixture. RSS samples include independent imports and uncontrolled GC, so they are not an allocation-normalized comparison. These are synthetic results, not a production event rate or provider-billing measurement.node scripts/run-vitest.mjs … --maxWorkers=1: final four-file behavior group 78.76 s wrapper wall time (76 tests, AWS); nine-file sibling group 105.15 s (213 tests, Testbox). The real storage/session boundaries and existing compiler/import preparation account for the longer files; no per-test Gateway boots or timers were added. The original shared hosted test shard took 503 s, including checkout and preparation; final-head CI passed that repaired fixture and all other selected test/type/lint checks; only the independently reproduced asset drift and its aggregate gate remained red.replacement for turn 1becomesoriginal turn 1on the next request. Restoring the old media-resolution flag fails the capture-window regression because the separate media row is missing (28.93 s); both capture and dispatch timing pass with admission-owned classification.run_d3f62bc4fcf6bb195beeed099d710986(974.76 s command time), followed by 73 recorder/media/persistence sibling tests (57.51 s wrapper). This is combined gate evidence, not a claim that one uninterrupted initial invocation passed.The reviewed patch rebased unchanged onto
9b46148b2680(git range-diffreports equality). PR head5a469ba5d9f92e84dae6bc32236587970711ffdbpassed another 168 focused tests (141.78 s), core types, both affected test-type graphs, touched-file lint, export-collision checking, and 147 closure/CI-planning tests (116.72 s) on AWS leasecbx_df964aa0bdcf, runrun_27c6999c0c78ff258e72a4ebe3ac9f7e(365.37 s command time).The initial hosted
build-artifactsfailure is inherited: on untouched main9b46148b26804c213e23b11e3974278128ab1d2b,pnpm build:ci-artifactspassed (180.9 s) andpnpm plugins:assets:checkreproduced the same sole drift inextensions/workboard/openclaw.plugin.json(exit 1). This ran on AWScbx_a8c69f3a06ed, runrun_aecef204d7f63fa32e6e0c42bf82c981.The lane-caused CI failure was an old fixture that sent two distinct keyless users through one attempt and expected both to receive enrichment. It now tests each preprocessing variant in its own attempt and checks final normalized model messages. Both retain the hook/provenance/display assertions. 34 tests across the four sibling fixture files passed (74.59 s), as did the affected test-type graph (56.4 s), file lint, and a fresh independent P0–P2 review. The two hook cases took 188/179 ms. No production code changed in this correction. Final head:
43bfb358d9db758d695de340a604d60adb53d189. Merged as6461c186e5180cbdfdbbfea1d5b9e85e1d6fe3fbusing the standing inherited-CI exception after final-head CI completed.No live Gateway was modified or deployed. Legacy rows cannot reconstruct previously discarded enrichment.