Files
gabrielvidalandClaude Opus 5.5 3ec287a493 refactor(conversations): turn parse.py into a package (pass a: pure moves)
conversations/parse.py (2,449 lines) becomes conversations/parse/:
records (JSONL records, timestamps, clipped blocks, _item), usertext (inbox /
cancel / relay / author / held / slash / skill / image / compact text), tools
(buckets, sub-labels, project / service / worktree / commit evidence,
lifecycle + deploys), errors (API-error kinds, limit resets), usage (delta /
estimate / cost-state helpers), turns (turn-end records), state
(ParserState + parse_conversation, unchanged) and cut (find_cut_line).

Code moved verbatim. The package re-exports every name the module had, and
its __all__ is exactly what `from .parse import *` exported before, so the
`conversations` namespace is identical (checked name by name).

Verified against 57a4d8ee: parse-ab 500 files x 2 modes 0 differing,
--chunked 0 mismatches, pricing-dump identical, test_parse_fixtures OK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:34:14 +01:00

52 lines
2.2 KiB
Python

"""Where to cut a transcript to fork it at a user message."""
import json
import pathlib
from .state import ParserState
def find_cut_line(path: pathlib.Path, mi: int) -> dict | None:
"""Locate the raw transcript line holding user message ordinal ``mi``.
Forking a conversation at a message needs the JSONL line where that
message lives. ``mi`` is assigned by ``ParserState.feed`` (one per
user/assistant text block, in transcript order), so instead of
reimplementing that rule — and silently drifting from it — this walks the
file through a throwaway ``ParserState`` and watches ``search_msgs`` grow.
Returns ``{"line", "text", "userOrd", "key"}`` for the record that produced
message ``mi`` — ``line`` is 0-based over *raw* file lines (so
``lines[:line]`` is the history strictly before it), ``text`` the
search-clipped message text (a canary for the sidecar's own slice), and
``userOrd`` this message's 0-based ordinal among *user* messages only
(how the pi runner finds the same point in pi's native session file).
Returns ``None`` when ``mi`` doesn't exist or belongs to an assistant
message (only user messages are fork points).
"""
st = ParserState(path, full=False)
try:
with path.open(encoding="utf-8", errors="ignore") as fh:
for i, line in enumerate(fh):
s = line.strip()
if not s or s[0] != "{":
continue
try:
o = json.loads(s)
except ValueError:
continue
before = len(st.search_msgs)
st.feed(o)
if before <= mi < len(st.search_msgs):
m = st.search_msgs[mi]
if m.get("role") != "user":
return None
return {"line": i, "text": m.get("text") or "",
"userOrd": sum(1 for e in st.search_msgs[:mi]
if e.get("role") == "user"),
# the opencode mirror's record key (user:<msg id>)
"key": o.get("ocKey")}
except OSError:
return None
return None