File size: 12,673 Bytes
158258b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
"""Head-to-head comparison between the Claude Code and Codex SDK sweeps.

Both swept the same 28 cells (7 benchmarks x 4 base models) with the same
10-hour budget on the same hardware, so the cells pair exactly. Claude has
reruns on 20 cells; for a paired comparison each cell contributes its latest
analysed run, which is also how the sweep's own results table is built.

    python analysis/compare.py            # tables + json
    python analysis/compare.py --figures

Writes `analysis/out/compare.json`, the comparison tables into the report at
`docs/results/agent_trace_comparison_2026-10.md`, and figures under
`docs/results/figures/compare/`.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from collections import defaultdict
from statistics import mean

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from run_analysis import AGENT_ROOTS, OUT_DIR, ROOT, build  # noqa: E402

AGENTS = ("claude", "codex")


def latest_per_cell(feats) -> dict[tuple[str, str], object]:
    """One run per (task, base model): the most recent analysed one."""
    best: dict[tuple[str, str], object] = {}
    for f in feats:
        if f.cohort not in ("primary", "recovered"):
            continue
        key = (f.task, f.base_model)
        if key not in best or f.run_id > best[key].run_id:  # stamps sort lexically
            best[key] = f
    return best


def _avg(xs):
    xs = [x for x in xs if x is not None]
    return round(mean(xs), 4) if xs else None


def headline(cells: dict[str, dict]) -> list[dict]:
    """The per-run metrics that actually differ between the two scaffolds."""
    spec = [
        ("accuracy", "final accuracy", 3),
        ("wall_h", "wall clock (h)", 2),
        ("turns", "turns", 0),
        ("tool_calls", "tool calls", 0),
        ("n_distinct_model_versions", "model versions evaluated", 1),
        ("n_eval_calls", "official eval invocations", 1),
        ("n_observed_scores", "distinct scores observed", 1),
        ("first_eval_h", "first eval (h)", 3),
        ("machine_busy_frac", "machine busy fraction", 3),
        ("dead_air_h", "idle hours", 2),
        ("tail_idle_h", "hours after best score", 2),
        ("bg_tasks", "background jobs launched", 1),
        ("tool_errors", "tool errors", 1),
        ("output_tokens", "output tokens", 0),
        ("thinking_chars", "readable reasoning chars", 0),
        ("narration_chars", "visible narration chars", 0),
        ("final_message_chars", "final report chars", 0),
        ("time_awareness_calls", "timer.sh checks", 1),
    ]
    rows = []
    for field, label, nd in spec:
        row = {"metric": label}
        for a in AGENTS:
            v = _avg([getattr(f, field) for f in cells[a].values()])
            row[a] = round(v, nd) if v is not None and nd else (int(v) if v is not None else None) if nd == 0 else v
        rows.append(row)
    return rows


def paired_accuracy(cells: dict[str, dict]) -> list[dict]:
    keys = sorted(set(cells["claude"]) & set(cells["codex"]))
    rows = []
    for task, model in keys:
        c = cells["claude"][(task, model)].accuracy
        x = cells["codex"][(task, model)].accuracy
        rows.append(
            {
                "task": task,
                "base_model": model.split("/")[-1],
                "claude": round(c, 4) if c is not None else None,
                "codex": round(x, 4) if x is not None else None,
                "delta": round(c - x, 4) if None not in (c, x) else None,
            }
        )
    return rows


def per_task_accuracy(rows: list[dict]) -> list[dict]:
    by: defaultdict[str, list[dict]] = defaultdict(list)
    for r in rows:
        by[r["task"]].append(r)
    out = []
    for task, g in sorted(by.items()):
        out.append(
            {
                "task": task,
                "claude": _avg([r["claude"] for r in g]),
                "codex": _avg([r["codex"] for r in g]),
                "delta": _avg([r["delta"] for r in g]),
                "claude_wins": sum(1 for r in g if (r["delta"] or 0) > 0),
                "n": len(g),
            }
        )
    return out


def prose_compare(summaries: dict[str, dict]) -> list[dict]:
    """Only the surfaces both SDKs expose.

    `said_` is report + narration; the plain report-only rows understate
    Codex (340-character sign-offs) and the `anywhere_` rows flatter it
    (only Codex exposes readable extended thinking), so neither is usable
    across agents.
    """
    probes = summaries["claude"]["prose_probes"]
    keys = [k for k in probes if k.startswith("said_")] + [
        k for k in probes if not k.startswith(("said_", "anywhere_")) and probes[k]["surface"] == "narration"
    ]
    rows = []
    for k in keys:
        row = {"habit": k.replace("said_", "")}
        for a in AGENTS:
            p = summaries[a]["prose_probes"].get(k)
            row[a] = f"{p['runs_with_evidence']}/{p['of']} ({p['pct']}%)" if p else ""
        row["surface"] = (summaries["claude"]["prose_probes"].get(k) or {}).get("surface", "")
        rows.append(row)
    return rows


def md_table(rows: list[dict], cols: list[tuple[str, str]]) -> str:
    out = ["| " + " | ".join(h for _, h in cols) + " |", "|" + "---|" * len(cols)]
    for r in rows:
        cells = []
        for k, _ in cols:
            v = r.get(k)
            cells.append("" if v is None else (f"{v:g}" if isinstance(v, float) else str(v)))
        out.append("| " + " | ".join(cells) + " |")
    return "\n".join(out)


# --- figures ----------------------------------------------------------------
def make_figures(cells, paired, per_task):
    import numpy as np
    from trace_analysis.figures import C, GRID, INK2, MUTED, SURFACE, _save

    import matplotlib.pyplot as plt

    # 1. accuracy by benchmark, paired
    fig, ax = plt.subplots(figsize=(9, 4.2))
    tasks = [r["task"] for r in per_task]
    y = np.arange(len(tasks))
    h = 0.34
    ax.barh(y - h / 2, [r["claude"] for r in per_task], height=h, color=C[0], label="Claude Code (opus-5)", edgecolor=SURFACE, linewidth=1.5)
    ax.barh(y + h / 2, [r["codex"] for r in per_task], height=h, color=C[1], label="Codex SDK (gpt-5.6-sol)", edgecolor=SURFACE, linewidth=1.5)
    for i, r in enumerate(per_task):
        ax.text(max(r["claude"], r["codex"]) + 0.012, i, f"Δ{r['delta']:+.3f}", va="center", fontsize=8.5, color=INK2)
    ax.set_yticks(y, tasks)
    ax.invert_yaxis()
    ax.set_xlim(0, 1.08)
    ax.set_xlabel("mean final accuracy over the 4 base models")
    ax.set_title("Same 28 cells, two scaffolds")
    ax.grid(axis="x", lw=0.6)
    ax.set_axisbelow(True)
    ax.legend(frameon=False, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.16), fontsize=9)
    _save(fig, "accuracy_by_task.png", "compare")

    # 2. progress curves overlaid
    fig, ax = plt.subplots(figsize=(7.5, 4.2))
    grid = np.linspace(0, 1, 101)
    for a, col in zip(AGENTS, (C[0], C[1])):
        curves = []
        for f in cells[a].values():
            if not f.observed_scores or (f.observed_gain or 0) <= 0.01:
                continue
            xs = np.array([t / 3600 / max(f.wall_h, 1e-6) for t, _ in f.observed_scores])
            ys = np.maximum.accumulate([v for _, v in f.observed_scores])
            lo, hi = ys[0], ys.max()
            if hi <= lo:
                continue
            curves.append(np.interp(grid, xs, (ys - lo) / (hi - lo), left=0.0, right=1.0))
        med = np.median(np.vstack(curves), axis=0)
        half = grid[np.argmax(med >= 0.5)] * 100
        ax.plot(grid * 100, med * 100, lw=2.5, color=col, label=f"{a} (n={len(curves)}, half by {half:.0f}%)")
    ax.plot([0, 100], [0, 100], lw=1.5, ls=(0, (4, 3)), color=MUTED, label="if progress were uniform")
    ax.set_xlabel("% of the run's wall clock elapsed")
    ax.set_ylabel("% of the run's total score gain captured")
    ax.set_title("Both front-load their gains")
    ax.grid(lw=0.6)
    ax.set_axisbelow(True)
    ax.legend(frameon=False, loc="lower right", fontsize=9)
    _save(fig, "progress_curve.png", "compare")

    # 3. loop shape: iterations vs time spent
    fig, ax = plt.subplots(figsize=(7, 4.4))
    for a, col in zip(AGENTS, (C[0], C[1])):
        xs = [f.wall_h for f in cells[a].values()]
        ys = [f.n_distinct_model_versions for f in cells[a].values()]
        ax.scatter(xs, ys, s=58, color=col, edgecolor=SURFACE, linewidth=1.5, label=a, zorder=3)
    ax.set_xlabel("wall clock used (h, of a 10 h budget)")
    ax.set_ylabel("distinct model versions evaluated")
    ax.set_title("Codex iterates faster and stops earlier")
    ax.grid(lw=0.6)
    ax.set_axisbelow(True)
    ax.legend(frameon=False, fontsize=9, loc="upper left")
    _save(fig, "loop_shape.png", "compare")

    # 4. what the trace exposes about the agent's own reasoning
    fig, ax = plt.subplots(figsize=(7, 3.6))
    labels = ["readable reasoning", "visible narration", "final report"]
    vals = {
        a: [
            _avg([f.thinking_chars for f in cells[a].values()]),
            _avg([f.narration_chars for f in cells[a].values()]),
            _avg([f.final_message_chars for f in cells[a].values()]),
        ]
        for a in AGENTS
    }
    y = np.arange(len(labels))
    h = 0.34
    for i, (a, col) in enumerate(zip(AGENTS, (C[0], C[1]))):
        v = [x or 0 for x in vals[a]]
        ax.barh(y + (i - 0.5) * h, v, height=h, color=col, label=a, edgecolor=SURFACE, linewidth=1.5)
        for j, x in enumerate(v):
            ax.text(x + 600, y[j] + (i - 0.5) * h, f"{x:,.0f}", va="center", fontsize=8, color=INK2)
    ax.set_yticks(y, labels)
    ax.invert_yaxis()
    ax.set_xlabel("characters per run")
    ax.set_title("How much of its own thinking each trace preserves")
    ax.grid(axis="x", lw=0.6)
    ax.set_axisbelow(True)
    ax.legend(frameon=False, ncol=2, fontsize=9, loc="lower right")
    _save(fig, "reasoning_visibility.png", "compare")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--figures", action="store_true")
    args = ap.parse_args()

    cells, summaries = {}, {}
    for a in AGENTS:
        _, feats = build(AGENT_ROOTS[a])
        cells[a] = latest_per_cell(feats)
        summaries[a] = json.load(open(os.path.join(OUT_DIR, a, "summary.json")))
        print(f"{a}: {len(cells[a])} paired cells")

    paired = paired_accuracy(cells)
    per_task = per_task_accuracy(paired)
    head = headline(cells)

    result = {
        "paired_cells": len(paired),
        "headline": head,
        "per_task_accuracy": per_task,
        "paired_accuracy": paired,
        "overall": {
            a: _avg([f.accuracy for f in cells[a].values()]) for a in AGENTS
        },
        "cells_claude_wins": sum(1 for r in paired if (r["delta"] or 0) > 0),
        "prose": prose_compare(summaries),
        "risks": {a: summaries[a]["risk_run_counts"] for a in AGENTS},
        "errors": {a: summaries[a]["error_run_counts"] for a in AGENTS},
        "verification": {a: summaries[a]["final_verification"] for a in AGENTS},
        "dev_drop": {a: summaries[a]["dev_to_harness_drop"] for a in AGENTS},
        "techniques": {a: summaries[a]["technique_run_counts"] for a in AGENTS},
        "actions": {a: summaries[a]["action_totals"] for a in AGENTS},
        "tools": {a: summaries[a]["tool_totals"] for a in AGENTS},
    }
    with open(os.path.join(OUT_DIR, "compare.json"), "w") as fh:
        json.dump(result, fh, indent=1)
    print(f"wrote {os.path.join(OUT_DIR, 'compare.json')}")

    tables = [
        "## 每 run 行为画像",
        "",
        md_table(head, [("metric", "指标(每 run 均值)"), ("claude", "Claude Code"), ("codex", "Codex SDK")]),
        "",
        "## 各 benchmark 准确率(同样 4 个 base model 取均值)",
        "",
        md_table(
            per_task,
            [("task", "benchmark"), ("claude", "Claude"), ("codex", "Codex"), ("delta", "Δ(C−X)"), ("claude_wins", "Claude 胜出格数"), ("n", "格数")],
        ),
        "",
        "## 逐格配对",
        "",
        md_table(paired, [("task", "benchmark"), ("base_model", "base model"), ("claude", "Claude"), ("codex", "Codex"), ("delta", "Δ")]),
        "",
        "## 文本习惯",
        "",
        md_table(prose_compare(summaries), [("habit", "习惯"), ("claude", "Claude"), ("codex", "Codex"), ("surface", "出现在")]),
        "",
    ]
    tpath = os.path.join(OUT_DIR, "compare_tables.md")
    with open(tpath, "w") as fh:
        fh.write("\n".join(tables))
    print(f"wrote {tpath}")

    if args.figures:
        make_figures(cells, paired, per_task)


if __name__ == "__main__":
    main()