Skip to content

perf(agents): keep enriched user prompt history stable - #167938

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-prompt-cache-history-rewrite-20260919
Oct 9, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-prompt-cache-history-rewrite-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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 __openclaw fields. 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, base 432ade6f500de6cdb0bcd4b0948a07bf466672f1. 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, lease cbx_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:

Measurement Main Candidate
Changed serialized provider prefixes / 216 transitions 216 0
historyRewrite diagnostics 216 2
Replay wall time 3.098 s 4.454 s
Replay CPU time 4.225 s 5.664 s
End-process RSS samples 1,606–1,771 MiB 1,649–1,825 MiB

Both remaining diagnostics are envelope-only idempotencyKey changes 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.

  • 289 focused tests passed across 13 owner/sibling files, covering full serialized prefixes, initial/midturn steering, compaction, reopen, redaction, late media, and existing submission behavior. All focused runs used 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.
  • Negative controls: the replacement-prefix regression fails on unchanged main at the serialized-prefix assertion: replacement for turn 1 becomes original turn 1 on 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.
  • 147 tooling tests passed for database-worker registration, eager-import closure, PR-wrapper source closure, and CI test planning (102.37 s wrapper wall time). Export-name collision guard passed.
  • Documentation links: 14,931 checked, zero broken. Local changed-file formatting and staged whitespace checks passed.
  • Independent Codex review: scoped-clean, no actionable P0–P2 findings, including the capture-window media repair. Staged changed-file gate completed across the initial run and native-plan continuation: core types and all 27 core-test type graphs passed (1,680.05 s for test types); the corrected candidate passed core types again, all dead-export scans, core/script/root-test lint, schema, database-first, media, sidecar, import-cycle, webhook and pairing guards. The continuation and final media proof ran on AWS in 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-diff reports equality). PR head 5a469ba5d9f92e84dae6bc32236587970711ffdb passed 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 lease cbx_df964aa0bdcf, run run_27c6999c0c78ff258e72a4ebe3ac9f7e (365.37 s command time).

The initial hosted build-artifacts failure is inherited: on untouched main 9b46148b26804c213e23b11e3974278128ab1d2b, pnpm build:ci-artifacts passed (180.9 s) and pnpm plugins:assets:check reproduced the same sole drift in extensions/workboard/openclaw.plugin.json (exit 1). This ran on AWS cbx_a8c69f3a06ed, run run_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 as 6461c186e5180cbdfdbbfea1d5b9e85e1d6fe3fb using the standing inherited-CI exception after final-head CI completed.

No live Gateway was modified or deployed. Legacy rows cannot reconstruct previously discarded enrichment.

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.
@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 size: XL labels Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 19:46
@steipete
steipete enabled auto-merge (squash) October 9, 2026 19:48
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The 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.

  • Before: The model sees “replacement for turn 1” initially but “original turn 1” on the next request.
  • After: Later requests and reopened sessions continue sending “replacement for turn 1”.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The repair is coherent and compatibility is supported, while behavior evidence remains an in-process replay with synthetic transport.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the external-contributor proof gate. Its synthetic replay exercises the production recorder, SQLite persistence, and Responses serializer and reports zero changed provider prefixes; it does not establish live provider billing or a shipped Gateway run. Released-reader inspection and mixed projected/unprojected reopen coverage sufficiently establish the additive stored-field compatibility contract.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Earlier plugin context disappears on later turns, reducing cache reuse and potentially discarding the model’s retained reasoning.
Reason: Stable historical prompts are an established contract, and prior merged history establishes the author’s ownership of this area. The repair preserves original chat content and existing hook framing.

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
Reviewed head: 43bfb358d9db758d695de340a604d60adb53d189

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No shipped CLI or Gateway conversation is shown; supplied proof exercises real persistence and provider serialization with a synthetic model stream.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main still uses temporary prompt enrichment: Current main retains installModelPromptTransform and its cleanup-based substitution. The relevant runner and recorder files have no changes between the pinned merge base and fetched main, so this repair remains necessary. (src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts:381, 7cf743ec145a)
  • Capture uses the existing transcript writer: Capture redacts text, refuses conflicting repeated captures, binds the write to the admitted transcript anchor, and supplies the current-write assertion to the existing rewrite owner. (src/sessions/user-turn-transcript-updates.ts:60, 43bfb358d9db)
  • Optional-field replay compatibility: Absent fields retain the existing path; version 1 replaces only model-facing text while retaining other content blocks. Malformed or unsupported present fields produce an explicit recovery message. (src/sessions/user-turn-transcript.message.ts:155, 43bfb358d9db)
  • Released reader accepts additive metadata: The v2026.9.9 user-message reader uses a loose schema, and its transcript type permits arbitrary __openclaw metadata. The reader blob was unavailable locally and was inspected through GitHub REST instead. (src/config/sessions/session-entry-codec.ts:24, bcfc88812a35)
  • Mixed persisted session and full serialized prefix coverage: The regression drives prompt submission, actual SQLite persistence, steering, another turn, and reopen through the Responses serializer. It compares complete serialized prefixes and verifies that the unprojected steering turn remains unprojected; the transport stream is mocked. (src/agents/embedded-agent-runner/run/attempt-prompt-submit.projections.test.ts:142, 43bfb358d9db)
  • Compatibility response and accepted limitation: The area owner’s PR body and follow-up comment document unchanged SQL migrations and installer behavior, legacy replay for absent fields, and loss of enriched-prefix continuity on older readers without loss of original transcript content. No stable-release installer upgrade is claimed. Captured body identity: fa506860517290449e553ea8b30ca15b9b3d2d0cc329bde28bd1c0e67bacfdd7.

PR surface

Source +218, Tests +593, Docs +29, Other 0. Total +840 across 24 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 11 449 231 +218
Tests 10 804 211 +593
Docs 2 30 1 +29
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 2 0
Total 24 1285 445 +840

Review metrics

Metric Value Why it matters
Production versus test growth Production net +218 lines; tests net +592 lines Production growth implements durable capture and bounded diagnostics while removing temporary restoration; tests cover persistence and serialized-prefix contracts.
Stored contract 1 optional versioned transcript field; 0 SQL migrations Compatibility is governed by additive message metadata rather than a database-version change.

Labels

Label changes:

  • add P2: Repeated history rewrites reduce cache reuse and can invalidate prefix-bound reasoning in affected sessions.
  • add merge-risk: 🚨 compatibility: The accepted optional stored field preserves original content, but older readers cannot maintain its enriched-prefix continuity.
  • 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: Repeated history rewrites reduce cache reuse and can invalidate prefix-bound reasoning in affected sessions.
  • merge-risk: 🚨 compatibility: The accepted optional stored field preserves original content, but older readers cannot maintain its enriched-prefix continuity.
  • 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.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-09T19:54:19.603Z sha 5a469ba :: blocked before merge. :: none

Reviewed October 9, 2026, 4:31 PM ET / 20:31 UTC (Revision 2).

@steipete

steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Landed as 6461c186e5180cbdfdbbfea1d5b9e85e1d6fe3fb under the standing inherited-CI exception. Final-head CI completed with only build-artifacts and its aggregate gate red; all selected test/type/lint checks and security contexts passed. The actual CI merge's asset source trees match its main parent. The native helper's automatic remote branch-deletion push conflicts with this lane's push restriction, so landing used the explicitly authorized REST fallback pinned to the exact 40-character head SHA.

The lane-caused CI fixture failure is fixed in 43bfb358d9db758d695de340a604d60adb53d189: each preprocessing variant now owns a separate attempt, and the assertions inspect normalized model messages rather than projection metadata. All 34 tests across the four sibling files passed on AWS cbx_a8c69f3a06ed, together with the affected type graph, lint, and fresh independent review.

The other failure is independently reproduced on untouched main 9b46148b26804c213e23b11e3974278128ab1d2b: pnpm build:ci-artifacts passes, then pnpm plugins:assets:check exits 1 solely for extensions/workboard/openclaw.plugin.json. This is the same failure as the original build-artifacts job. The baseline's generated asset paths change from e7967afe… to eea70db0…; none of this lane's source is present in that checkout. Run: run_aecef204d7f63fa32e6e0c42bf82c981. No generated assets were copied into this branch and no CI jobs were rerun.

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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@steipete
steipete merged commit 6461c18 into main Oct 9, 2026
142 of 145 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-cache-history-rewrite-20260919 branch October 9, 2026 20:36
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
* 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
RomneyDa added a commit that referenced this pull request Oct 11, 2026
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
RomneyDa added a commit that referenced this pull request Oct 11, 2026
…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.
RomneyDa added a commit that referenced this pull request Oct 11, 2026
#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.
RomneyDa added a commit that referenced this pull request Oct 11, 2026
…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.
obviyus added a commit that referenced this pull request Oct 12, 2026
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]>
RomneyDa added a commit that referenced this pull request Oct 12, 2026
#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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…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]>
amittell added a commit to amittell/openclaw that referenced this pull request Oct 13, 2026
…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.
RomneyDa pushed a commit that referenced this pull request Oct 16, 2026
…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.
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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