Files
ai-agent/backend/test_transcripts_v1.py
gabrielvidalandClaude Opus 5.5 f72371d1e8 fix(diff): the uncommitted diff sees a shell rm in a v1 transcript
editsdiff found deletes in Claude-Code-shaped Bash tool_use blocks only; a
pi / opencode / agy shell call is a v1 tool_call now (and after the rewrite,
for the past ones too), timed by its `at`, run in the session's cwd.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:44:43 +01:00

360 lines
19 KiB
Python

"""Step 1c of the unified transcript format: the converters write v1, the
past pi / opencode / agy transcripts are rewritten to it.
- ``rewrite_v1.to_v1`` with no fix is faithful: the v1 file parses exactly
like the old one, summary and thread, fed in chunks too; each fix changes
only what it says (``scripts/transcripts-v1.py --verify`` runs the same
over the lab's real files);
- a file in the old format that a converter continues in v1 (a resume of a
conversation from before v1) parses like the same conversation written in
one format: ``LegacyReader`` switches at the v1 header line;
- what else reads a transcript's lines reads v1 too: the uid's timestamp
(``ids.head_timestamp_ms``), an image Read's path (``toolimage``), a shell
``rm`` in the uncommitted diff (``editsdiff``), the fork point and the
opencode mirror's key (``find_cut_line``)."""
import json
import pathlib
import tempfile
import unittest
import conversations as c
from conversations import ids, toolimage
from conversations.parse import rewrite_v1
from conversations.parse.readers import LegacyReader, V1Reader
HERE = pathlib.Path(__file__).resolve().parent
FIXTURES = HERE / "fixtures" / "transcripts"
LEGACY = {"pi": FIXTURES / "pi.jsonl", "opencode": FIXTURES / "opencode.jsonl",
"agy": FIXTURES / "agy.jsonl"}
def canonical(obj) -> str:
return json.dumps(obj, sort_keys=True, ensure_ascii=False)
def _parse_lines(lines: list[str], full: bool, name: str = "x.jsonl") -> dict:
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / name
p.write_text("\n".join(lines) + "\n", encoding="utf-8")
return c.parse_conversation(p, full=full)
def _chunked(lines: list[str], full: bool) -> dict:
"""The file fed line by line through ``feed_lines``, as the indexer does."""
with tempfile.TemporaryDirectory() as d:
p = pathlib.Path(d) / "x.jsonl"
p.write_text("", encoding="utf-8")
st = c.ParserState(p, full=full)
off = 0
for ln in lines:
with p.open("a", encoding="utf-8") as fh:
fh.write(ln + "\n")
off = c.feed_lines(st, p, off)
return st.summary()
def _lines(path: pathlib.Path) -> list[str]:
return [ln for ln in path.read_text(encoding="utf-8").splitlines() if ln.strip()]
def _paths(a, b, path="$") -> list[str]:
if isinstance(a, dict) and isinstance(b, dict):
out = []
for k in sorted(set(a) | set(b)):
out += ([f"{path}.{k}"] if k not in a or k not in b
else _paths(a[k], b[k], f"{path}.{k}"))
return out
if isinstance(a, list) and isinstance(b, list):
out = [f"{path}.length"] if len(a) != len(b) else []
for i, (x, y) in enumerate(zip(a, b)):
out += _paths(x, y, f"{path}[{i}]")
return out
return [] if a == b and type(a) is type(b) else [path]
class RewriteIsFaithful(unittest.TestCase):
def test_no_fix_parses_exactly_like_the_old_file(self):
for harness, path in LEGACY.items():
old = _lines(path)
new = rewrite_v1.to_v1(old, harness, fixes=())
self.assertTrue(json.loads(new[0])["v"] == 1, harness)
for full in (False, True):
a = c.parse_conversation(path, full=full)
self.assertEqual(canonical(_parse_lines(new, full, path.name)), canonical(a),
f"{harness} full={full}")
self.assertEqual(canonical(_chunked(new, full)),
canonical(_parse_lines(new, full)), f"{harness} chunked")
def test_what_each_fix_changes(self):
# pi: the header names the harness (pi's runner stamped it nowhere
# the hub read).
old = _lines(LEGACY["pi"])
a = c.parse_conversation(LEGACY["pi"], full=True)
b = _parse_lines(rewrite_v1.to_v1(old, "pi", fixes=("harness",)), True, "pi.jsonl")
self.assertEqual(_paths(a, b), ["$.harness"])
self.assertEqual(b["harness"], "pi")
# agy: the turn's close took the mirror's clock in the fixture? It
# carries source times there already — nothing to move.
old = _lines(LEGACY["agy"])
self.assertEqual(rewrite_v1.to_v1(old, "agy"), rewrite_v1.to_v1(old, "agy", fixes=()))
def test_whole_steps_join_a_late_usage_to_its_step(self):
"""quirk (a): opencode's step seen while it streamed — content, its
tool's result, then a content-less usage record — folds like the
step seen whole (the item keeps its output tokens)."""
sid = "33333333-aaaa-4bbb-8ccc-000000000009"
base = {"sessionId": sid, "cwd": "/w", "entrypoint": "opencode", "isSidechain": False}
msg = {"id": "msg_1", "type": "message", "role": "assistant", "model": "gpt-5.5"}
split = [
{**base, "type": "user", "ocKey": "user:u", "uuid": "a",
"timestamp": "2026-11-01T10:00:00.000Z",
"message": {"role": "user", "content": "go"}},
{**base, "type": "assistant", "ocKey": "step:msg_1", "uuid": "b", "requestId": "msg_1",
"timestamp": "2026-11-01T10:00:02.000Z",
"message": {**msg, "content": [{"type": "text", "text": "Listing."},
{"type": "tool_use", "id": "c1", "name": "Bash",
"input": {"command": "ls"}}]}},
{**base, "type": "user", "ocKey": "result:c1", "uuid": "c",
"timestamp": "2026-11-01T10:00:03.000Z",
"message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "c1",
"content": [{"type": "text", "text": "a"}],
"is_error": False}]}},
{**base, "type": "assistant", "ocKey": "usage:msg_1", "uuid": "d", "requestId": "msg_1",
"timestamp": "2026-11-01T10:00:04.000Z",
"message": {**msg, "content": [], "usage": {"input_tokens": 100,
"output_tokens": 30}}},
]
whole = [split[0], {**split[1], "ocKeys": ["usage:msg_1"],
"message": {**split[1]["message"], "usage": split[3]["message"]["usage"]}},
split[2]]
lines = [json.dumps(o) for o in split]
faithful = rewrite_v1.to_v1(lines, "opencode", fixes=())
fixed = rewrite_v1.to_v1(lines, "opencode", fixes=("whole_steps",))
old = _parse_lines(lines, True)
self.assertEqual(canonical(_parse_lines(faithful, True)), canonical(old))
new = _parse_lines(fixed, True)
self.assertEqual(canonical(new), canonical(_parse_lines([json.dumps(o) for o in whole],
True)))
self.assertNotIn("out", old["thread"][1])
self.assertEqual(new["thread"][1]["out"], 30)
# the mirror's keys survive: both records are known to it
keys = [json.loads(ln).get("ocKey") for ln in fixed] + \
[k for ln in fixed for k in json.loads(ln).get("ocKeys") or []]
self.assertLessEqual({"user:u", "step:msg_1", "result:c1", "usage:msg_1"}, set(keys))
def test_source_times_close_an_agy_turn_at_the_last_source_time(self):
"""quirk (c): the records the agy mirror closed a turn with carried
its clock; they take the latest time agy recorded before them."""
sid = "44444444-aaaa-4bbb-8ccc-000000000009"
base = {"sessionId": sid, "cwd": "/w", "entrypoint": "agy", "isSidechain": False}
recs = [
{**base, "type": "user", "agyKey": "user:0", "uuid": "a",
"timestamp": "2026-11-01T10:00:00.000Z", "message": {"role": "user", "content": "go"}},
{**base, "type": "assistant", "agyKey": "step:1", "uuid": "b", "requestId": "agy:x:1",
"timestamp": "2026-11-01T10:00:05.000Z",
"message": {"id": "msg_agy_x_1", "role": "assistant", "model": "gemini-4-neon",
"content": [{"type": "text", "text": "done"}],
"usage": {"input_tokens": 10, "output_tokens": 2}}},
{**base, "type": "user", "agyKey": "interrupt:0:1", "uuid": "c",
"timestamp": "2099-01-01T00:00:00.000Z",
"message": {"role": "user", "content": "[Request interrupted by user]"}},
{**base, "type": "system", "subtype": "turn_end", "agyKey": "end:0:1", "uuid": "d",
"timestamp": "2099-01-01T00:00:00.000Z"},
]
lines = [json.dumps(o) for o in recs]
old = _parse_lines(lines, False)
self.assertEqual(old["endedAt"], "2099-01-01T00:00:00.000Z")
new = _parse_lines(rewrite_v1.to_v1(lines, "agy", fixes=("source_times",)), False)
self.assertEqual(new["endedAt"], "2026-11-01T10:00:05.000Z")
self.assertEqual(_paths(old, new), ["$.endedAt"])
def test_no_pi_fallback_drops_the_made_up_error_of_an_empty_failed_step(self):
sid = "33333333-aaaa-4bbb-8ccc-00000000000a"
base = {"sessionId": sid, "cwd": "/w", "entrypoint": "opencode", "isSidechain": False}
recs = [
{**base, "type": "user", "ocKey": "user:u", "uuid": "a",
"timestamp": "2026-11-01T10:00:00.000Z", "message": {"role": "user", "content": "go"}},
{**base, "type": "assistant", "ocKey": "step:m", "uuid": "b", "requestId": "m",
"timestamp": "2026-11-01T10:00:01.000Z",
"message": {"id": "m", "role": "assistant", "model": "gpt-5.5", "stop_reason": "error",
"content": []}},
{**base, "type": "assistant", "ocKey": "error:m", "uuid": "c",
"timestamp": "2026-11-01T10:00:01.000Z", "isApiErrorMessage": True,
"error": "rate_limit",
"message": {"id": "error:m", "role": "assistant", "model": "<synthetic>",
"content": [{"type": "text", "text": "API Error: 429 usage limit"}],
"usage": {"input_tokens": 0, "output_tokens": 0}}},
]
lines = [json.dumps(o) for o in recs]
old = _parse_lines(lines, True)
cards = [it for it in old["thread"] if it.get("apiError")]
self.assertEqual(len(cards), 2) # the made-up one, then the real one
new = _parse_lines(rewrite_v1.to_v1(lines, "opencode", fixes=("no_pi_fallback",)), True)
self.assertEqual([it.get("apiError") for it in new["thread"] if it.get("apiError")],
["rate_limit"])
self.assertIn("step:m", "".join(rewrite_v1.to_v1(lines, "opencode"))) # its key kept
def test_harness_detection(self):
for harness, path in LEGACY.items():
recs = [json.loads(ln) for ln in _lines(path)]
self.assertEqual(rewrite_v1.detect_harness(recs), harness)
recs = [json.loads(ln) for ln in _lines(FIXTURES / "claude.jsonl") if ln.startswith("{")]
self.assertIsNone(rewrite_v1.detect_harness(recs))
v1 = [json.loads(ln) for ln in _lines(FIXTURES / "pi.v1.jsonl")]
self.assertIsNone(rewrite_v1.detect_harness(v1))
self.assertEqual(rewrite_v1.to_v1(_lines(FIXTURES / "pi.v1.jsonl"), "pi"),
_lines(FIXTURES / "pi.v1.jsonl")) # a v1 file is left as is
class OldFormatContinuedInV1(unittest.TestCase):
"""A converter appending to a file in the old format writes a v1 header
line first; the rest is v1. Cut a legacy fixture at a record, write the
rest as v1 behind a header: it parses like the whole old file."""
def test_every_cut(self):
for harness, path in LEGACY.items():
old = _lines(path)
want = {full: canonical(c.parse_conversation(path, full=full)) for full in (False, True)}
for k in range(1, len(old)):
tail = rewrite_v1.to_v1(old[k:], harness, fixes=())
head = json.loads(tail[0])
if head.get("t") != "session":
continue
mixed = old[:k] + tail
for full in (False, True):
got = canonical(_parse_lines(mixed, full, path.name))
if got != want[full]:
a, b = json.loads(want[full]), json.loads(got)
# a cut mid-conversation loses what the reader carried
# across records (a Skill call's name, a priced call);
# these fixtures carry none of it
self.fail(f"{harness} cut at {k} full={full}: {_paths(a, b)[:6]}")
def test_the_reader_switches_at_the_header(self):
r = LegacyReader(full=True)
r.feed({"type": "user", "timestamp": "2026-11-01T10:00:00.000Z",
"message": {"role": "user", "content": "hi"}})
evs = r.feed({"t": "session", "v": 1, "id": "s"})
self.assertIsInstance(r._v1, V1Reader)
self.assertEqual(evs[0]["t"], "session")
self.assertEqual(r.feed({"t": "prompt", "text": "again", "origin": "user"})[0]["text"],
"again")
# a Claude Code record after the switch is not an event: dropped
self.assertEqual(r.feed({"type": "user", "message": {"role": "user", "content": "x"}}), [])
class RawReadersReadV1(unittest.TestCase):
def setUp(self):
self._d = tempfile.TemporaryDirectory()
self.dir = pathlib.Path(self._d.name)
def tearDown(self):
self._d.cleanup()
def _v1(self, *evs) -> pathlib.Path:
p = self.dir / "s.jsonl"
p.write_text("".join(json.dumps(e) + "\n" for e in evs))
return p
def test_the_uid_timestamp_is_the_first_at(self):
p = self._v1({"t": "session", "v": 1, "id": "s"},
{"t": "prompt", "at": "2026-11-01T10:00:00.000Z", "text": "hi"})
self.assertEqual(ids.head_timestamp_ms(p), 1793527200000)
def test_an_image_reads_path(self):
p = self._v1({"t": "session", "v": 1, "id": "s"},
{"t": "tool_call", "id": "c1", "tool": "read", "native": "read",
"input": {"file_path": "/w/shot.png"}})
self.assertEqual(toolimage.read_path(p, "c1"), "/w/shot.png")
self.assertIsNone(toolimage.read_path(p, "c2"))
def test_a_shell_rm_is_a_delete_in_the_uncommitted_diff(self):
from diff import editsdiff
cwd = "/home/u/projects/demo"
legacy = [
{"type": "user", "sessionId": "s", "cwd": cwd, "timestamp": "2026-11-01T10:00:00.000Z",
"message": {"role": "user", "content": "rm it"}},
{"type": "assistant", "sessionId": "s", "cwd": cwd,
"timestamp": "2026-11-01T10:00:01.000Z",
"message": {"role": "assistant", "model": "m",
"usage": {"input_tokens": 1, "output_tokens": 1},
"content": [{"type": "tool_use", "id": "c1", "name": "Bash",
"input": {"command": "rm old.txt"}}]}}]
old = self.dir / "old.jsonl"
old.write_text("".join(json.dumps(o) + "\n" for o in legacy))
new = self.dir / "new.jsonl"
new.write_text("\n".join(rewrite_v1.to_v1(_lines(old), "pi")) + "\n")
want = [{"ts": "2026-11-01T10:00:01.000Z", "file": f"{cwd}/old.txt", "kind": "delete"}]
self.assertEqual(editsdiff._events_from_file(old), want)
self.assertEqual(editsdiff._events_from_file(new), want)
def test_the_fork_point_and_its_key(self):
p = self._v1({"t": "session", "v": 1, "id": "s", "harness": "opencode"},
{"t": "prompt", "at": "2026-11-01T10:00:00.000Z", "text": "one",
"origin": "user", "ocKey": "user:m1"},
{"t": "call", "at": "2026-11-01T10:00:01.000Z", "id": "a"},
{"t": "text", "at": "2026-11-01T10:00:01.000Z", "text": "1", "call": "a"},
{"t": "usage", "at": "2026-11-01T10:00:01.000Z", "input": 1, "output": 1,
"call": "a"},
{"t": "prompt", "at": "2026-11-01T10:00:02.000Z", "text": "two",
"origin": "user", "ocKey": "user:m2"})
st = c.ParserState(p, full=False)
c.feed_lines(st, p, 0)
mi = next(i for i, m in enumerate(st.search_msgs) if m.get("text") == "two")
cut = c.find_cut_line(p, mi)
self.assertEqual((cut["line"], cut["userOrd"], cut["key"]), (5, 1, "user:m2"))
class RewriteScript(unittest.TestCase):
"""``scripts/transcripts-v1.py`` on a throw-away home: --apply rewrites a
source and its archive copy alike (backups, mtime + 1 s), leaves a
worker's copy, is idempotent; --restore puts the originals back."""
def test_apply_then_restore(self):
import os
import subprocess
import sys
import time
script = HERE.parent / "scripts" / "transcripts-v1.py"
with tempfile.TemporaryDirectory() as d:
home = pathlib.Path(d)
src = home / ".pi-runner/transcripts/-w" / "22222222-aaaa-4bbb-8ccc-000000000002.jsonl"
arc = home / "data/transcripts/-w" / src.name
wrk = home / "data/workers/transcripts/-m" / "oc.jsonl"
for dst, fx in ((src, "pi.jsonl"), (arc, "pi.jsonl"), (wrk, "opencode.jsonl")):
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_bytes((FIXTURES / fx).read_bytes())
os.utime(dst, (time.time() - 3600, time.time() - 3600))
env = {**os.environ, "HOME": str(home), "AI_AGENT_DATA": str(home / "data"),
"SIDECAR_LOG_DIR": str(home / "logs"),
"TRANSCRIPT_BACKUPS": str(home / "backups")}
mtime = src.stat().st_mtime
def run(*args):
r = subprocess.run([sys.executable, str(script), *args], env=env,
capture_output=True, text=True, timeout=300)
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
return r.stdout
out = run("--verify")
self.assertIn("OK: with no fix every rewritten copy parses exactly", out)
self.assertIn("workers' synced copies: 1 opencode", out)
run("--apply")
for f in (src, arc):
self.assertEqual(json.loads(f.read_text().split("\n", 1)[0])["v"], 1)
self.assertAlmostEqual(f.stat().st_mtime, mtime + 1, delta=0.01)
self.assertEqual(src.read_bytes(), arc.read_bytes())
self.assertEqual(wrk.read_bytes(), (FIXTURES / "opencode.jsonl").read_bytes())
self.assertEqual(c.parse_conversation(src, full=True)["harness"], "pi")
once = src.read_bytes()
self.assertIn("v1 already", run("--apply")) # idempotent
self.assertEqual(src.read_bytes(), once)
run("--restore")
self.assertEqual(src.read_bytes(), (FIXTURES / "pi.jsonl").read_bytes())
self.assertEqual(arc.read_bytes(), (FIXTURES / "pi.jsonl").read_bytes())
if __name__ == "__main__":
unittest.main()