"""Parse PostTrainBench agent traces into a normalized event stream. A trace is `/solve_out.txt`: one line per event, prefixed with an ISO timestamp the harness stamps on, followed by either a plain log line (from the wrapper scripts) or one JSON object from the Claude Code SDK's `--output-format stream-json`. Everything downstream works on `Run`, which holds the normalized events plus the run's identity and ground-truth score, so no other module has to know the on-disk layout. """ from __future__ import annotations import json import os import re from dataclasses import dataclass, field from datetime import datetime from typing import Any, Iterator LINE_RE = re.compile(r"^\[(\d{4}-\d{2}-\d{2}T[\d:]+Z)\] (.*)$") # results/___/___ RUN_DIR_RE = re.compile(r"^(?P[a-z0-9]+)_(?P.+)_(?P\d{8}-\d{6})$") def _ts(raw: str) -> datetime: return datetime.strptime(raw, "%Y-%m-%dT%H:%M:%SZ") @dataclass class Event: """One line of the trace, already split into time + payload.""" ts: datetime t_rel: float # seconds since the first event of the run kind: str # SDK event `type`, or "log" for non-JSON wrapper output subtype: str | None raw: dict[str, Any] | str @dataclass class ToolCall: """An assistant tool_use paired with the tool_result that answered it.""" idx: int # ordinal within the run ts: datetime t_rel: float name: str tool_id: str inp: dict[str, Any] result_text: str = "" is_error: bool = False result_t_rel: float | None = None @property def duration_s(self) -> float | None: """Wall-clock the tool occupied. For Bash this is the command's runtime.""" if self.result_t_rel is None: return None return self.result_t_rel - self.t_rel @property def command(self) -> str: """The shell command, for Bash calls; "" for every other tool.""" return self.inp.get("command", "") if self.name == "Bash" else "" @property def text_payload(self) -> str: """Everything the agent *wrote* in this call — command, file contents, edits. Used by the technique detectors, which care about what the agent put into the environment rather than which tool it used to do it. """ parts = [str(self.inp.get(k, "")) for k in ("command", "content", "new_string", "file_path", "description", "prompt")] return "\n".join(p for p in parts if p) @dataclass class Run: run_dir: str task: str base_model: str stamp: str events: list[Event] = field(default_factory=list) tool_calls: list[ToolCall] = field(default_factory=list) accuracy: float | None = None # ground truth from the harness' own final eval time_taken: str | None = None result: dict[str, Any] | None = None # the SDK's terminal `result` event init: dict[str, Any] | None = None prompt: str = "" final_message: str = "" @property def run_id(self) -> str: return os.path.basename(self.run_dir) @property def cell(self) -> str: """(task, base model) — the unit the benchmark scores. Reruns share a cell.""" return f"{self.task}|{self.base_model}" @property def wall_s(self) -> float: return self.events[-1].t_rel if self.events else 0.0 @property def completed(self) -> bool: return self.accuracy is not None def _result_text(content: Any) -> str: if isinstance(content, str): return content if isinstance(content, list): return "".join(c.get("text", "") for c in content if isinstance(c, dict)) return "" def iter_raw(path: str) -> Iterator[tuple[datetime, str]]: with open(path, errors="replace") as fh: for line in fh: m = LINE_RE.match(line.rstrip("\n")) if m: yield _ts(m.group(1)), m.group(2) def parse_run(run_dir: str) -> Run | None: """Build a Run from a results directory. Returns None if there is no trace. Dispatches on the trace format: the Claude Code SDK and the Codex SDK emit different event streams, and a results root only ever holds one of them, but sniffing beats making every caller declare which. """ name = os.path.basename(run_dir.rstrip("/")) m = RUN_DIR_RE.match(name) if not m: return None trace = os.path.join(run_dir, "solve_out.txt") if not os.path.exists(trace): return None from .codex import looks_like_codex, parse_codex_run if looks_like_codex(trace): return parse_codex_run(run_dir) return _parse_claude_run(run_dir, m, trace) def _parse_claude_run(run_dir: str, m: re.Match[str], trace: str) -> Run: run = Run( run_dir=run_dir, task=m.group("task"), base_model=m.group("model").replace("_", "/", 1), stamp=m.group("stamp"), ) for fname, attr in (("prompt.txt", "prompt"), ("time_taken.txt", "time_taken")): p = os.path.join(run_dir, fname) if os.path.exists(p): setattr(run, attr, open(p, errors="replace").read().strip()) mp = os.path.join(run_dir, "metrics.json") if os.path.exists(mp): try: run.accuracy = json.load(open(mp)).get("accuracy") except Exception: pass t0: datetime | None = None pending: dict[str, ToolCall] = {} for ts, body in iter_raw(trace): if t0 is None: t0 = ts rel = (ts - t0).total_seconds() if not body.startswith("{"): run.events.append(Event(ts, rel, "log", None, body)) continue try: ev = json.loads(body) except json.JSONDecodeError: run.events.append(Event(ts, rel, "log", None, body)) continue kind = ev.get("type", "?") run.events.append(Event(ts, rel, kind, ev.get("subtype"), ev)) if kind == "system" and ev.get("subtype") == "init": run.init = ev elif kind == "result": run.result = ev # On an error terminal the `result` string is the error message, # not the agent's sign-off; treating it as a report would put # "API Error: 502" into the prose analysis. if ev.get("terminal_reason") == "completed" and isinstance(ev.get("result"), str): run.final_message = ev["result"] elif kind == "assistant": for c in ev.get("message", {}).get("content", []) or []: if isinstance(c, dict) and c.get("type") == "tool_use": tc = ToolCall( idx=len(run.tool_calls), ts=ts, t_rel=rel, name=c.get("name", "?"), tool_id=c.get("id", ""), inp=c.get("input", {}) or {}, ) run.tool_calls.append(tc) pending[tc.tool_id] = tc elif kind == "user": for c in ev.get("message", {}).get("content", []) or []: if isinstance(c, dict) and c.get("type") == "tool_result": tc = pending.pop(c.get("tool_use_id", ""), None) if tc is not None: tc.result_text = _result_text(c.get("content")) tc.is_error = bool(c.get("is_error")) tc.result_t_rel = rel return run def load_all(results_root: str) -> list[Run]: runs = [] for name in sorted(os.listdir(results_root)): d = os.path.join(results_root, name) if os.path.isdir(d): r = parse_run(d) if r is not None: runs.append(r) return runs