Skip to content

fix: prevent duplicate Claude answers in session history - #167069

Closed
jaxonparrott wants to merge 7 commits into
openclaw:mainfrom
jaxonparrott:codex/native-cli-history-upstream
Closed

jaxonparrott wants to merge 7 commits into
openclaw:mainfrom
jaxonparrott:codex/native-cli-history-upstream

Conversation

@jaxonparrott

@jaxonparrott jaxonparrott commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

October 10 contributor update

The replacement-message defect is fixed at the CLI producer. After an accepted hook or preparer returns, producer receipts are restored only when the final authored text still equals the accepted aggregate. Rewritten content loses stale receipt correspondence; blocked writes remain blocked. Regression controls cover a fresh hook object without metadata, a preparer dropping metadata, rewritten text, and blocked persistence.

Integrated current upstream main ff1303e4e8 to resolve the parser conflict. The combined upstream assistant/commentary flush retains buffered receipt selection for accepted assistant text and discards commentary correspondence.

Current contributor head: 14e879642b19e3f04bc1ff5c337a979f5bb4a9bd. Exact-head GitHub CI has a failed UI E2E job; no full CI pass is claimed for this head. Current Railway source gates (Linux, Node 24.21.0, pinned pnpm 12.9.0): frozen-lock install passed (32.9s); parser, native history, and history paging suites passed 88 assertions in the four-file qualification run (209.74s overall). Final persistence-only replay passed 9/9 (64.96s), covering both original coordination/run-ID assertions and the separate replacement/rewrite/block/preparer controls. All three touched files passed final type-aware lint with zero warnings/errors (24.4s); the final test-only adjustment renames a shadowed local variable without changing the green test behavior. Local and Railway source digests match; git diff --check passed. Fresh independent review found no blocking code findings.

The subsequent check-test-types-core-2 failure was confined to the new hook fixture. The fixture now narrows assistant messages, returns a fresh spread preserving mandatory provider/runtime fields, explicitly removes __openclaw, and assigns rewritten content through the typed assistant object. This preserves the receipt-loss discriminator without incomplete-message union typing. On a new disposable Railway sandbox: frozen-lock install passed (30.3s), the exact previously failing test/tsconfig/tsconfig.core.test.agents-other.json leaf passed, one-file type-aware lint passed with zero warnings/errors (31.0s), and the existing persistence suite passed 9/9 through the native agents-support config (190.27s including cold worker compilation). Source digests match. Initial default-workspace scanning encountered upload-generated AppleDouble sidecars; those were removed from the disposable source. Unit/core launcher attempts collected no tests and are not qualification. No production code changed in this final correction.

Exact-head UI E2E shard 1/2 failed two session-dashboard.e2e.test.ts pin cases (81 tests passed): Playwright timed out after 30s because SVG/span children of chat-gutter-stack--details intercepted clicks on “Pin to dashboard.” The cases install mock Gateway history directly and do not execute the CLI producer/persistence fixture. UI source, workflow/test configuration, and the test launcher are unchanged from the merged upstream base ff1303e4e8. This is an inherited UI hit-testing failure; no claim about intermittency or baseline test execution is made. The focused type leaf, typed lint, and 9/9 persistence receipts above remain valid. No UI fix or rerun was added to this receipt PR.

Read-only inspection of three existing owned production Claude handoff turns at fa05b483af7a72949c3ea738dff33a721af18453 now establishes a real tool→producer receipt→Gateway history path: each native final UUID and authored-text SHA256 matches its canonical receipt, history returns the answer once, and the preceding Read call/result remains. These are ordinary single-text finals following a tool call; native records contain no thinking/signature blocks. The receipt consumer file is byte-identical to this upstream head, but fa05 has earlier stream/producer source and lacks the replacement-object repair. This closes the absence of any authentic ordinary receipt/history observation, not exact-head repair, multi-text/thought retention, or upgrade proof. Owned source/history evidence is retained privately; no transcripts or credentials are published.

The initial four-file run also exposed an existing separate ownership defect: fresh-object replacements drop preattached __openclaw.runId, so readSessionTranscriptRunId(update.message) becomes undefined. Original spread-object run-ID assertions remain intact and pass; the new replacement cases scope their assertions to receipt correspondence. This PR does not repair generic run-ID preservation. A broad core compiler run exhausted the sandbox's working memory and was terminated; no full core typecheck pass is claimed. The contention-affected persistence replay was interrupted and then rerun serially to the green result above. Earlier evidence below remains attributed to its original head. Current-head contributor qualification remains synthetic. The fa05 ordinary real-tool observation above is version-scoped; an authentic after-fix replacement/multi-block turn, latest-stable transcript upgrade and reopen, and upstream history-owner acceptance remain outstanding. No production activation or merge is claimed.

What Problem This Solves

Fixes duplicate assistant answers when an imported Claude CLI transcript and OpenClaw's canonical reply represent the same provider turn, while preserving distinct turns and non-text records.

User Impact

Users receive one copy of the accepted answer. Tools, thoughts, signatures and native provenance remain visible. Historical rows without valid receipts retain their compatibility behavior; canonical history and durable database schemas are unchanged.

Why This Change Was Made

The parser records fully selected text under provider, session and native record UUID with an exact body digest. The derived history index consumes only text proven by that receipt. Receipt-bearing replies cannot use the legacy text fallback to consume a distinct UUID with an identical answer. The trusted importer carries the original digest separately from the redacted display payload; external metadata cannot supply this fact. Each selected source occurrence retains its exact identity, including multiple content records sharing a message ID.

Refreshed onto official main 3223e13a514c6134e10ee7f585627434d245fd20, consuming the landed native fixes for prior inherited CI failures. The complete feature patch is byte-for-byte equal to the prior revision; range-diff keeps every commit equal, and upstream changed none of this PR’s touched files. The stream conflict preserves upstream #165031's interrupted raw-tool-protocol rejection, text selection, code-region exclusion, fallback, and checkpoint semantics. Partial receipts attach only in the accepted-output branch. Three parser controls cover accepted prose, rejected unfinished raw protocol with no receipt, and an accepted fenced XML example. No patch was superseded by this base.

Evidence

Reviewed source head: 837148900f34eb65a2eafe7f5fd9aa1ee0861660. Exact-head native CI completed successfully: 46 successful jobs, 27 skipped, no failures or unfinished jobs. Prior-head failures and passes below remain historical. No maintainer acceptance or merge is claimed.

Prior Railway proof used Linux, Node 24.20.0 / pnpm 12.5.1 and one frozen-lock install. Current upstream uses pnpm 12.7.0, TypeScript 7.1.0-dev.20260922.1, oxlint 1.85.0, tsgolint 7.0.2003 and oxfmt 0.71.0. The successful exact-head native CI qualified its selected checks against this changed dependency graph; no duplicate local suites or installs were run. Existing receipts remain attributed to their exact prior source heads:

  • Focused native command below at dc83c3e3 exited 0: seven files across four shards, 140 passed / no skips, wall 319.02 seconds. The 16-case receipt shard, including the three new partial-output controls, completed in 6.11 seconds. The affected three-file Gateway shard completed 49 cases in 199.18 seconds.
  • Prior 50dd Gateway baseline passed 44 cases across four files, wall 406.91 seconds, including 199.948 seconds of cold worker-artifact preparation. These are differently grouped measurements, not a performance comparison.
  • The final receipt-only delta at fe52593a passed all 16 cases with no skips, wall 12.18 seconds (Vitest 3.39 seconds). It removes a redundant dialect predicate: receipt construction already requires the Claude dialect. Native callers preserve the per-turn provider/dialect; custom-event exclusion and interrupted raw-protocol rejection remain intact.
  • Final head fe52593a passed native changed formatting and type-aware lint for all 17 changed files: zero warnings/errors, wall 136.42 seconds. The existing changed-file planner selected these commands with lintOnly: true, exact base 50dd07c2 and head fe52593a; no hand-filtered lint set.
  • The previous changed typed-lint attempt at dc83c3e3 failed the native 700-line limit by one line. The final delta removes the redundant condition without a suppression or limit change.
  • Full local check:changed and remaining type graphs were not repeated before this contributor update. The successful new-head GitHub CI owns its selected proof; no complete local check:changed PASS or maintainer acceptance is claimed.
  • Historical native CI for fe525 failed the inherited assertion allowance mismatch and Windows listener argument error, plus the aggregate gate. Both are now fixed at their native owners: Peter’s allowance correction and signal argument correction. No duplicate fixes were added here. The refreshed head’s successful native CI is linked above; no prior failure was relabeled as a pass.
  • git diff --check passed and the reviewed source tree remained clean.
pnpm test src/agents/cli-output-jsonl.test.ts src/agents/cli-output-stream.test.ts src/agents/cli-output-text-receipt.test.ts src/agents/cli-runner/cli-run-transcript.test.ts src/gateway/cli-session-history.claude-snapshot.test.ts src/gateway/cli-session-history.paging.test.ts src/gateway/cli-session-history.test.ts --maxWorkers=1
pnpm test src/agents/cli-output-text-receipt.test.ts --maxWorkers=1

Prior-head evidence remains historical: abe43dbe passed 95 assertions, core types, selected agent/Gateway graphs, formatting and typed lint. Earlier real entry-point controls reproduced the identical-body rival, redaction-boundary duplicate, and per-block occurrence loss; earlier drafts also failed exact-repeat and buffered-final selection controls before correction. Prior scoped-clean reviews did not establish absence of those later findings. Beta-runtime and prior-head receipts do not substitute for current-head CI proof. Native staging recorded a transport deadline and an obsolete pnpm launcher failure before the successful durable fetch/install; neither is test-pass evidence.

A launcher metadata error admitted duplicate receipt-only jobs; both completed and were settled before the final attributed receipt run. They are not counted as additional coverage.

All fixtures are synthetic; no private transcripts or production data. These are scoped source gates; no full package build, production activation, or blanket repository CI pass is claimed.

@clawsweeper

clawsweeper Bot commented Oct 8, 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 agents Agent runtime and tooling size: L labels Oct 8, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 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 Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR records which native Claude text belongs to an accepted reply so history can remove duplicate text while preserving distinct turns, tools, and thoughts.

Example: A Claude turn emits “Checking the result.”, calls lookup, and finishes with “Verified answer.”

  • Before: History can show both native text records and the canonical “Checking the result.\n\nVerified answer.” reply.
  • After: Receipt-covered native text is omitted, the canonical reply appears once, and native tool and thinking records remain.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is useful and has meaningful focused coverage, but supplied runtime evidence does not yet demonstrate the changed defect path and persisted receipt compatibility remains unqualified.
Proof confidence 🧂 unranked krab (1/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: Yes · Fix scope: Complete
User problem: A single Claude answer appears again when native text fragments and the canonical aggregate both survive history reconciliation.
Reason: Official-release reports and current source establish useful repair work, without adding configuration or changing answer-selection defaults.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: it addresses a concrete Claude history correlation bug that remains on current main, and the earlier replacement-message defect is fixed with no new blocking code findings.

Priority: P2
Reviewed head: 14e879642b19e3f04bc1ff5c337a979f5bb4a9bd

Before merge

  • Add real behavior proof - The contributor’s three ordinary production-turn observations on fa05b48 add useful receipt-consumer evidence, but use earlier producer code and single-text finals without thoughts or signatures. Current-head evidence remains synthetic, and the inspected screenshots exercise a different coordination fix. Provide redacted logs, terminal output, screenshots, or a recording of the changed multi-block and replacement-message path, removing IPs, API keys, phone numbers, and non-public endpoints. 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.
  • 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: An authentic after-fix multi-block Claude turn through producer persistence and Gateway history, including retained tools/thoughts and a replacement-message case, remains unshown; this review did not independently replay the reported red/green controls.
Agent review details

How this fits together

The CLI parser selects answer text, the transcript writer persists its source receipts, and the Gateway’s worker-owned history index combines canonical messages with native Claude records for clients.

flowchart LR
  A[Claude CLI records] --> B[CLI streaming parser]
  B --> C[Canonical transcript writer]
  C --> E[Worker history index]
  A --> D[Native history importer]
  D --> E
  E --> F[Gateway history response]
  F --> G[Chat clients]
Loading

Technical review

Best possible solution:

Keep exact accepted-text correlation in the existing parser, transcript writer, and worker history owner while preserving canonical content and distinct native turns.

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

Current-main source supports the multi-text trigger: an identityless canonical aggregate cannot text-match its unequal native fragments, consistent with the detailed release reports; this review ran no target code.

Is this the best way to solve the issue?

Exact source identity plus full-text coverage is a sound repair because it preserves answer-selection policy and avoids collapsing unrelated equal answers.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Claude answer selection keeps the original intent (c661061: Keep tool-connected pre-tool answer text so final delivery does not erase it.)
  • Worker history reconciliation changes intended behavior with a stated reason (6968a45: Provide bounded, revision-scoped history pages while retaining canonical bytes and native identities.)
  • CLI transcript hooks and identity keeps the original intent (fix(agents): preserve complete CLI subagent answers #162843: Persist the owning run ID so complete subagent answers remain recoverable; this PR preserves the existing assertions and scopes its replacement repair to text receipts.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +401, Tests +961. Total +1362 across 17 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 425 24 +401
Tests 7 971 10 +961
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 1396 34 +1362

Review metrics

Metric Value Why it matters
Production versus test growth Production +425/-24 LOC; tests and test support +971/-10 LOC Production growth implements source occurrence tracking and receipt consumption; the larger test delta covers selection, replacements, redaction, and distinct-turn preservation.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #118185
Summary: This PR is a receipt-based candidate for native/local assistant-history correlation; the older open candidate is not a safely landable replacement.

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: The fix addresses confusing duplicate Claude history with a limited provider-specific blast radius and no established urgent regression introduced by this PR.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Show an authentic after-fix multi-block Claude turn through Gateway history with one accepted answer and retained tools/thoughts, including replacement-message preparation.
  • Upgrade a transcript from v2026.9.9 to the candidate and reopen it, demonstrating intact existing settings, stored rows, and receipt-less history.

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 (8 earlier review cycles)
  • reviewed 2026-10-08T08:46:57.587Z sha 7b8e181 :: needs real behavior proof before merge. :: [P2] Verify receipt coverage before native text is redacted
  • reviewed 2026-10-08T11:43:35.165Z sha abe43db :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-09T03:03:13.076Z sha abe43db :: needs real behavior proof before merge. :: [P2] [P2] Preserve valid receipts through replacement-message preparation
  • reviewed 2026-10-09T05:41:51.211Z sha abe43db :: needs real behavior proof before merge. :: [P2] [P2] Preserve valid receipts through replacement-message preparation
  • reviewed 2026-10-09T09:28:16.630Z sha fe52593a8993d17811784c632cfd7d2f0343fbad :: needs real behavior proof before merge. :: [P2] [P2] Preserve valid receipts through replacement-message preparation
  • reviewed 2026-10-09T10:16:14.815Z sha 8371489 :: needs real behavior proof before merge. :: [P2] [P2] Preserve valid receipts through replacement-message preparation
  • reviewed 2026-10-10T06:31:43.584Z sha f95364d :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-10T09:57:31.660Z sha 14e8796 :: needs real behavior proof before merge. :: none

Reviewed October 10, 2026, 6:23 AM ET / 10:23 UTC (Revision 9).

@jaxonparrott
jaxonparrott marked this pull request as ready for review October 9, 2026 05:35
@jaxonparrott
jaxonparrott force-pushed the codex/native-cli-history-upstream branch from abe43db to fe52593 Compare October 9, 2026 09:07
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 10, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 10, 2026
@jaxonparrott

Copy link
Copy Markdown
Contributor Author

Additional downstream evidence: the narrow producer-receipt preservation port is deployed in native source 6dacdd00cf0349dc6ec3d00511c252e5032405bd. Its focused fixture discriminated baseline 2 failures/7 passes from repaired 9/9 passes; owning test types, format and typed lint passed on isolated Railway.

After an actual production restart from the previous native build, three previously completed real Claude child sessions were reopened through native history. Persisted messages and producer receipts exactly matched their pre-upgrade records: one user, retained real Read call/result, one canonical final answer, zero duplicates per session. This proves saved-history continuity for those observed records; it does not claim live coverage of all hook replacements, multi-text or thinking shapes, or the exact upstream head.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 26, 2026
@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.

@openclaw-barnacle openclaw-barnacle Bot closed this Nov 6, 2026
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 P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant