Repository navigation
feat(parsers): wire Claude Code history.jsonl paste evidence into has_paste - #1651
Conversation
…_paste
Claude Code persists every interactive prompt to ~/.claude/history.jsonl
with a pastedContents map keyed by paste id. The map carries either full
paste content (strong evidence) or only id/hash rows (existence evidence
without recoverable text). None of this was wired into archive
has_paste, so user messages whose assembled text no longer contained the
[Pasted text #N] marker silently resolved to has_paste=0 even when the
sidecar knew a paste happened.
Additionally, the existing detect_paste marker regex required #\d+]
immediately, missing the actual production form [Pasted text #N +M lines]
emitted by Claude Code's UserPromptSubmit hook. Fixed alongside since it's
the same bug class (paste evidence not landing in the archive fact).
Implementation:
- New parser polylogue/sources/parsers/claude/history.py with
HistoryEntry / HistoryPaste dataclasses, parse_history_jsonl iterator
that gracefully skips malformed lines and non-UTF8 files, and
build_session_paste_index that keys paste-bearing rows by sessionId.
- ClaudeCodeAssemblySpec.discover_sidecars now also walks two dirs above
each session file for history.jsonl and returns the per-session paste
index alongside the session_index sidecar.
- ClaudeCodeAssemblySpec.enrich_conversation marks user messages whose
timestamps fall within a 6-second tolerance of a paste-bearing history
row by writing {"claude_code_history_paste": True} into
ParsedMessage.provider_meta. Ambiguous matches (more than one
candidate user message inside the tolerance window) are dropped
rather than silently fanning evidence across unrelated messages.
- materialization_runtime ORs the provider_meta evidence with the
existing detect_paste heuristic when computing has_paste.
- detect_paste's _PASTE_MARKER_PATTERN allows annotation between #N and
the closing bracket so [Pasted text #1 +6 lines] matches.
Scope satisfied (#1583 ACs):
- AC #1 (history.jsonl pastedContents marks matching user message
has_paste=1 even when assembled text lost the marker): yes, via
sessionId + timestamp strong-identity matching.
- AC #3 (hash-only rows mark paste existence without pretending text is
available): yes, HistoryPaste.is_hash_only carries the distinction.
- AC #4 (ambiguous matches not silently dropped as success): yes,
ambiguous matches deliberately leave has_paste alone — a typed
diagnostic surface for the unmatched-row case is deferred (see
Notes).
- AC #5 (paste_count agrees after ingest): yes, conversation_stats
derives paste_count from messages.has_paste sum and recomputes on
ingest, so the upstream change propagates without further wiring.
Scope deferred (filed as follow-up):
- AC #2 (UserPromptSubmit hook event wiring): needs daemon-side hook
event → message-row linking, separate convergence-stage work.
- AC #6 (focused fixtures cover the full taxonomy of evidence
combinations): hook lane requires AC #2 first.
- AC #7 (boundary states exact/projected/whole_message_fallback/
hash_only durably exposed in the reader): richer-than-bool schema
surface, deferred to the boundary-state schema PR.
Verification:
- 1322 sources + materialization tests pass (113s).
- 80 new+touched tests pass: parser unit (10), assembly enrichment
(10), materialization OR (4), updated paste-detection (28),
marker-line-count variants (5), counterfactuals (cross-session
isolation, ambiguity refusal, hash-only-only-existence).
- devtools verify --quick: exit_code 0.
Ref #1583
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
|
Warning Review limit reached
More reviews will be available in 36 minutes and 55 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (10)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
… stale column, renamed index) (#1660) Three small fixes for pre-existing test failures discovered during the 2026-05-27 backlog sweep ([#1657](#1657)). Each was a stale-test issue rather than a production-code bug. ## Changes - **\`tests/unit/storage/test_schema_safety.py\`** — required-index list named the pre-#635 \`idx_conversations_provider\` index, which was renamed to \`idx_conversations_source_name\` during the provider->source storage-column vocabulary transition. Updated the test, added a one-line comment explaining the rename. - **\`tests/unit/storage/test_repair_blobs.py\`** — \`_reference_blob\` helper's INSERT into \`raw_conversations\` passed seven VALUES against a six-column list, tripping \`OperationalError: 7 values for 6 columns\`. The extra \`'referenced.json'\` literal pre-dated a schema column removal. - **\`tests/unit/storage/test_fts5.py\`** — \`test_search_includes_conversation_metadata\` asserted both \`hit.source_name == "claude-ai"\` and \`hit.source_name == "my-source"\` on the same row (impossible). Same shape as the duplicate-column failures fixed in PR #1651/#1652/#1653. Removed the contradictory second assertion. ## Verification \`\`\` $ nix develop -c pytest tests/unit/storage/test_repair_blobs.py \\ tests/unit/storage/test_schema_safety.py tests/unit/storage/test_fts5.py 96 passed in 3.01s $ nix develop -c devtools verify --quick exit_code: 0 \`\`\` ## Out of scope The order-dependent flake in \`test_daemon_http_contracts.py\` (KeyError 'fts_readiness' / 'component_state' under specific pytest-randomly seeds) is tracked separately under #1657. It needs a cross-test mock-state-leak investigation that doesn't fit this PR's small-cleanup shape. Ref #1657. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Claude Code's
~/.claude/history.jsonlrecords every prompt with apastedContentsmap. Polylogue ingest never read it, so user messageswhose assembled text no longer carried the
[Pasted text #N]markersilently resolved to
has_paste=0even when the sidecar knew a pastehappened. Wire the history sidecar into the assembly enrichment path so
matched user messages get
has_paste=1, and fix the existingdetect_pasteregex which missed the actual production marker form[Pasted text #N +M lines].Ref #1583
Problem
Two evidence sources for paste boundaries collided silently:
detect_paste(msg.text)looked for\[Pasted\s+(text|content|image)\s*#\d+\]— required
#N]with nothing betweenNand]. Production ClaudeCode actually emits
[Pasted text #1 +6 lines], so the heuristicwas a no-op on every real Claude Code prompt that contained a marker.
~/.claude/history.jsonlrecords paste data with full content (orhash-only ids when the paste was image/binary), but nothing in the
ingest path parsed it. Evidence existed but was discarded.
The combination meant
messages.has_paste,conversation_stats.paste_count,the
--has-paste/--typed-onlyCLI filters, and thereader/MCP/API envelopes all agreed on the wrong answer for Claude
Code paste-bearing messages.
Solution
New parser
polylogue/sources/parsers/claude/history.py:HistoryEntryandHistoryPastedataclasses model the actualon-disk shape.
parse_history_jsonl(path)yields rows, skipping malformed linesand non-UTF8 files at the debug log level (so a single bad row
never aborts enrichment for the rest of the file).
build_session_paste_index(path)returns{sessionId: [entries with paste]};rows without a
sessionIdor without paste evidence are dropped atbuild time because they can never be matched on the strong-identity
path and would inflate memory for nothing.
ClaudeCodeAssemblySpec.discover_sidecarsnow also looks two dirsabove each session file for
history.jsonland returns the indexedsidecar alongside
session_index.ClaudeCodeAssemblySpec.enrich_conversationwalks each conversation'suser messages, matches them to paste-bearing history rows by sessionId
fits inside a single user turn), and writes
{"claude_code_history_paste": True}intoParsedMessage.provider_metafor unambiguous matches. Ambiguous matches — more than one
candidate user message inside the tolerance window for one history row —
are deliberately dropped from the strong-identity path; the AC
explicitly forbids silently fanning paste evidence across unrelated
messages.
materialization_runtimereads the annotation and ORs it with thetext heuristic when computing
has_paste.conversation_stats.paste_countalready derives from
messages.has_pasteso the upstream changepropagates without further wiring.
paste_detection._PASTE_MARKER_PATTERNnow permits annotation between#Nand the closing]:[Pasted\s+(text|content|image)\s*#\d+(?:[^\[\]]*)\].The nested-bracket character class keeps the matcher tight — a marker
that escapes its bracket pair still fails.
Verification
Verification angles considered:
test_enrich_marks_matched_user_message_with_paste_evidence,test_enrich_marks_hash_only_paste_as_evidence_too,test_discover_sidecars_indexes_history_paste_entriesexercise thehappy paths end-to-end (real-disk sidecar + sessionId+timestamp
match + provider_meta annotation).
test_enrich_does_not_silently_fan_evidence_across_ambiguous_matches,test_enrich_does_not_cross_session_boundaries,test_enrich_skips_message_outside_timestamp_tolerancepin thethree failure modes that the matcher must refuse: ambiguity, cross-
session pollution, and out-of-window false positive. A future edit
that loosens any of these constraints would break a test.
test_materialization_ors_heuristic_with_history_evidencecoversthe 2×2 grid of (heuristic, history-annotation) → expected
has_paste at the materialization boundary.
_PASTE_MARKER_PATTERNchange is pinnedby
test_detect_paste_marker_with_line_count_annotationandtest_detect_paste_marker_must_close_in_same_bracket_pair. Theexisting 28-case
test_paste_detection.pysuite passesunchanged, so the matcher relaxation didn't loosen any
previously-rejected case.
variants observed in production (
[Pasted text #1 +6 lines],[Pasted text #1]) and the exactpastedContentsschema(
{<id>: {id, type, content}}).Verification angles skipped:
per conversation during assembly; there is no shared mutable state
across conversations.
build_session_paste_indexiterates the sidecar once per source-walk, drops non-paste rows
immediately. The matcher iterates only user messages, which is the
small minority. No new amplification class.
Commands run:
Notes (deferred to follow-up)
requires daemon-side hook event → message-row linking on a separate
convergence stage. Distinct enough scope to warrant its own PR;
filed-as-follow-up captured in body so no AC silently disappears.
hash_only durably exposed in the reader): richer-than-bool schema
surface, separate schema-touching PR (re-ingest plan required).
matcher drops them silently today. A typed
paste_match_diagnosticssidecar would let the reader surface "history row had no unique
match" cases. Deferred — the AC says "ambiguous rows must not
silently mark unrelated messages", which is honored; the reader
diagnostic surface is the additional richness.