"""Aggregates run records into the protocol's headline numbers (§13, §15, §16, §17): Verified Success Rate, repair cycles to an accepted solution, context consumed and expected cost per correct solution.""" import glob import json import os import statistics from . import util def load(paths): runs = [] for p in paths: for f in [p] if p.endswith("run.json") else glob.glob(os.path.join(p, "**", "run.json"), recursive=True): if "/superseded/" in f: continue runs.append(util.read_json(f)) return runs def mean(xs): xs = [x for x in xs if x is not None] return round(statistics.mean(xs), 2) if xs else None def aggregate(runs): cells = {} for r in runs: if r.get("track") == "B": a = r["agent"] key = (r["task"]["id"], r["language"]["name"], "B:" + (a.get("label") or a["name"]), a["name"] + ":" + a["model"]) else: key = (r["task"]["id"], r["language"]["name"], r["model"].get("class") or "-", r["model"]["id"]) cells.setdefault(key, []).append(r) rows = [] for (task, lang, cls, model), rs in sorted(cells.items()): acc = [r for r in rs if r.get("accepted")] costs = [r.get("cost_usd") for r in rs] total_cost = None if any(c is None for c in costs) else round(sum(costs), 4) rows.append({ "task": task, "language": lang, "class": cls, "model": model, "runs": len(rs), "accepted": len(acc), "verified_success_rate": round(len(acc) / len(rs), 3), "repair_cycles_accepted": mean([r["metrics"]["failed_verifier_cycles"] + r["metrics"]["failed_test_cycles"] for r in acc if r["metrics"].get("failed_verifier_cycles") is not None]), "context_tokens_mean": mean([r["metrics"].get("input_tokens") for r in rs]), "uncached_input_tokens_mean": mean([((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]), "cumulative_context_tokens_mean": mean([(r["metrics"].get("context") or {}).get("cumulative_context_tokens") for r in rs]), "unique_reference_tokens_mean": mean([(r["metrics"].get("context") or {}).get("unique_reference_tokens") for r in rs]), "reference_coverage_mean": mean([(r["metrics"].get("context") or {}).get("reference_coverage") for r in rs]), "elapsed_seconds_mean": mean([r["metrics"].get("elapsed_seconds") for r in rs]), "output_tokens_mean": mean([r["metrics"].get("output_tokens") for r in rs]), "tool_calls_mean": mean([r["metrics"]["tool_calls"] for r in rs]), "first_check_accepted": sum(1 for r in rs if r["metrics"].get("first_check_accepted") or r["metrics"].get("first_build_accepted")), "cost_total_usd": total_cost, "cost_per_correct_usd": None if total_cost is None or not acc else round(total_cost / len(acc), 4), "unclassified_failures": sum(1 for r in rs if r.get("accepted") is False and not r.get("classification")), "terminations": sorted({r["metrics"]["termination"] for r in rs}), }) return rows def markdown(rows): head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "tool calls", "provider input (uncached)", "cumulative context", "unique reference", "ref. coverage", "seconds", "cost/correct USD", "unclassified failures"] out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] for r in rows: # Track B runs on subscriptions: no honest cost per solution (protocol §39b). cost = "n/a (Track B)" if r["class"].startswith("B:") else r["cost_per_correct_usd"] out.append("| " + " | ".join(str(x) for x in [ r["task"], r["language"], r["class"], r["model"], r["runs"], r["accepted"], r["verified_success_rate"], r["repair_cycles_accepted"], r["tool_calls_mean"], f"{r['context_tokens_mean']} ({r['uncached_input_tokens_mean']})", r["cumulative_context_tokens_mean"], r["unique_reference_tokens_mean"], r["reference_coverage_mean"], r["elapsed_seconds_mean"], cost, r["unclassified_failures"]]) + " |") return "\n".join(out) def print_report(paths, as_json=False): rows = aggregate(load(paths)) print(json.dumps(rows, indent=2) if as_json else markdown(rows)) def _agent_key(r): if r.get("track") == "B": return (r["agent"].get("label") or "") + " " + r["agent"]["name"] return (r["model"].get("class") or "") + " " + r["model"]["id"] def summary(paths): """The shareable summary of an experiment (no task details beyond task IDs): the PASS/FAIL matrix per task, per-cell metrics, and aggregates by language and by agent/model.""" runs = load(paths) langs = sorted({r["language"]["name"] for r in runs}) agents = sorted({_agent_key(r) for r in runs}) tasks = sorted({r["task"]["id"] for r in runs}) out = [] for t in tasks: out.append(f"### {t}\n") out.append("| agent | " + " | ".join(langs) + " |") out.append("|---|" + "---|" * len(langs)) for a in agents: cells = [] for lang in langs: rs = [r for r in runs if r["task"]["id"] == t and r["language"]["name"] == lang and _agent_key(r) == a] cells.append(" ".join("PASS" if r.get("accepted") else ("FAIL" if r.get("accepted") is False else "?") for r in rs) or "-") out.append(f"| {a} | " + " | ".join(cells) + " |") out.append("") head = ["task", "language", "agent", "verified", "first attempt", "repair cycles", "tool calls", "seconds", "unique bundle", "context via tools", "provider input cached/uncached", "classification", "caught by"] out.append("### Cells\n") out.append("| " + " | ".join(head) + " |") out.append("|" + "---|" * len(head)) for r in sorted(runs, key=lambda r: (r["task"]["id"], r["language"]["name"], _agent_key(r))): m = r["metrics"] ctx = m.get("context") or {} pin = ctx.get("provider_input_tokens") or {} cyc = None if m.get("failed_verifier_cycles") is None else m["failed_verifier_cycles"] + (m.get("failed_test_cycles") or 0) cl = r.get("classification") or {} out.append("| " + " | ".join(str(x) for x in [ r["task"]["id"], r["language"]["name"], _agent_key(r), "PASS" if r.get("accepted") else "FAIL", m.get("first_public_test_passed"), cyc, m.get("tool_calls"), m.get("elapsed_seconds"), ctx.get("unique_reference_tokens"), ctx.get("cumulative_context_tokens"), f"{pin.get('cached')}/{pin.get('uncached')}", cl.get("category", "-" if r.get("accepted") else "unclassified"), cl.get("caught_by") or "-"]) + " |") out.append("") for title, keyf in (("language", lambda r: r["language"]["name"]), ("agent", _agent_key)): out.append(f"### By {title}\n") out.append(f"| {title} | runs | accepted | VSR | mean repair cycles | mean tool calls | mean seconds | mean uncached input |") out.append("|---|---|---|---|---|---|---|---|") for k in sorted({keyf(r) for r in runs}): rs = [r for r in runs if keyf(r) == k] acc = sum(1 for r in rs if r.get("accepted")) cyc = [r["metrics"]["failed_verifier_cycles"] + (r["metrics"].get("failed_test_cycles") or 0) for r in rs if r["metrics"].get("failed_verifier_cycles") is not None] unc = [((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs] out.append(f"| {k} | {len(rs)} | {acc} | {round(acc / len(rs), 3)} | {mean(cyc)} | {mean([r['metrics'].get('tool_calls') for r in rs])} | {mean([r['metrics'].get('elapsed_seconds') for r in rs])} | {mean(unc)} |") out.append("") return "\n".join(out) def _source_size(run_dir, exts): files = lines = nbytes = 0 ws = os.path.join(run_dir, "workspace") for root, dirs, names in os.walk(ws): dirs[:] = [d for d in dirs if d not in ("target", ".zig-cache", "zig-cache", "zig-out", ".git")] for n in names: if os.path.splitext(n)[1] in exts: p = os.path.join(root, n) with open(p, "rb") as f: data = f.read() files, lines, nbytes = files + 1, lines + data.count(b"\n"), nbytes + len(data) return files, lines, nbytes def _diagnostic_codes(r, run_dir): """Counts of verifier/compiler diagnostic codes seen in the run's command outputs (codes only: no message text, no task content).""" import collections import re from . import native counts = collections.Counter() if r.get("track") == "B": cmds = native.command_events(r["agent"]["name"], os.path.join(run_dir, "transcript.jsonl")) outputs = [o for _, _, o in cmds] else: outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l] lang = r["language"]["name"] for o in outputs: if lang == "aji_air": counts.update(re.findall(r'"code":"([ET]\d{4})"', o)) elif lang == "rust": counts.update(re.findall(r"error\[(E\d{4})\]", o)) counts["error(no code)"] += len(re.findall(r"(?m)^error: ", o)) else: counts["error"] += len(re.findall(r": error: ", o)) return dict(counts.most_common()) def profile(paths): """Per-run cost profile for failure and cost analysis (protocol §27, §38): termination, output tokens, solution size and diagnostic codes. Shareable: numbers and diagnostic codes only.""" from . import languages out = ["| task | language | agent | termination | output tokens | source files / lines / bytes | diagnostic codes (count) |", "|---|---|---|---|---|---|---|"] for p in paths: for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)): if "/superseded/" in f: continue r = util.read_json(f) d = os.path.dirname(f) exts = set(languages.load(r["language"]["name"]).get("source_extensions", [])) files, lines, nbytes = _source_size(d, exts) codes = _diagnostic_codes(r, d) m = r["metrics"] out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | " f"{files} / {lines} / {nbytes} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |") return "\n".join(out)