Skip to content

feat(parsers): wire Claude Code history.jsonl paste evidence into has_paste - #1651

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/has-paste-hook-history-evidence
May 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/has-paste-hook-history-evidence

Conversation

@Sinity

@Sinity Sinity commented May 27, 2026

Copy link
Copy Markdown
Owner

Summary

Claude Code's ~/.claude/history.jsonl records every prompt with a
pastedContents map. Polylogue ingest never read it, so user messages
whose assembled text no longer carried the [Pasted text #N] marker
silently resolved to has_paste=0 even when the sidecar knew a paste
happened. Wire the history sidecar into the assembly enrichment path so
matched user messages get has_paste=1, and fix the existing
detect_paste regex which missed the actual production marker form
[Pasted text #N +M lines].

Ref #1583

Problem

Two evidence sources for paste boundaries collided silently:

  1. detect_paste(msg.text) looked for \[Pasted\s+(text|content|image)\s*#\d+\]
    — required #N] with nothing between N and ]. Production Claude
    Code actually emits [Pasted text #1 +6 lines], so the heuristic
    was a no-op on every real Claude Code prompt that contained a marker.
  2. ~/.claude/history.jsonl records paste data with full content (or
    hash-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-only CLI filters, and the
reader/MCP/API envelopes all agreed on the wrong answer for Claude
Code paste-bearing messages.

Solution

New parser polylogue/sources/parsers/claude/history.py:

  • HistoryEntry and HistoryPaste dataclasses model the actual
    on-disk shape.
  • parse_history_jsonl(path) yields rows, skipping malformed lines
    and 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 sessionId or without paste evidence are dropped at
    build time because they can never be matched on the strong-identity
    path and would inflate memory for nothing.

ClaudeCodeAssemblySpec.discover_sidecars now also looks two dirs
above each session file for history.jsonl and returns the indexed
sidecar alongside session_index.

ClaudeCodeAssemblySpec.enrich_conversation walks each conversation's
user messages, matches them to paste-bearing history rows by sessionId

  • timestamp proximity (6s tolerance — covers realistic clock skew but
    fits inside a single user turn), and writes
    {"claude_code_history_paste": True} into ParsedMessage.provider_meta
    for 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_runtime reads the annotation and ORs it with the
text heuristic when computing has_paste. conversation_stats.paste_count
already derives from messages.has_paste so the upstream change
propagates without further wiring.

paste_detection._PASTE_MARKER_PATTERN now permits annotation between
#N and 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:

  • Direct behavior ✓ — test_enrich_marks_matched_user_message_with_paste_evidence,
    test_enrich_marks_hash_only_paste_as_evidence_too,
    test_discover_sidecars_indexes_history_paste_entries exercise the
    happy paths end-to-end (real-disk sidecar + sessionId+timestamp
    match + provider_meta annotation).
  • Counterfactual ✓ —
    test_enrich_does_not_silently_fan_evidence_across_ambiguous_matches,
    test_enrich_does_not_cross_session_boundaries,
    test_enrich_skips_message_outside_timestamp_tolerance pin the
    three 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.
  • Property-shaped parametrized check ✓ —
    test_materialization_ors_heuristic_with_history_evidence covers
    the 2×2 grid of (heuristic, history-annotation) → expected
    has_paste at the materialization boundary.
  • Contract / envelope ✓ — _PASTE_MARKER_PATTERN change is pinned
    by test_detect_paste_marker_with_line_count_annotation and
    test_detect_paste_marker_must_close_in_same_bracket_pair. The
    existing 28-case test_paste_detection.py suite passes
    unchanged, so the matcher relaxation didn't loosen any
    previously-rejected case.
  • Witness ✓ — the test fixtures use the exact paste-marker
    variants observed in production ([Pasted text #1 +6 lines],
    [Pasted text #1]) and the exact pastedContents schema
    ({<id>: {id, type, content}}).

Verification angles skipped:

  • Concurrency / lifecycle — N/A. Enrichment runs synchronously
    per conversation during assembly; there is no shared mutable state
    across conversations.
  • Performance / amplification — build_session_paste_index
    iterates 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:

$ nix develop -c pytest tests/unit/sources/ \
    tests/unit/pipeline/test_materialization_runtime.py \
    tests/unit/core/test_paste_detection.py -x
1322 passed in 113.34s

$ nix develop -c devtools verify --quick
exit_code: 0

Notes (deferred to follow-up)

  • AC feat: unify Gemini export rendering and Drive sync in gmd #2 (UserPromptSubmit hook event → message.has_paste wiring):
    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.
  • AC The project name and filesystem layout still assume a Gemini-only tool #7 (boundary-state schema: exact/projected/whole_message_fallback/
    hash_only durably exposed in the reader):
    richer-than-bool schema
    surface, separate schema-touching PR (re-ingest plan required).
  • Diagnostic surface for ambiguous-history-row matches: the
    matcher drops them silently today. A typed paste_match_diagnostics
    sidecar 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.

…_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]>
@coderabbitai

coderabbitai Bot commented May 27, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f810597f-2050-4ac6-9950-4c77b67c2e93

📥 Commits

Reviewing files that changed from the base of the PR and between 8f4941b and 0c2c01b.

📒 Files selected for processing (10)
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/archive/message/paste_detection.py
  • polylogue/pipeline/materialization_runtime.py
  • polylogue/sources/assembly.py
  • polylogue/sources/assembly_claude_code.py
  • polylogue/sources/parsers/claude/history.py
  • tests/unit/core/test_paste_detection.py
  • tests/unit/sources/test_assembly_claude_code_history.py
  • tests/unit/sources/test_parsers_claude_history.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/has-paste-hook-history-evidence

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Sinity
Sinity merged commit 2872c65 into master May 27, 2026
7 checks passed
@Sinity
Sinity deleted the feature/feat/has-paste-hook-history-evidence branch May 27, 2026 08:11
Sinity added a commit that referenced this pull request May 27, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant