Files
ai-agent/backend/test_parse_fixtures.py
gabrielvidalandClaude Opus 5.5 c3945fe965 refactor: retire core runner/ — pi's runner lives in the harness-pi plugin
runner/ (cli.mjs, extensions/folder-permissions.ts, test, README) was a
byte-for-byte duplicate of the harness-pi plugin's runner/, kept only as the
driver's fallback through the sidecar's config.RUNNER_BIN.

- delete runner/ and sidecar config.RUNNER_BIN
- scripts/test.py: drop the `runner` suite (it runs in ai-agent-plugins now)
- scripts/ab: the pi mirror replay uses a tree's runner/ when it has one
  (refs before this), else the plugin's (AB_PI_RUNNER)
- CLAUDE.md / docs / comments point at harness-pi's runner
- sidecar/local-model.md stays (harness-opencode's LOCAL_MODEL_GUIDE)

Merge only after harness-pi 1.1.0 is installed on the lab: harness-pi 1.0.x
reads config.RUNNER_BIN and would fail every pi run on this core.

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

605 lines
31 KiB
Python

"""The parser's byte-offset contract, on synthetic transcripts.
``fixtures/transcripts/`` holds one small hand-written transcript per harness
(claude, a claude subagent, pi, opencode, agy — the shapes harness-pi's ``runner/cli.mjs``,
``sidecar/opencode_mirror.py`` and ``sidecar/agy_mirror.py`` write; no real
content). For each, feeding the file through ``feed_lines`` in chunks cut at
any byte offset — mid-line, mid-character — with ``summary()`` called after
every chunk must end on exactly what the one-shot ``parse_conversation``
returns, for ``full=False`` and ``full=True``. That is what the indexer and
the detail route rely on to parse a growing transcript incrementally.
The same check over the lab's real transcripts: ``scripts/ab/parse-ab.py
--chunked`` (and ``--base REF`` for an A/B of two versions of the parser).
The event layer (``conversations/parse/events.py``, ``readers/``): each
``<harness>.v1.jsonl`` fixture expresses the same conversation as
``<harness>.jsonl`` in v1 events, and both must parse to the same summary and
thread (``V1EqualsLegacy``, with the differences each harness's v1 form is
meant to have listed); the claude reader's events, one record shape at a
time (``ClaudeReaderEvents``); reader state across chunks
(``ReaderStateAcrossChunks``); ``events.validate`` and the doc's event table
(``Validate``).
"""
import copy
import json
import pathlib
import random
import re
import tempfile
import unittest
import conversations as c
from conversations.parse import events
from conversations.parse.readers import ClaudeReader, LegacyReader, V1Reader, reader_for, toolnames
FIXTURES = pathlib.Path(__file__).resolve().parent / "fixtures" / "transcripts"
FILES = sorted(FIXTURES.rglob("*.jsonl"))
def canonical(obj) -> str:
return json.dumps(obj, sort_keys=True, ensure_ascii=False)
def chunked(path: pathlib.Path, data: bytes, cuts: list[int], full: bool,
tmp: pathlib.Path) -> tuple[dict, int]:
"""Grow ``tmp`` to each cut in turn, feeding the new bytes; (last summary,
final offset). The state carries the transcript's own path."""
state = c.ParserState(path, full=full)
offset, prev, last = 0, 0, state.summary()
tmp.write_bytes(b"")
with open(tmp, "ab") as grow:
for cut in cuts:
grow.write(data[prev:cut])
grow.flush()
prev = cut
new = c.feed_lines(state, tmp, offset)
assert new is not None and offset <= new <= cut, (offset, new, cut)
offset = new
last = state.summary()
return last, offset
class ChunkedEqualsOneShot(unittest.TestCase):
def setUp(self):
self._dir = tempfile.TemporaryDirectory()
self.tmp = pathlib.Path(self._dir.name) / "growing.jsonl"
def tearDown(self):
self._dir.cleanup()
def test_there_is_a_fixture_per_harness(self):
names = {p.name for p in FILES}
self.assertLessEqual({"claude.jsonl", "pi.jsonl", "opencode.jsonl", "agy.jsonl"}, names)
self.assertTrue(any("subagents" in p.parts for p in FILES))
def test_fixtures_parse_as_their_harness(self):
got = {p.name: c.parse_conversation(p) for p in FILES}
self.assertEqual(got["opencode.jsonl"]["harness"], "opencode")
self.assertEqual(got["agy.jsonl"]["harness"], "agy")
self.assertIsNone(got["claude.jsonl"]["harness"])
for name, s in got.items():
self.assertGreater(s["assistantTurns"], 0, name)
self.assertGreater(s["tokens"], 0, name)
sub = next(s for n, s in got.items() if n.startswith("agent-"))
self.assertTrue(sub["isSidechain"])
def test_random_cuts(self):
rng = random.Random(20261123)
for path in FILES:
data = path.read_bytes()
self.assertTrue(data.endswith(b"\n"), path)
for full in (False, True):
want = canonical(c.parse_conversation(path, full=full))
for _ in range(10):
n = rng.randint(1, 12)
cuts = sorted({rng.randrange(1, len(data)) for _ in range(n)}) + [len(data)]
got, offset = chunked(path, data, cuts, full, self.tmp)
self.assertEqual(offset, len(data))
self.assertEqual(canonical(got), want,
f"{path.name} full={full} cuts={cuts}")
def test_every_single_cut(self):
"""One cut at every 41st byte and around every line end: a prefix,
then the rest."""
for path in FILES:
data = path.read_bytes()
ends = [i for i, b in enumerate(data) if b == 0x0A]
offsets = set(range(1, len(data), 41))
for e in ends:
offsets.update(x for x in (e, e + 1, e + 2) if 0 < x < len(data))
want = canonical(c.parse_conversation(path, full=False))
for cut in sorted(offsets):
got, _ = chunked(path, data, [cut, len(data)], False, self.tmp)
self.assertEqual(canonical(got), want, f"{path.name} cut={cut}")
def test_summary_is_a_pure_snapshot(self):
for path in FILES:
for full in (False, True):
state = c.ParserState(path, full=full)
c.feed_lines(state, path, 0)
a = canonical(state.summary())
self.assertEqual(a, canonical(state.summary()), path.name)
self.assertEqual(a, canonical(c.parse_conversation(path, full=full)))
def test_an_unterminated_last_line_waits_for_its_newline(self):
"""``feed_lines`` leaves a trailing line with no newline for the next
pass (it may still be being written) and says so in its offset; once
the newline lands, the result is the one-shot parse."""
for path in FILES:
data = path.read_bytes().rstrip(b"\n")
last_start = data.rfind(b"\n") + 1
state = c.ParserState(path, full=True)
self.tmp.write_bytes(data)
offset = c.feed_lines(state, self.tmp, 0)
self.assertEqual(offset, last_start, path.name)
self.tmp.write_bytes(data + b"\n")
self.assertEqual(c.feed_lines(state, self.tmp, offset), len(data) + 1)
self.assertEqual(canonical(state.summary()),
canonical(c.parse_conversation(path, full=True)), path.name)
# ── the event layer ─────────────────────────────────────────────────────────
# What each v1 fixture is *meant* to parse to differently from its legacy
# twin: JSON paths dropped from both sides before comparing (`[*]` = any
# thread item). Everything else must be equal.
V1_DIFFERENCES = {
# pi: the header names the harness (legacy pi stamped none the parser
# read). A failed call that never reached a model has no model and no
# usage in v1; the legacy runner wrote a zero usage under the
# `<synthetic>` model — counted as an assistant turn and a (zero) cost
# delta on the error card, whose model the v1 card takes from the session.
#
# pi, agy: a tool's `native` is the harness's own name in v1 (`bash`,
# `run_command`); the legacy converters wrote Claude Code's (`Bash`), and
# that is all a legacy file can say.
"pi": {"harness", "assistantTurns", "messages", "turns",
"thread[7].model", "thread[8].model",
"thread[7].turn*", "thread[8].turn*", "thread[1].native"},
"opencode": set(),
"agy": {"thread[2].native"},
}
def _drop(obj: dict, paths: set) -> dict:
obj = copy.deepcopy(obj)
for p in paths:
m = re.fullmatch(r"thread\[(\d+)\]\.(\w+)(\*?)", p)
if m:
if "thread" not in obj:
continue
it = obj["thread"][int(m.group(1))]
for k in [k for k in it if k == m.group(2) or (m.group(3) and k.startswith(m.group(2)))]:
del it[k]
else:
obj.pop(p, None)
return obj
class V1EqualsLegacy(unittest.TestCase):
def test_v1_fixtures_parse_like_their_legacy_twin(self):
for harness, paths in V1_DIFFERENCES.items():
legacy, v1 = FIXTURES / f"{harness}.jsonl", FIXTURES / f"{harness}.v1.jsonl"
for full in (False, True):
a = c.parse_conversation(legacy, full=full)
b = c.parse_conversation(v1, full=full)
self.assertEqual(canonical(_drop(a, paths)), canonical(_drop(b, paths)),
f"{harness} full={full}")
def test_the_listed_differences_are_real(self):
"""Each listed path does differ (a stale entry would hide nothing)."""
for harness, paths in V1_DIFFERENCES.items():
a = c.parse_conversation(FIXTURES / f"{harness}.jsonl", full=True)
b = c.parse_conversation(FIXTURES / f"{harness}.v1.jsonl", full=True)
for p in paths:
self.assertNotEqual(canonical(_drop(a, paths - {p})),
canonical(_drop(b, paths - {p})), f"{harness}: {p}")
def test_readers_are_picked_from_the_first_record(self):
self.assertIsInstance(reader_for({"t": "session", "v": 1}), V1Reader)
self.assertIsInstance(reader_for({"type": "user"}), LegacyReader)
self.assertIsInstance(reader_for({"t": "text", "text": "x"}), LegacyReader)
for path in FILES:
st = c.ParserState(path)
c.feed_lines(st, path, 0)
self.assertIsInstance(st.reader, V1Reader if ".v1." in path.name else LegacyReader)
def test_every_event_the_readers_emit_validates(self):
for path in FILES:
r = None
for o in c._iter_records(path):
r = r or reader_for(o)
for ev in r.feed(o):
events.validate(ev)
T0 = "2026-01-05T10:00:00.000Z"
def _ts(s: int) -> str:
return f"2026-01-05T10:00:{s:02d}.000Z"
def _user(content, s=1, **extra):
return {"type": "user", "timestamp": _ts(s), "message": {"role": "user", "content": content},
**extra}
def _assistant(blocks, s=2, mid="m1", usage=None, model="claude-opus-4-8", **extra):
msg = {"id": mid, "model": model, "content": blocks}
if usage is not None:
msg["usage"] = usage
return {"type": "assistant", "timestamp": _ts(s), "requestId": "r-" + mid,
"message": msg, **extra}
class ClaudeReaderEvents(unittest.TestCase):
"""One record shape at a time → the events it means."""
def feed(self, *records, reader=None):
r = reader or ClaudeReader()
out = []
for o in records:
evs = r.feed(o)
for ev in evs:
events.validate(ev)
out.append(evs)
return out
def types(self, evs):
return [e["t"] for e in evs if e["t"] != "session"]
def test_session_facts_only_when_they_change(self):
a = {"type": "x", "sessionId": "s", "cwd": "/a", "gitBranch": "main", "timestamp": T0}
b = {**a, "timestamp": _ts(1)}
c2 = {**a, "cwd": "/b", "isSidechain": True, "agentId": "ag"}
e1, e2, e3 = self.feed(a, b, c2)
self.assertEqual(e1[0], {"t": "session", "at": T0, "id": "s", "cwd": "/a", "branch": "main"})
self.assertEqual(e2, [{"t": "tick", "at": _ts(1)}]) # nothing changed: only time
self.assertEqual(e3[0], {"t": "session", "at": T0, "cwd": "/b", "agent": "ag",
"sidechain": True})
def prompt_of(self, record) -> dict:
(evs,) = self.feed(record)
return next(e for e in evs if e["t"] == "prompt")
def test_prompt_and_its_envelopes(self):
inbox = "[Follow-up from your user (sent from the ai-agent)]\n\nplease also do X"
author = '<ai-agent-from user="u1" name="Ana" role="guest"/>\nhello'
relay = ("Stop hook feedback:\nStop guard (headless run): held.\n"
"<<<USER MESSAGE>>>\nwait, stop\n<<<END USER MESSAGE>>>")
p = self.prompt_of(_user("plain"))
self.assertEqual((p["origin"], p["text"]), ("user", "plain"))
p = self.prompt_of(_user(inbox))
self.assertEqual((p["origin"], p["text"]), ("inbox", "please also do X"))
p = self.prompt_of(_user(author))
self.assertEqual((p["author"]["name"], p["text"]), ("Ana", "hello"))
p = self.prompt_of(_user(relay))
self.assertEqual((p["origin"], p["text"]), ("relay", "wait, stop"))
p = self.prompt_of(_user([{"type": "text", "text": "listed"}]))
self.assertEqual(p["text"], "listed")
absorbed = {"type": "attachment", "timestamp": T0, "attachment": {
"type": "queued_command", "origin": {"kind": "peer"}, "prompt": inbox}}
p = self.prompt_of(absorbed)
self.assertEqual((p["origin"], p["text"]), ("queued", "please also do X"))
def test_the_claude_text_conventions(self):
r = ClaudeReader()
cases = [
(_user("[Request interrupted by user]"), "turn_end", {"reason": "interrupted"}),
(_user("Stop hook feedback:\nStop guard (headless run): the turn was held 42 s"),
"inject", {"kind": "held", "text": "turn held 42 s for a background shell"}),
(_user("<ai-agent-cancel/> drop it\n<<<\nold message\n>>>"), "inject",
{"kind": "cancel", "text": "old message"}),
(_user("<command-name>/babysit-pr</command-name><command-args>42</command-args>"),
"inject", {"kind": "command", "name": "babysit-pr", "args": "42"}),
(_user("[Image: original 2048x2048, displayed at 1932x1932. Multiply coordinates "
"by 1.06 to map to original image.]"), "tick", {"busy": True}),
(_user("<system-reminder>x</system-reminder>"), "tick", {"busy": True}),
(_user("This session is being continued from a previous conversation.\n\n"
"Summary: we did X", isCompactSummary=True), "inject",
{"kind": "compact_summary", "text": "we did X"}),
(_user("<task-notification><task-id>b1</task-id><tool-use-id>t1</tool-use-id>"
"<status>completed</status><summary>done</summary></task-notification>"),
"inject", {"kind": "task_done"}),
]
for rec, t, want in cases:
evs = [e for e in r.feed(rec) if e["t"] != "session"]
self.assertEqual(evs[0]["t"], t, rec)
for k, v in want.items():
self.assertEqual(evs[0][k], v, rec)
def test_a_slash_command_then_its_skill_prompt(self):
r = ClaudeReader()
self.feed(_user("<command-name>/deploy</command-name><command-args>now</command-args>",
s=1), reader=r)
(evs,) = self.feed(_user("Base directory for this skill: /x/.claude/skills/deploy\n\nDo it.",
s=2, isMeta=True), reader=r)
sk = [e for e in evs if e["t"] == "inject"][0]
self.assertEqual((sk["kind"], sk["name"], sk["text"], sk["baseDir"]),
("skill", "deploy", "Do it.", "/x/.claude/skills/deploy"))
self.assertEqual(sk["invoked"], {"args": "now", "at": _ts(1)})
def test_a_skill_call_then_its_prompt(self):
r = ClaudeReader()
self.feed(_assistant([{"type": "tool_use", "id": "tu1", "name": "Skill",
"input": {"skill": "plan"}}]), reader=r)
(evs,) = self.feed(_user([{"type": "text", "text": "Plan things."}], s=3,
sourceToolUseID="tu1"), reader=r)
sk = [e for e in evs if e["t"] == "inject"][0]
self.assertEqual((sk["name"], sk["ref"], sk["text"]), ("plan", "tu1", "Plan things."))
def test_one_call_written_as_one_record_per_block(self):
u = {"input_tokens": 3, "output_tokens": 5, "cache_read_input_tokens": 7,
"cache_creation_input_tokens": 11,
"cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 9},
"speed": "fast"}
r = ClaudeReader()
(a,), (b,) = (self.feed(_assistant([{"type": "thinking", "thinking": "hm"}], usage=u),
reader=r),
self.feed(_assistant([{"type": "tool_use", "id": "t", "name": "Read",
"input": {"file_path": "/f"}}], s=3, usage=u),
reader=r))
a = [e for e in a if e["t"] != "session"]
self.assertEqual([e["t"] for e in a], ["call", "usage", "thinking"])
self.assertEqual(a[0]["tier"], "fast")
self.assertEqual({k: a[1][k] for k in events.USAGE_TOKENS if k in a[1]},
{"input": 3, "output": 5, "cacheRead": 7, "cacheWrite5m": 2,
"cacheWrite1h": 9, "cacheWrite": 11})
self.assertEqual(self.types(b), ["call", "tool_call"]) # usage counted once
self.assertEqual(b[0]["elapsedMs"], 1000)
def test_an_api_error_turn(self):
(evs,) = self.feed(_assistant([{"type": "text", "text": "You've hit your session "
"limit · resets 2:20pm (Europe/Paris)"}],
model="<synthetic>", isApiErrorMessage=True,
error="rate_limit"))
self.assertEqual(self.types(evs), ["call", "error", "turn_end"])
err = evs[-2]
self.assertEqual(err["kind"], "rate_limit")
self.assertIsNotNone(err["resetsAt"])
self.assertTrue(next(e for e in evs if e["t"] == "call")["failed"])
self.assertEqual(evs[-1]["reason"], "error")
def test_no_response_requested_is_a_paused_text(self):
(evs,) = self.feed(_assistant([{"type": "text", "text": "No response requested."}]))
self.assertTrue([e for e in evs if e["t"] == "text"][0]["paused"])
def test_turn_end_records_and_the_stop_hook_that_blocked(self):
r = ClaudeReader()
end = {"type": "system", "subtype": "stop_hook_summary", "timestamp": _ts(5)}
self.assertEqual(self.types(r.feed(end)), ["turn_end"])
r.feed(_user([{"type": "text", "text": "Stop hook feedback:\nkeep going"}]))
self.assertEqual(r.feed(end)[-1]["reason"], "held")
self.assertEqual(r.feed(end)[-1]["reason"], "done")
# the mirrors' own subtype is the legacy reader's
self.assertEqual(self.types(ClaudeReader().feed({**end, "subtype": "turn_end"})), ["tick"])
self.assertEqual(self.types(LegacyReader().feed({**end, "subtype": "turn_end"})), ["turn_end"])
def test_bookkeeping_records(self):
recs = [
({"type": "queue-operation", "operation": "enqueue", "timestamp": T0,
"content": [{"type": "text", "text": "a"}, {"type": "image"}]},
{"t": "queue", "op": "enqueue", "text": "a"}),
({"type": "ai-title", "aiTitle": "T"}, {"t": "meta", "kind": "title", "data": "T"}),
({"type": "repl-mode", "replMode": True}, {"t": "meta", "kind": "mode", "data": True}),
({"type": "pr-link", "prNumber": 3, "prRepository": "o/r", "timestamp": T0},
{"t": "meta", "kind": "pr", "data": {"number": 3, "repo": "o/r"}}),
({"type": "cost-state", "modelUsage": {"m": {"inputTokens": 4, "outputTokens": 2}}},
{"t": "meta", "kind": "cost_state"}),
({"type": "system", "subtype": "compact_boundary", "timestamp": T0,
"compactMetadata": {"trigger": "manual", "preTokens": 9000}},
{"t": "compact", "trigger": "manual", "preTokens": 9000}),
({"type": "attachment", "timestamp": T0, "attachment": {
"type": "hook_success", "hookName": "PostToolUse:Bash", "toolUseID": "t1",
"stdout": "{}"}},
{"t": "meta", "kind": "hook_output", "toolCall": "t1", "text": "{}"}),
({"type": "attachment", "timestamp": T0, "attachment": {"type": "skill_listing"}},
{"t": "tick", "busy": True}),
({"type": "api-request", "timestamp": T0}, {"t": "tick", "busy": True}),
]
for rec, want in recs:
ev = ClaudeReader().feed(rec)[-1]
events.validate(ev)
self.assertEqual({k: ev.get(k) for k in want}, want, rec["type"])
cs = ClaudeReader().feed(recs[4][0])[-1]["data"]["m"]
self.assertEqual((cs["input"], cs["output"], cs["cacheRead"]), (4, 2, None))
def test_code_mode_scripts_and_their_calls(self):
r = ClaudeReader()
repl = _assistant([{"type": "tool_use", "id": "s1", "name": "REPL",
"input": {"code": "await sh('ls -la')"}}])
r.feed(repl)
res = _user([{"type": "tool_result", "tool_use_id": "s1", "content": "(dispatched #4)"}],
s=3, toolUseResult={"evalId": 4})
self.assertEqual(r.feed(res)[-1]["data"], {"evalId": 4})
poll = {"type": "attachment", "timestamp": _ts(4), "attachment": {
"type": "poll_events", "envelopes": [
'<event kind="repl-eval" eval="4" ms="120" status="settled">'
'<result>ok</result></event>']}}
settled = r.feed(poll)[-1]
self.assertEqual((settled["t"], settled["toolCall"], settled["text"], settled["ms"]),
("tool_settled", "s1", "ok", 120))
virt = _assistant([{"type": "tool_use", "id": "repl_x", "name": "Bash",
"input": {"command": "ls -la"}}], s=5, mid="m2",
usage={"input_tokens": 0}, isVirtual=True)
evs = r.feed(virt)
self.assertEqual(self.types(evs), ["call", "tool_call"]) # virtual: no usage
self.assertEqual(evs[-1]["caller"], "s1")
class ToolNames(unittest.TestCase):
"""A ``tool_call``'s neutral ``tool`` and its ``native`` name (toolnames.py)."""
def tools(self, reader, *records):
out = []
for o in records:
out += [(e["tool"], e.get("native")) for e in reader.feed(o) if e["t"] == "tool_call"]
return out
def call(self, name, s=2, **extra):
return _assistant([{"type": "tool_use", "id": f"t{s}", "name": name, "input": {}}],
s=s, mid=f"m{s}", **extra)
def test_claude_code_names(self):
names = ["Bash", "BashOutput", "TaskOutput", "KillShell", "TaskStop", "Read",
"NotebookRead", "Write", "Edit", "MultiEdit", "NotebookEdit", "Grep", "Glob",
"LS", "WebFetch", "WebSearch", "Agent", "Task", "Skill", "TodoWrite",
"TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "AskUserQuestion",
"CronCreate", "ToolSearch", "REPL", "mcp__linear__get_issue"]
got = self.tools(LegacyReader(), *[self.call(n, s=i) for i, n in enumerate(names, 1)])
self.assertEqual([t for t, _ in got], [
"shell", "shell_output", "shell_output", "shell_kill", "shell_kill", "read",
"read", "write", "edit", "edit", "edit", "grep", "glob", "list_dir", "web_fetch",
"web_search", "agent", "agent", "skill", "todo", "todo", "todo", "todo", "todo",
"ask_user", "claude:CronCreate", "claude:ToolSearch", "claude:REPL",
"mcp__linear__get_issue"])
self.assertEqual([n for _, n in got], names)
for t, _ in got:
self.assertTrue(t in toolnames.CORE or ":" in t or t.startswith("mcp__"), t)
def test_a_converter_written_file_namespaces_under_its_harness(self):
r = LegacyReader()
got = self.tools(r, self.call("Bash", s=1, entrypoint="agy"),
self.call("manage_task", s=2, entrypoint="agy"),
self.call("mcp_github_list_prs", s=3, entrypoint="agy"))
self.assertEqual(got, [("shell", "Bash"), ("agy:manage_task", "manage_task"),
("mcp_github_list_prs", "mcp_github_list_prs")])
got = self.tools(LegacyReader(), self.call("Execute", s=1, entrypoint="opencode"),
self.call("DeleteFile", s=2, entrypoint="opencode"),
self.call("lsp_hover", s=3, entrypoint="opencode"))
self.assertEqual([t for t, _ in got], ["opencode:execute", "delete_file", "opencode:lsp_hover"])
def test_pi_stamps_no_harness_its_lowercase_names_are_its_own(self):
got = self.tools(LegacyReader(), self.call("Read", s=1), self.call("bash", s=2))
self.assertEqual(got, [("read", "Read"), ("pi:bash", "bash")])
# Claude Code's own reader has one harness
self.assertEqual(self.tools(ClaudeReader(), self.call("bash", s=1)), [("claude:bash", "bash")])
def test_the_thread_item_keeps_the_native_name_when_it_differs(self):
with tempfile.TemporaryDirectory() as d:
path = pathlib.Path(d) / "s.jsonl"
path.write_text("\n".join(json.dumps(o) for o in (
_user("go", s=1), self.call("Bash", s=2), self.call("mcp__x__y", s=3))) + "\n")
items = [it for it in c.parse_conversation(path, full=True)["thread"]
if it["kind"] == "tool_use"]
self.assertEqual([(it["name"], it.get("native")) for it in items],
[("shell", "Bash"), ("mcp__x__y", None)])
def test_todo_calls_told_apart_by_their_input(self):
from conversations.parse.tools import todo_op
self.assertEqual(todo_op({"todos": []}), "snapshot")
self.assertEqual(todo_op({"taskId": "2", "status": "completed"}), "update")
self.assertEqual(todo_op({"taskId": "2"}), "update") # TaskGet: changes nothing
self.assertEqual(todo_op({"subject": "x", "description": "y"}), "create")
self.assertEqual(todo_op({}), "list")
with tempfile.TemporaryDirectory() as d:
path = pathlib.Path(d) / "s.jsonl"
calls = [("TaskCreate", {"subject": "a", "description": "."}),
("TaskCreate", {"subject": "b", "description": "."}),
("TaskList", {}), ("TaskGet", {"taskId": "1"}),
("TaskUpdate", {"taskId": "1", "status": "completed"})]
recs = [_user("go", s=1)] + [
_assistant([{"type": "tool_use", "id": f"t{i}", "name": n, "input": inp}],
s=i + 2, mid=f"m{i}") for i, (n, inp) in enumerate(calls)]
path.write_text("\n".join(json.dumps(o) for o in recs) + "\n")
tasks = c.parse_conversation(path)["tasks"]
self.assertEqual([(t["subject"], t["status"]) for t in tasks],
[("a", "completed"), ("b", "pending")])
class ReaderStateAcrossChunks(unittest.TestCase):
"""What a reader keeps between records survives ``feed_lines`` cut
anywhere — and a partial line produces nothing."""
def grow(self, lines: list[dict], full=True) -> dict:
"""Cut the transcript at every byte: a prefix, then the rest; each
must end on the one-shot parse. Returns that parse."""
data = b"".join(json.dumps(o, ensure_ascii=False).encode() + b"\n" for o in lines)
with tempfile.TemporaryDirectory() as d:
tmp = pathlib.Path(d) / "x.jsonl"
tmp.write_bytes(data)
want = canonical(c.parse_conversation(tmp, full=full))
for cut in range(1, len(data)):
st = c.ParserState(tmp, full=full)
tmp.write_bytes(data[:cut])
off = c.feed_lines(st, tmp, 0)
tmp.write_bytes(data)
c.feed_lines(st, tmp, off)
self.assertEqual(canonical(st.summary()), want, f"cut={cut}")
return json.loads(want)
def test_a_slash_command_and_its_prompt_in_two_chunks(self):
s = self.grow([
_user("<command-name>/deploy</command-name><command-args>now</command-args>", s=1),
_user("Base directory for this skill: /x/.claude/skills/deploy\n\nDo it.", s=2,
isMeta=True)])
card = [it for it in s["thread"] if it.get("name") == "skill"][0]
self.assertEqual(card["skillBody"], "Do it.")
def test_a_partial_line_feeds_nothing(self):
line = json.dumps(_user("hello there")).encode()
with tempfile.TemporaryDirectory() as d:
tmp = pathlib.Path(d) / "x.jsonl"
tmp.write_bytes(line[:20])
st = c.ParserState(tmp)
self.assertEqual(c.feed_lines(st, tmp, 0), 0)
self.assertIsNone(st.reader)
self.assertEqual(st.summary()["userTurns"], 0)
def test_a_v1_step_held_until_complete(self):
"""A v1 step waits for its usage (or the next event) — whatever the
chunks — and a late usage prices it on its own."""
lines = [l for l in map(json.loads, (FIXTURES / "opencode.v1.jsonl").read_text().splitlines())]
r = V1Reader()
batches = [r.feed(o) for o in lines]
self.assertEqual([e["t"] for e in batches[3]], []) # call held
self.assertEqual([e["t"] for e in batches[6]], ["call", "text", "tool_call", "tool_result"])
self.assertEqual([e["t"] for e in batches[7]], ["call", "usage"]) # the late usage
self.assertTrue(batches[7][0]["empty"])
self.assertEqual([e["t"] for e in batches[10]], ["call", "usage", "text"])
class Validate(unittest.TestCase):
def test_well_formed_and_unknown_events_pass(self):
for ev in ({"t": "session", "v": 1, "id": "s"}, {"t": "prompt", "text": "hi"},
{"t": "usage", "call": "c", "input": 3, "cost": {"usd": 0.1}},
{"t": "brand_new_type", "whatever": 1}, {"t": "tick", "at": None}):
self.assertIs(events.validate(ev), ev)
def test_malformed_events_are_refused(self):
for ev in ([], {"x": 1}, {"t": ""}, {"t": "prompt"}, {"t": "prompt", "text": 3},
{"t": "tool_call"}, {"t": "turn_end", "reason": "bored"},
{"t": "inject", "kind": "ad"}, {"t": "usage", "input": "3"},
{"t": "usage", "output": True}, {"t": "usage", "cost": {"usd": "1"}},
{"t": "session", "v": 2}, {"t": "text", "text": "x", "at": 5}):
with self.assertRaises(ValueError, msg=ev):
events.validate(ev)
def test_the_v1_reader_drops_what_does_not_validate(self):
r = V1Reader()
self.assertEqual(r.feed({"t": "prompt"}), [])
self.assertEqual(r.feed({"t": "prompt", "text": "ok"})[0]["text"], "ok")
def test_the_doc_lists_the_same_events(self):
path = pathlib.Path(__file__).resolve().parent.parent / "docs" / "transcript-format.md"
if not path.exists():
self.skipTest("docs/ is not in this tree (the service image mounts backend/ only)")
doc = path.read_text()
# Only "## The events": the "## Tool names" tables have rows of the
# same shape (`shell` | Bash …).
doc = doc.split("\n## The events", 1)[1].split("\n## ", 1)[0]
rows = dict(re.findall(r"^\| `(\w+)` \| ([^|]*) \|", doc, re.M))
self.assertEqual(set(rows), set(events.FIELDS), "event types")
for t, (req, opt) in events.FIELDS.items():
named = set(re.findall(r"`(\w+)`", rows[t]))
required = set(re.findall(r"\*\*`(\w+)`\*\*", rows[t]))
self.assertEqual(required, set(req), f"{t}: required fields")
self.assertEqual(named, set(req) | set(opt), f"{t}: fields")
if __name__ == "__main__":
unittest.main()