Skip to content

fix(sessions): ground assistant transcript media refs before replay - #101866

Closed
amittell wants to merge 20 commits into
openclaw:mainfrom
amittell:fix/transcript-media-grounding-upstream
Closed

amittell wants to merge 20 commits into
openclaw:mainfrom
amittell:fix/transcript-media-grounding-upstream

Conversation

@amittell

@amittell amittell commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: in later turns, the model treats managed-media paths the assistant wrote itself as verified attachments, even when no trusted tool produced the file in that turn.

Related gaps this also closes:

  • A persisted case or alias collision such as Bash or Web_Search inherited local-media trust on replay.
  • A reused session manager kept its first run's trusted-tool set after the run's tools changed.
  • A 100,000-entry structured media array made write-time authorization and replay scan the whole array.
  • Many spellings still named a managed file without matching any root alias: dot segments, separator runs, percent escapes, NFC/NFD, a filename boundary that a later .. discards, a root whose own path contains a space, a tab, LF or CR inside a file: URL (the URL parser deletes them), an authorized path followed by /../.., ~/..., on Windows a drive path the URL parser and path.win32 read differently (~/..., a rooted path with no drive, C://..., a # or ? in a segment a later .. discards), and an authorized file: or media://inbound reference followed by a tab, LF or CR that the resolver joins onto another stored file (ok.png<TAB>.fake opens ok.png.fake).

Grounding does not rewrite user-authored text or stored transcript rows. The channel replay byte budget also applies to retained user entries, as described below.

User Impact

Later model turns no longer see fabricated managed-media paths as verified attachments. Exact trusted paths survive. Case-colliding tool results do not inherit trust. A reused manager honors both removal and restoration of trusted tools. A 100,000-element duplicate or rejected structured-media array stops after 64 raw inspections. Configured history limits above 128 keep working.

Three compatibility changes need maintainer acceptance; each is listed under "Open for maintainers" below:

  • Channel replay history is capped at 32 KiB per entry and 128 KiB per read, after grounding.
  • media://inbound:<port>/..., a bare media://inbound:/... and empty userinfo (media://@inbound/...) no longer resolve. Non-empty userinfo was already refused on main.
  • The authorization marker is additive transcript metadata, and transcripts written before it replay under the existing core-name rule.

There is no SQLite schema version, migration, config/default or Gateway protocol change. The internal recent-text read of the session-history worker and the memory actor gains an optional request flag (includeTurnMediaReferences) and an optional result field (turnMediaReferences). The public SessionRecentConversationText type is unchanged.

Why This Change Was Made

Authority stays with the production transcript writer, and verification stays with the media and replay owners. Before persisting, the guarded writer records the run's local-media authorization decision, using the trust set that the prepared agent session carries (attempt-session-runtime-prepare.ts hands it over). Before a local path enters channel history, replay checks it against that recorded decision, same-turn provenance and the managed media store.

Whether a spelling names a managed file is decided by the resolver's own parsers rather than a hand-written fold: WHATWG URL for a URI root, path.win32.normalize for a Windows drive root and path.posix.normalize for any other filesystem root, after expanding a leading ~ the way resolveUserPath does. That includes spellings that run past a token boundary. The same boundary walk decides where an authorized path ends. For file: URLs, the matcher also reads the text with tab, LF and CR deleted, as the URL parser does, keeps only the redactions that a deleted character makes possible, and maps them back to the original offsets.

Where an authorized reference is followed by a tab, LF or CR and more of the same token, text alone cannot say whether it is prose (ok.png<LF>next line) or another file (ok.png<TAB>.fake, which the URL parser reads as ok.png.fake). The scan reports the raw spellings a reader could stop at, and the media owner (findUnverifiedJoinedMediaSpellings in media-reference.ts) resolves each one through the same path that verifies same-turn references. If one opens a managed file no same-turn reference verified, the alias is redacted; a joined name the store does not hold stays prose. Probes are capped at 64 per entry, and an alias whose joined token runs past 4,096 characters or offers more than 8 places to stop is redacted. A run directly after the alias followed by / or \ is not probed unless the rest of the token, read with the run deleted, holds a .. segment: without one it is a path beneath the authorized regular file, which is how a list of paths one per line looks.

An authorized alias followed by more text is also checked for names the resolver keeps, including ok.png .fake and a directory named ok.png<TAB>. findRefusedMediaContinuations reads the alias's directory, probes plausible other names, and refuses the alias when the listing fails or the placement/probe budget runs out. The resolver-to-replay case opens the other files, verifies redaction, removes those files, and verifies the same text then survives as prose.

The shared extractor has separate limits for accepted references and for raw structured candidates, and writer authorization and replay both apply the existing 64-reference policy to each.

Channel replay (mergeSessionTranscriptContext) opts into a byte budget applied after grounding: 32 KiB per retained entry and 128 KiB per read. Provenance readers do not. session-upstream-monitor.ts compares complete prompt text, and the plugin-SDK export returns complete text, as on main.

Selection is main's single-snapshot reader, readRecentTranscriptConversationText (#169619). It runs inside one transcript snapshot in the session-history worker, the read-only reader and the memory actor, so it runs off the Gateway thread and through the actor that holds an incognito session. This PR adds an opt-in includeTurnMediaReferences option to it.

The reader walks the snapshot newest first. Each selected assistant entry collects the earlier rows of its own turn, stopping at the turn's user row and keeping at most 1,000 rows. The managed media that those rows' trusted tool results named come back on the entry as turnMediaReferences, capped by the same 64-reference policy. If the requested entries are already found but the oldest selected reply has not reached its turn start, the reader keeps paging until it does. Rows and their provenance therefore come from one snapshot. There is no page-to-page snapshot comparison, no retry and no provenance drop. Readers that do not set the option get main's result unchanged.

The collector lives in transcript-turn-media-references.ts. transcript-recent-grounding.ts keeps grounding and the replay budget. transcript.ts requests the references through main's worker-read entry and assertCurrent, then grounds. main moved the reader out of transcript.ts, which is now 639 counted lines against main's 628, and the line-cap ratchet passes.

Evidence

Shipped Gateway proof at d929366aca6c, October 26

Built d929366aca6c0a79b980ffdd2d3225e9a6925520 on macOS arm64 with Node 24.22.1, pnpm 12.15.0, pnpm install --frozen-lockfile and pnpm build qaRuntime, followed by the full rebuild scripts/run-node.mjs started on its own (dist is stale: missing_private_qa_dist); dist/index.js SHA-256 b94167b331b542449a2775ac3d44bb7ffb353bc9bfa71a51b5cf036557848254. The checkout also carried #168611's four qa-lab files, which this Gateway does not load: plugins.allow is telegram plus the fixture below. Every run had its own throwaway HOME, state and config, started node dist/index.js gateway run --bind loopback, and drove the real Telegram plugin against a loopback Bot API stub, with a loopback scripted Responses provider as the model. No credentials or external endpoints.

A run-owned, non-bundled fixture plugin registers a speech provider, so the core tts tool runs and writes under media/tool-speech-synthesis/. The same plugin registers music_generate. No music provider is configured, so that tool is the plugin's, under a core name.

Trusted path, core-named plugin and trust withdrawal. 18:32:17 to 18:36:24 UTC, 10 of 10 checks passed. Five DMs in one Telegram session:

  1. A: the model calls tts and music_generate, then replies with both managed paths and an unmanaged control path.
  2. B: a plain turn, whose provider request is checked.
  3. tools.deny: ["tts"] is written to the config file. The running Gateway accepts the revision without a restart, and turn C's provider requests carry no tts tool.
  4. C: music_generate returns the file A's tts call wrote, and the reply names it twice.
  5. The deny is removed. Turn D's requests offer tts again, and it writes a new file.
  6. E: a plain turn, whose provider request is the final check.

The channel-history block ("Conversation context") of turn E's provider request, file names shortened:

OpenClaw: AUTH-A trusted <state>/media/tool-speech-synthesis/voice---6780415c-....wav plugin [unverified media reference removed]/generated/upg-core-named.mp3 unmanaged /tmp/upg-unmanaged.txt
User: AUTH-B Reply exactly: AUTH-B
OpenClaw: AUTH-B
User: AUTH-C make a melody from the earlier note
OpenClaw: AUTH-C withdrawn [unverified media reference removed]/tool-speech-synthesis/voice---6780415c-....wav stale [unverified media reference removed]/tool-speech-synthesis/voice---6780415c-....wav
User: AUTH-D please speak another note
OpenClaw: AUTH-D restored <state>/media/tool-speech-synthesis/voice---c0eaa749-....wav

Turn B's request already showed A's line exactly as above. The persisted tool results, read from the stopped Gateway's database:

seq  6  tts             voice---6780415c-....wav        localMediaReplayAuthorized=true
seq  9  music_generate  generated/upg-core-named.mp3    localMediaReplayAuthorized=false
seq 19  music_generate  voice---6780415c-....wav        localMediaReplayAuthorized=false
seq 26  tts             voice---c0eaa749-....wav        localMediaReplayAuthorized=true

The trusted path survives the final request. The core-named plugin's path does not. A result written while tts was withdrawn gets no authority, even for the file a trusted call produced in an earlier turn, and that earlier row keeps its own authority through the withdrawal and the restoration.

The withdrawal is an operator tools.deny. The plugin tool registry refuses a plugin tool whose name collides with a core tool that exists (plugin tool name conflict), and core tts is always constructed, so I found no shipped way to keep the same tts name callable while it loses trust.

Scope: the same final request also carries the session's own earlier assistant messages as assistant input items, unchanged. Items 6 and 12 of turn E hold the A and C replies with every path as written. This PR grounds the channel-history block and does not rewrite stored transcript rows, as described above.

Upgrade from latest stable 2026.10.7. 17:56:09 to 18:09:07 UTC. npm view openclaw dist-tags reported latest: 2026.10.7 on October 26. Installed the published package into a throwaway prefix. npm 11.19.1 skipped dependency install scripts, so I ran the package's own scripts/postinstall-bundled-plugins.mjs (exit 0); koffi's native install did not run.

  1. 2026.10.7's Gateway (node openclaw.mjs gateway run) ran turn UPG-1, with the same tools plus a forged managed path (a real file in media/inbound/ that no tool produced), and turn UPG-2. Its own replay kept all four paths as written. It left agent schema 25, global schema 20, 16 transcript rows and 1 session, and did not change the config file (SHA-256 0d5596706adc before and after).
  2. With the Gateway stopped, the PR head's openclaw doctor --fix --non-interactive exited 0 and migrated agent schema 25 -> 33 and global schema 20 -> 31.
  3. The PR head's Gateway then ran UPG-3 to UPG-5 on the same state and config.
2026.10.7 replay, UPG-2 request:
  UPG-1 trusted <state>/media/tool-speech-synthesis/voice---1f778f68-....wav plugin <state>/media/generated/upg-core-named.mp3 forged <state>/media/inbound/upg-forged.png unmanaged /tmp/upg-unmanaged.txt
PR head replay of that 2026.10.7 row, UPG-3 request:
  UPG-1 trusted <state>/media/tool-speech-synthesis/voice---1f778f68-....wav plugin <state>/media/generated/upg-core-named.mp3 forged [unverified media reference removed]/inbound/upg-forged.png unmanaged /tmp/upg-unmanaged.txt
PR head replay of its own row, UPG-5 request:
  UPG-4 trusted <state>/media/tool-speech-synthesis/voice---dde2ff13-....wav plugin [unverified media reference removed]/generated/upg-core-named.mp3
  • Transcript rows: all 16 rows written by 2026.10.7 are byte-identical after the PR head ran (SHA-256 of each stored row; 33 rows now), and the session key is still there.
  • Settings: none of the 36 config values written for 2026.10.7 changed or disappeared. Doctor added 15 entries: migration and wizard stamps, agents.defaults.modelPolicy.allow, agents.entries.main, channels.telegram.accounts.proof.groupAllowFrom: ["*"], messages.queue.allowCollaborativeSteering: false, and four disabled skills.entries. The harness's whole-file equality check reports FAIL for that reason; the other 9 checks passed.
  • The 2026.10.7 row's music_generate path replays because rows without the marker fall back to the core-name rule, one of the open decisions below. The forged path is redacted because no tool result in its turn named it.

A first attempt skipped doctor. On the unmigrated 2026.10.7 state the PR head's Gateway did not answer /readyz within 600 s and logged Sessions remain unavailable. Stop the Gateway, run "openclaw doctor --fix". This PR changes nothing under src/state, and base 794d6500f382 already declares agent schema 33.

openclaw qa suite --channel-driver crabline with an equivalent scenario did not get past Gateway startup here: the QA harness's 120 s listen deadline expired twice at load average 150 to 320, so the runs above use a 600 s readiness wait instead. Both runs used harness proof-101866-gateway.mjs, SHA-256 601a1a62e0efc521cba2bfb238c11615da5fbe3393181d5c29ca9db3eeb7b41f. Raw harness logs: authority 87cb7047de800e0e2a244b6772a46a6b9723f76342211e986348fee20e5f3d17, upgrade 98ae49f309bf62a2122b7a38ad8d1fd215388e792d75d6b5302c7087f6de400d. Every Gateway exited 0 on SIGTERM.

Current-head validation

At d929366aca6c, merged main 794d6500f382311cab58f5d474a9ef248598e5f2 without rebasing. The merge keeps boundReplayBytes with main's delivered-message context flags and keeps the media-grounding probes with main's classifier declarations. Tree: aa78156fab9d9b6b0b39a17d19b130816a077b89.

The Bun history-cache failure is present on the exact CI base without this PR. The same five-file group, Node 24.22.1, Bun 1.4.4-canary.1+ef37c31de, pnpm 12.15.0, frozen installs, Linux x64, one worker:

Source Result
CI base 70b25401a70afe25917ce312aaaed15a63d212cb 66 passed, 1 failed, exit 1
CI checkout d7e301ea1098622ce6eb88e99f240a758814bb36 66 passed, 1 failed, exit 1
Current head d929366aca6c0a79b980ffdd2d3225e9a6925520 67 passed, 0 failed, exit 0

The candidate uses main's lockfile, including Vitest 5.0.5; the historical controls use 5.0.3. This comparison measures the complete integration.

Both failures are session-accessor.sqlite-history-cache.test.ts:157, expected [] to have a length of 1 but got +0, matching job 120036958812. All tracked source blobs matched the selected trees before running. Main already contains the cache's retained pressure channel in ca3f7433914a; this merge carries that fix, with no separate cache patch.

Current-head focused results: 276 passed, 1 skipped across 14 files. The groups were the CI configuration group (67), grounding and turn provenance (137), media helpers/comparison (25), channel context (9), and guarded-writer/session preparation (38). The skipped case is normalizeMediaReferenceForComparison > matches Windows network file URLs across scheme casing, restricted by it.runIf(process.platform === "win32"). These runs were on Linux; they do not establish Windows behavior.

The space-continuation regression passes. Disabling only the continuation store probes makes that same case fail at line 310: the three ok.png .fake spellings and the tab-named directory replay verbatim instead of being redacted. The prose controls remain unchanged. Restored the production file and verified its SHA-256 returned to cc9c6abaa1dd4d7b10ac67df45633007aa81668cf5bdd36a23b1690fdf1b9970.

Reproduction of the five-file comparison, from each named tree with its frozen dependencies and the pinned Bun fork selected:

OPENCLAW_VITEST_RUNTIME=bun node scripts/run-vitest.mjs run \
  --config test/vitest/vitest.runtime-config.config.ts \
  src/config/io.load-async.test.ts \
  src/config/sessions/session-accessor.sqlite-history-cache.test.ts \
  src/config/sessions/transcript-assistant-delivery.test.ts \
  src/config/sessions/transcript-payload.test.ts \
  src/config/sessions/transcript.media-identity.test.ts \
  --maxWorkers=1 --no-file-parallelism

The other groups used the same wrapper, Bun selection, and worker flags with these files:

grounding:
  src/config/sessions/transcript-grounding.unit.test.ts
  src/config/sessions/transcript-grounding.test.ts
  src/config/sessions/transcript-turn-media-references.test.ts
media:
  src/media/media-reference.test.ts
  src/media/media-reference-comparison.test.ts
context:
  src/channels/inbound-event/session-transcript-context.runtime.test.ts
writer:
  src/agents/embedded-agent-subscribe.tools.media.test.ts
  src/agents/session-tool-result-guard.transcript-events.test.ts
  src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.ts

Oxfmt/Bun parity and scoped oxlint pass for the two conflict resolutions. Core typecheck passes: node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo. Independent source review against 794d6500f382311cab58f5d474a9ef248598e5f2 found no P0-P2 findings; it did not execute the project. All 59,191 tracked blobs matched the reviewed tree after validation and mutation restoration.

Hosted CI run 40123672646 completed: 79 successful jobs, 26 skipped, 0 failed. The CI gate job and the separate openclaw/ci-gate, openclaw/dependency-review, and openclaw/security-sensitive-review commit statuses are successful. At 19:31 UTC on October 24, all 18 workflows on this head were terminal: 16 successful and 2 skipped; all 161 check-runs were terminal: 105 successful, 55 skipped and 1 neutral.

The preflight checked out merge 4efc146f92780a56604d80565c3b2d6d04c0a35b, tree b80612f193e208ad5870d32a6ba4aa3fa47be2e4, with parents main 820c30a3a0101abd0a739406a116a95e1e99429d and this head. That base is newer than the main commit used for the focused local validation. The complete CI log archive is 9,191,036 bytes, 944 members, CRC verified, SHA-256 1239613479a3242f4fe70f099216bc946bb3008b975e6535ad7819999832832b. In job 120960718369, Bun passed SQLite transcript history cache > reuses recent payloads with fresh result ownership until append or rewrite and readRecentUserAssistantTextForSession grounding > refuses an authorized reference a space continues onto another stored file.

The compatibility decisions below remain open. Current security requirements are evaluated by the security-review workflow.

Earlier measurements, on the older heads named below:

Head 0ff83d79b6c on an M4 Pro, with each file run on its own. The head merges main e69e34001fb5 at 62dd1ca78a2, then moves selection onto main's single-snapshot reader. Dependencies come from the frozen lockfile, installed with pnpm 12.10.1 because the local install of the pinned 12.11.1 was broken.

transcript-grounding.unit.test.ts                        113 passed
transcript-grounding.test.ts                              15 passed
transcript-turn-media-references.test.ts                   5 passed
transcript.test.ts                                        44 passed
transcript.media-identity.test.ts                         14 passed
embedded-agent-subscribe.tools.media.test.ts               7 passed
embedded-agent-subscribe.tools.test.ts                    27 passed
attempt-session-runtime-prepare.test.ts                   11 passed
session-transcript-context.runtime.test.ts                 9 passed
media-reference.test.ts                                   12 passed
media-reference-comparison.test.ts                        13 passed, 1 skipped
session-upstream-monitor.test.ts                          25 passed
session-tool-result-guard.transcript-events.test.ts       18 passed
session-transcript-memory-read.test.ts                     8 passed
transcript.memory.test.ts                                  3 passed
session-history-readonly-reader.test.ts                   17 passed
session-transcript-readers.test.ts                        11 passed
session-transcript-readers.markers.test.ts                10 passed
                                                         362 passed, 0 failed

openclaw-agent-execution-incognito.history.test.ts is gone from main (#170712). The memory-actor recent-text route is covered by session-transcript-memory-read.test.ts, transcript.memory.test.ts and the actor case in transcript-turn-media-references.test.ts. The last five rows are main's tests of the three reader backends.

transcript-grounding.test.ts > "bounds every retained entry and the complete replay prompt after grounding" failed 2 of 9 whole-file runs before the merge with database is locked while opening the state database (openNativeStateDatabase -> requireRollbackJournalMode); on the merge it passed 6 of 6 at load average 9 to 23. The new probe never runs in that test and reads no SQLite. Not changed. On the redesign, the file passed 5 of 5 whole-file runs. Two of those runs came before the type-only lint fixes.

embedded-agent-subscribe.tools.media.test.ts holds only this PR's cases now: main deleted the rest of that file (#158721, #160205, #166619). Its fixture now sets an empty runtime config snapshot. main's session-history worker reads the prepared runtime config and throws Runtime config is not prepared without one.

Fail-before, pass-after, run with the new tests against the production files from before each fix:

  • 1b81028477e (tab/LF/CR in file: URLs): the 6 new matcher cases and the resolver-to-replay test fail. Without the fix, the three file: spellings replay verbatim even though resolveInboundMediaReference opens each of them to the real media/inbound/x.png. A prose-boundary control test passes both before and after. Mutating any one of the fix's three rules fails exactly the test that pins it.

  • b77491c03dd (authorized path run-on and ~): 7 new matcher cases fail, as does a resolver-to-replay test for two ~/... spellings that resolveInboundMediaReference opens with OPENCLAW_HOME set to a temp dir. A control test for ~ spellings that reach no root passes both before and after.

  • 9faa6bd04d4 (Windows drive roots): with transcript-grounding.ts from the merge commit, 11 of the 111 unit cases fail. Ten win32 spellings replay verbatim and C:/Users/Bot/.openclaw/%6dedia/x.png is redacted. Injected Windows groundings only; not run on Windows.

  • 0ff83d79b6c (provenance inside the single-snapshot reader). Each mutation was applied to the head and reverted. They were measured on the redesign before two type-only lint fixes.

    • Grounding skipped in transcript-recent-grounding.ts: 13 of 15 transcript-grounding.test.ts cases fail, and so do both channel-context cases in embedded-agent-subscribe.tools.media.test.ts.
    • Grounding kept, but transcript.ts not requesting includeTurnMediaReferences: the 6 grounding cases and 2 channel-context cases that need a trusted reference to survive fail.
    • The reader stopping at the limit instead of reading on to the oldest reply's turn start: 5 cases fail, 2 in transcript-turn-media-references.test.ts and 3 in transcript-grounding.test.ts.

    The two page-read tests from ef8a251fe9a are replaced:

    • "never lends a later same-turn result to a reply at a page boundary, before or after a write" reads the 251-row session, appends a turn and reads again.
    • "reads past the requested limit for a reply's provenance on an earlier page" puts the reply's image result 300 rows back in its own turn.
  • 2d2b895f508 (joined names): with transcript-grounding.ts, transcript-recent-grounding.ts and media-reference.ts from a2e8eca58cf, the resolver-to-replay test "refuses an authorized reference the resolver joins onto another stored file" fails in 5 of 5 runs (the spellings replay verbatim although resolveInboundMediaReference opens ok.png.fake for each), and the unit case "keeps prose boundaries around file URLs and reports the names a resolver could join" fails. Both pass on the head; ok.png<LF>next line and a one-per-line path list stay verbatim.

Gates at 0ff83d79b6c, --base e69e34001fb5. These pass:

  • the line-cap, assertion-safety, SQLite worker, test-timeout-race and mock-export ratchets;
  • config:docs:check, plugins:inventory:check and the deprecated-API guard;
  • the history-reader import boundaries (session-history-read.imports.test.ts) and the PR-wrapper inventory (eager-import-closure.test.ts);
  • tsgo core, src tests and root tests;
  • oxfmt, and the repo's oxlint wrapper on the 22 changed files.

Two fail identically on e69e34001fb5 alone, in files this PR does not touch: the max-lines ratchet (new suppressions in three ui/ files) and the env-var budget (456 OPENCLAW_* names against 452). Not rerun at this head: the core tsgo graph boundary and the dead-export scan.

Grounding cost is linear in input size. An M4 Pro at load average 17 to 22, before the tab/LF/CR fix:

input                                            b061bff34cc   4a374d027f5
128 KiB token of comma-separated managed paths     3589.7 ms        8.8 ms
512 KiB token, same shape                         58704.0 ms       29.2 ms
128 KiB prose, no managed root                       13.5 ms       12.5 ms
128 KiB "/a /../" flood                              15.3 ms      120.0 ms
512 KiB "/a /../" flood                          not measured      491.0 ms
128 KiB "/managed/state/x y/../z " flood             13.9 ms      103.6 ms

The tab/LF/CR scan runs only when the text holds both file: and one of those characters. At 1b81028477e, on a MacBook Air at load average 50 to 60 (read the ratios, not the absolute times), a file:///managed/state/x y/../me<TAB>dia/x flood took 229/457/961/2182 ms before and 653/1281/2572/5211 ms after, at 64/128/256/512 KiB.

The extent flood test now redacts 16,000 comma-separated paths in one token (474 KiB) with a 10 s timeout as the assertion: 41-43 ms at the head, and a timeout at 46,351 ms with reanchorToken forced to discard the extent.

The older in-process runtime run at 6876d240238, the v2026.9.9 upgrade transcript and the earlier "no Gateway run" note are superseded by the shipped Gateway proof above.

Not run locally: the full suite.

Open for maintainers:

  • Replay budgets: 32 KiB per entry and 128 KiB per read, channel replay only.
  • Persisted authorization marker: additive. Transcripts without it replay under the existing core-name rule.
  • Recent-text reader option and PR-wrapper inventory: includeTurnMediaReferences on main's recent-text reader is off by default, and other readers' results are unchanged. The reader now eagerly imports transcript-turn-media-references.ts, which imports embedded-agent-tool-media.ts. So scripts/pr-lib/wrapper-components.txt gains 18 files: the collector, plus the 17 files of its eager import closure that the inventory lacked. One of those, media-grounding-limits.ts, was already missing before the redesign: at the merge commit 62dd1ca78a2 the inventory check failed on exactly that file, because this PR's media-reference.ts imports it.
  • Port-bearing inbound URIs: parseInboundMediaUri now refuses media://inbound:<port>/..., a bare media://inbound:/... and empty userinfo. Non-empty userinfo was already refused on main. All in-tree writers use media://inbound/${...}, so only a hand-written or model-written form like these in an existing transcript stops resolving. No real transcripts were scanned.
  • Worker runs: src/worker/embedded-agent.runtime.ts guards without a trust set. A worker's tool results persist without the marker and replay under the core-name rule, as all tool results do on main. Not changed here.
  • The previously open space-continuation and tab-named-directory cases now have the resolver-to-replay proof above. The Windows-only comparison case was skipped on Linux; no Windows execution is claimed.
  • Merge with current main: git merge-tree of d929366aca6c with main a48aabc669b65212a088714985995d70b3363095 (October 26, 18:27 UTC) conflicts in attempt-session-runtime-prepare.test.ts, transcript-recent-text.ts and media-reference.ts. Not resolved in this update.

Copilot AI review requested due to automatic review settings July 7, 2026 19:47
@clawsweeper

clawsweeper Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR records tool-result media trust and removes unverified managed-media references from assistant text replayed into channel history.

Example: An assistant names media://inbound/forged.png without a trusted tool producing that reference in its turn.

  • Before: Later channel history repeats media://inbound/forged.png verbatim.
  • After: Channel history contains [unverified media reference removed]/forged.png.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Substantial production-path evidence supports the implementation; the unresolved product choices and latest-stable compatibility gate prevent a merge-ready assessment.
Proof confidence 🐚 platinum hermit (4/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Assistant-invented managed-media references gain misleading reinforcement when repeated in later channel history.
Reason: The scoped channel-history repair has demonstrated value, but its additional compatibility policies remain explicitly unapproved; ordinary assistant transcript input remains unchanged by design.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: this PR contains useful replay-grounding work absent from current main, with no new correctness finding established; its compatibility policies still need an owner decision.

Priority: P2
Reviewed head: d929366aca6c0a79b980ffdd2d3225e9a6925520
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should channel replay adopt the 32 KiB entry and 128 KiB read limits, preserve core-name trust for marker-free transcripts, and reject previously accepted port-bearing or empty-userinfo inbound URIs?
  • Recommendation: Approve the documented policies: Accept bounded channel history, the historical core-name fallback, and canonical inbound authorities while preserving stored transcript bytes.
  • Why: These deliberately change historical replay and accepted reference behavior; contributor explanations and passing tests establish the implementation but cannot approve the product tradeoffs.

Before merge

  • Add real behavior proof - Exact-head Gateway output through the real Telegram plugin exercises the changed writer-to-channel-history path with trusted tts, a core-named plugin, trust withdrawal, and restoration. This satisfies the previously requested authority-chain scenario. The supplied upgrade preserves 2026.10.7 rows and settings, but latest-stable v2026.10.8 compatibility is not demonstrated. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Complete next step - The author should resolve GitHub's reported conflicts, preserve the snapshot and media-owner contracts, and run affected checks on the resolved head.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Add a Gateway upgrade from latest stable v2026.10.8 showing existing settings and transcript rows preserved; redact credentials, IPs, phone numbers, and non-public endpoints.
Agent review details

How this fits together

The transcript writer records run-local media trust; the snapshot reader collects earlier same-turn references, and the media-store owner verifies them before channel history enters a model request.

flowchart LR
  A[Tool results] --> B[Guarded transcript writer]
  B --> C[Session transcript]
  C --> D[Snapshot reader]
  D --> E[Replay grounding]
  F[Managed media store] --> E
  E --> G[Channel history]
  G --> H[Model request]
Loading

Technical review

Best possible solution:

Keep trust decisions in the existing transcript writer, collect same-turn facts in the snapshot reader, and ground replay through the media owner under an approved compatibility policy.

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

Current-main source returns assistant references without grounding, and the contributor supplies before/after production-boundary output; this read-only review executed no target code.

Is this the best way to solve the issue?

The implementation uses the existing writer, snapshot reader, and media resolver owners and preserves canonical transcript bytes. The substantial parser machinery addresses demonstrated resolver spellings; the independent history limits and URI compatibility changes require owner acceptance.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Single-snapshot recent conversation selection keeps the original intent (681c9c8: Keep recent context consistent while concurrent appends change transcript pagination.)
  • Run-owned transcript preparation keeps the original intent (1929324: Release completed prompt history while accepted writes retain their original run context.)
  • Structured media extraction keeps the original intent (303191d: Preserve generated attachment names, dimensions, and durations alongside accepted URLs.)
  • Inbound URI parsing changes intended behavior with a stated reason (fc62052: Allow canonical inbound references to resolve through the media store and existing access policy; this PR explains why it narrows accepted authorities.)
  • Channel replay text limits changes intended behavior with a stated reason (681c9c8: The existing reader selects complete requested text; this PR explicitly introduces channel-only byte limits while keeping provenance reads complete.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +1708, Tests +2593, Other +18. Total +4319 across 23 files. Added test files: 4.

View PR surface stats
Area Files Added Removed Net
Source 15 1734 26 +1708
Tests 7 2593 0 +2593
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 18 0 +18
Total 23 4345 26 +4319

Review metrics

Metric Value Why it matters
Production versus test growth Production +1,734/-26 lines; tests +2,593/-0 lines. Most production growth implements path spelling and continuation handling; the regressions cover distinct resolver, authority, pagination, and persistence boundaries.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs misleading media references in later channel context without evidence of an urgent runtime outage.
  • merge-risk: 🚨 compatibility: The patch intentionally shortens sufficiently large channel histories and rejects previously accepted inbound URI forms.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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 execution lanes are retired.

History

Review history (50 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-23T17:19:37.441Z sha 039c256 :: needs real behavior proof before merge. :: [P2] Check deleted characters through the authorized URL's full extent | [P2] Normalize home-relative candidates against Windows drive roots
  • reviewed 2026-10-09T22:34:27.743Z sha a2e8eca :: needs real behavior proof before merge. :: [P2] Check deleted characters through the authorized URL's full extent
  • reviewed 2026-10-10T13:42:57.045Z sha ef8a251 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-10T14:18:08.731Z sha ef8a251 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-16T15:55:11.010Z sha ef8a251 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-21T23:23:49.849Z sha ffc77f1 :: needs real behavior proof before merge. :: [P2] Probe space-continued references before retaining an authorized alias
  • reviewed 2026-10-26T15:26:36.961Z sha d929366 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-27T19:39:36.343Z sha d929366 :: needs real behavior proof before merge. :: none

Reviewed October 27, 2026, 3:51 PM ET / 19:51 UTC (Revision 51).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a grounding pass for assistant-authored transcript text before it is replayed into later session context, redacting absolute managed-media paths that do not resolve to real media on disk. The goal is to prevent fabricated “attachment” references from becoming self-reinforcing during prompt replay, while leaving user-authored text untouched by this redaction step.

Changes:

  • Add redactUngroundedMediaRefs to deterministically redact unverified managed-media absolute paths in assistant text.
  • Wire grounding into parseRecentConversationText (assistant branch only) so replay readers inherit the behavior.
  • Add unit + reader-level tests covering redaction behavior and the reported incident shape.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.

File Description
src/config/sessions/transcript.ts Grounds assistant-visible text via redactUngroundedMediaRefs during transcript replay parsing.
src/config/sessions/transcript-grounding.ts Implements managed-media path token detection + existence probing + redaction placeholder.
src/config/sessions/transcript-grounding.test.ts Adds unit cases for token handling and a regression test for replay grounding behavior.

Comment thread src/config/sessions/transcript.ts Resolved
@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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 7, 2026
@amittell

amittell commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up: the "not yet fleet-deployed" gap in the proof section is now closed.

Live proof on a production host (macOS gateway, installed build at 2cb19c7ae6): replayed the incident shape through the deployed package's public surface (dist/plugin-sdk/session-store-runtime.js → readRecentUserAssistantTextForSession) with a real session store, real transcript file, and real files on disk:

Input assistant turn:

IMAGE:<mediaDir>/whats-app-image-2026-07-06-909898742550877-194.jpg That is a serious setup, Ally. Real one at <mediaDir>/inbound/real.jpg.

Output after replay through the installed dist:

IMAGE:[unverified media reference removed] That is a serious setup, Ally. Real one at <mediaDir>/inbound/real.jpg.

The fabricated ref is redacted, the verified real-file ref and all prose survive. Both production gateways have been running this build with Telegram serving normally.

Also verified the sibling transcript readers are deliberately out of scope, not missed: readTailAssistantTextFromSessionTranscript (src/agents/command/attempt-execution.ts:357) is a transcript-mirror equality check where rewriting text would break dedupe semantics, and readLatestAssistantTextFromSessionTranscript (src/auto-reply/reply/commands-tts.ts) feeds TTS of what the assistant actually said. Grounding applies only where assistant text re-enters prompt context.

@amittell
amittell force-pushed the fix/transcript-media-grounding-upstream branch from f1858cf to 89e387d Compare July 8, 2026 04:26
@amittell

amittell commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Since the last review pass:

  • Rebased onto current main (827f2c4); new head is 89e387dbc9 (single commit, clean rebase).
  • Addressed all four Copilot findings: the default grounding probe now requires a regular file via statSync(..., { throwIfNoEntry: false })?.isFile() matching the media store contract (src/config/sessions/transcript-grounding.ts:39-46); matching is Windows-separator-aware (both-separator bail at :99, path.win32.isAbsolute guard at :105, backslash-normalized root/text matching at :57/:113 with authored spelling preserved for redaction and fs probes); the imprecise "never rewritten" comment in src/config/sessions/transcript.ts:202 is tightened to "only whitespace-trimmed, never redacted".
  • Tests: 4 new unit cases (real-directory default probe, backslash spelling, mixed separators, authored-spelling probe). Local run at 89e387dbc9: node scripts/run-vitest.mjs run src/config/sessions/transcript-grounding.test.ts src/config/sessions/transcript.test.ts -> 2 files, 65/65 passed; oxlint and oxfmt clean on the three changed files.
  • The "needs real behavior proof" gap was closed by the live production replay proof posted 2026-07-07 (fix(sessions): ground assistant transcript media refs before replay #101866 (comment)); please re-score with that evidence in scope.

@clawsweeper

clawsweeper Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@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. 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 8, 2026
@amittell
amittell force-pushed the fix/transcript-media-grounding-upstream branch from 89e387d to 83fc457 Compare July 9, 2026 00:25
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Jul 9, 2026
@amittell

amittell commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 83fc4572f39d46ca14dd49290c3ff122177b0c8b (rebased onto current main @ d3ff48c51f). Changes in this push:

Symlink probe fix (the open P2/P1 finding). src/config/sessions/transcript-grounding.ts:43 now uses lstatSync(candidate, { throwIfNoEntry: false })?.isFile() instead of statSync, so a symlink at the referenced path is redacted instead of being laundered through its target. The macOS /var -> /private/var twin handling is unaffected: that symlink is an intermediate directory component, and lstat only skips following the final component. The probe stays inside the existing try/catch, preserving the no-throw guarantee. Regression test added at src/config/sessions/transcript-grounding.test.ts:68 ("treats a symlink at the referenced path as ungrounded"): a real file plus a symlink pointing at it inside a mkdtemp media dir, no injected probe -- the symlink token is redacted, the real-file token is preserved.

CI fix for checks-node-compact-small-3. The failure in that lane was caused by this PR, not flake: src/commands/agents.delete.test.ts imports ../config/sessions.js, and this PR's transcript.ts -> transcript-grounding.ts -> media/store.js -> store.runtime.js chain pulls ../infra/fs-safe.js into that graph. The test's vi.mock("../infra/fs-safe.js", ...) replaced the whole module with only movePathToTrash, so store.runtime.ts's readLocalFileSafely re-export had no binding and the file failed at module load. Fixed by making the mock partial (src/commands/agents.delete.test.ts:52): spread await importOriginal() and override only movePathToTrash, so isPathInside/readLocalFileSafely keep their real bindings.

Local proof (hydrated worktree, node scripts/run-vitest.mjs run src/config/sessions/transcript-grounding.test.ts src/config/sessions/transcript.test.ts src/commands/agents.delete.test.ts):

 Test Files  2 passed (2)
      Tests  66 passed (66)
...
 Test Files  1 passed (1)
      Tests  11 passed (11)

[test] passed 2 Vitest shards in 12.14s

oxlint and oxfmt --check clean on the three touched files.

@amittell

amittell commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Jul 9, 2026
@amittell
amittell force-pushed the fix/transcript-media-grounding-upstream branch from 83fc457 to 082f9ce Compare July 10, 2026 01:43
@amittell

Copy link
Copy Markdown
Contributor Author

Addressed the ClawSweeper P2 (path traversal) and rebased onto latest main.

Containment fix — src/config/sessions/transcript-grounding.ts:135-136

Previously a token that starts with the managed-media root but uses .. to resolve outside the dir (e.g. <mediaDir>/../../etc/passwd) was preserved as "grounded" whenever exists() found a real file at the traversed path. The probe walked out of the sandbox, so a fabricated ref pointing at any real host file laundered itself back into replayed prompts.

Now, before trusting the probe, the matched token is verified to stay contained in the managed media root via isPathInside(root, normalizedToken) (re-exported from @openclaw/fs-safe, the same containment helper media/store.ts uses). An escaping token is redacted like any other ungrounded ref. The existing lstat regular-file check and the POSIX//private-twin/win32 handling are unchanged.

Regression tests — src/config/sessions/transcript-grounding.test.ts

  • <mediaDir>/../../etc/passwd with exists: () => true -> redacted (traversal cannot be laundered by an existing file).
  • Real on-disk variant: <mediaDir>/../secret.jpg resolving to a real sibling file via the default lstat probe -> redacted.
  • In-dir token <mediaDir>/inbound/./photo.jpg that stays contained after normalization -> preserved (guards against over-redaction).

Both escaping tests fail on the pre-fix code and pass after; full file green.

Proof: node scripts/run-vitest.mjs run src/config/sessions/transcript-grounding.test.ts src/config/sessions/transcript.test.ts -> 2 files, 69 tests passed. oxlint clean on both changed files.

New head SHA: 082f9ce64cf691e0d56205d212d648dbc6e049ba

@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@amittell
amittell force-pushed the fix/transcript-media-grounding-upstream branch 2 times, most recently from f5997a6 to 596d44d Compare July 11, 2026 02:13
…removed

Main's test lifecycle now fails a file whose agent or state database
outlives its fixture directory, and openclaw#163045 moved the active-stats read
this branch's snapshot test used into a test-support module. After the
merge that left three of the branch's own suites red:

- transcript-grounding.test.ts and
  session-accessor.sqlite-conversation-snapshot.test.ts passed their cases
  and then failed teardown with "Agent database close failed" (ENOENT on
  the removed state/openclaw.sqlite). Both now await the agent and state
  database closes in afterEach, as
  session-accessor.sqlite-active-events.test.ts does.
- The snapshot test called readSessionTranscriptActiveStats, which no
  longer exists; it reads the same count through readActiveTranscriptStats.
- embedded-agent-subscribe.tools.media.test.ts closed its databases
  synchronously. Its case stores now sit under one suite root from
  useSessionStoreTempDirs, drained once before removal (openclaw#161871).

No assertion changes.
@amittell

amittell commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged main (6b2afbfe981) into the branch, GitHub had it CONFLICTING, and fixed the Windows P2 from revision 43. Three commits on top of 039c25673c7, no rebase.

258d3a1ff36 merge. Six files conflicted:

9faa6bd04d4 Windows drive roots (revision-43 P2, "Normalize home-relative candidates against Windows drive roots"). Confirmed, and it was wider than ~. A drive root took the URL branch of the fold because C: parses as a scheme, while the resolver reads a drive path with path.win32 (maybeLocalPathFromSource -> path.isAbsolute / path.resolve, or resolveUserPath for ~). Every place those two parsers disagree was a spelling that opens a file under C:\Users\Bot\.openclaw\media and replayed verbatim:

~/.openclaw/./media/x.png                       "~" expanded for filesystem roots only
/Users/Bot/.openclaw/media/x.png, \Users\...    absolute on the current drive for path.win32
C://Users/Bot/.openclaw/media/x.png             a slash run for path.win32, an authority for URL
C:\Users\Bot\.openclaw\x#\..\media\x.png        "#" and "?" are path bytes for path.win32

So I took the review's suggestion literally: a drive root is now a filesystem root that keeps its drive apart, and candidates fold through path.win32.normalize after ~ expands onto homeDir and a rooted drive-less path takes the root's drive. Two consequences worth knowing. A drive-less path that mirrors the root on another drive is redacted too, since the current drive isn't knowable lexically. And a percent-escape in a drive path is no longer decoded, which the resolver never did: C:/Users/Bot/.openclaw/%6dedia/x.png used to be redacted and now stays.

With transcript-grounding.ts put back to the merge commit, 11 of the 111 unit cases fail: the three ~ spellings and seven other win32 spellings replay verbatim, and the %6dedia control is redacted. Injected Windows groundings only, as the existing drive-letter cases are. I have not run this on Windows.

a2e8eca58cf test lifecycle. After the merge three of this PR's own suites were red for reasons on main's side. transcript-grounding.test.ts and session-accessor.sqlite-conversation-snapshot.test.ts passed their cases and then failed teardown with Agent database close failed (ENOENT on the removed state/openclaw.sqlite); both now await the agent and state database closes in afterEach, as session-accessor.sqlite-active-events.test.ts does. The snapshot test called readSessionTranscriptActiveStats, which #163045 moved to a test-support module as readActiveTranscriptStats. embedded-agent-subscribe.tools.media.test.ts now keeps its case stores under one useSessionStoreTempDirs root (#161871). No assertion changes.

Measured at a2e8eca58cf on an M4 Pro:

transcript-grounding.unit.test.ts                        111 passed
transcript-grounding.test.ts                              12 passed
session-accessor.sqlite-conversation-snapshot.test.ts      2 passed
transcript.test.ts                                        48 passed
transcript.media-identity.test.ts                         14 passed
embedded-agent-subscribe.tools.media.test.ts               7 passed
embedded-agent-subscribe.tools.test.ts                    29 passed
attempt-session-runtime-prepare.test.ts                    9 passed
session-transcript-context.runtime.test.ts                 9 passed
media-reference.test.ts                                   12 passed
session-upstream-monitor.test.ts                          26 passed
session-tool-result-guard.transcript-events.test.ts       17 passed
                                                         296 passed, 0 failed
check:changed --base 6b2afbfe981                          all gates pass

check:changed includes typecheck core and core tests, oxlint, format, dead exports, import cycles, and the line-cap, max-lines, assertion-safety, mock-export and SQLite worker ratchets (no T1 call-count growth). Test cost for the changed unit file: pnpm test src/config/sessions/transcript-grounding.unit.test.ts --maxWorkers=1, 111 tests, 9.9 s Vitest duration, 12.8 s wall.

ok.png<TAB>.fake (revision-43 P2, "Check deleted characters through the authorized URL's full extent"). Unchanged, and still on purpose. An authorized reference ends at a token boundary, and the tab is treated the way the space already is: ok.png .fake is kept too, and the URL parser reads that one as ok.png%20.fake, also a different file. The parser deletes LF the same way it deletes a tab, so no lexical rule separates ok.png<TAB>.fake from ok.png<LF>next line, and the second is every authorized file: URL that ends a line. What separates them is whether ok.png.fake exists in the store. The store writer names files <name>---<uuid><ext> or <uuid><ext> (buildSavedMediaId, src/media/store.ts), so a file whose name is an authorized name plus a suffix needs a second save with the same UUID. I checked the store writer, not every writer into the media directory. If you want it closed regardless, the choice I'd make is a store probe for the joined name at replay time, not a lexical rule. Say so and I'll add it.

The red jobs at 039c25673c7 (run of 2026-09-23 15:16 UTC) are all in files this PR doesn't touch, and all pass on main 6b2afbfe981 and on the merged head:

                                                               main 6b2afbfe981   merged
check-test-types-core-4      TS2741, session-row-placement-
                             projection.lifecycle.test.ts      0 errors           0 errors
changed-extensions-bundle-35 telegram bot-message-context.
                             dm-session.test.ts                7 passed           7 passed
changed-extensions-bundle-29 openai speech-runtime.contract    19 passed          19 passed
compact-large-30             subagent-registry.test.ts         102 passed         102 passed
compact-large-37             cron.webchat-delivery.test.ts     7 passed           7 passed

The type error came in with #156221 (f6a3ed707c2, 15:14 UTC), was in the merge ref this run built, and 09012603235 fixed it on main at 15:52 UTC.

Still open: the three owner decisions in #101866 (comment), and the running-gateway authority proof. Neither changed in this push.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…s onto another file

With only file:///<state>/media/inbound/ok.png authorized, replay kept
"file:///<state>/media/inbound/ok.png<TAB>.fake" unchanged. The media
resolver hands that spelling to the URL parser, which deletes the tab, and
opens inbound/ok.png.fake. The deleted-character scan only looked inside
the managed-root range, so it never saw a tab after the authorized alias,
and the store read contract accepts any safe single-component id, so the
writer's UUID names do not rule the joined name out.

The lexical scan cannot decide this alone: "ok.png<LF>next line" is the
same shape and is ordinary prose. So the scan now reports, for every
authorized alias followed by tab, LF or CR and more of the same token, the
raw spellings a reader could stop at (each later run, the boundary, and
before trailing punctuation). The replay owner hands them to a new media
owner probe, findUnverifiedJoinedMediaSpellings, which resolves each one
through the same path prepareManagedMediaGrounding uses (now shared as
verifiedManagedPath). A spelling that opens a managed file whose real path
no authorized reference verified is refused, and replay rescans with it, so
the alias is redacted like any other unverified reference. A joined name
the store does not hold stays prose. Probes are capped at
MAX_GROUNDING_PATHS per entry, and an alias whose joined token runs past
MAX_GROUNDING_TOKEN_CHARS or offers more than eight places to stop is
refused; all three fail closed, and the last keeps the scan linear, since
every spelling is a string the probe set hashes in full. A run directly
after the alias followed by "/" or "\" is not probed unless the rest of
the token, read with the run deleted, holds a ".." segment: without one
it names a path beneath the authorized file, which is a regular file, and
it is how a list of paths one per line looks. With one ("/.<LF>./x" reads
"/../x") it is probed like any other spelling. A scan with no joined
spelling costs nothing new.

Tested: tab, LF and CR after a file: alias, a line break inside a ".."
that climbs out of the authorized file, and a tab after a media://inbound
alias (the URL parser deletes it there too, and
parseInboundMediaUri then yields ok.png.fake). Because the probe hands the
raw slice to the resolver, a percent-escaped continuation, punctuation
between the alias and the run, and a plain or ~ path alias followed by a
character the resolver keeps in the name go through the same check; those
are not separately tested. Not covered: a name that continues across a
boundary the resolver keeps, such as a space or a quote ("ok.png .fake"),
whose extent prose cannot bound, and a directory named the authorized file
name plus a trailing tab or line break, which a plain path keeps.

The regression stores ok.png and ok.png.fake, authorizes ok.png through a
trusted same-turn tool result, checks that resolveInboundMediaReference
opens ok.png.fake for each spelling, and replays the session.
…ng String and RegExp calls

Review rev 44 flagged two assertions that pin implementation choices.

"does not rescan prefixes when a bounded prompt has no managed root" spied
on String.prototype.slice and required zero calls for a 32 KiB prompt of
"x". With the count gone, what is left is that a prompt without a root
comes back unchanged, which every benign case in this file already shows,
so the test is removed. The source comment that cited it now states the
property without naming a test.

"keeps one token's extent across the redactions inside it" summed every
RegExp.prototype.test call and every sliced character in the process and
compared them with 16 times the token length. It now redacts 16,000
comma-separated managed paths in one token (about 464 KiB) and lets the
10 s timeout be the assertion, as the other floods in this file do. At
4,000 paths on an M4 Pro the case took 11 to 15 ms, and 2,885 ms with
reanchorToken forced to discard the extent, which is the regression it
guards; 4,000 was too few for the timeout to catch it, so the flood is
four times longer.
Conflict in src/config/sessions/transcript.ts with main's openclaw#167952
(320d57b). Main moved readRecentUserAssistantTextForSession off
synchronous main-thread reads: the session entry is now read in a worker
(withSessionEntryReadOnlyInWorker), the store path can be an incognito
actor's, every page comes from readSessionTranscriptBoundedMessageTailPageAsync,
and readRestoredSessionTranscript takes the owner's assertCurrent. This
branch had replaced the same read with a synchronous one-snapshot selection
(readSessionTranscriptConversationSnapshot) followed by async grounding.

Resolution: main's entry read, scope and assertCurrent stay as they are.
The selection keeps this branch's contract (newest entries first, each
assistant entry with the media from its own turn's earlier tool results,
at most 1,000 rows of turn and 64 references) but now runs in
selectRecentConversationRows on main's async tail-page reader, so it works
off the Gateway thread and for incognito sessions. Offsets count from the
end, so a write between pages would shift the next page onto rows already
read and could lend a later tool result to an earlier reply; each page's
projection snapshot (generation, indexed seq, boundary) must match the
first, and a mismatch restarts the read. The third read that sees a
change keeps paging, as replay did before, and returns every row with no
references, so replay redacts their managed media rather than shortening
the window. Grounding still runs after the cold-storage retry.

The synchronous readSessionTranscriptConversationSnapshot, its type, its
session-accessor re-export and its accessor test are removed; those three
accessor files are main's again. Two new regressions land rows between
pages: one write, where a reply's later tool result must not become its
provenance, and a write in each of three reads, where the last read
re-reads that tool result into the reply's turn and must still drop it
and still reach the oldest row.
@amittell

amittell commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Pushed 2d2b895f508 and c3e783e8e15 on top of a2e8eca58cf, then ef8a251fe9a, a merge of main at c30579e85091. The P2 is fixed, both test notes are done, and the v2026.9.9 upgrade run passes. The plugin trust handoff is still not proven at a production boundary; I'm leaving that harness as a follow-up, and what it takes is under its heading.

Merge. main's #167952 rewrote the same read this PR changes in src/config/sessions/transcript.ts: the session entry is now read in a worker, the store path can be an incognito actor's, every page comes from readSessionTranscriptBoundedMessageTailPageAsync, and the cold-storage retry takes the owner's assertCurrent. My branch had a synchronous one-snapshot selection there. I kept all of main's side and moved the selection onto main's async page reader (selectRecentConversationRows in transcript-recent-grounding.ts), with the same contract: newest entries first, each reply with the media from its own turn's earlier tool results, at most 1,000 rows of turn and 64 references. Offsets count from the end, so a write between pages would shift the next page onto rows already read and could hand a later tool result to an earlier reply. Each page's projection snapshot must match the first, and a mismatch restarts the read. If the third read also sees a change, it keeps paging, as replay did before, and returns every row with no references, so replay redacts their managed media rather than shortening the window. The synchronous readSessionTranscriptConversationSnapshot and its accessor test are gone; those three accessor files are main's again. Two regressions land writes between pages through a pass-through of the reader: with the restart disabled the first fails (expected [ 'start', …(2) ] to deeply equal [ 'start', …(3) ]), and with the last read breaking early or keeping references the second fails. main's incognito history suite (openclaw-agent-execution-incognito.history.test.ts, 51 tests) passes on the merge.

Check deleted characters through the authorized URL's full extent (P2). Fixed in 2d2b895f508. This is the finding from b77491c03dd, 039c25673c7 and rev 43. I kept the behavior on purpose and argued in #101866 (comment) that the store writer's UUID names make ok.png.fake unreachable. That does not hold: resolveMediaRelativePath (src/media/store.ts:83) accepts any non-empty id without /, \, NUL or .., so anything that writes into media/ can create the joined name. The unit case that pinned ${granted}\t.fake as kept was pinning the bug.

The fix is the store probe I offered in that comment. Text alone cannot tell ok.png<TAB>.fake from ok.png<LF>next line, so the scan no longer decides. After an authorized alias followed by tab, LF or CR and more of the same token, it records the raw spellings a reader could stop at (each later run, the token boundary, and before trailing punctuation). Replay hands those to a new media-owner function, findUnverifiedJoinedMediaSpellings, which resolves each one through the same path that verifies same-turn references (now shared as verifiedManagedPath). If a spelling opens a managed file whose real path no same-turn reference verified, replay rescans and the alias is redacted like any other unverified reference. A joined name the store does not hold stays prose. Probes are capped at 64 per entry, and an alias whose joined token runs past 4,096 characters or offers more than 8 places to stop is redacted; all three fail closed. A run right after the alias followed by / or \ is not probed unless the rest of the token, read with the run deleted, holds a .. segment: without one it is a path beneath the authorized regular file, which is what a list of paths one per line looks like. Text with no authorized alias followed by tab, LF or CR does no new work.

Regression, transcript-grounding.test.ts > "refuses an authorized reference the resolver joins onto another stored file". It stores ok.png and ok.png.fake, authorizes ok.png through a trusted same-turn tool result, asserts that resolveInboundMediaReference opens ok.png.fake for each of five spellings, then replays the session. On an M4 Pro, on main 657f09fea181 merged with this branch, before the merge above:

                                          a2e8eca58cf prod files    head
resolver-to-replay regression             failed, 5 of 5 runs       passed, 1.2-1.9 s
  expected 'file:///private/var/folders/...' to be '[unverified media reference removed]/...'
unit "reports the names a resolver
  could join"                             failed                    passed, 14-17 ms
  expected [] to deeply equal [ Array(1) ]

The "before" column restores transcript-grounding.ts, transcript-recent-grounding.ts and media-reference.ts from a2e8eca58cf; main has not touched those three files since 6b2afbfe981. It passes on the merge too (1.7 s). Cost on the merge, pnpm test <file> --maxWorkers=1, wall on a shared M4: 61.4 s at load average 17 for the 15-test integration file, of which the new P2 regression is 1.2 to 1.9 s and each page-write regression about 1.9 s, and 7.0 to 9.4 s for the 113-case unit file, of which the new and changed cases take 59 ms, 43 of it the extent flood.

Siblings of the same shape:

  • Covered and tested: tab, LF and CR after a file: alias, and a tab after a media://inbound alias (the URL parser deletes it there too, and parseInboundMediaUri then yields ok.png.fake). The prose control ok.png<LF>next line stays verbatim in the same replay, and so does a list of paths one per line.
  • Covered and tested in the same regression: a line break inside the .. itself (ok.png<LF>/.<LF>./ok.png.fake), which the run-on check cannot see and the probe catches.
  • Already refused, now with tests for one ..: a run followed by /.. (ok.png<LF>/../ok.png.fake for file: and media://inbound, ok.png<TAB>/../ok.png.fake for a plain path). The path is read across the boundary when a later .. discards it, so the alias is never accepted.
  • Covered by the same probe, not separately tested: a percent-escaped continuation, punctuation between the alias and the run (ok.png.<TAB>.fake), and a plain or ~ path alias, where the resolver keeps the tab in the file name.
  • Not covered: a name that continues across a boundary the resolver keeps in the name, such as a space, quote, NBSP, VT or FF (ok.png .fake); WHATWG deletes only tab, LF and CR. Also a directory named the authorized file name plus a trailing tab or line break, which only a plain path can reach.
  • Other callers of the span check: none. invalidateUngroundedMediaPrefixes has one production caller, groundRecentConversationRows.

Resolve security concern: Actual plugin trust handoff remains unproven. Not closed by this push, and I'm leaving it as a follow-up rather than growing this PR. No link needs a live channel, but the last one, mergeSessionTranscriptContext into the model request, cannot be reached through any harness that exists today:

  • QA Channel, which the credential-free QA Lab gateway harness drives, never sets sessionTranscript when it builds the inbound context (extensions/qa-channel/src/inbound.ts:424; its historyLimit key is declared in config-schema.ts:45 and read nowhere), so channel history is never merged for it. The Gateway agent RPC does not merge it either; the only caller is src/channels/turn/execution.ts:234.
  • QA Lab with Crabline Telegram would reach it: the real Telegram plugin sets sessionTranscript for DMs and groups (extensions/telegram/src/bot-message-context.session.ts:641). What is missing is the model side. The mock OpenAI provider cannot be told to call a named tool with chosen arguments; each behavior is code keyed on a prompt marker in extensions/qa-lab/src/providers/mock-openai/server.ts.

So the proof needs a mock-provider behavior that calls exec to print a managed path, calls a non-bundled fixture plugin's tool registered under a core name that is absent from the run (music_generate with no music provider configured), and replies with both paths; the fixture plugin; and a scenario that sends two Telegram DMs and checks the second turn's history in the provider's /debug/requests. That is QA Lab code outside this PR's files, so I'd do it as its own PR. Until it exists, coverage is the in-process tests named in the body, plus the head-written rows in the upgrade run below.

Add data-model compatibility proof. Done on an M4 Pro, with an isolated state dir and no Gateway. Phase 1 ran from the v2026.9.9 tag's source (bcfc88812a35, tree checked equal to the tag's), not the npm tarball. That release's guarded SessionManager wrote one session: an exec result, a Bash result and a music_generate result, each with one managed path; an assistant line naming those three paths, a forged path and a joined file: URL (exact.png<TAB>.fake, with exact.png.fake in the store); and a second turn whose assistant text repeats exact.png with no tool result. v2026.9.9's own replay of that session returned every path verbatim, the forged one included.

Phase 2 ran on this branch merged with main 657f09fea181, in place on the same state dir, before the rule for runs followed by / and before the merge above. main moved the agent database from schema 24 to 25 after the release (#167932) and refuses the older file until Doctor migrates it, so phase 2 first ran the owner openclaw doctor --fix uses (migrateOpenClawAgentDatabaseForMaintenance under the agent maintenance lease). Paths shortened to <media>:

schema 24 -> 25
rows equal to phase 1: true (11)
session entry equal to phase 1: true (label, overrides, thinking/verbose levels, send policy)
replay of the v2026.9.9 rows:
  inspect the files
  exact <media>/inbound/exact.png; collision [unverified media reference removed]/generated/collision.png; core-named <media>/generated/core-named.png; forged [unverified media reference removed]/inbound/forged.png; joined [unverified media reference removed]/inbound/exact.png\t.fake
  and now?
  stale [unverified media reference removed]/inbound/exact.png
head run appended with only exec trusted; markers on its rows: exec true, music_generate false
release rows unchanged after the head write: true (17 rows now)
replay of the head turn:
  head exact <media>/inbound/exact.png; head core-named [unverified media reference removed]/generated/core-named.png

Marker-free rows keep the release's core-name trust, which is why music_generate survives in the old turn and not in the new one; that is the marker-free decision below. I reran both phases after the merge: phase 1 again from the tag's source, and phase 2 on the pushed head ef8a251fe9a merged with main 7b125134f386, with the same Doctor migration first. Every line of the block above came out the same, so the async page reader and the rule for runs followed by / change nothing for this session.

Tests. Both notes are addressed in c3e783e8e15. The String.prototype.slice count test is removed: without the count it only showed that a prompt without a root comes back unchanged, which the benign cases already show. The extent test drops the RegExp.prototype.test and sliced-character accounting and now redacts 16,000 comma-separated paths in one token (474 KiB) with the 10 s timeout as the assertion, like the other floods in that file. At the head it takes 41-43 ms. With reanchorToken forced to discard the extent it timed out at 46,351 ms. At the old size of 4,000 paths the same mutation took 2,885 ms, inside the timeout, which is why the flood is longer.

CI. CI on a2e8eca58cf (run 37999182564, merged into main 87d3db2aea6) is red on six checks-node-changed jobs: nine tests in six files, none in this diff. Eight of the nine fail under the same names on main's scheduled runs at 21:31Z (e05ca71024a, run 37994000596) and 22:32Z (f8239ea9470, run 37999811982):

  • src/auto-reply/reply/agent-runner-required-maintenance.pending-input.test.ts > "keeps the approved user current through preflight maintenance", one archive and two archives
  • src/gateway/server-plugin-in-process-dispatch.commit-guards.test.ts > "keeps opaque commit guards native without pinning prepared host guards", direct dispatch and tool dispatch
  • src/gateway/server.agent-artifact-apis.test.ts > "composes agent, environment, and artifact RPCs over one real Gateway"
  • src/gateway/server.visible-spawn-fallback.product-proof.test.ts > "hidden child control" and "direct agent distinct child ladder"
  • src/gateway/session-lifecycle-source-authority.test.ts > "keeps cross-store patches native and refuses a source revoked before submission"

The ninth is test/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts > "retires unphased Slack previews across tool-only assistant messages", expected [ +0, +0, 1, 2 ] to deeply equal [ +0, 1, 2 ] at line 764. It is not among those two main runs' failures, and I could not confirm they run that file. The same test failed with the same assertion at 21:42Z in run 37995100260 (743934b9de, checks-node-changed-18), on a six-file UI branch that shares no file with this PR. Of the 13 failed checks-node-changed-N jobs in the 37 failed PR runs created between 20:30Z and 23:59Z on 2026-10-09, those two are the only ones that failed this test. I did not run it locally.

Gates on ef8a251fe9a, --base c30579e85091: line-cap, max-lines, assertion-safety, SQLite worker, test-timeout-race and mock-export ratchets pass, as do config:docs:check, plugins:inventory:check, the core tsgo graph boundary, the deprecated-API guard, typecheck core and core tests, oxfmt and oxlint. Two things fail, and both fail identically on c30579e85091 alone. The env-var budget: OPENCLAW_* count 456 against a budget of 455, with the same 456 names on main and on the merge. That check sits inside the max-lines step, so check:changed stops there; I ran the gates after it one by one. The dead-export scan: tools/solid-lint/index.mjs: default, POST_ACTIVATION_INSPECTIONS_STEP in src/cli/update-cli/update-command-post-activation-inspections.ts, and two stubs in src/agents/tools/sessions-channel-fixture.test-support.ts, none in a file this PR touches.

The database is locked failure in "bounds every retained entry and the complete replay prompt after grounding", a test this PR added earlier, did not come back on the merge: 6 of 6 whole-file runs passed at load average 9 to 23. Before the merge it failed 2 of 9 whole-file runs, both thrown while opening the state database (openNativeStateDatabase -> requireRollbackJournalMode). That test has no tab, LF or CR in it, so the new probe never runs there, and the probe reads only the media store, never SQLite. I have not changed it.

The three maintainer decisions (replay budgets, marker-free trust, port-bearing URIs) are unchanged.

@amittell

Copy link
Copy Markdown
Contributor Author

CI on ef8a251fe9a (run 38056151219) is red on two jobs, and both fail the same way on main without this PR:

  • check-source-contracts: lint:tmp:session-accessor-boundary reports src/auto-reply/reply/dispatch-from-config.test-support.ts [sessionAccessorRead]: 6 legacy call site(s), baseline allows 0. This PR does not touch that file, and main's scheduled run at 13:31Z on 10-10 (7b125134f38, job 114224856770) fails with the same line.
  • checks-node-changed-extensions-bundle-1: three extensions/agentsapi/agentsapi-attempt.test.ts > "Agents API retry prompt history" cases (new run, reset binding, new budget), expected { kind: 'ok' } to deeply equal { kind: 'failed', …(2) }. On an M4 Pro, main c30579e8509 alone, this PR's base, fails the same 3 of 6 in 3 of 3 runs, and so does this head. A failure in that file also shows in 24 other PR runs on 12 other branches on 10-10. main has since updated that expectation in test(agentsapi): expect rescoped retries after steering to succeed #168569 (aec6e7a56eb, "expect rescoped retries after steering to succeed").

No change to the branch for either.

- src/agents/session-tool-result-guard-wrapper.ts: keep upstream's prompt-image metadata and tool-result truncation imports alongside the local-media replay authorization import.
- src/config/sessions/transcript.ts: take upstream's recent-text types from transcript-recent-text.ts, declare boundReplayBytes on the grounded read options, and keep the replay grounding read on top of the moved extractor.
- src/config/sessions/transcript-recent-text.ts: export extractRecentConversationText for the grounding selector.
- src/agents/embedded-agent-subscribe.tools.media.test.ts: prepare the runtime config the session history worker now requires.
…shot reader

Upstream now selects recent conversation text inside one transcript snapshot in the
worker kernel, the read-only reader and the memory actor. Replace the replay
grounding's own paging selector (snapshot compare, three retries, provenance drop)
with an opt-in includeTurnMediaReferences option on that reader: each selected
assistant entry carries the managed media its own turn's trusted tool results
named, collected from the same snapshot, and reading continues past the limit
until the oldest selected reply reaches its turn start (at most 1,000 rows).

Callers that do not request references get upstream's result unchanged. The
recent-text result type carries the optional field through the worker and actor
protocols, transcript.ts requests it and grounds assistant text after the read,
and the public SessionRecentConversationText shape is unchanged.

Add the reference collector's eager imports to the PR wrapper inventory.
Merges upstream main at b90b2cf.

- scripts/pr-lib/wrapper-components.txt: keep main's new inventory entries and this branch's 18 reference-collector imports; no entry is duplicated.
- src/agents/embedded-agent-tool-media.ts: keep main's pushUniqueMessagingMediaUrl return value (openclaw#175022). collectStructuredMedia keeps this branch's capped, acceptMediaUrl-gated push, which already keys attachment metadata by the normalized accepted URL.
- src/agents/session-tool-result-guard-wrapper.ts: main's openclaw#176804 gives each run its own transcript context and rebuilds it when a guarded manager is reused. The local-media trust set now lives on that context: the trustedLocalMediaToolNames option seeds it, setTrustedLocalMediaToolNames replaces it on the current context, and a reuse that passes no set inherits the previous context's, so a same-run helper keeps the run's trust and an accepted write keeps the set of the context it captured.
@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Merged main b90b2cfb40ec in ffc77f1613d8 to clear three conflicts:

  • session-tool-result-guard-wrapper.ts: main changed setTranscriptRunContext to take one options object, so trustedLocalMediaToolNames is now a GuardOptions field. setTrustedLocalMediaToolNames stays.
  • embedded-agent-tool-media.ts: collectStructuredMedia keeps this PR's accepted-URL check (the maxMediaUrls cap and acceptMediaUrl) where main now calls pushUniqueMessagingMediaUrl, which only normalizes and adds. The helper's other caller, collectMessagingMediaUrlsFromRecord, is unchanged.
  • scripts/pr-lib/wrapper-components.txt: both sides' entries kept.

Focused tests at the merge on an M4 Pro: 25 files, 403 passed, 1 skipped, 0 failed. CI on this head passes typecheck, lint and the baseline ratchets. Three jobs fail:

  • checks-ui-e2e (1/9) and (4/9): e2e cases in boot-module-boundaries, sidebar-outbox, chat-mobile-bubble-margin and session-management.sidebar. This PR touches no ui/ file. The two boot-module-boundaries cases fail the same way on fix(telegram): state the current message body inside the Current-message carrier block #151099, which shares no files with this PR, and main's last two hourly runs (39679539559, 39671240295) each failed a different checks-ui-e2e shard.
  • checks-node-changed-compact-small-5: session-accessor.sqlite-history-cache.test.ts > reuses recent payloads with fresh result ownership until append fails in the Bun shard (expected [] to have a length of 1 but got +0). Under Node it passes 14 of 14 at this merge and at b90b2cfb40ec, two runs each. I have not run it under Bun.

@clawsweeper

clawsweeper Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

Merges upstream main at 3cd9bdd. No textual conflicts.

- src/media/media-reference.ts: main moved relativePathEscapesBase to infra/path-guards as relativePathEscapesRoot and dropped this file's node:fs/promises import (openclaw#180175). The grounding helpers this branch added still call both, so they now use relativePathEscapesRoot and the import is restored.
…onto another file

An authorized alias ends at a space, quote or bracket, but the resolver keeps
those characters in a file name. With ok.png authorized and ok.png .fake also
stored, file:///.../inbound/ok.png .fake replayed unchanged while the resolver
opens ok.png .fake for it; the bare path and media://inbound/ok.png .fake did
the same. A plain path also keeps a tab before "/", so .../ok.png<TAB>/x.png
names a file in a directory called "ok.png<TAB>".

The scan now records each authorized alias it keeps. For each one that more
text follows, the media owner (findRefusedMediaContinuations) lists the alias's
directory once. If a stored name there extends the alias's file name, each place
a reader could end the name is placed with the resolver's own parsers, and a
spelling that lands on another listed name, or outside the directory, is
resolved the way same-turn references are verified. If it opens a managed file
no same-turn reference verified, a rescan redacts the alias. With no extending
name nothing is probed, so prose replays as written. A failed listing, text
running more than 4,096 characters past the alias, or the 1,024-spelling and
64-probe caps refuse.

The spelling enumeration sits with the replay orchestration in
transcript-recent-grounding.ts, which keeps transcript-grounding.ts under its
700-line cap.
Keep replay byte bounds with upstream delivered-message context. Preserve
media grounding probes with the current classifier declarations.

This merge includes upstream history-cache pressure-channel retention from
openclaw#179399.
@amittell

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The P2 and the matching security finding (a space-continued reference keeping an authorized alias) are fixed in 2b72aeba12. For each kept alias that more text follows, the scan lists the alias's directory once. If a stored name extends the alias and a reader could land on that other file, the alias is redacted. With no extending name nothing is probed, and prose replays as written. A failed listing, text running more than 4,096 characters past the alias, or the 1,024-spelling and 64-probe caps all refuse.

d929366aca reconciles the branch with current main, and all 103 checks that ran pass.

Still open in this push: the authority-chain proof (a trusted path against a core-named plugin at the final channel request, then trust withdrawal) and the upgrade-from-10.5 data proof.

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@amittell

Copy link
Copy Markdown
Contributor Author

Added the authority-chain and upgrade proof to the Evidence section. Both run d929366aca6c through openclaw gateway run with the real Telegram plugin, a loopback Bot API stub and a scripted provider.

  • Trusted path, core-named plugin, withdrawal: in the final provider request's channel history, the core tts path replays as written and the plugin music_generate path is redacted. With tools.deny: ["tts"] hot-loaded, a new result naming the earlier tts file is redacted in both spellings, and after the deny is removed a new tts path replays as written. The four persisted results read true, false, false, true. 10 of 10 checks.
  • Upgrade from [email protected] (npm latest): after the PR head's openclaw doctor --fix (agent schema 25 -> 33), all 16 transcript rows 2026.10.7 wrote are byte-identical and none of the 36 config values changed. The 2026.10.7 row replays with its forged managed path redacted and its marker-free music_generate path kept under the core-name rule.

The same final request also carries the session's own earlier assistant messages with their paths unchanged. This PR grounds the channel-history block only, and the body says so.

Still open: the maintainer decisions, and main a48aabc669b6 now conflicts in 3 files.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@roboclaw-bot

Copy link
Copy Markdown
Collaborator

Thanks @amittell for the detailed investigation and proof. Closing this implementation because the narrow provider-replay failure was not reproduced on current main, and the remaining provenance policy needs a maintainer-owned design.

On 2464bd85e0bc (relevant code unchanged through 31af5fa987e7), a focused SQLite-backed probe persisted assistant text containing a deleted image path, MEDIA:, file:, an unresolved media://inbound/ reference, and a missing PDF path. Channel replay, prompt image preparation, media materialization, and Responses conversion completed without a replay error. The references remained literal text; they produced no input_image or input_file payloads, and stored transcript rows stayed unchanged. The channel suite passed 3/3 and structured-image replay passed 15/15. This is request-construction evidence, not a live-model grounding verdict.

Main separates inbound text from context in #140859. As your latest proof also notes, this PR leaves canonical earlier assistant messages unchanged. A follow-up should define handling of trusted generated media versus fabricated/missing references across both history surfaces, preserve stable conversation bytes, and begin with a final-provider-request regression demonstrating the concrete failure. The same-turn provenance cases and the related #168611 QA work are useful inputs to that follow-up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime 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. scripts Repository scripts size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: blank-template Candidate: PR template appears mostly untouched.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants