--verify (read-only, the default) rewrites every lab transcript and its hub archive copy in a temp dir and parses both with this tree's backend: with no fix the copy must parse exactly like the original (summary, full, chunked); each fix alone lists the parse paths it changes. --dry-run, --apply (skips a session with a live run, a file modified in the last 10 min or one that changes meanwhile; originals to ~/.cache/ai-agent/transcript-backups/ v1-rewrite-<date>/ with a manifest; mtime + 1 s), --restore (a file a run appended to since keeps its v1 tail behind a header), --prune (30 days). The workers' synced copies are left in the old format and counted: the FeedMirror syncs them by size, a rewrite here would be undone or corrupted. The v1 reader no longer times a call from a session event (a fact that changed, not what unblocked the call), so a session event keeps its time (the resource miner dates a worktree's branch with it); a converter's header takes the first moment it writes. A mirror that loaded a file in the old format re-checks its head before appending (it may have been rewritten). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
263 lines
12 KiB
Python
263 lines
12 KiB
Python
"""A legacy pi / opencode / agy transcript → the v1 events a converter would
|
|
have written for it (``docs/transcript-format.md``): the one-off rewrite of
|
|
the unified-format plan's step 1c (``scripts/transcripts-v1.py``).
|
|
|
|
The translation is the hub's own reading of the file: each record goes
|
|
through ``LegacyReader`` and its events are written out as v1 lines, so the
|
|
v1 file folds to the summary and thread the legacy one did. What the writing
|
|
adds:
|
|
|
|
- a v1 header first (``{"t": "session", "v": 1, …}``);
|
|
- a step written whole: its ``call``, its blocks, then its ``usage`` (the
|
|
reader holds a step until its usage, so this is how one stays one batch);
|
|
- the converters' dedup keys (``ocKey`` / ``ocKeys`` / ``agyKey``) on the
|
|
first event of each record's events, so the live mirrors, which rebuild
|
|
what a file holds from the file, never write a record twice (a record that
|
|
leaves no event carries them on a bare ``tick``);
|
|
- a ``tick`` after a last step that has no usage (the reader would hold it
|
|
forever);
|
|
- the v1 part of a file that already switched to v1 mid-file, copied as is.
|
|
|
|
``FIXES`` — what the rewrite changes on purpose, each one switchable (the
|
|
proof rewrites with none of them first, and the parse must then be
|
|
identical):
|
|
|
|
- ``whole_steps`` (quirk a): an opencode step the mirror saw while it
|
|
streamed was written as its content, then a content-less record with its
|
|
usage after the tools ran; the hub folded that pair differently from the
|
|
one-shot step (the item lost its output tokens, the turn's cost landed on
|
|
another item). The usage joins its step, as the mirror writes a step now;
|
|
- ``source_times`` (quirk c): the records the agy mirror wrote to close a
|
|
turn (``turn_end``, the interrupt marker, the interrupted tool results, the
|
|
API-error turn) carried the mirror's clock; they take the latest time the
|
|
source recorded before them, as the mirror stamps them now;
|
|
- ``harness``: the header names the harness — pi's runner stamped it on no
|
|
record the hub read, so a pi conversation read as ``harness: null``;
|
|
- ``no_pi_fallback`` (found on the way): an opencode step that failed with
|
|
no content was also read as one of pi's empty error turns from before
|
|
2026-11-06 (``errors.legacy_error_turn``) — a second, made-up API-error
|
|
card ("the model call failed — this run didn't record why") ahead of the
|
|
real one. Such a step leaves nothing (the real error follows), as the
|
|
mirror writes it now.
|
|
|
|
Quirk (b) of the plan (a provider cost counted for a repeat of an
|
|
already-priced call) was fixed in the fold before this (``e0d9dc42``)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
|
|
from .events import STEP_TYPES, V, is_v1_header
|
|
from .readers.legacy import LegacyReader
|
|
|
|
FIXES = ("whole_steps", "source_times", "harness", "no_pi_fallback")
|
|
HARNESSES = ("pi", "opencode", "agy")
|
|
KEY_FIELDS = ("ocKey", "ocKeys", "agyKey")
|
|
|
|
# agy: the records ``agy_mirror._records.close`` wrote with the mirror's own
|
|
# clock — keyed by what closed the turn, plus the canned results it gave the
|
|
# calls left open.
|
|
_AGY_CLOSE_PREFIXES = ("end:", "interrupt:", "apierr:")
|
|
_AGY_CLOSE_RESULTS = frozenset((
|
|
"[Request interrupted by user for tool use]", "tool did not finish",
|
|
"[no result recorded — the run ended]"))
|
|
_BLOCKS = ("text", "thinking", "tool_call", "error")
|
|
|
|
|
|
# Flags whose absence means false, and the token counts whose absence means 0:
|
|
# left out of a line when they say nothing.
|
|
_FALSE_FLAGS = {"call": ("virtual", "failed", "empty"), "text": ("paused",),
|
|
"tool_settled": ("late",)}
|
|
_ZERO_TOKENS = ("cacheRead", "cacheWrite5m", "cacheWrite1h", "cacheWrite", "reasoning")
|
|
|
|
|
|
def compact(ev: dict) -> dict:
|
|
"""``ev`` without the fields that say nothing (null, a false flag, a zero
|
|
token count): the fold reads each of them as absent. A ``session`` event
|
|
is kept whole — a fact set to null there is a change of fact."""
|
|
if ev.get("t") == "session":
|
|
return ev
|
|
flags = _FALSE_FLAGS.get(ev.get("t"), ())
|
|
zeros = _ZERO_TOKENS if ev.get("t") == "usage" else ()
|
|
return {k: v for k, v in ev.items()
|
|
if v is not None and not (k in flags and v is False)
|
|
and not (k in zeros and v == 0)}
|
|
|
|
|
|
def dumps(ev: dict) -> str:
|
|
"""One v1 line (no newline): compact, UTF-8 as is, ``t`` and ``at`` first."""
|
|
ev = compact(ev)
|
|
head = {k: ev[k] for k in ("t", "at") if k in ev}
|
|
return json.dumps({**head, **ev}, ensure_ascii=False, separators=(",", ":"))
|
|
|
|
|
|
def detect_harness(records) -> str | None:
|
|
"""Which converter wrote a legacy transcript: the ``entrypoint`` the
|
|
opencode / agy mirrors stamp on every record, the one pi's runner stamps
|
|
on its turn-end record — else pi when its user / assistant records carry
|
|
no ``uuid`` (Claude Code's always do). None: Claude Code's own."""
|
|
saw_turn = False
|
|
for o in records:
|
|
if not isinstance(o, dict):
|
|
continue
|
|
if is_v1_header(o):
|
|
break
|
|
ep = o.get("entrypoint")
|
|
if ep in HARNESSES:
|
|
return ep
|
|
if o.get("type") in ("user", "assistant"):
|
|
if o.get("uuid") or not o.get("sessionId"):
|
|
return None
|
|
saw_turn = True
|
|
return "pi" if saw_turn else None
|
|
|
|
|
|
def _agy_close(o: dict) -> bool:
|
|
key = o.get("agyKey") or ""
|
|
if key.startswith(_AGY_CLOSE_PREFIXES):
|
|
return True
|
|
if key.startswith("result:") and o.get("type") == "user":
|
|
c = (o.get("message") or {}).get("content")
|
|
b = c[0] if isinstance(c, list) and c and isinstance(c[0], dict) else {}
|
|
inner = b.get("content")
|
|
text = inner[0].get("text") if isinstance(inner, list) and inner \
|
|
and isinstance(inner[0], dict) else None
|
|
return b.get("type") == "tool_result" and text in _AGY_CLOSE_RESULTS
|
|
return False
|
|
|
|
|
|
def _whole(evs: list[dict]) -> list[dict]:
|
|
"""A record's events with its step written whole: ``usage`` after the
|
|
step's blocks (the legacy reader puts it right after the call)."""
|
|
ci = next((i for i, e in enumerate(evs) if e["t"] == "call"), None)
|
|
if ci is None:
|
|
return evs
|
|
ui = next((i for i in range(ci + 1, len(evs)) if evs[i]["t"] == "usage"), None)
|
|
if ui is None:
|
|
return evs
|
|
usage = evs[ui]
|
|
rest = evs[:ui] + evs[ui + 1:]
|
|
end = ci + 1
|
|
while end < len(rest) and rest[end]["t"] in _BLOCKS:
|
|
end += 1
|
|
return rest[:end] + [usage] + rest[end:]
|
|
|
|
|
|
def _with_call(evs: list[dict]) -> list[dict]:
|
|
"""Blocks and usage name their call when it has an id."""
|
|
cid = None
|
|
out = []
|
|
for e in evs:
|
|
if e["t"] == "call":
|
|
cid = e.get("id")
|
|
elif e["t"] in STEP_TYPES and cid is not None and "call" not in e:
|
|
e = {**e, "call": cid}
|
|
elif e["t"] not in STEP_TYPES:
|
|
cid = None
|
|
out.append(e)
|
|
return out
|
|
|
|
|
|
class _Stats:
|
|
def __init__(self):
|
|
self.records = 0
|
|
self.events = 0
|
|
self.merged_steps = 0 # whole_steps: usage records joined to their step
|
|
self.retimed = 0 # source_times: agy close records
|
|
self.v1_lines = 0 # lines copied from a v1 part
|
|
self.fallbacks = 0 # no_pi_fallback: opencode failed steps not read as pi's
|
|
|
|
|
|
def to_v1(lines, harness: str | None, fixes=FIXES, stats: _Stats | None = None) -> list[str]:
|
|
"""The v1 lines (no newlines) of a legacy transcript given as its lines
|
|
(``str``; what is not a JSON object is dropped, as the hub does).
|
|
``harness``: ``pi`` / ``opencode`` / ``agy`` (``detect_harness``)."""
|
|
st = stats or _Stats()
|
|
reader = LegacyReader(full=True)
|
|
groups: list[list[dict]] = [] # one per record
|
|
unpriced: dict[tuple, list[dict]] = {} # opencode: (call id, request) → its step's group
|
|
tail: list[str] = [] # a v1 part, as is
|
|
last_src_at = None
|
|
for raw in lines:
|
|
s = raw.strip()
|
|
if not s or s[0] != "{":
|
|
continue
|
|
try:
|
|
o = json.loads(s)
|
|
except ValueError:
|
|
continue
|
|
if tail or is_v1_header(o):
|
|
tail.append(s)
|
|
continue
|
|
st.records += 1
|
|
keys = {k: o[k] for k in KEY_FIELDS if o.get(k)}
|
|
msg = o.get("message") if o.get("type") == "assistant" else None
|
|
if harness in ("opencode", "agy") and "no_pi_fallback" in fixes \
|
|
and isinstance(msg, dict) and msg.get("stop_reason") == "error" \
|
|
and not msg.get("content") and not o.get("isApiErrorMessage"):
|
|
st.fallbacks += 1
|
|
if not msg.get("usage"):
|
|
groups.append([{"t": "tick", **keys}] if keys else [])
|
|
continue
|
|
o = {**o, "message": {**msg, "stop_reason": None}}
|
|
evs = _with_call(_whole([dict(e) for e in reader.feed(o)]))
|
|
if harness == "agy" and "source_times" in fixes and _agy_close(o):
|
|
if last_src_at:
|
|
for e in evs:
|
|
if e.get("at"):
|
|
e["at"] = last_src_at
|
|
if e["t"] == "call":
|
|
e["elapsedMs"] = None # the reader times it from the event before
|
|
st.retimed += 1
|
|
elif o.get("timestamp") and (last_src_at is None or o["timestamp"] > last_src_at):
|
|
last_src_at = o["timestamp"]
|
|
if harness == "opencode" and "whole_steps" in fixes:
|
|
steps = [e for e in evs if e["t"] != "session"]
|
|
call = steps[0] if steps and steps[0]["t"] == "call" else None
|
|
ckey = (call["id"], call.get("request")) if call and call.get("id") else None
|
|
if ckey is not None and len(steps) == 2 and steps[1]["t"] == "usage" \
|
|
and call.get("empty") and ckey in unpriced:
|
|
# The usage of a step already written without it: it joins
|
|
# that step, as if the step had been seen whole.
|
|
g = unpriced.pop(ckey)
|
|
ci = next(i for i, e in enumerate(g) if e["t"] == "call")
|
|
u = {**steps[1], "at": g[ci].get("at")}
|
|
end = ci + 1
|
|
while end < len(g) and g[end]["t"] in _BLOCKS:
|
|
end += 1
|
|
g.insert(end, u)
|
|
carrier = g[0]
|
|
extra = [keys[k] for k in ("ocKey",) if keys.get(k)] + list(keys.get("ocKeys") or [])
|
|
if extra:
|
|
carrier["ocKeys"] = list(carrier.get("ocKeys") or []) + extra
|
|
st.merged_steps += 1
|
|
rest = [e for e in evs if e["t"] == "session"]
|
|
groups.append(rest)
|
|
continue
|
|
if ckey is not None and not call.get("empty") \
|
|
and not any(e["t"] == "usage" for e in steps):
|
|
unpriced[ckey] = evs
|
|
if keys:
|
|
if evs:
|
|
evs[0] = {**evs[0], **keys}
|
|
else:
|
|
evs = [{"t": "tick", **keys}]
|
|
groups.append(evs)
|
|
events = [e for g in groups for e in g]
|
|
if not events:
|
|
return tail # nothing in the old format (or nothing at all)
|
|
# The header: the reader's first session event (the facts of the first
|
|
# record) with the version and the harness.
|
|
named = harness if ("harness" in fixes or harness != "pi") else None
|
|
if events and events[0]["t"] == "session" and "v" not in events[0]:
|
|
events[0] = {**events[0], "v": V, **({"harness": named} if named else {})}
|
|
else:
|
|
events.insert(0, {"t": "session", "v": V, **({"harness": named} if named else {})})
|
|
if not tail and events[-1]["t"] in STEP_TYPES and events[-1]["t"] != "usage":
|
|
# A last step with no usage: the reader holds a step until its usage
|
|
# or the next event — this is the next event (it changes nothing).
|
|
events.append({"t": "tick", "at": events[-1].get("at")})
|
|
st.events += len(events)
|
|
st.v1_lines += len(tail)
|
|
return [dumps(e) for e in events] + tail
|