Skip to content

fix(gateway): Claude CLI sessions show runtime prompts as user messages - #166080

Merged
RomneyDa merged 7 commits into
openclaw:mainfrom
Marvinthebored:fix/claude-cli-internal-inputs
Oct 11, 2026
Merged

RomneyDa merged 7 commits into
openclaw:mainfrom
Marvinthebored:fix/claude-cli-internal-inputs

Conversation

@Marvinthebored

@Marvinthebored Marvinthebored commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Related: #165041

What Problem This Solves

Fixes: on the Claude CLI backend, prompts that OpenClaw itself generates show up in the Control UI (and other history clients) as messages the user appears to have typed.

Claude's native session file records every prompt the Gateway sends as an ordinary user row with no provenance. When that file is imported into chat history, any row that does not match a canonical transcript row is shown as a user turn. Seen in practice:

  • exec-completion wake prompts ("An async command you ran earlier has completed…"), including when queued System: event lines or the interrupted-run note come first
  • the session-resume note on its own row, and prepended to real user turns
  • default heartbeat prompts and the gateway-restart recovery turn
  • Claude's own /compact command records
  • queued System: [timestamp] … event lines glued in front of a real user message
  • [Claude CLI history record omitted from context because it exceeded 1 MiB.] rendered as a user message, when the omitted record was a tool result

User Impact

User impact: Claude CLI sessions no longer show these runtime prompts as user messages. Real user turns keep their text; a resume note or queued system-event block in front of an imported turn that has no canonical row is removed from the displayed copy only.

Risks and limits, stated plainly:

  • Recognition is by text, because the native file carries nothing else. Only complete producer frames are hidden: the exec prompt's fixed opening plus its fixed instruction sentence, the default heartbeat prompts, the restart-recovery opening sentence, and Claude's /compact records. A person who types one of those complete frames, and whose turn has no canonical row, would have that imported row hidden. The broad [System] tag on its own is no longer treated as a frame (review feedback); other system turns stay visible as they are on main.
  • A heartbeat prompt customized in config is not recognized.
  • Untimestamped channel-summary System: lines on a session's first turn are not stripped.
  • [cron:…] prompts in automation-run sessions are unchanged.

No config, schema, or stored-data change. Canonical transcript rows are never rewritten or hidden by this change.

Why This Change Was Made

The import adapter is the one place where the native row shape is known, so it records provenance there: complete producer-owned frames are marked internal_system with display: false, and the display projection hides them without inferring authorship later. Frames are matched through their producers' own builders where one is exported (HEARTBEAT_PROMPT, formatSystemTurnPrompt, stripCliSessionDriftNote).

The importer does not rewrite user text. The merge index still receives the original text and tries it first, then the prefix-free alternative (now also covering a queued system-event block). Generated prefixes are removed only afterwards, in the history reader, and only from the first text block of an imported row that found no canonical match. Quoted context and later text blocks remain intact. This addresses the review finding that stripping before deduplication broke literal matching.

For oversized records, the off-thread projection kept the role but replaced the content with a plain string, which turned a tool result into user text. It now keeps tool_result shape (id and error flag, at most 64 blocks) so the row coalesces with its tool call as a normal-sized one does.

Evidence

The evidence below was supplied on earlier revisions. Current-head maintainer proof is recorded separately below. Routed inter-session inputs now remain visible and are covered by #163521; they are no longer classified as hidden internal wakes by this PR. The earlier 200-row replay classification totals include that removed behavior and are historical rather than current-head counts.

Regression tests fail on main and pass with the change (source hunks reverted, tests kept):

main, tests only (first revision of this PR):
 Test Files  2 failed (2)
      Tests  16 failed | 11 passed (27)

earlier contributor head:
pnpm test <the six cli-session-history test files> --maxWorkers=1
 Test Files  6 passed (6)
      Tests  94 passed (94)      42s wall

Review finding (literal resume-note text must match its canonical row): a new end-to-end test drives the real reader (prepareCliSessionHistoryReader over a canonical SQLite transcript plus a native JSONL file). It fails on the previous head of this PR, which produced a sixth, shortened turn, and passes now:

previous head 3eec8cb9bcb:
 ×  cli-session-history.paging.test.ts > matches native rows on their original text and cleans only unmatched imports
      Tests  1 failed | 2 passed (3)
earlier contributor head:
      Tests  3 passed (3)

It asserts that a canonical row whose text is literally <resume note>\n\nhello absorbs its native copy and keeps its text, a canonical hello absorbs the plain native hello, a native row carrying a resume note and queued events matches its clean canonical row, an unmatched native row is shown without the generated prefixes, and an exec wake behind queued events is marked internal. The existing merge tests that require unmatched imports to come back verbatim pass unchanged.

The tests assert absence as well as presence: each internal frame is hidden while the same text quoted inside a real message stays visible, a canonical human row with identical text wins the merge, and look-alike human messages (System: … without the event timestamp, [System] …, [foo] [System] …, a timestamped [System] line that is not the recovery sentence, a System: line after a user's own code fence) are left untouched with no provenance.

Other checks reported on the earlier contributor branch: pnpm tsgo:core exit 0; tsconfig.core.test.gateway-root.json exit 0; oxfmt --check clean; oxlint 0 warnings, 0 errors on the changed files.

Live data: replaying 200 native Claude session files from one install (8 days of use, 989 string user rows) through the importer, the display cleanup and the display projection, 200 rows are classified internal (148 exec wakes, 28 sub-agent notices, 10 /compact records, 9 sessions_send, 3 restart-recovery turns, 1 heartbeat, 1 media completion), no displayed row begins with one of those frames, and no hidden row begins with the user-turn context block. All ten oversized rows in that sample are image tool results.

Gaps: not exercised in a running Control UI; the replay covers one install's usage patterns.

This change was written with AI assistance and reviewed adversarially before filing.

Maintainer shepherding (2026-10-10)

Current head: 451aafaa3abb9b337082ed9f5c4e7921646bf445. Rebased onto main 13296b17cd0f, including landed #163521 and main’s DM-policy export-name repair; non-draft, independently mergeable.

  • Removed blanket hiding of inter-session envelopes: legitimate peer inputs remain available to the shared attribution projection (fix(gateway): keep routed CLI prompts off the owner's side in chat history #163521).
  • Anchored system-event cleanup to the start of the input; quoted context inside human text stays unchanged.
  • Limited block-array cleanup to the first text block; later quoted logs stay byte-identical.
  • Retained main's archived-history regression while resolving the rebase conflict.

Scope/LOC: production +127 net; tests +360 net. Growth implements bounded native-input classification/provenance and sender-scoped matching at the existing importer/index owner boundaries; no configuration, durable database schema, or stored transcript rewrite.

Integration update: #163521 has landed. Resolved importer conflicts by retaining its forwarded provenance together with this PR’s internal-input classification. Retained main’s canonical stripCliPromptDecorations and sender-aware worker matching; this PR no longer changes the index worker. Native text remains unchanged before matching. No merge is authorized.

Rebased onto 48588a652222 to pick up main’s shared UI-import, wrapper-inventory, and typecheck repairs. No unrelated CI workaround was added to either PR.

Current-head isolated proof

AWS Crabbox run_78f30b011bb4dbd1dd74d1bd2f214340, exact head 408246d9d0392041020d47d9593807edc12cd42e, Node 24.21.0 / pnpm 12.9.0, 16 GB memory. Fresh public-network machine; no instance role, no Tailscale, isolated HOME; trusted bootstrap verified the exact SHA and absence of IAM credentials before contributor execution.

  • pnpm test src/gateway/cli-session-history.claude-input.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: 76 passed, four files.
  • oxfmt --check on all eight changed TypeScript files: clean.
  • Negative control: kept current tests and substituted only the earlier importer (422502e7d6287aa48a174db85a10f6c977c5a989). All four newly repaired cases fail as expected: both routed-input kinds, quoted context inside human text, and quoted evidence in a later text block. Six look-alike controls pass. Candidate importer restored afterward.
  • This proves the real native JSONL import, canonical merge, reader projection, and oversized snapshot boundaries; it does not claim a newly captured running-UI screenshot or provider call.

Earlier 2 GB AWS fallback attempts were killed during subprocess compilation, before producing usable behavioral proof; no production/test workaround was added.

Running compiled-Gateway proof

Exact-head Gateway trace: run_be330ed52ee10b4af4b32d54ec15d435, head 408246d9d0392041020d47d9593807edc12cd42e. Built with pnpm build, started node dist/index.js gateway, then called gateway call chat.history --json from two separate CLI processes against the running Gateway. Agent model selection explicitly uses Claude CLI. Canonical SQLite messages and synthetic native Claude JSONL fixtures live in an isolated HOME; no provider credentials or external model call.

Both reads return exactly one canonical OWNER_CHECK, one cleaned native UNMATCHED_HUMAN, the later quoted System: [unknown-time] evidence block intact, and an assistant tool activity containing toolcall plus tool_result with the same tool-oversized id and bounded “exceeded 1 MiB” placeholder. The multiline startup-event/default-heartbeat row is absent, and no tool placeholder becomes plain user text.

{"verdict":"PASS","reload":0,"ownerRows":1,"humanTextRetained":true,"heartbeatHidden":true,"quotedSystemTextRetained":true,"oversizedToolShapeRetained":true}
{"verdict":"PASS","reload":1,"ownerRows":1,"humanTextRetained":true,"heartbeatHidden":true,"quotedSystemTextRetained":true,"oversizedToolShapeRetained":true}

This exercises the shipped Gateway history entry point and rebuilt worker output, without a mock Gateway. No new Control UI screenshot or live provider generation is claimed. Initial probe setup mistakes (model-selection metadata and escaped fixture newlines) were corrected; only the linked passing run is counted. All current-head CI checks, including openclaw/ci-gate, are green.

Post-#163521 rebase validation

Rebased and pushed 25b5eccb052c9828d7a395652f2f349ddae40e58 onto landed #163521 (97e81ce0d5d96449449b545b80fb0c989c591c78). Earlier exact-head proof above remains historical proof for the previous revision. Fresh combined regression and compiled-Gateway probes are running on the new head, along with CI.

Integration repair: the first combined regression run run_1a8f233d308cf884e7240f1622d35be4 reproduced a queued-event duplicate when the native turn starts with OpenClaw’s fenced conversation context. The landed comparison helper did not recognize context before event lines. The repair preserves that context in the shared stripCliPromptDecorations owner and reuses that helper for display cleanup, deleting this PR’s duplicate cleanup regex. Existing regression retained; production delta for the integration commit is net zero (+8/−8). Fresh combined tests, compiled-Gateway proof, and independent autoreview are running.

Shared-main CI follow-up: the earlier test merge has a resolveChannelDmPolicy export collision in src/channels/account-resolution.ts and src/channels/plugins/dm-access.ts; main 13296b17cd0f fixes it and this branch now includes that commit. plugin-sdk-surface-report.test.ts also reports public exports 3672 > 3656, callable exports 2133 > 2122, and deprecated exports 158 > 154, including conversation runtime budgets. This PR does not change SDK barrels, shipped surfaces, budgets, or exported API names. No SDK-budget workaround was added.

Independent autoreview of the integration repair is scoped-clean (no accepted/actionable P0–P2 findings). Its earlier event-separator finding was addressed by consuming leading separator newlines before restoring the fenced context. Final combined validation and exact-head CI are running for 451aafaa3abb9b337082ed9f5c4e7921646bf445.

Final integration results

Final head 451aafaa3abb9b337082ed9f5c4e7921646bf445, base 13296b17cd0f (includes landed #163521).

  • Combined regression run_fea803c63011f86cd5368518384a872c: 148 unique tests passed, seven files (60 agent/provenance tests + 88 Gateway history tests). The wrapper then stopped on a quoting error before the additional checks; those are in the follow-up run, not counted as completed here.
  • Remaining proof run_c07aed8ac8f8f66061f006ce40df011c: formatting on both integration modules is clean. A same-environment SDK baseline control temporarily substituted pinned-main versions for all PR production files, ran plugin-sdk-surface-report.mts --check, and restored the candidate before build. Candidate and main both exit 1 with identical five budget violations (3672 exports, 2133 callable exports, 158 deprecated exports, plus conversation-binding-inspection/runtime deprecated budgets). No budget change or suppression added. Compiled Gateway probes are running.
  • Independent integration autoreview: scoped-clean, no accepted/actionable P0–P2 findings after the event-separator correction.

Current CI holds are unrelated to this PR: SDK surface budgets above; check-lint-core-2 reports shadowing/type-conversion errors in src/plugin-state/plugin-state-observation-cache.ts; check-lint-core-4 reports an unbound method in src/infra/sqlite-worker-plugin-comparison.test.ts. The test merge includes main 6cc0e8460192; neither owner is changed by this branch. These remain named shared-main follow-ups, not history-repair patches.

Final-head compiled-Gateway receipts

run_c07aed8ac8f8f66061f006ce40df011c completed successfully on exact head 451aafaa3abb9b337082ed9f5c4e7921646bf445. Formatting is clean, the SDK baseline control confirms identical main/PR failures, pnpm build succeeds, and both shipped-entry-point probes pass through running node dist/index.js gateway instances and separate CLI chat.history calls.

{"scenario":"runtime-inputs","verdict":"PASS","reload":0,"ownerRows":1,"humanTextRetained":true,"heartbeatHidden":true,"quotedSystemTextRetained":true,"oversizedToolShapeRetained":true}
{"scenario":"runtime-inputs","verdict":"PASS","reload":1,"ownerRows":1,"humanTextRetained":true,"heartbeatHidden":true,"quotedSystemTextRetained":true,"oversizedToolShapeRetained":true}
{"scenario":"routed-inputs","verdict":"PASS","reload":0,"ownerRows":1,"routedRows":2,"distinctEqualBodyOwner":true,"distinctOtherSender":true,"unmatchedForwarded":true}
{"scenario":"routed-inputs","verdict":"PASS","reload":1,"ownerRows":1,"routedRows":2,"distinctEqualBodyOwner":true,"distinctOtherSender":true,"unmatchedForwarded":true}

Synthetic native Claude JSONL fixtures and isolated canonical SQLite transcripts; real compiled Gateway/worker output and real CLI RPC, no mock Gateway or live provider call. This validates coexistence with landed #163521. All history regression suites pass (148 tests); independent integration review is clean. CI remains held by the documented unrelated main SDK/lint failures. No merge requested.

@clawsweeper

clawsweeper Bot commented Oct 6, 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 Oct 6, 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR hides recognized Claude CLI runtime prompts, cleans unmatched imported display text after deduplication, and preserves oversized tool-result shapes.

Example: A Claude CLI transcript records an exec-completion prompt beginning “An async command you ran earlier has completed.”

  • Before: History displays the runtime prompt as a message from the user.
  • After: The imported runtime row is hidden, while matching canonical user messages remain visible.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong shipped-entry-point evidence supports the scoped repair; broader linked-issue coverage remains partial, with a minor documentation defect and redundant test coverage.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied compiled-Gateway receipts exercise chat.history with isolated canonical SQLite and synthetic native JSONL, showing hidden heartbeat rows, retained human and quoted text, bounded tool results, and routed identities across repeated reads; intervening source changes were inspected against the proven revision.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: History attributes OpenClaw runtime prompts and oversized tool placeholders to the human user.
Reason: The scoped repair has clear value and maintainer direction; Related is appropriate because the linked issue also includes legacy requester-hint leakage outside this change.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR contains useful runtime-history fixes that current main does not provide; one minor documentation correction remains.

Priority: P2
Reviewed head: 6066e187ce841538147b1f244edbb8d1ce822ad0

Before merge

Findings

  • [P3] Document cleanup of unmatched native-history display text — src/gateway/cli-session-history.claude.ts:342-343

Tests

  • Low-value test src/gateway/cli-session-history.claude-input.test.ts: The added literal-resume-note matching case duplicates the stronger new paging test, which protects the same ordering through native JSONL, canonical SQLite, and the real reader; consolidate this case into that boundary.
Agent review details

How this fits together

The Gateway imports native Claude JSONL, merges it with canonical OpenClaw history in a worker-owned temporary index, and returns display messages to history clients.

flowchart LR
  A[Claude native transcript] --> B[Import adapter]
  B --> D[History merge index]
  C[Canonical transcript] --> D
  D --> E[Unmatched display cleanup]
  E --> F[Chat history RPC]
  F --> G[History clients]
Loading

Technical review

Best possible solution:

Retain the bounded importer repair and document the distinction between preserved stored transcripts and cleaned unmatched display copies.

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

Main imports unrecognized runtime prompts as user rows and projects oversized tool results as plain text; supplied negative controls establish failures, but this read-only review ran no target code.

Is this the best way to solve the issue?

The repair uses existing importer, merge, and display owners, preserves literal matching and canonical bytes, and deliberately limits recognition to fixed producer frames.

Full review comments:

Overall correctness: patch is correct
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Unmatched native-history display changes intended behavior with a stated reason (6968a45: The worker-owned temporary index preserves canonical bytes and returns bounded native-history pages.)
  • Queued-event comparison keeps the original intent (97e81ce: Compare-only decoration removal deduplicates routed and event-prefixed turns while preserving literal matches and sender identity.)
  • Oversized native projection changes intended behavior with a stated reason (acbe50a: Oversized records use one reusable off-thread worker and bounded projections to avoid blocking history reads.)
  • Adopted-session activity classification keeps the original intent (bb6874f: Native history supplies human-activity signals for adopted sessions; hidden runtime rows should not become human activity.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • git diff --check

What I checked:

PR surface

Source +126, Tests +360. Total +486 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 132 6 +126
Tests 3 365 5 +360
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 497 11 +486

Review metrics

Metric Value Why it matters
Production versus tests Production +127 net; tests +360 net Production growth implements bounded classification and tool-result projection at existing owners; tests cover native encodings, human look-alikes, matching order, and the real reader.

Labels

Label changes:

  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: Runtime-generated user bubbles cause limited history confusion without preventing normal agent operation.
  • merge-risk: 🚨 compatibility: Display behavior changes for existing native transcripts, including native-only human text identical to complete recognized frames; the narrowed direction and documented limitation are covered by the maintainer's shepherding.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

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

  • Consolidate the duplicate literal-resume-note test into the existing paging regression.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-06T10:44:45.534Z sha 3eec8cb9bcbac269a89c54d9b4fbfcf50f9b5679 :: blocked before merge. :: [P1] Preserve original text until canonical deduplication finishes
  • reviewed 2026-10-06T11:24:36.071Z sha d0d41b15b8ae6183fb2ca3ee1392456c96910efa :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T21:35:53.057Z sha 408246d9d0392041020d47d9593807edc12cd42e :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-10T21:57:59.524Z sha 408246d9d0392041020d47d9593807edc12cd42e :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T00:13:26.472Z sha 451aafaa3abb9b337082ed9f5c4e7921646bf445 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 10:42 PM ET / October 11, 2026, 02:42 UTC (Revision 6).

@Marvinthebored

Copy link
Copy Markdown
Contributor Author

Pushed a follow-up for the review finding. The importer no longer rewrites user text: the merge matches on the original text first, and generated prefixes are removed afterwards in the history reader, only from an imported row with no canonical match. A new end-to-end test through the real reader fails on the previous head and passes now. On the display tradeoff I took the recommended option and narrowed it: the bare [System] tag is no longer treated as a frame, only complete producer frames are. The PR description is updated with the details and evidence.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
@RomneyDa
RomneyDa force-pushed the fix/claude-cli-internal-inputs branch from d0d41b1 to 3c2667d Compare October 10, 2026 21:08
@RomneyDa
RomneyDa force-pushed the fix/claude-cli-internal-inputs branch from f073081 to a755844 Compare October 10, 2026 21:16
@RomneyDa

Copy link
Copy Markdown
Member

@clawsweeper re-review

Shepherding complete at a7558440da3da2b63cc6bb9d1bd56167eb4f7412: rebase/conflicts resolved; removed blanket hiding of legitimate inter-session inputs; anchored prefix cleanup to the start of the input and limited block cleanup to the first text block. Regressions preserve routed messages, quoted context, and later quoted logs. Prior accepted code findings remain addressed.

Current isolated AWS Crabbox proof is running and will be appended when complete. The PR body now states the narrowed scope and marks earlier classification counts historical. CI failures are shared-main defects documented in the body (duplicate UI import; newly added binding-persistence dependency absent from the wrapper inventory). Please review the current introduced diff and its owner boundaries; do not merge or enable automerge.

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@RomneyDa
RomneyDa force-pushed the fix/claude-cli-internal-inputs branch from a755844 to 408246d Compare October 10, 2026 21:24
@clawsweeper clawsweeper Bot removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 10, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 11, 2026
@RomneyDa
RomneyDa enabled auto-merge (squash) October 11, 2026 03:16
@RomneyDa
RomneyDa merged commit 667b2e5 into openclaw:main Oct 11, 2026
125 checks passed
steipete added a commit that referenced this pull request Oct 11, 2026
Keep the internal async approval handler factory and Claude display-prefix
helper private. Remove the redundant async adapter re-export from the approval
runtime and have its existing test import the canonical adapter module. The
public Plugin SDK entrypoint, synchronous wrappers, and runtime behavior remain
unchanged.

Complete the full-tree findings by removing the unused catalog-fixture
re-export, deleting the uncalled Skill Workshop reconnect test helper, and
keeping the codemod diagnostic annotation private. Workshop's last helper
consumer was removed by 224c0bc (#168656). No assertions or runtime function
bodies change.

Correct the preceding UI cleanup's historical attribution: git log -S shows
that the approval exports originated in 4128f11 (#168482), and were retained
through 8fc31c9; they were not introduced by 8fc31c9. The unused Claude
helper export came from 667b2e5 (#166080).

Validation: 15 existing approval tests passed in 31.33s; 34 existing Claude
import/display tests passed in 43.65s. Core production types passed in 45.92s,
the owning infra test graph in 38.93s, and targeted type-aware lint passed for
all six files. Formatting and diff checks passed. No tests were added and
existing assertions are unchanged. Fresh independent review of all six files
found no actionable P0-P2 issues.

The exact pnpm deadcode:full gate passed both production and full-tree scans
on the final six-file patch in 171.64s.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…es (openclaw#166080)

* fix(gateway): Claude CLI sessions show runtime prompts as user messages

Claude's native session file records every Gateway prompt as an ordinary user row. Mark complete producer-owned frames internal at the import adapter, strip queued system-event lines and the resume note from real user turns, and keep oversized tool results in tool_result shape.

* fix(gateway): match native rows on original text before display cleanup

Keep imported user text intact through the merge so literal matching still works, strip generated prefixes only from an unmatched import in the history reader, and limit system-turn recognition to the restart-recovery sentence.

* fix(gateway): preserve routed Claude imports for shared display policy

* fix(gateway): anchor generated Claude context cleanup

* fix(gateway): preserve later Claude text blocks during display cleanup

* fix(gateway): share CLI context decoration cleanup after integration

* fix(gateway): consume queued event separators before restoring context

---------

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
Keep the internal async approval handler factory and Claude display-prefix
helper private. Remove the redundant async adapter re-export from the approval
runtime and have its existing test import the canonical adapter module. The
public Plugin SDK entrypoint, synchronous wrappers, and runtime behavior remain
unchanged.

Complete the full-tree findings by removing the unused catalog-fixture
re-export, deleting the uncalled Skill Workshop reconnect test helper, and
keeping the codemod diagnostic annotation private. Workshop's last helper
consumer was removed by 5bc8e47 (openclaw#168656). No assertions or runtime function
bodies change.

Correct the preceding UI cleanup's historical attribution: git log -S shows
that the approval exports originated in 36a5eef (openclaw#168482), and were retained
through 6f9dc11; they were not introduced by 6f9dc11. The unused Claude
helper export came from d075300 (openclaw#166080).

Validation: 15 existing approval tests passed in 31.33s; 34 existing Claude
import/display tests passed in 43.65s. Core production types passed in 45.92s,
the owning infra test graph in 38.93s, and targeted type-aware lint passed for
all six files. Formatting and diff checks passed. No tests were added and
existing assertions are unchanged. Fresh independent review of all six files
found no actionable P0-P2 issues.

The exact pnpm deadcode:full gate passed both production and full-tree scans
on the final six-file patch in 171.64s.
RomneyDa added a commit that referenced this pull request Oct 11, 2026
…es (#166080)

* fix(gateway): Claude CLI sessions show runtime prompts as user messages

Claude's native session file records every Gateway prompt as an ordinary user row. Mark complete producer-owned frames internal at the import adapter, strip queued system-event lines and the resume note from real user turns, and keep oversized tool results in tool_result shape.

* fix(gateway): match native rows on original text before display cleanup

Keep imported user text intact through the merge so literal matching still works, strip generated prefixes only from an unmatched import in the history reader, and limit system-turn recognition to the restart-recovery sentence.

* fix(gateway): preserve routed Claude imports for shared display policy

* fix(gateway): anchor generated Claude context cleanup

* fix(gateway): preserve later Claude text blocks during display cleanup

* fix(gateway): share CLI context decoration cleanup after integration

* fix(gateway): consume queued event separators before restoring context

---------

Co-authored-by: Marvinthebored <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit 667b2e5)
(cherry picked from commit 73aed3f0b8d2089a41fc3cbcc1652fc4d2d9ff5e)
RomneyDa added a commit that referenced this pull request Oct 11, 2026
obviyus added a commit that referenced this pull request Oct 27, 2026
…matchers (#185746)

Related: #184216, #174780, #166080

## What Problem This Solves

Claude CLI history hid OpenClaw-generated turns (exec completion wakes, heartbeats, restart recovery) by matching their exact prompt text. Each time a prompt's wording changed, the matcher missed it, and the internal turn showed in history as if the user had typed it. The current restart-recovery wording is already unmatched.

## Why This Change Was Made

#184216 used Claude Code's native marker for exec wakes. Input sent with `isSynthetic: true` is stored as a meta row (`isMeta: true`, `turnOrigin: "host_synthetic"`). The model still receives it, and the history importer already drops meta rows.

This PR applies the same marker to every OpenClaw-generated turn and deletes the text matchers:

- The CLI runner sets `promptOrigin: "host"` exactly when the run's input provenance is `internal_system`. Provenance is the one signal for "OpenClaw wrote this turn".
- Isolated cron recorded its `internal_system` provenance on the transcript row only and never passed it to the CLI run, so cron prompts reached Claude as ordinary user input. The cron executor now passes that provenance to `runCliAgent`. Hook-mapped jobs carry external content and get no provenance, so they stay ordinary input. Other runtimes are unchanged: Codex's scheduled-MCP authority and the requester tool policy read run provenance, and this change does not touch them.
- The importer keeps only Claude's own frames (`/compact`, a resume note with no prompt), the task-notification and interrupt markers, and the inbound-context stripping that matches decorated human rows to canonical rows.
- Removed:
  - the exec-wake, heartbeat and restart-recovery text matchers in `cli-session-history.claude.ts`
  - the silent exec-wake branch in `heartbeat-filter.ts`
  - their fixtures and tests

Net: +15 / −182.

## User Impact

- New Claude CLI history never shows OpenClaw-generated turns as user messages, whatever the prompt wording.
- Older Claude CLI transcripts, written before #184216, can show those internal frames as user messages again. This is a display change.
- One model-facing reader is affected. When a Claude CLI run falls back to another provider, `readClaudeCliFallbackSeed` builds a recent-turns prelude from native history. That reader skips meta rows, so cron and recovery prompts are now left out of the prelude, as exec wakes already are since #184216. The assistant replies stay in it.
- Other backends are unchanged.

## Evidence

Isolated Gateway on this branch, real Claude CLI (Claude Code 2.1.310), `claude-cli` Sonnet. I checked the native Claude rows and `chat.history`:

| Turn | Native row | Model followed the turn | Shown as user |
| --- | --- | --- | --- |
| Isolated cron job: "create `cron-isolated.txt` containing `<nonce>`" | `isMeta: true`, `host_synthetic` | yes, the file was written with the exact nonce | no |
| Main-session cron job, same task | `isMeta: true`, `host_synthetic` | yes, the file was written | no (history shows only the assistant's "Done.") |
| Background exec completion wake | meta (as in #184216) | yes, it reported `wake-e2e-done` | no |
| Person pastes wake text plus a question | ordinary row | yes | yes (`external_user`) |

Before the cron provenance hand-off, the isolated cron row was `turnOrigin: "sdk"`, an ordinary user row, because the run had no provenance.

These cron runs also answer the open question from #184216: Claude labels synthetic input "NOT USER INPUT", but the model still carried out the job's instructions.

Tests:

- `execute-plugin.test.ts`: `internal_system` provenance (exec, cron) gives `promptOrigin: "host"`; inter-session, external-user and absent provenance do not.
- `run.cli-ownership.test.ts`: the cron executor passes `{kind: "internal_system", sourceTool: "cron"}` to `runCliAgent`. It fails without the executor change.
- Focused suites pass: `execute-plugin`, `run.cli-ownership`, `run.message-tool-policy`, `run.payload-fallbacks`, `heartbeat-filter`, `cli-session-history.claude-input`, `cli-session-history.paging`, `cli-session-history`, `extensions/anthropic/cli-runtime`.
- `tsgo:core` and `tsgo:core:test` pass. `oxlint` and `oxfmt` are clean.

Gaps:

- Restart recovery uses the same `internal_system` provenance as the exec wake. I could not trigger an automatic recovery turn on a non-main CLI session in the isolated Gateway, so it is covered by the provenance rule and unit test, not by a live run.
- Paired-node Claude execution does not use stream-json input and is unchanged.

Credit: @Marvinthebored reported the exec-wake and restart-recovery history regressions that led here.

**Merge danger:** two-way door. A revert restores the matchers. Meta rows already written stay hidden, which is correct for internal turns. Blast radius: Claude CLI history display, and the fallback recent-turns prelude described above. Pre-#184216 internal frames reappear in old transcripts. Third-party CLI backends can ignore `promptOrigin`.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…matchers (openclaw#185746)

Related: openclaw#184216, openclaw#174780, openclaw#166080

## What Problem This Solves

Claude CLI history hid OpenClaw-generated turns (exec completion wakes, heartbeats, restart recovery) by matching their exact prompt text. Each time a prompt's wording changed, the matcher missed it, and the internal turn showed in history as if the user had typed it. The current restart-recovery wording is already unmatched.

## Why This Change Was Made

openclaw#184216 used Claude Code's native marker for exec wakes. Input sent with `isSynthetic: true` is stored as a meta row (`isMeta: true`, `turnOrigin: "host_synthetic"`). The model still receives it, and the history importer already drops meta rows.

This PR applies the same marker to every OpenClaw-generated turn and deletes the text matchers:

- The CLI runner sets `promptOrigin: "host"` exactly when the run's input provenance is `internal_system`. Provenance is the one signal for "OpenClaw wrote this turn".
- Isolated cron recorded its `internal_system` provenance on the transcript row only and never passed it to the CLI run, so cron prompts reached Claude as ordinary user input. The cron executor now passes that provenance to `runCliAgent`. Hook-mapped jobs carry external content and get no provenance, so they stay ordinary input. Other runtimes are unchanged: Codex's scheduled-MCP authority and the requester tool policy read run provenance, and this change does not touch them.
- The importer keeps only Claude's own frames (`/compact`, a resume note with no prompt), the task-notification and interrupt markers, and the inbound-context stripping that matches decorated human rows to canonical rows.
- Removed:
  - the exec-wake, heartbeat and restart-recovery text matchers in `cli-session-history.claude.ts`
  - the silent exec-wake branch in `heartbeat-filter.ts`
  - their fixtures and tests

Net: +15 / −182.

## User Impact

- New Claude CLI history never shows OpenClaw-generated turns as user messages, whatever the prompt wording.
- Older Claude CLI transcripts, written before openclaw#184216, can show those internal frames as user messages again. This is a display change.
- One model-facing reader is affected. When a Claude CLI run falls back to another provider, `readClaudeCliFallbackSeed` builds a recent-turns prelude from native history. That reader skips meta rows, so cron and recovery prompts are now left out of the prelude, as exec wakes already are since openclaw#184216. The assistant replies stay in it.
- Other backends are unchanged.

## Evidence

Isolated Gateway on this branch, real Claude CLI (Claude Code 2.1.310), `claude-cli` Sonnet. I checked the native Claude rows and `chat.history`:

| Turn | Native row | Model followed the turn | Shown as user |
| --- | --- | --- | --- |
| Isolated cron job: "create `cron-isolated.txt` containing `<nonce>`" | `isMeta: true`, `host_synthetic` | yes, the file was written with the exact nonce | no |
| Main-session cron job, same task | `isMeta: true`, `host_synthetic` | yes, the file was written | no (history shows only the assistant's "Done.") |
| Background exec completion wake | meta (as in openclaw#184216) | yes, it reported `wake-e2e-done` | no |
| Person pastes wake text plus a question | ordinary row | yes | yes (`external_user`) |

Before the cron provenance hand-off, the isolated cron row was `turnOrigin: "sdk"`, an ordinary user row, because the run had no provenance.

These cron runs also answer the open question from openclaw#184216: Claude labels synthetic input "NOT USER INPUT", but the model still carried out the job's instructions.

Tests:

- `execute-plugin.test.ts`: `internal_system` provenance (exec, cron) gives `promptOrigin: "host"`; inter-session, external-user and absent provenance do not.
- `run.cli-ownership.test.ts`: the cron executor passes `{kind: "internal_system", sourceTool: "cron"}` to `runCliAgent`. It fails without the executor change.
- Focused suites pass: `execute-plugin`, `run.cli-ownership`, `run.message-tool-policy`, `run.payload-fallbacks`, `heartbeat-filter`, `cli-session-history.claude-input`, `cli-session-history.paging`, `cli-session-history`, `extensions/anthropic/cli-runtime`.
- `tsgo:core` and `tsgo:core:test` pass. `oxlint` and `oxfmt` are clean.

Gaps:

- Restart recovery uses the same `internal_system` provenance as the exec wake. I could not trigger an automatic recovery turn on a non-main CLI session in the isolated Gateway, so it is covered by the provenance rule and unit test, not by a live run.
- Paired-node Claude execution does not use stream-json input and is unchanged.

Credit: @Marvinthebored reported the exec-wake and restart-recovery history regressions that led here.

**Merge danger:** two-way door. A revert restores the matchers. Meta rows already written stay hidden, which is correct for internal turns. Blast radius: Claude CLI history display, and the fallback recent-turns prelude described above. Pre-openclaw#184216 internal frames reappear in old transcripts. Third-party CLI backends can ignore `promptOrigin`.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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.

3 participants