Skip to content

fix: keep completed CLI pre-tool text after session replacement - #164293

Open
Oldrich333 wants to merge 3 commits into
openclaw:mainfrom
Oldrich333:fix/cli-commentary-history-135244
Open

Oldrich333 wants to merge 3 commits into
openclaw:mainfrom
Oldrich333:fix/cli-commentary-history-135244

Conversation

@Oldrich333

@Oldrich333 Oldrich333 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Agent-written on behalf of @Oldrich333 · agent: hive-admin/executor · model: anthropic/claude-opus-5-5 · origin: agent-initiated

Related: #135244

What Problem This Solves

Fixes: with commentary enabled (block streaming / progress drafts), completed pre-tool Claude CLI text is diverted to commentary and lives only in the native Claude session. After the native CLI binding is replaced (/reset soft, auth/account change), chat.history no longer shows it; only the final reply survives.

User Impact

Pre-tool text the user already saw stays readable in the conversation after a later CLI reset, each text once, with one final answer. No user action or migration. Out of scope: the issue's separate missing-record-window, timestamp-reassignment and old-session-list claims; interrupted (non-completed) turns.

Why This Change Was Made

The parser already decides which text becomes commentary (flushPendingClaudeCommentaryText). This change persists exactly that text, at that point, through the existing canonical transcript writer (persistCliAssistantTranscript: same hooks, room-event guard, session/lifecycle/writer fences), as one assistant row per diverted block with idempotency key cli-assistant:<runId>:seg:<nativeMessageId>:<ordinal>. Backend output replacements are applied before persistence, the same transform live commentary gets. The final reply write is unchanged. The segment also records Claude's own record id for that text block (the stream-json assistant snapshot uuid, which equals the native JSONL row uuid) as __openclaw.cliNativeRef; the history index uses it as the local row's external identity, so while the binding is live the native import pairs with the canonical segment by identity even when display transforms changed the text. After binding replacement the canonical segment remains.

Changes vs the previous head (ClawSweeper rev 3 findings):

  1. Granularity: a segment = the exact diverted block, not an aggregate of a native message; native Claude JSONL stores one row per content block, so the one-to-one history dedup matches.
  2. Output replacements applied to persisted commentary (adapter test: OldName → NewName).
  3. No combined-final fallback: the final reply never re-includes commentary, so a failed segment write cannot duplicate earlier segments; segment appends are serialized and drained before the final write.
  4. Leading tagged reasoning (<thinking>…</thinking>) is routed by the existing partition before text reaches the commentary buffer; only visible text is persisted.
  5. Identity pairing (independent review finding): when output replacements or a leading tagged-reasoning prefix make the canonical text differ from the native text, the bound history used to show both; the canonical row now carries the native record id, so the merge keeps one row (tests for both variants; they fail with the index change reverted). Without --include-partial-messages (custom args only) no id is captured and matching falls back to the existing text comparison.
    Rebased on current main (conflicts resolved; merges cleanly with d65e8ec89).

Evidence

Real behavior: installed Claude Code 2.1.287 (subscription login), claude-cli/claude-sonnet-5-5, two disposable gateways with isolated state, agents.defaults.blockStreamingDefault: "on" in both base (2d3ac4a35, unpatched main) and head (this branch). Same script per build: two chat.send turns, each asking the model to write a marker sentence, call Read, then answer → stop gateway → drop the session's cliSessionIds/cliSessionBindings (the state effect of /reset soft → clearAllCliSessions) → start gateway → chat.history.

Base (unpatched), bound — pre-tool text visible only via the native import:

assistant 'PRE-TOOL-MARKER I will now read the fixture file.'   key=-                      importedFrom=claude-cli
assistant 'FINAL-MARKER The fixture value is BLUE-HERON-42.'    key=cli-assistant:<run1>   importedFrom=claude-cli
assistant 'PRE-TOOL-MARKER-2 Reading the fixture again.'         key=-                      importedFrom=claude-cli
assistant 'FINAL-MARKER-2 The fixture value is BLUE-HERON-42…'  key=cli-assistant:<run2>   importedFrom=claude-cli

Base after binding replacement + restart — pre-tool text gone:

user      'Proof turn. …'
assistant 'FINAL-MARKER The fixture value is BLUE-HERON-42.'    key=cli-assistant:<run1>
user      'Second proof turn. …'
assistant 'FINAL-MARKER-2 The fixture value is BLUE-HERON-42…'  key=cli-assistant:<run2>

Head (d4e97554e), bound — each text once (canonical segment paired with its native row by id; canonical cliNativeRef.externalId 8fdfcdce-… = native JSONL uuid 8fdfcdce-… of the PRE-TOOL-MARKER text block):

assistant 'PRE-TOOL-MARKER I will now read the fixture file.'   key=cli-assistant:<run1>:seg:msg_…:0
assistant 'FINAL-MARKER The fixture value is BLUE-HERON-42.'    key=cli-assistant:<run1>
assistant 'PRE-TOOL-MARKER-2 Reading the fixture again.'         key=cli-assistant:<run2>:seg:msg_…:0
assistant 'FINAL-MARKER-2 The fixture value is BLUE-HERON-42.'  key=cli-assistant:<run2>

Head after binding replacement + restart — both pre-tool texts retained, once each:

assistant 'PRE-TOOL-MARKER I will now read the fixture file.'   key=cli-assistant:<run1>:seg:msg_…:0
assistant 'FINAL-MARKER The fixture value is BLUE-HERON-42.'    key=cli-assistant:<run1>
assistant 'PRE-TOOL-MARKER-2 Reading the fixture again.'         key=cli-assistant:<run2>:seg:msg_…:0
assistant 'FINAL-MARKER-2 The fixture value is BLUE-HERON-42.'  key=cli-assistant:<run2>

On the previous head (5ca101fcf, same script) a third turn on the new native session also merged once (segment + final). The binding was dropped in the stopped store because the CLI operator client was not authorized to run /reset soft as a chat command.

Tests:

  • src/agents/cli-output-stream.test.ts, src/agents/cli-runner/cli-run-transcript.test.ts, new src/agents/cli-runner/execute.commentary-history.test.ts, new src/gateway/cli-session-history.segments.test.ts: 4 files, 48 tests pass; vitest 32–37 s locally; new tests under 40 ms each. Negative controls: removing the replacement step fails the adapter test; reverting the index change fails both identity-pairing tests.
  • src/gateway/cli-session-history.test.ts: 54/54.
  • tsgo core + agents/gateway test shards clean; oxfmt/oxlint clean.
  • src/gateway history-boundary + cli-session-history suites: 91/91.
  • pnpm check:changed: all stages pass except a type error in ui/…/mcp-app-bridge.cursor.test.ts, reproduced identically on plain 2d3ac4a35 (untouched by this PR).
  • Two independent GPT-6.1-Sol high reviews: first clean on 5ca101fcf; second found the identity-pairing case above, then re-reviewed d4e97554e clean (including a replay of the real Claude Code stream).

@clawsweeper

clawsweeper Bot commented Oct 3, 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: M labels Oct 3, 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The PR saves completed Claude CLI pre-tool commentary in conversation history and pairs it with native records so it remains visible once after session replacement.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with convincing real runtime evidence and meaningful regression coverage; no remaining blocking correctness concern was identified.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The captured terminal trace connects the changed parser and canonical writer to real Claude CLI chat.send turns, then shows each commentary block surviving binding removal, Gateway restart, and chat.history exactly once. Proof is on d4e9755; the latest no-hook options repair does not change that exercised path. Optional metadata preserves existing records without migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Merge readiness

✅ Ready for maintainer review

The PR remains useful: current main still drops diverted commentary from canonical history. The earlier findings are addressed, the supplied runtime evidence covers the intended behavior, and no remaining actionable defect was found.

Priority: P2
Reviewed head: e73c53ecec0f7239be3142335084a702cf75f550

Before merge

None.

Findings

None.

Agent review details

How this fits together

OpenClaw’s CLI runner converts local model output into live commentary and final replies. Its canonical transcript and native-history importer feed the conversation history shown by the Gateway.

flowchart TD
  A[Claude CLI output] --> B[Streaming parser]
  B --> C[Live commentary]
  B --> D[Canonical transcript writer]
  B --> E[Final reply]
  F[Native session history] --> G[History identity matching]
  D --> G
  G --> H[Conversation history]
Loading

Technical review

Best possible solution:

Keep completed visible commentary in the canonical transcript through the existing writer, while leaving the broader timestamp and missing-window claims separately tracked.

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

Yes: current main diverts pre-tool text into commentary without persisting it, and the supplied real Claude CLI before/after trace exercises binding replacement and restart. This review established the current-main mechanism from source without executing it.

Is this the best way to solve the issue?

Yes: persisting the exact diverted blocks through the existing transcript writer and pairing native records by identity is a focused repair that preserves final-reply behavior.

AGENTS.md: found and applied where relevant.

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

Security

None.

Evidence

What I checked:

  • Verified introduced change: Read the pinned merge-base-to-head diff. The change adds commentary persistence and native-record pairing; endpoint drift was not attributed to this PR. (e73c53ecec0f)
  • Current main still needs the fix: Current main’s commentary flush only invokes the live commentary callback, and its runner has no commentary persistence callback. The history index also lacks canonical native-reference matching. (src/agents/cli-output-stream.ts:114, b48245c41428)
  • Canonical persistence and prior finding resolution: Segments use the existing transcript writer, distinct idempotency keys, output replacements, and visible-text reasoning partition. Writes are serialized and drained before the unchanged final reply write; there is no combined fallback that duplicates committed segments. (src/agents/cli-runner.ts:334, e73c53ecec0f)
  • Real Claude CLI before/after evidence: The captured PR body reports Claude Code 2.1.287 in isolated Gateways with commentary enabled on both builds. Two real chat.send turns each produced pre-tool text, Read tool activity, and a final reply. After binding removal and restart, the base lost both commentary texts while d4e9755 retained each once. The stopped-store binding removal matches the clearAllCliSessions state effect in commands-reset.ts; this proves persistence across replacement, not reset-command authorization. The latest head only adjusts the no-hook options shape. (src/auto-reply/reply/commands-reset.ts:83, e73c53ecec0f)
  • Existing-state compatibility: cliNativeRef is optional metadata on ordinary assistant records; no schema, existing-row rewrite, or configuration migration is introduced. The history matcher tolerates its absence and retains text matching for older records. Regression coverage includes records without the field and identity matching when transformed text differs, before and after binding replacement. (src/gateway/cli-session-history-index.worker.ts:171, e73c53ecec0f)
  • Latest hook-options repair: The current runner passes undefined when neither diagnostic nor commentary hooks apply, matching the existing main contract. The contributor reports the previously failing context-engine cases and all 75 relevant non-live test files passing. These are contributor-reported results; this read-only review did not execute tests. (src/agents/cli-runner.ts:394, e73c53ecec0f)

PR surface

Source +129, Tests +328. Total +457 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 134 5 +129
Tests 4 328 0 +328
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 462 5 +457

Review metrics

Metric Value Why it matters
Production versus regression coverage production +129 net lines; tests +328 lines Production growth connects parsing to the existing persistence owner and identity matcher rather than introducing another store.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs a bounded history-retention defect for completed Claude CLI commentary after native-session replacement.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (4 earlier review cycles)
  • reviewed 2026-10-03T12:34:36.733Z sha b43f1e6fcd3306e8642b199c1740bd9a5504426f :: needs real behavior proof before merge. :: [P2] [P2] Preserve native-message granularity for history deduplication | [P2] [P2] Apply output transforms to both new transcript paths | [P2] [P2] Exclude committed segments from combined fallback writes
  • reviewed 2026-10-03T14:01:46.467Z sha b43f1e6fcd3306e8642b199c1740bd9a5504426f :: needs real behavior proof before merge. :: [P2] [P2] Preserve native-message granularity for history deduplication | [P2] [P2] Apply output transforms to both new transcript paths | [P2] [P2] Exclude committed segments from combined fallback writes | [P2] [P2] Separate tagged reasoning before persisting answer segments
  • reviewed 2026-10-03T15:14:38.820Z sha b43f1e6fcd3306e8642b199c1740bd9a5504426f :: needs real behavior proof before merge. :: [P2] [P2] Preserve native-message granularity for history deduplication | [P2] [P2] Apply output transforms to both new transcript paths | [P2] [P2] Exclude committed segments from combined fallback writes | [P2] [P2] Separate tagged reasoning before persisting answer segments
  • reviewed 2026-10-04T07:08:59.895Z sha d4e9755 :: needs maintainer review before merge. :: none

Reviewed October 4, 2026, 6:25 PM ET / 22:25 UTC (Revision 5).

@openclaw-barnacle openclaw-barnacle Bot closed this Oct 3, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 3, 2026
@openclaw-barnacle openclaw-barnacle Bot closed this Oct 3, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 3, 2026
@Oldrich333
Oldrich333 force-pushed the fix/cli-commentary-history-135244 branch from b43f1e6 to d4e9755 Compare October 4, 2026 07:00
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 4, 2026
@Oldrich333

Copy link
Copy Markdown
Contributor Author

Fixed the checks-node-changed-2 failure from run 37184561864 (src/agents/cli-runner.context-engine.test.ts:205,231) in e73c53e. runPreparedCliAgentOwned built an options object for executePreparedCliRun even when no hook applied, so it passed {} where the existing contract passes undefined. It now passes options only when onPhase or onCommentarySegment is set, the same shape as on main. Behaviour is unchanged when either hook is present.

Ran locally: all 75 non-e2e/live files in src/agents/cli-runner*.test.ts, src/agents/cli-runner/*.test.ts, src/agents/cli-output-stream.test.ts and src/gateway/cli-session-history*.test.ts pass. tsgo -p tsconfig.core.json, oxfmt and oxlint are clean.

This branch has not been deployed

No deployments
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant