Skip to content

fix(gateway): render Claude CLI history turns once - #124543

Closed
spunzon wants to merge 4 commits into
openclaw:mainfrom
spunzon:fix/cli-aggregate-turn-duplication-123792
Closed

spunzon wants to merge 4 commits into
openclaw:mainfrom
spunzon:fix/cli-aggregate-turn-duplication-123792

Conversation

@spunzon

@spunzon spunzon commented Aug 16, 2026 •

Copy link
Copy Markdown

Closes #123792

What Problem This Solves

Claude CLI history could render one assistant turn twice in the Control UI and Android app. The rich imported turn appeared first with native tool cards. A flat persisted copy appeared below it.

Telegram delivery is not affected because it does not render merged history.

Root Cause

The CLI runner persists one synthetic assistant aggregate with api: "cli" and idempotencyKey: "cli-assistant:<runId>". The Gateway also imports the bound Claude transcript as native text and tool-call blocks.

The old merge compared one message at a time. It could not match one aggregate such as text one\n\ntext two to several imported blocks from the same turn.

Underneath that, nothing linked the two shapes at all. Only the producer sees both the flattened aggregate and the native records it came from, and it recorded no relation, which left every reader inferring one from text, provider and timing.

Fix

The producer records the relation, and the merge resolves it instead of inferring one.

  • Run settlement already resolves the native record id of a run's terminal assistant message, for resume. It now records that id, with the native session that owns it, on the aggregate it persists: cliNativeTurn: { cliSessionId, terminalRecordId }, a declared field on the transcript message contract.
  • The Gateway history owner groups imported assistant messages into turns and indexes them by the native record their last message came from.
  • An aggregate is only ever replaced by the turn it names, in the native session it names.
  • The remaining text comparison is a completeness check on that identified pair, not an identity test: a trimmed or partially imported turn no longer covers the aggregate's text, so the aggregate is kept as the durable copy.
  • Imported native blocks are unchanged, including toolcall IDs, names, and arguments.

This removes the five-minute window for aggregates, the text-and-provider keyed index, the ordered pairing and the nearest-turn selection. The resolver uses result identity so a one-for-one replacement still counts as an import.

Fail-open by construction. An aggregate that names no native turn is never replaced. That covers every record persisted before this field existed, every backend that writes no native transcript, and every run whose terminal record was not reported. The consequence is deliberate: the duplicate stays visible for history already on disk until those sessions produce new turns. Removing those would require exactly the text-and-time inference this design rejects, because no rule built from text, provider and time can tell a true duplicate from a distinct same-text turn when either history is partial.

The async snapshot reader projects any JSONL line past 1 MiB through a bounded worker. That projection rebuilds the entry from a fixed field list, so the turn-boundary facts the grouping reads have to survive it; an importer/resolver parity regression covers both readers over the same oversized transcript.

The rebase onto current main integrates #130463 and #133316, the commits that have touched cli-session-history.merge.ts since this PR's original base. #133316's prepared-facts refactor is the base — its injected identity key, its localImageMediaCounts map — and the aggregate/turn matching is layered on top, so its tests and this PR's regressions both hold. Preparing the whole import ahead of the merge loop is gated on the session actually holding a persisted aggregate, so a session without one keeps #133316's lazy, skip-on-identity path unchanged.

Evidence

Head: 8a7447409ff9c3ae3118a029116e1ab7a83fa2c6, rebased onto 43e9a3d817 (current main). The evidence below was measured on b538e9752c, the same four commits before that rebase; the rebase carried them across 409 upstream commits with no conflicts and no diff change.

Current-main reproduction, re-run on that exact base: applying this PR's regression file to 86b6ec0afa and leaving main's merge owner in place fails 11 tests.

Test Files  1 failed (1)
     Tests  11 failed | 77 passed (88)

Four of them:

  • replaces a persisted aggregate with the imported native turn blocks — expected a length of 4, got 5. The persisted aggregate remains beside the imported native blocks.
  • keeps a skill instruction row inside the turn it belongs to — expected 0 aggregates, got 1. fix(gateway): chat history shows injected skill instructions on claude-cli sessions #130269 already hides the skill instruction row on that base, and the turn still renders twice.
  • projects an oversized skill instruction row exactly as the sync reader does — expected 0 aggregates, got 1. The same defect through the async snapshot's bounded worker projection.
  • keeps the only local aggregate when the import holds a different turn with the same text — the aggregate is deleted. This is the crossed partial-history loss path, and it is the reason this PR resolves aggregates by recorded identity rather than by text and time.

Focused proof on the head:

node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts
88 passed

node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts \
  src/gateway/server-methods/chat-history-pages.test.ts \
  src/gateway/server.chat-history-cursor.test.ts \
  src/gateway/server.chat.gateway-server-chat-b.test.ts \
  src/agents/tools/embedded-gateway-stub.test.ts \
  src/agents/cli-runner/cli-run-transcript.test.ts
273 passed (3 shards)

node scripts/run-vitest.mjs ui/src/lib/chat/message-normalizer.test.ts \
  -t 'detects tool messages by toolcall content blocks'
1 passed | 85 skipped

One of those, carries the recorded native turn from the CLI producer through to the merge, drives the real producer, the real SQLite store, the real display projection, the real JSONL importer and the real resolver, so a field lost at any of those seams fails the suite instead of silently disabling the fix.

Repo checks on the head: pnpm tsgo:core and pnpm tsgo:test:src clean, run-oxlint src/gateway src/agents 0 warnings and 0 errors, the assertion-safety and max-lines ratchets OK, oxfmt --check clean. The cli-session-history.merge.ts assertion-safety baseline entry shrinks 6 → 1.

The resolver test reads a real Claude JSONL fixture. It asserts the retained imported content is exactly the text block plus { type: "toolcall", id: "toolu_1", name: "Bash", arguments: { command: "pwd" } }. The UI normalization test confirms that shape remains a native tool card.

Repeated-text benchmark with 24,000 imported turns and 24,000 aggregates. Measured on 6e25b0ae, an earlier head, and not re-run since:

Matcher Three samples Result
Previous claim forests 95–112 ms 72,000 native messages, 0 aggregates
Ordered turn pairing 80–95 ms 72,000 native messages, 0 aggregates

The Telegram fallback run, also on 6e25b0ae, recorded one deterministic direct-message turn because this history-only change is not Telegram-visible. The bot typed and returned OPENCLAW_E2E_OK; the mock provider received one POST /v1/responses.

Control UI Proof

Measured on two live Gateways, each built from source and serving its own chat.history from the same store: a copy of a production OpenClaw agent store holding 878 persisted cli-assistant:<runId> aggregates. Only the commit differs, and the Control UI is byte-identical on both sides because this PR changes 0 files under ui/.

commit
base 86b6ec0afa
head b538e9752c

The turn was produced by running a real agent turn through the head build, not by editing a store: Claude CLI 2.1.250 on the claude-cli backend, prompted for a line of text, then pwd through Bash, then a closing sentence — the two-text-blocks-around-a-tool-call shape this bug needs. The producer recorded the relation on that run:

"idempotencyKey": "cli-assistant:be40a3bc-c230-4e59-bb83-c5fa6e8846c9",
"cliNativeTurn": {
  "cliSessionId": "881503c4-fa93-4da4-b514-b94ba6afd637",
  "terminalRecordId": "5d666065-18d8-4a2c-8651-d2dfa6e330c9"
}

terminalRecordId is the turn's terminal native assistant record.

rendered rows 86b6ec0afa b538e9752c
imported native blocks 3, incl. the Bash card 3, unchanged
persisted aggregate msg:id:687e4295-… present — the turn renders twice absent
total 6 5

The durable fallback holds on that same head: a session whose aggregate predates cliNativeTurn keeps its 6,781-character aggregate, because it names no native turn. In that store 1 aggregate carries the relation and 877 do not, and none of the 877 can be replaced.

Screenshots and the full measurement are in this comment, including what the capture does not cover: that store holds no Skill turn, so the skill case stays covered by the regressions rather than by a capture.

🤖 Generated with Claude Code

@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Aug 16, 2026
@spunzon
spunzon force-pushed the fix/cli-aggregate-turn-duplication-123792 branch from 82a001f to 0b68d26 Compare August 16, 2026 11:52
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. 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 Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR records which native Claude turn a stored assistant aggregate represents and replaces covered aggregates with native history blocks.

Example: Claude emits “Checking.”, calls Bash with “pwd”, then emits “Done.”

  • Before: History displays the native text and tool card followed by a second “Checking. Done.” aggregate.
  • After: A newly linked, completely imported turn displays once with its Bash card.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-boundary repair with strong supplied behavior evidence, but accepted-message metadata and unique display media are not preserved reliably.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (screenshot): Inspected real Control UI before/after captures and the accompanying Claude CLI 2.1.250 run: the producer records the native reference, the duplicate aggregate disappears, the Bash card remains, and unlinked legacy aggregates survive; the captures precede the reviewed rebase and do not exercise the two defective cases.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Claude CLI conversations can display the same assistant turn twice, with tool cards in one copy and flattened text in the other.
Reason: The established bug and maintainer discussion justify producer-owned reconciliation; existing unlinked history deliberately remains unchanged, so the broader issue is not completely resolved.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open: it addresses a confirmed history bug with meaningful unique work, but two correctness defects still block merging.

Priority: P2
Reviewed head: aa195079ee5b70d6347ae57817432e122e722680

Before merge

  • Preserve cliNativeTurn after accepted transcript preparation (P2) - The link is attached before beforeMessageWrite and prepareAssistantTranscriptMessage run. Those contracts permit returning a replacement assistant object; applyBeforeMessageWriteToAssistant restores only idempotencyKey. A replacement preserving the same text but omitting cliNativeTurn therefore persists an unlinked aggregate, and findCoveredAggregates retains it beside the native turn. Preserve the producer-owned reference on the accepted prepared message while continuing to honor blocked writes, and extend the persistence-to-history regression with a replacing preparer. This previously reported finding remains unfixed.
  • Keep aggregates that own media absent from the imported turn (P2) - An aggregate can retain cliNativeTurn while outgoing-media finalization adds audio or another attachment to openclawDisplayContent on that exact stored row. For text “part one\n\npart two” and matching native records ending at the named terminal ID, this check declares coverage using text alone and removes the whole local row. The imported Claude messages carry no OpenClaw-managed display attachment, so reloading history loses the audio or attachment. Preserve the local row unless its non-text display content is represented, or explicitly carry that content into the replacement. Add a keyed aggregate regression through chat.history. This is a late discovery on code unchanged since the October 4 review of the same head.
  • Resolve merge risk - Before merge, port exact-turn reconciliation into current main's worker-owned history indexes while preserving bounded paging, redaction and memory-only incognito history; GitHub reports conflicts with the reviewed branch.

Findings

  • [P2] Preserve cliNativeTurn after accepted transcript preparation — src/agents/cli-runner/cli-run-transcript.ts:220
  • [P2] Keep aggregates that own media absent from the imported turn — src/gateway/cli-session-history.merge.ts:436-440

Provenance

  • Current-main history ownership: original intent not found (6968a45: Replace full-array history merging with bounded worker-owned indexes and ordinary pagination.)

Tests

  • Missing end-to-end proof: Add persistence-to-history coverage for a replacing preparer and aggregate-owned media; supplied live proof exercises ordinary text/tool reconciliation.
Agent review details

How this fits together

The CLI runner persists assistant aggregates; Gateway history combines those records with native Claude transcripts and returns display messages to chat clients.

flowchart LR
  A[Claude CLI turn] --> B[CLI runner]
  B --> C[Stored aggregate and native reference]
  A --> D[Native transcript importer]
  C --> E[Gateway history reconciliation]
  D --> E
  E --> F[Control UI and native clients]
Loading

Technical review

Best possible solution:

Preserve producer identity through accepted preparation and reconcile complete turns within the current history indexes without discarding aggregate-owned media or legacy fallback rows.

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

The producer joins assistant text while current history matching compares individual imported rows; supplied real-Gateway captures and release-specific reports independently establish the multi-block duplicate, without a new execution in this read-only review.

Is this the best way to solve the issue?

The producer-owned identity is the right repair boundary and avoids unsafe text/time inference, but this implementation remains incomplete at transcript preparation and attachment preservation and must move into current main's canonical indexes.

Full review comments:

  • [P2] Preserve cliNativeTurn after accepted transcript preparation — src/agents/cli-runner/cli-run-transcript.ts:220
    The link is attached before beforeMessageWrite and prepareAssistantTranscriptMessage run. Those contracts permit returning a replacement assistant object; applyBeforeMessageWriteToAssistant restores only idempotencyKey. A replacement preserving the same text but omitting cliNativeTurn therefore persists an unlinked aggregate, and findCoveredAggregates retains it beside the native turn. Preserve the producer-owned reference on the accepted prepared message while continuing to honor blocked writes, and extend the persistence-to-history regression with a replacing preparer. This previously reported finding remains unfixed.
    Confidence: 0.99
  • [P2] Keep aggregates that own media absent from the imported turn — src/gateway/cli-session-history.merge.ts:436-440
    An aggregate can retain cliNativeTurn while outgoing-media finalization adds audio or another attachment to openclawDisplayContent on that exact stored row. For text “part one\n\npart two” and matching native records ending at the named terminal ID, this check declares coverage using text alone and removes the whole local row. The imported Claude messages carry no OpenClaw-managed display attachment, so reloading history loses the audio or attachment. Preserve the local row unless its non-text display content is represented, or explicitly carry that content into the replacement. Add a keyed aggregate regression through chat.history. This is a late discovery on code unchanged since the October 4 review of the same head.
    Confidence: 0.98
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Integrate with the current history owner (recommended)
    Port the recorded-identity decision into the worker and memory indexes, remove the obsolete array path, and validate paging, redaction and fallback retention.
  2. Pause this branch for a coordinated repair
    Keep the useful producer-identity work available while the related history repairs converge on one implementation.

Provenance checked

  • Prepared and bounded history matching keeps the original intent (c9afcbb: Avoid repeated scans that could monopolize the Gateway while retaining identity, timestamp and ordering behavior.)
  • Prepared display and session facts keeps the original intent (a22f9d8: Reuse prepared facts and avoid repeated discovery and projection work.)
  • Exact correlation with legacy retention keeps the original intent (6f6b649: Correlate new CLI image turns using recorded identity while retaining ambiguous historical rows.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • node scripts/run-vitest.mjs src/agents/cli-runner/cli-run-transcript.test.ts
  • node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts src/gateway/cli-session-history.merge.test.ts src/gateway/cli-session-history.paging.test.ts
  • node scripts/run-vitest.mjs src/gateway/cli-session-history.claude-snapshot.test.ts src/gateway/cli-session-history.routed-prompts.test.ts
  • Verify real chat.history reload retains a managed attachment and renders a newly linked text/tool turn once.
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3089dec adds src/gateway/cli-session-history.merge.ts:9 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3089decd6309; files: src/gateway/cli-session-history.merge.ts)
  • Josh Lehman: Raw commit 6f6b649 adds src/gateway/cli-session-history.merge.ts:177 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6f6b6491fd49; files: src/gateway/cli-session-history.merge.ts)
  • Vincent Koc: Raw commit c9afcbb adds src/gateway/cli-session-history.merge.ts:13 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c9afcbb90473; files: src/gateway/cli-session-history.merge.ts)

PR surface

Source +288, Tests +915, Other 0. Total +1203 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 355 67 +288
Tests 2 915 0 +915
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 8 1271 68 +1203

Review metrics

Metric Value Why it matters
Production versus test LOC Production +355/-67, net +288; tests +915/-0; assertion baseline +1/-1. Recording identity and protecting replacement blocks serve a concrete ownership boundary, but the array-specific growth should be absorbed into current main's existing index owner during conflict resolution.
Persisted metadata addition One optional cliNativeTurn object with two string fields; zero configuration options. Existing unlinked aggregates remain readable and retained; suppression applies only after a new producer records the relation.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #123792
Summary: The canonical issue tracks native Claude fragments displayed beside a concatenated local aggregate; related PRs propose different reconciliation mechanisms and do not safely supersede this work.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A bounded Claude CLI history defect causes duplicated turns; the proposed repair also needs metadata and attachment preservation.
  • merge-risk: 🚨 session-state: The patch removes stored aggregate rows from displayed history and can hide their unique attachments; integration must also preserve current paging and fallback behavior.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦞 diamond lobster and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

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 (32 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-31T08:55:11.319Z sha b538e9752ccf3d229b8d50209a4b1dc6667c2164 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-31T12:07:25.307Z sha 8a7447409ff9c3ae3118a029116e1ab7a83fa2c6 :: needs maintainer review before merge. :: none
  • reviewed September 3, 2026, 3:05 AM ET / 07:05 UTC sha unknown :: blocked before merge. :: [P2] Preserve the native turn after transcript preparation
  • reviewed 2026-09-03T08:10:18.394Z sha 8a7447409ff9c3ae3118a029116e1ab7a83fa2c6 :: blocked before merge. :: [P2] Preserve the native turn after transcript preparation
  • reviewed 2026-09-03T08:27:46.353Z sha 8a7447409ff9c3ae3118a029116e1ab7a83fa2c6 :: blocked before merge. :: [P2] Preserve cliNativeTurn after transcript preparation
  • reviewed 2026-09-03T08:51:18.460Z sha aa19507 :: blocked before merge. :: [P2] Preserve cliNativeTurn after transcript preparation
  • reviewed 2026-10-04T04:05:37.563Z sha aa19507 :: blocked before merge. :: [P2] Preserve cliNativeTurn after transcript preparation
  • reviewed 2026-10-04T04:16:37.433Z sha aa19507 :: blocked before merge. :: [P2] Preserve cliNativeTurn after transcript preparation

Reviewed October 17, 2026, 11:14 PM ET / October 18, 2026, 03:14 UTC (Revision 33).

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 16, 2026
@spunzon

spunzon commented Aug 16, 2026

Copy link
Copy Markdown
Author

Follow-up on the last review — the outstanding items are now addressed.

[P1] Consume each imported turn only once — fixed in cae55ca. Suppression previously filtered every local message against every imported turn (.some(...)), so one imported turn could satisfy the match for several identical aggregates: two genuinely repeated replies inside the dedupe window were both dropped even when the import held only one of them. Turns are now claimed one-to-one — each aggregate takes the nearest unclaimed turn that covers it, and an aggregate left without a remaining turn is retained. Two regressions cover both directions: one imported turn against two identical aggregates keeps the unrepresented one, and an import holding both repeated turns suppresses both.

[P2] Complete next step — both halves done: the matching defect is repaired above, and the client-visible proof is attached below.

Real behavior proof — before/after Control UI screenshots are now in the PR body, captured on a real Gateway (2026.8.1-beta.2, claude-cli / claude-opus-5) where only the installed merge module differs. To be precise about what they show: they are two different turns of the same shape, not the same turn re-rendered — the "before" was captured earlier the same day, while the Gateway was still running stock code. The "after" turn was measured against the live store before capturing it (two text blocks of 636 and 1378 chars separated by tool calls, aggregate 2554 chars):

Gateway module rendered messages api: "cli" aggregates that turn renders
stock 256 115 twice
patched 255 113 once

One finding worth recording for anyone reproducing this — the duplicate only manifests on turns with two or more assistant text blocks separated by tool calls. A turn whose text is a single final block after N tool calls never duplicated: the aggregate and the native block are byte-identical, so the pre-existing per-message equality dedupe already collapsed them. That is why a casual reproduction attempt tends to come back clean; it cost me several failed attempts before the shape became obvious. It is now documented in the PR body.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 16, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 16, 2026
@spunzon

spunzon commented Aug 16, 2026

Copy link
Copy Markdown
Author

[P1] Restrict suppression to cli-assistant aggregates — fixed in 91f8dcb. The finding is correct and I had over-generalised: api: "cli" is the shape of any persisted CLI assistant reply, not only of the synthetic aggregate, so an imported turn whose text and timestamp happened to match could have deleted a real local reply.

Suppression now requires the aggregate's own contract rather than its shape:

  • persistCliTurnTranscript stamps idempotencyKey: "cli-assistant:<runId>" — src/agents/cli-runner/cli-run-transcript.ts
  • buildTranscriptAssistantMessage copies that key onto the stored message — src/config/sessions/transcript-assistant-message.ts

so the key is available at merge time and is authoritative. Any api: "cli" record without a cli-assistant: key is now retained. Regressions added for both non-aggregate cases: no idempotency key, and a foreign key (cli-hook:…).

Verified against a live store that this narrows without regressing: all 118 api: "cli" assistant records in that session carry the cli-assistant: prefix, so the same aggregates are suppressed as before — 0 duplicate turns, and no aggregate newly retained by accident.

[P2] Complete next step — done as the mechanical repair described, no product-direction change.

On "behind current main" — validation was refreshed on the exact merge head: the branch was rebased onto 6880681 locally and the focused Gateway suites pass there (174 in the merge module, 216 including the chat-history server methods and the embedded gateway stub). I did not push the rebased branch because the rebase pulls upstream commits that touch .github/workflows/, which an OAuth token without the workflow scope is not allowed to push. Say the word and I will force-push the rebased branch from a differently-scoped credential, or a maintainer can rebase it directly — edits from maintainers are enabled.

One unrelated observation while validating: pnpm check fails on config/assertion-safety-baseline.txt for src/gateway/server.auth.control-ui.pairing.suite.ts (6 < 11) on current main, untouched by this branch. Flagging it rather than fixing it here, per the contributing guidance on known main failures.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 16, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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. labels Aug 16, 2026
@spunzon
spunzon force-pushed the fix/cli-aggregate-turn-duplication-123792 branch from 91f8dcb to b1aae1f Compare August 16, 2026 15:36
@spunzon

spunzon commented Aug 16, 2026

Copy link
Copy Markdown
Author

Last remaining item closed: the branch is now rebased onto current main (b864da4) and force-pushed, so the exact merged head is what CI and reviewers evaluate. The earlier blocker was the workflow OAuth scope — the rebase carries upstream commits touching .github/workflows/ — which is now granted, so no maintainer rebase is needed.

Validation re-run on that exact head (b1aae1f):

  • pnpm vitest run src/gateway/cli-session-history.test.ts src/gateway/server-methods/chat-history src/agents/tools/embedded-gateway-stub.test.ts → 216 passed
  • oxlint on the three touched files → clean
  • tsconfig.core.json typecheck → clean

No code changes since the last review; the three commits are the same work replayed on the new base.

One pre-existing failure I am deliberately not fixing here, per the contributing guidance on known main failures: pnpm check fails the assertion-safety ratchet on src/gateway/server.auth.control-ui.pairing.suite.ts (6 < 11) on current main, and that file is untouched by this branch.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 16, 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 exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@spunzon

spunzon commented Aug 16, 2026

Copy link
Copy Markdown
Author

CI has finished on the rebased head (b1aae1f): 140 checks green, 45 skipped, and two red — check-lint and openclaw/ci-gate.

Both reduce to one infrastructure event, not a code failure. From the check-lint job log:

##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped,
or a manually started runner is canceled.
[oxlint] FAILED (exit 143)
##[error]The operation was canceled.

Exit 143 is SIGTERM — the hosted runner was reclaimed ~5 minutes into the Run check shard step, mid-oxlint. openclaw/ci-gate then fails only as the aggregate: its REQUIRED_RESULTS shows every other required entry as success or skipped, with check-shard=failure as the single cause.

For what it is worth, oxlint -c .oxlintrc.json on the three touched files is clean locally on this exact head, alongside the 216 focused Gateway tests and the tsconfig.core.json typecheck.

A re-run of that job should clear both. I cannot trigger it myself — the API returns 403: Must have admin rights to Repository for a fork contributor — so this needs a maintainer click, unless you would rather I push an empty commit to re-trigger the whole run.

@spunzon
spunzon force-pushed the fix/cli-aggregate-turn-duplication-123792 branch from b1aae1f to b64a712 Compare August 17, 2026 10:54
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Aug 28, 2026
@spunzon

spunzon commented Aug 30, 2026

Copy link
Copy Markdown
Author

Rebased onto current main, and the Control UI proof is now measured on a live Gateway instead of a mock.

The conflict

Exactly one commit on main has touched cli-session-history.merge.ts since this PR's base: #130463 (6f6b6491fd), the image cache-path fix. That was the whole conflict. It is resolved by keeping main's image logic as the base and layering the aggregate/turn matching on top, so #130463's image tests and this PR's regressions both hold — nothing from either side was dropped to make them fit.

Six commits replayed onto c0cafd7289. New head: bdbcadf644.

node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts \
  src/gateway/server-methods/chat-history-pages.test.ts \
  src/gateway/server.chat-history-cursor.test.ts \
  src/agents/tools/embedded-gateway-stub.test.ts
128 passed (2 shards), 0 failed

Real-Gateway Control UI proof

The earlier captures came from installMockGateway plus a Vite server. That objection was right, so these replace them.

Two Gateways, each built from source and serving its own chat.history from a real store: a consistent SQLite snapshot of a production OpenClaw agent store — 29 sessions bound to claude-cli, 428 persisted cli-assistant:<runId> aggregates — together with that operator's real ~/.claude/projects transcripts. Both instances read the identical snapshot. The only variable is the commit each was built from:

commit
base c0cafd7289 (current main)
head bdbcadf644 (this PR)

Same Control UI on both sides, and that is checkable rather than asserted: this PR changes 0 files under ui/, and both builds report an identical startup bundle — 8 requests, 337.7 KiB gzip, 311.3 KiB br, largest chunk 206.6 KiB.

The session shown is a real subagent run. Its local store holds two message events; the bound Claude transcript holds one assistant turn of 17 text blocks separated by 66 Bash calls. The persisted aggregate is those 17 blocks joined — 6,781 characters.

Base c0cafd7289 — the turn renders twice

cli-turn-before-main

The imported native turn ends at the top. Immediately below, the same turn again as one flat block with no tool cards at all. That second bubble is the persisted aggregate, not another native block: its data-message-id carries no msg:import: prefix, and its data-message-text is exactly 6,781 characters.

Head bdbcadf644 — once

cli-turn-after-head

Same anchor, and the thread now ends with the native turn. Read from the rendered DOM, the 6,781-character persisted bubble is present on base and absent on head; the last bubble on head is the imported 5,489-character block. Nothing else in the session changes.

Native cards survive the replacement

cli-turn-native-cards-head

The grouped Ejecutó N comandos disclosures are the imported toolcall blocks on the head build, unchanged.

The incomplete-import fallback, measured on the whole store

The replacement is deliberately narrow, and on real data that is measurable rather than argued. Applying the matcher's own pairing rule to the same snapshot — same provider, joined turn text identical to the aggregate, inside the existing five-minute window:

count
persisted cli-assistant: aggregates in the store 428
covered by an imported turn, i.e. replaced by this PR 48
retained as the durable fallback 380
sessions bound to claude-cli 29
sessions whose rendered history changes at all 15

So 11% of the aggregates are replaced and 89% survive. The session rendered above matches that scan: its covered aggregate is dropped, and an uncovered aggregate in the same session is still rendered by the head build.

Limits of this evidence, stated plainly

  • One operator's store on one machine. It is a real production store rather than a fixture, but it is a single sample.
  • The snapshot needed openclaw doctor --fix to migrate its schema before either Gateway would open it. Both Gateways then read the identical migrated snapshot, so the migration cannot account for the difference between them.
  • The screenshots are cropped to the transcript pane to keep operator session titles and account identifiers out of frame. Nothing inside the pane is altered.
  • No skill-invoking turn. You asked to see the skill case rendered once with its native cards. None of the 48 covered turns in this store invokes the Skill tool — they are Bash, Edit, Read, web_fetch, browser. I could stage one, but a staged turn is a fixture with extra steps, so I would rather report that the shape is absent from the real data available to me than present it as found evidence. The regressions in this PR still cover the harness-row contract at the importer level.

@spunzon

spunzon commented Aug 30, 2026

Copy link
Copy Markdown
Author

Rebased onto 86b6ec0afa, and the async projection gap is closed with an executed regression rather than an argument.

The fact the async projection has to carry is isMeta, not sourceToolUseID

Tracing your finding on the current base changed what it is about. #130269 (f054203aba) made parseClaudeCliHistoryEntry return null for isMeta === true at cli-session-history.claude.ts:328-335. A skill instruction body is an isMeta row, so it never reaches the projection at all — on either path — and it cannot close a turn.

That made the 23b601008888 continuation marking dead code on this base. The rebase dropped it, and sourceToolUseID is now read nowhere under src/:

$ grep -rni "sourcetooluse" src/ --include=*.ts | grep -v test
(no matches)

So the fact that must survive the bounded worker is isMeta, and both halves of the async path do carry it — the worker payload and the result normalizer.

Executed proof, both readers, real importer and real resolver

Two regressions in describe("harness rows inside a CLI turn") drive the same JSONL through readClaudeCliSessionMessages and through readChatHistoryCliSessionImportSnapshot, then hand the async projection to resolveChatHistoryWithCliSessionImports — not to mergeImportedChatHistoryMessages. The mid-turn harness row is "s".repeat(1024 * 1024 + 1), past the 1 MiB threshold, and each test asserts that before reading, so neither can silently stop exercising the worker.

The first one is load-bearing, not a tautology. Deleting isMeta from the worker payload and its normalizer, and nothing else:

$ node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts -t oversized
AssertionError: expected [ { role: 'user', …(3) }, …(4) ] to deeply equal [ { role: 'user', …(3) }, …(3) ]
Tests  1 failed | 2 passed | 82 skipped (85)

The async reader emits the harness row the sync reader drops, which is the split you predicted. Restored, the file is green.

Rebase

#133316 (a22f9d8ef7) reworked the same loop, so this was a real conflict rather than a textual one. It is resolved by keeping your shape, not mine:

  • prepareComparableMessage(message, order, externalIdentityKey) keeps the injected identity key.
  • Local image-turn correlation keeps the localImageMediaCounts map; findLocalImageMediaMatch and its splice stay deleted.
  • resolveImportedExternalIdentityKey keeps its (message: unknown) signature. Its body now reaches the metadata through asOptionalRecord, which drops four unchecked assertions — the cli-session-history.merge.ts baseline entry goes 6 → 1.

One deliberate addition on top of that: grouping needs every imported row prepared before the merge loop, so the eager pass is gated on localEntries.some((entry) => entry.isCliAggregate). A session with no persisted aggregate — every non-CLI session — keeps your lazy, skip-on-identity path untouched. That gate and the prepared ?? prepareComparableMessage(...) fallback are about 20 lines; if you would rather have the simpler unconditional flow, say so and I will drop them.

Verification on the exact head

Current-main reproduction, re-run on the new base: this PR's regression file applied to 86b6ec0afa with main's merge owner left in place fails 8 of 85, including both async regressions above — the oversized-skill one fails there for the same reason the synchronous one does, so it is not vacuous in either direction.

Tests  8 failed | 77 passed (85)
node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts
85 passed

node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts \
  src/gateway/server-methods/chat-history-pages.test.ts \
  src/gateway/server.chat-history-cursor.test.ts \
  src/gateway/server.chat.gateway-server-chat-b.test.ts \
  src/agents/tools/embedded-gateway-stub.test.ts
268 passed

pnpm tsgo:core && pnpm tsgo:test:src              clean
node scripts/run-oxlint.mjs src/gateway           0 warnings and 0 errors
check-assertion-safety-ratchet --base upstream/main   OK
check-max-lines-ratchet --base upstream/main          OK
oxfmt --check                                     clean

Counts

Production +359/-66 (net +293), tests +634/-0, baseline +1/-1.

That is up from the +782 you last measured, and the growth is accounted for: +117 test lines are the async parity regressions you asked for, and roughly +20 production lines preserve the #133316 lazy path described above. The turn grouping and the ordered pairing themselves are unchanged in substance from the version you reviewed at 23b601008888.

Still open, and I am not claiming otherwise

The canonical turn identity remains unresolved. This is still reconciliation by text, producer and time, and I agree a native session ID does not identify an individual turn. Closing it needs the producer to stamp a turn boundary the merge can consume directly, which is a change to persistCliAssistantTranscript and its stored shape rather than to this owner — I am happy to open that separately if you want it as the real repair and this treated as the interim one.

The final-head Gateway/Control UI proof you asked for is in this comment: two Gateways built from source, base and head, each serving its own chat.history from the same real store snapshot, showing the skill-invoking turn rendered once with its native cards and the incomplete-import fallback retained (428 aggregates in that store, 48 replaced, 380 kept).

This comment is not a claim of a complete safety review.

@spunzon

spunzon commented Aug 30, 2026

Copy link
Copy Markdown
Author

CI on this head is green except one shard, and it is the same flake that was red on the previous head.

checks-node-changed-extensions-config-16 fails on extensions/codex/src/app-server/run-attempt.dynamic-tools.test.ts > runCodexAppServerAttempt dynamic tools > returns a credential result after the 'default' human wait without harness cancellation with Test timed out in 120000ms, at run-attempt.dynamic-tools.test.ts:71.

The same test, in the same shard, with the same timeout, failed on head bdbcadf644:

head job result
bdbcadf644 99263580836 Test timed out in 120000ms
3dfe635ab0 99297686028 Test timed out in 120000ms

The run before the timeout is not a partial failure — the shard logs the preceding run-attempt.turn-watches.test.ts cases as passing, and the timeout is a wall-clock expiry on a human-wait test, not an assertion.

On the exact head the file is green locally:

node scripts/run-vitest.mjs extensions/codex/src/app-server/run-attempt.dynamic-tools.test.ts
Test Files  1 passed (1)
     Tests  13 passed (13)

This PR changes 0 files under extensions/; the diff is src/gateway/cli-session-history.merge.ts, src/gateway/cli-session-history.ts, src/gateway/cli-session-history.test.ts and one baseline line. I do not have rerun rights on this repository, so I cannot clear it myself — a rerun of that shard is all it should need. If it reproduces on a rerun I will treat it as real and investigate rather than assume the flake.

Everything else is passing. Final tally on this head: 205 green, 47 skipped, 0 pending, 2 red — that shard and openclaw/ci-gate, which is the aggregate reporting it. That is the same shape the previous head ended on.

@spunzon

spunzon commented Aug 31, 2026

Copy link
Copy Markdown
Author

Addressed. The P1 is real, and the answer is not a narrower heuristic — the merge no longer infers the relation at all, because the producer now records it.

Why no text rule can be made safe

The counterexample does not need repeated aggregates or an unusual window. One local aggregate, one imported turn, identical text, same provider, correct ordering — and they are different turns. I checked whether requiring global uniqueness on both sides rescues it: it does not. That shape is globally unique on both sides and still crosses. Text, provider and time establish resemblance; nothing built from them establishes identity.

The relation already existed in the data flow — it was just never persisted

Run settlement is the one point that sees both the flattened aggregate and the native records it came from. It already resolves the native record id of the run's terminal assistant message, for resume (pickCliResumeCheckpointId), and that id is exactly what the importer stamps as externalId on the imported row.

So the producer records it (cli-runner.ts:556, cli-run-transcript.ts:224) on the aggregate it persists, as a declared field on the transcript message contract (CliNativeTurnRef):

cliNativeTurn: { cliSessionId, terminalRecordId }

What the merge does now

indexImportedAssistantTurns keys imported turns by the native record their last message came from. findCoveredAggregates resolves each aggregate against the turn it names, in the native session it names. One lookup.

The text comparison that remains is not an identity test any more. It runs on an already-identified pair and asks a different question: whether the import still carries the whole turn. A trimmed or partial import no longer covers the aggregate's text, so the aggregate is kept — the fail-open fallback you asked to preserve, now on a proven pair rather than a guessed one.

Deleted: the five-minute window for aggregates, the text-and-provider keyed index, the ordered two-pointer pairing, and the nearest-turn selection.

Fail-open by construction: an aggregate that names no turn is never replaced. That is every record persisted before this existed, every backend with no native transcript, and every run whose terminal record was not reported.

The regression you asked for

keeps the only local aggregate when the import holds a different turn with the same text (test) is exactly the crossed partial-history shape: local holds one aggregate whose own turn is missing from the import, the import holds an earlier turn with identical text whose aggregate is missing locally.

Run against the previous matcher it fails, together with five other fail-open guarantees that matcher violated:

× keeps the only local aggregate when the import holds a different turn with the same text
× keeps an aggregate whose named turn was rebound to another native session
× keeps an aggregate that names no native turn
× keeps an aggregate that names a record the import does not hold
× keeps an aggregate that names a non-terminal record of the turn
× replaces a lone text turn with the native record it names
Tests  6 failed | 10 passed

All pass on this head.

End to end, not just at the seams

A field lost between the producer and the merge would turn this into a silent no-op that unit tests still pass. carries the recorded native turn from the CLI producer through to the merge drives the real producer, the real SQLite store, the real display projection, the real JSONL importer and the real resolver, and asserts the stamp survives storage and projection before asserting the replacement.

Verification on the exact head

node scripts/run-vitest.mjs src/gateway/cli-session-history.test.ts
88 passed

src/gateway/cli-session-history.test.ts + chat-history-pages + chat-history-cursor
  + gateway-server-chat-b + embedded-gateway-stub + cli-run-transcript
273 passed

pnpm tsgo:core && pnpm tsgo:test:src               clean
run-oxlint src/gateway src/agents                  0 warnings and 0 errors
assertion-safety + max-lines ratchets              OK
oxfmt --check                                      clean

Two things I want to be explicit about

The Control UI capture in the PR body no longer demonstrates this head. It showed a legacy aggregate — persisted long before this field existed — being replaced. Under identity that aggregate is now correctly left alone. The "before" half still stands as evidence that the defect is real in production history; the "after" half is superseded and I have marked it so in the body rather than leave it reading as current proof. New live evidence needs a real CLI turn recorded by this build, which I have not run yet.

This fix is forward-looking, deliberately. Aggregates already on disk carry no link and are never replaced, so the duplicate stays visible for existing history until those sessions produce new turns. Cleaning those up would require exactly the text-and-time inference this finding rejects. If you would rather have a one-time backfill, that is a separate decision with its own risk, not something I will smuggle in here.

Production is +372/-82 across five files; tests +915. The producer commit stands alone and could ship separately if you would rather review it on its own.

This comment is not a claim of a complete safety review.

@spunzon

spunzon commented Aug 31, 2026

Copy link
Copy Markdown
Author

Live Control UI proof on the exact head, from a real Claude CLI turn recorded by this build.

Setup

Two Gateways built from source, each serving its own chat.history from the same store: a copy of a production OpenClaw agent store, 878 persisted cli-assistant:<runId> aggregates. Only the commit differs.

commit
base 86b6ec0afa (current main)
head b538e9752c (this PR)

The turn was produced by running a real agent turn through the head build, not by editing a store. Claude CLI 2.1.250, anthropic/claude-opus-5 via the claude-cli backend. The prompt asked for a line of text, then pwd through Bash, then a closing sentence — the two-text-blocks-around-a-tool-call shape that this bug needs.

The native transcript the CLI wrote:

assistant 375c967e-…  text        "Comprobando el directorio de trabajo."
assistant 63db82c7-…  tool_use    Bash
user      a77a6ac7-…  tool_result
assistant 5d666065-…  text        "Ha impreso `/home/fulcrum/clawd`."

And the aggregate the producer persisted alongside it, read back out of SQLite:

"idempotencyKey": "cli-assistant:be40a3bc-c230-4e59-bb83-c5fa6e8846c9",
"cliNativeTurn": {
  "cliSessionId": "881503c4-fa93-4da4-b514-b94ba6afd637",
  "terminalRecordId": "5d666065-18d8-4a2c-8651-d2dfa6e330c9"
}

terminalRecordId is the turn's terminal assistant record. That is the whole relation, established by the producer on real data.

The turn on 86b6ec0afa

live-base

Rendered twice: the native blocks with the $ pwd card, then the flat aggregate repeating the same turn without it. Six rows in the DOM:

msg:send:8fb62534-…                                   (prompt)
msg:send:be40a3bc-…                                   (prompt)
msg:import:["claude-cli","881503c4-…","375c967e-…"]   "Comprobando el directorio de trabajo."
msg:import:["claude-cli","881503c4-…","63db82c7-…"]   Bash tool card
msg:import:["claude-cli","881503c4-…","5d666065-…"]   "Ha impreso `/home/fulcrum/clawd`."
msg:id:687e4295-…                                     the flat aggregate  ← the duplicate

The same turn on b538e9752c

live-head

Five rows. msg:id:687e4295-… is gone; the three imported rows are untouched, $ pwd still a native card.

The prompt appears twice on both sides. That is a separate send-mirror artifact of driving the turn from the CLI, identical on base and head, and outside this PR.

The fallback, on the same head

The same head, same session list, a session whose aggregate was persisted long before cliNativeTurn existed:

persisted rows: 1   (aggregate text length 6,781)
imported rows:  3

That 6,781-character aggregate is the one the previous text-and-time matcher deleted, and it is exactly the deletion the P1 finding was about. It names no native turn, so this head leaves it alone. In that store, 1 aggregate carries the relation and 877 do not; none of the 877 can be replaced.

What this does and does not show

It shows the producer establishing the relation on a real run, and the merge owner acting on it — the duplicate gone, the native tool card kept, and an unlinked aggregate preserved in the same rendered history.

It does not show a skill-invoking turn: this operator's store has no Skill turn, so that case stays covered by the regressions rather than by a capture. The Control UI is byte-identical on both sides — this PR changes 0 files under ui/ — so the rendered difference comes only from what the Gateway returned.

Sidebars are cropped out of both captures; they carry unrelated session titles.

Fulcrum and others added 4 commits September 3, 2026 08:42
CLI backends persist each assistant turn twice: once as the synthetic
`api: "cli"` aggregate whose text is the turn's text blocks joined, and
again as the native blocks the Claude CLI transcript import brings back.
Those are two shapes of the same turn, so per-message equality can never
pair them and the turn renders twice (openclaw#123792).

The merge owner now groups imported assistant messages into turns and
pairs each turn with the persisted aggregate that duplicates it. Within
one text and producer the two sides are matched in timestamp order: the
aggregate is written once the turn completes, so the earliest turn that
finished no more than the dedupe window before an aggregate owns it.
Pairing is one-to-one, so two genuinely repeated replies with identical
text are only both suppressed when the import actually holds both turns.
An unmatched aggregate is retained, which keeps the durable fallback for
an incomplete or trimmed import.

`api: "cli"` alone is not unique to the aggregate — ordinary CLI
assistant replies are persisted the same way. The producer stamps
`idempotencyKey: "cli-assistant:<runId>"` and the transcript append
spreads it onto the stored message, so that key is the discriminator;
every other `api: "cli"` record is retained.

Blocks of a turn that replaced an aggregate are flagged, because such a
block is then the only surviving copy of its text and weak role/text
dedupe must not discard it as well. A one-for-one replacement leaves the
message count unchanged, so the resolver reports an import by identity
rather than by length.

Grouping needs every imported row prepared before the merge loop, which
only pays for itself when a local aggregate could actually be covered.
A session without one keeps the lazy, skip-on-identity path from openclaw#133316
untouched. `prepareComparableMessage` derives the turn facts from the
single read it already makes of each field, so the added pass reads no
raw property twice, and `resolveImportedExternalIdentityKey` reaches the
same metadata through `asOptionalRecord` instead of four unchecked type
assertions.

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
The async snapshot routes any JSONL line past 1 MiB through a bounded
worker projection instead of the synchronous decoder. That projection
rebuilds the entry from a fixed field list, so a turn-boundary fact the
grouping reads has to survive it: a harness row dropped on one path and
kept on the other would split the turn on that path alone, and the
aggregate would stay beside the native blocks again.

Both regressions run the real JSONL importer and the real resolver, not
the merge helper:

- An oversized `isMeta` skill instruction row projects to exactly what
  the synchronous reader produces, and the resolver replaces the
  aggregate with the two native text blocks.
- An oversized compaction summary survives as the bounded placeholder,
  still ends the turn, and the aggregate is kept as the durable
  fallback.

The first is load-bearing: dropping `isMeta` from the worker payload and
its normalizer makes the async reader emit the harness row, and the
parity assertion fails.

Co-Authored-By: Claude Opus 5 <[email protected]>
A CLI backend persists one synthetic assistant message per run whose text
is that run's assistant text blocks joined. The same turn also exists as
native records in the backend's own transcript, and the Gateway imports
those when serving chat history. Nothing linked the two, so every reader
had to guess which imported turn an aggregate duplicated from its text,
its provider and its timestamp.

Run settlement is the one point that sees both at once. It already
resolves the native record id of the run's terminal assistant message for
resume, so it now records that id, with the native session that owns it,
on the aggregate it persists.

The link is absent whenever it cannot be established: a backend that
writes no native transcript, a run whose terminal record was not
reported, and every aggregate written before this existed. Readers then
have no relation to act on, which is the safe direction.

Co-Authored-By: Claude Opus 5 <[email protected]>
The merge paired a persisted aggregate with an imported turn by
normalized text, provider and a five-minute window. That is resemblance,
not identity: when either side of the history is partial, an unrelated
turn with the same text can claim an aggregate whose own turn is missing
from the import, and the only durable copy of a distinct assistant turn
disappears from chat history.

The producer now records which native turn each aggregate flattens, so
the merge resolves that relation instead of inferring one. Imported turns
are indexed by the native record their last message came from, and an
aggregate is only ever replaced by the turn it names, in the native
session it names.

The text comparison that remains is no longer an identity test. It runs
on an already-identified pair and asks a different question: whether the
import still carries the whole turn. A trimmed or partially imported turn
no longer covers the aggregate's text, and the aggregate is kept as the
durable copy.

An aggregate that names no turn is never replaced. That covers every
record persisted before the producer recorded the link, so the fix
applies to turns written from here on rather than deleting history on a
guess about the past.

This removes the dedupe window, the text-and-provider keyed index, the
ordered two-pointer pairing and the nearest-turn selection. What is left
is one lookup by native record id.

Co-Authored-By: Claude Opus 5 <[email protected]>
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Assistant turns render twice with CLI backends — live per-block view plus a concatenated aggregate record

2 participants