File size: 7,815 Bytes
22decf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""Parse PostTrainBench agent traces into a normalized event stream.

A trace is `<run_dir>/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/<agent>_<model>_<hours>_<exp>/<task>_<org>_<model>_<YYYYmmdd-HHMMSS>
RUN_DIR_RE = re.compile(r"^(?P<task>[a-z0-9]+)_(?P<model>.+)_(?P<stamp>\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