"""Improvement triage (protocol §38): turns classified failures into routed proposals, and measures how far Jev suggestions agree with human labels. A failure counts once it has a classification: a human one, or a Jev suggestion auto-accepted under `triage.json` (`calibrated: true` and every confidence at its threshold). Unconfirmed suggestions are listed for review and never count. A proposal needs the same (cause, language, category) across `min_events` runs, `min_tasks` tasks and `min_agents` agents, so one model struggling on one task never proposes anything. Thresholds and routes live only in `triage.json`; this module decides nothing on its own. """ import collections import json import os from . import freeze, jev, report, util CONFIG = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "triage.json") def load_config(path=None): return util.read_json(path or CONFIG) def agent_of(r): if r.get("track") == "B": return r["agent"]["name"] + ":" + r["agent"]["model"] return r["model"]["id"] def confident(suggestion, cfg): """True when every answer meets its `min_confidence` threshold.""" answers = suggestion.get("answers", {}) return bool(answers) and all((a.get("confidence") or 0) >= cfg["min_confidence"].get(q, 1.0) for q, a in answers.items()) def accept(suggestion): return {"category": suggestion["answers"]["category"]["choice"], "caught_by": (suggestion["answers"].get("caught_by") or {}).get("choice"), "cause": suggestion["answers"]["cause"]["choice"], "note": None, "source": "jev", "model": suggestion.get("model")} def frozen_incomplete(plan): """True while a frozen plan still has cells to run.""" if not plan or not os.path.exists(freeze.freeze_path(plan)): return False order = util.read_json(freeze.freeze_path(plan))["order"] out = os.path.join(os.path.dirname(os.path.abspath(plan)), util.read_json(plan).get("out", "runs")) return len(report.load([out])) < len(order) def collect(paths): """(classified failures, runs awaiting review, unclassified failures).""" classified, review, missing = [], [], [] for f in report._run_files(paths): r = util.read_json(f) if r.get("accepted") is not False: continue run_dir = os.path.dirname(f) c = r.get("classification") if c and c.get("cause"): codes = report._diagnostic_codes(r, run_dir) if r["language"]["name"] in ("aji_air", "aji_source") else {} classified.append({"run": r["run_id"], "task": r["task"]["id"], "language": r["language"]["name"], "agent": agent_of(r), "category": c["category"], "cause": c["cause"], "source": c.get("source", "human"), "codes": codes}) elif r.get("classification_suggestion"): review.append(r["run_id"]) else: missing.append(r["run_id"]) return classified, review, missing def proposals(classified, cfg): groups = collections.defaultdict(list) for e in classified: groups[(e["cause"], e["language"], e["category"])].append(e) p = cfg["proposal"] out = [] for (cause, lang, cat), es in sorted(groups.items()): tasks, agents = {e["task"] for e in es}, {e["agent"] for e in es} codes = collections.Counter() for e in es: codes.update(e["codes"]) row = {"cause": cause, "language": lang, "category": cat, "events": len(es), "tasks": sorted(tasks), "agents": sorted(agents), "runs": sorted(e["run"] for e in es), "codes": dict(codes.most_common(5)), "jev_labels": sum(e["source"] == "jev" for e in es), "route": cfg["routes"].get(cause)} row["proposed"] = (len(es) >= p["min_events"] and len(tasks) >= p["min_tasks"] and len(agents) >= p["min_agents"] and row["route"] is not None and row["route"]["target"] is not None) out.append(row) return out def triage(paths, cfg, plan=None): classified, review, missing = collect(paths) rows = proposals(classified, cfg) withheld = frozen_incomplete(plan) if withheld: for row in rows: row["proposed"] = False return {"withheld": withheld, "groups": rows, "awaiting_review": review, "unclassified": missing} def render(t): out = ["## Improvement triage (protocol §38)\n"] if t["withheld"]: out.append("**Frozen experiment in progress: proposals withheld until every cell has run.**\n") props = [g for g in t["groups"] if g["proposed"]] out.append(f"{len(props)} proposal(s); {len(t['groups'])} group(s); {len(t['awaiting_review'])} run(s) awaiting review; {len(t['unclassified'])} unclassified.\n") for g in props: r = g["route"] out += [f"### {g['cause']} · {g['language']} · {g['category']}\n", f"- layer: {r['layer']}; target: {r['target']}", f"- action: {r['action']}", f"- evidence: {g['events']} runs, tasks {', '.join(g['tasks'])}, agents {', '.join(g['agents'])} ({g['jev_labels']} labelled by Jev)", f"- diagnostic codes: {', '.join(f'{c} ×{n}' for c, n in g['codes'].items()) or '-'}", f"- runs: {', '.join(g['runs'])}\n"] rest = [g for g in t["groups"] if not g["proposed"]] if rest: out += ["### Below threshold\n", "| cause | language | category | runs | tasks | agents |", "|---|---|---|---|---|---|"] out += [f"| {g['cause']} | {g['language']} | {g['category']} | {g['events']} | {len(g['tasks'])} | {len(g['agents'])} |" for g in rest] out.append("") if t["awaiting_review"]: out += ["### Awaiting review (Jev suggestion, not counted)\n"] + [f"- {r}" for r in t["awaiting_review"]] + [""] return "\n".join(out) def calibration(paths, cfg): """Per question: runs with both a human label and a suggestion, how many the thresholds would auto-accept (coverage), and agreement among those and overall. Suggestions made under other questions are skipped. Decide `calibrated` from these numbers.""" current = {util.sha256_text(json.dumps(jev.questions(aji), sort_keys=True)) for aji in (False, True)} stats = collections.defaultdict(lambda: {"pairs": 0, "agree": 0, "covered": 0, "covered_agree": 0}) for f in report._run_files(paths): r = util.read_json(f) c, s = r.get("classification"), r.get("classification_suggestion") if not c or not s or c.get("source", "human") != "human": continue if s.get("questions_hash") not in current: continue for q, a in s.get("answers", {}).items(): if c.get(q) is None: continue st = stats[q] hit = a.get("choice") == c[q] st["pairs"] += 1 st["agree"] += hit if (a.get("confidence") or 0) >= cfg["min_confidence"].get(q, 1.0): st["covered"] += 1 st["covered_agree"] += hit return dict(stats) def main_triage(a): cfg = load_config(a.config) t = triage(a.paths, cfg, a.plan) print(json.dumps(t, indent=2) if a.json else render(t)) def main_calibrate(a): cfg = load_config(a.config) stats = calibration(a.paths, cfg) if a.json: print(json.dumps(stats, indent=2)) return print("| question | pairs | agreement | auto-accepted | agreement when auto-accepted |\n|---|---|---|---|---|") pct = lambda n, d: f"{n}/{d} ({100 * n // d}%)" if d else "-" for q, s in sorted(stats.items()): print(f"| {q} | {s['pairs']} | {pct(s['agree'], s['pairs'])} | {pct(s['covered'], s['pairs'])} | {pct(s['covered_agree'], s['covered'])} |")