Repository navigation
feat(plugin-sdk): public transcript watermark API for context engines - #167481
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesAdds a typed public transcript delta API with reset-aware cursors and replacement identifiers for rewritten messages. Example: A context engine bootstraps after a clear reset with 40 transcript messages, including two post-reset messages.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Partial Merge readiness✅ Ready for maintainer review Keep this PR open: it provides a useful supported transcript API, the prior findings are addressed, and no new actionable defect was found. Exact-head CI is still running. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherContext-engine plugins pass session identity, paging limits, and an optional cursor to the SDK; existing transcript owners return bounded message pages or explicit discontinuity results. flowchart LR
Plugin[Context engine plugin] --> SDK[Public transcript SDK]
SDK --> Owner[Existing transcript read owner]
Owner --> SQL[SQLite or PostgreSQL projection]
Owner --> Memory[Incognito memory actor]
SQL --> Page[Message page or reset result]
Memory --> Page
Page --> Plugin
Technical reviewBest possible solution: Land this supported cursor slice through the normal gates while retaining final reset-admission work in its existing follow-up. Do we have a high-confidence way to reproduce the issue? This is an API feature: current-main source confirms the missing supported reset-window contract, and supplied Gateway and SDK output demonstrates the intended behavior. Is this the best way to solve the issue? The narrow facade reuses existing transcript owners, preserves default cursor behavior, and records replacement identity at the rewrite producer. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 38f411fbe793. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +359, Tests +769, Docs +146, Config +4, Other +23. Total +1301 across 40 files. Added test files: 3. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (9 earlier review cycles; latest 8 shown)
Reviewed October 17, 2026, 10:45 AM ET / 14:45 UTC (Revision 10). |
Live proof on
|
| Read | Entries |
|---|---|
start: "transcript" |
40 (pre-reset history plus the post-reset exchange) |
start: "reset-window" |
2 (post-reset user + assistant only) |
Persisted rewrite of the post-reset assistant entry 0854899e:
A. reset-window, maxMessages=1 (cursor C_mid): user 4dcd79b0
B. reset-window drain (cursor C_end): user 4dcd79b0, assistant 0854899e
C. rewriteTranscriptEntriesInSessionManager(0854899e): changed=true rewrittenEntries=1
D. resume C_mid: assistant 23f603fb supersedes=0854899e "after-reset (rewritten in place)"
E. resume C_end: <reset reason=anchor_missing>
F. drain from E's fresh cursor: user 4dcd79b0, assistant 23f603fb supersedes=0854899e
G. start=transcript fresh read: 40 entries
- D: a cursor whose anchor survives the rewrite receives the re-appended copy with
supersedesEntryIdset. - E–F: a cursor anchored on the rewritten entry gets
anchor_missing. The fresh cursor that comes with that reset still starts at the reset window (2 entries, not 40), which is the precedence fix ine395e45.
Plugin consumption. I fed step F's entries and Lossless's stored rows for the post-reset conversation into Lossless's real resync planner (planResync). It plans one restamp, of stored row seq 12 (0854899e) to the new id, with unimportedBeforeAnchor=0. So the rewrite is observed as an id restamp with no duplicate row.
What this live run also showed. Lossless 1c77bf8 still reads through session-transcript-runtime without start: "reset-window". On the live /reset, its first bootstrap ran before the post-reset message became visible, and it re-imported all 10 pre-reset rows into the new conversation (origin=fresh visible=38 postResetStart=0 imported=10). The host side was correct: chat.history and the reset-window read both return only the post-reset window. Filed as Martian-Engineering/lossless-claw#1244. Adopting this subpath and reset-window (Martian-Engineering/lossless-claw#1240) fixes it outright.
Not covered live:
- Preserve-tail resets (idle, daily, stale cron) need session expiry, which I could not trigger without changing the shared Gateway config. They are covered only by
context-engine-transcript-runtime.test.ts. - A rewrite inside the running Gateway itself. This deployment does not reach a rewrite producer for a throwaway session. Code-mode
execexternalizes large tool results, so overflow truncation never fires, and Lossless owns compaction, so server-endpoint compaction is skipped. That is why step C ran on the copy.
Tests at this head: src/plugin-sdk/context-engine-transcript-runtime.test.ts (2 passed) and src/agents/embedded-agent-runner/transcript-rewrite-plugin-reads.test.ts (3 passed).
CI: checks-node-changed-2 failed only extensions/qa-lab/src/gateway-kill-restart-send.e2e.test.ts (SIGKILL recovery timeout after 120 s), which does not touch this change. I re-ran the failed job.
e395e45 to
212b3a5
Compare
212b3a5 to
2a59327
Compare
…sessions Incognito sessions read and rewrite through the memory actor, which the reset-window and supersedesEntryId changes had not reached. A fresh reset-window drain returned pre-reset history and later resets never reported session_reset, and incognito rewrites returned copies without the entry id they replace. Move the memory visible-delta reader into its own module and give it the SQLite core's contract: reset-window cursors record the latest reset, drain its retained tail with paired tool results, then the suffix, and rank a newer reset first. Share the reset-boundary comparison through the cursor owner. Carry supersedesEntryId through the memory append envelope and the returned rewrite entries.
Incognito parity in
|
| Test | Without the fix | With the fix |
|---|---|---|
Reset-window drain with a retained tool pair and an orphan, then a later reset reporting session_reset |
Fails: 8 ids, including pre-reset history, instead of 5 | Passes |
Repeated incognito rewrites chain supersedesEntryId across both readers |
Fails: markers missing | Passes |
The whole file passes 12/12 in 17 s wall time.
Other checks
- 19 files across the memory actor, the incognito session manager, the SDK reset-window, visible-delta, rewrite-read and cursor suites: 175 passed.
- The PostgreSQL retained-tail test still passes on local PostgreSQL 17.11.
tsgo:coreand theagents-sessionstest typecheck graph pass.- The SQLite dialect, line-cap and SQLite worker ratchets pass.
- Type-aware oxlint and oxfmt pass.
- The max-lines suppression ratchet reports only main's existing
ui/files.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Wrapper inventory in
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Related: #160613
What Problem This Solves
Context-engine plugins can't track the transcript incrementally through a supported API. The watermark reader lives in a private-local SDK subpath with no types and no compatibility promise. When a transcript rewrite re-issues entry ids, plugins can't tell which new entry replaced which old one.
User Impact
Context-engine plugins get a typed public subpath,
openclaw/plugin-sdk/context-engine-transcript-runtime. It provides a visible-message delta reader with an opaque cursor, documented reset reasons, an optional start at the latest same-session reset, andsupersedesEntryIdon messages that a rewrite re-appended. Lossless Claw uses this to replace per-turn full-transcript reconciliation, which measured 0.3–28.5 s per turn on large sessions, with millisecond delta reads (lossless-claw#1238). Existing callers see no change: default cursors and results are unchanged.Why This Change Was Made
supersedesEntryId:rewriteTranscriptEntries) now record the replaced entry id in each re-appended message envelope. Repeated rewrites form a chain.event_jsonlikeappendMode, and has no schema or index change. Plain appends never carry it.Public subpath: it exports only five things:
readSessionTranscriptVisibleMessageDelta;SessionTranscriptMessageEntry;SessionTranscriptReadFenceError.The params accept only
agentId,sessionId,sessionKeyandstorePath, plus the cursor and page limits.session-transcript-runtimestays private-local and gains no exports.start: "reset-window":preserve-tailreset, then everything after the reset row.session_reset. Only reset-window cursors produce it."transcript"start encodes cursors exactly as before.session_reset, notanchor_missingorgeneration_mismatch. Cursors record the reset row's entry id, so resets can be compared across generation rotations.SDK surface budget: raised by one entry point, five exports and one callable export over current
main(153 / 3666 / 2128). A maintainer approved this.Not covered: exposing the reset entry's id. This change also does not close the plugin-side race in #160613, where a reset can land between a read and the plugin's commit.
session_resetmakes that race detectable but does not close it.Evidence
src/plugin-sdk/context-engine-transcript-runtime.test.tsimports through the public subpath against a real SQLite store. It covers:preserve-tailreset with paired and orphan tool results, drained across pages;clearreset producingsession_resetwhile a default cursor continues.transcript-rewrite.test.tschecks that every re-appended message carriessupersedesEntryIdequal to its source id, in both the visible read and the delta page. It checks that plain appends do not, and that a second rewrite after reload chains to the first copies. The test fails with the production change reverted.main(2026-10-11):pnpm tsgo:core: clean.pnpm plugin-sdk:check-exportsandpnpm plugin-sdk:surface:check: pass.git diff --check: clean.origin/main: 160 affected exports. Apart from the new subpath, every change is the optionalsupersedesEntryIdfield onSessionMessageEntry, reached through types that reference it. Acknowledgement digest:b903fecb(against merge base599d0dec55e, after rebasing onto currentmain).check:database-worker-ratchetreports no growth in main-thread call sites. The max-lines, line-cap, assertion-safety, timeout-race and mock-export ratchets all pass.e395e4550dd".mainand not caused by this PR. Each fails identically on cleanmainat599d0dec55e, reproduced locally:test/e2e/qa-lab/runtime/node-worker-launch-wire.e2e.test.ts: transcript persistence is rejected withSessionActorStaleVersionError([Bug]: node-worker-launch-wire e2e fails on main: transcript persistence rejected with SessionActorStaleVersionError #169095).extensions/memory-core/src/tools.local-fallback.test.ts: keyword-fallback results are returned where a disabled, empty result is expected ([Bug]: memory-core tools.local-fallback test fails on main (keyword fallback returned where disabled result expected) #169096).extensions/qa-lab/src/gateway-kill-restart-send.e2e.test.ts: SIGKILL recovery aborts ([Bug]: Restart recovery after SIGKILL aborts and tombstones the orphaned session (gateway-kill-restart-send e2e fails on main) #167602), when its shard runs.extensions/discord/src/subagent-hooks.test.ts: three tests time out ([Bug]: discord subagent-hooks tests time out on main #169103).test/e2e/qa-lab/runtime/telegram-model-picker-prepared-gateway.e2e.test.ts: two tests fail ([Bug]: telegram-model-picker-prepared-gateway e2e fails on main #169104).extensions/codex/src/app-server/run-attempt.steering.test.ts: five tests fail with hook timeouts ([Bug]: codex run-attempt.steering tests fail on main (hook timeouts) #169105).Rebase onto
main(d59a9b8ec84, 2026-10-17)The branch was 5,422 commits behind. Conflicts were resolved as follows:
transcript-rewrite.test.ts: kept main's refactored file. ThesupersedesEntryIdtest still lives intranscript-rewrite-plugin-reads.test.ts.Main moved underneath the branch in two places, and two commits on top adapt to that:
fix(sessions): carry reset entry ids through prepared projection facts. Main now prepareslatestIndexedResetfrom actor receipts without SQL (perf(sessions): reuse actor projection receipts for history reads #170127, perf(sessions): keep append receipts independent of transcript length #172462). Without this change, reset-window cursors read through that path would lose the reset entry id they compare across generation rotations, and core typecheck would fail. The facts type is now the single owner of the reset shape.refactor(sessions): move closed reset intervals into a sibling module.session-accessor.sqlite-reset-window.tsreached 706 counted lines against its 700-line cap.resolveClosedResetInterval, which has one consumer (history-interval), moved unchanged tosession-accessor.sqlite-closed-reset-interval.tstogether with its worker-only classification. The visible delta core's private range, metadata and payload helpers are registered under its existing T3 inventory evidence. The SQLite worker ratchet reports no T1 growth.Evidence on
9215147d9d9pnpm test src/plugin-sdk/context-engine-transcript-runtime.test.ts src/agents/embedded-agent-runner/transcript-rewrite-plugin-reads.test.ts src/agents/embedded-agent-runner/transcript-rewrite.test.ts: 20 passed; 49 s wall time.Ten sibling suites covering the visible delta, the cursor, projection facts, the bounded session manager and the transcript runtime: 100 passed; 65 s wall time.
Six history-read suites covering closed intervals (history events, legacy history events, reset-boundary race, reset header, query plan, input visibility): 31 passed; 21 s wall time.
pnpm check:changed: typecheck (core, extensions, scripts, test), the line-cap ratchet, the SQLite worker and dialect ratchets, the Plugin SDK exports and surface budget, plugin boundaries and format all pass.Upgrade compatibility from published
2026.10.4to this PR passes all 16 checks: settings, legacy transcript rows and default cursors are preserved, andsupersedesEntryIdsurvives a rewrite and a restart. See the upgrade proof.Autoreview (codex
gpt-5.6-sol, high, whole branch againstorigin/main) is clean: "patch is correct (0.98)", with no actionable findings.PostgreSQL retained tail (
b590695131b). Retained reset-window positions now go throughjsonArrayElementswith aBIGINTcast instead of SQLite'sjson_each. The new testsrc/infra/database-engine/context-engine-transcript-reset-window.postgres.test.tsfails without the fix (operator does not exist: bigint = json) and passes with it on local PostgreSQL 17.11.Incognito parity (
2676daa4bb4). The memory-actor reader now honorsstart: "reset-window": retained tail with tool pairs, then the suffix, withsession_resetranking first. Incognito rewrites now recordsupersedesEntryId. Two new public-reader tests insession-manager-incognito.test.tsfail without the fix and pass with it.These gates still fail, and each fails identically on plain
main, which this PR doesn't touch:ui/src/pages/{config,sessions}state files. The ratchet fails when main is compared against itself.infratsgo shard root count (732 > 720). That shard covers onlysrc/infraandsrc/media, and this PR changes no files there.Inherited CI failures on
81dc4eb941bRun 39031145558 had two red checks. Each failed the same way locally on the PR's exact base,
d59a9b8ec84, without this PR:checks-node-changed-16:test/e2e/qa-lab/runtime/agent-terminal-delivery.e2e.test.ts› "holds every strict NO_REPLY prefix…" failed withexpected [] to deeply equal [ 'no_reply' ].no_replysilent and updated the documented contract, but this fix(agents): honor exact NO_REPLY and drop fabricated turn-ending replies #170534 test still expected it to be delivered.e04f6acc172, which changes the lowercase case to expect silence. The whole test passes locally: 1 passed, 39 s wall time.checks-node-changed-extensions-bundle-25:extensions/memory-core/src/memory/manager.reindex-recovery.test.ts› "bounds the shadow cache before any entries reach the primary" fails withprimary cache overflow.Inherited CI failures on
e04f6acc172Run 39034822708 merged into main
42be4a448d7. Two new extension failures appeared there, and both are inherited from #175459:checks-node-changed-extensions-bundle-17:extensions/discord/src/monitor/ingress.test.ts› "does not normalize or dispatch before the durable append completes" fails withexpected "vi.fn()" to be called 1 times, but got 0 times.checks-node-changed-extensions-bundle-11:extensions/signal/src/signal-ingress.test.ts› "propagates durable append failure before dispatch scheduling" fails withpromise resolved "undefined" instead of rejecting.Locally, both files pass on this PR's head, which sits on
d59a9b8ec84(15 passed). Both fail on plain main42be4a448d7(2 failed, 13 passed), and the same split holds for #175459 itself:f966b28d497, the parent of perf(channels): claim idle ingress during durable admission #175459: 15 passed.3f76f0b62d1, "perf(channels): claim idle ingress during durable admission" (perf(channels): claim idle ingress during durable admission #175459): 2 failed.PostgreSQL conformance (infra):src/infra/database-engine/git-backup.postgres.test.tstimed out after 120 s. The next test in the file then hitGatewayStateOwnerContentionError, which is fallout from the hung test.mainruns pass this job.Both ingress failures are fixed by #175579, now merged. The memory-core
bundle-25failure is fixed by #175566, now merged.Inherited CI failure on
d8f956937aachecks-node-changed-compact-small-17:src/gateway/worker-environments/provider-crabbox-runtime-preflight.test.tsfails 15 of 25 tests.0f1c1247ca1and passes 25/25 on this PR's head, which sits ond59a9b8ec84.9513b30b786(run 39041733748).