diff --git a/.claude/skills/aji-jev/SKILL.md b/.claude/skills/aji-jev/SKILL.md new file mode 100644 index 0000000..87a4f20 --- /dev/null +++ b/.claude/skills/aji-jev/SKILL.md @@ -0,0 +1,33 @@ +--- +name: aji-jev +description: Use when classifying failed Aji evaluation runs, deciding whether a spec, diagnostic, agent-bundle or documentation improvement is warranted, or when TypeSafe/Jev comes up in this repository. Covers `ajieval classify --suggest`, `calibrate` and `triage`, and the hard limits on where Jev may be used. +--- + +# Jev in Aji: advisory triage only + +Jev (TypeSafe) is a System One classifier. It answers typed questions (`choice`, `score`, `noul`) about a small state and returns calibrated probabilities. In this repository it only *suggests*. The verifier, conformance tests and the owner decide. + +## Hard limits + +- Only `tools/eval/`. Never call Jev from `src/`, the verifier, the interpreter, `build.zig`, CI gates or conformance verdicts. Aji is deterministic, and an external model is not. +- Only failed runs of the `dev` and `validation` sets. Never send a `test`-set run, a held-out task or anything from the private benchmark repository (protocol §29, spec 14 §12). `jev.check_sendable` enforces this; do not bypass it. +- No language change follows from a classification alone. Protocol §38 requires repeated failures across tasks and agents; `triage` enforces this through the minimums in `tools/eval/triage.json`. +- Nothing during a frozen experiment. Pass `--plan` to `triage`. Record observations with `ajieval journal` and act only after the last cell has run. +- Never tune the language to the M or C corpus or to one benchmark task. + +## Workflow + +1. For each failed dev/validation run: `python3 -m ajieval classify RUN --suggest`. This needs `TYPESAFE_API_KEY`; never print or record it. +2. A human confirms or overrides the suggestion with `python3 -m ajieval classify RUN CATEGORY --cause CAUSE [--caught-by ...]`. +3. Once enough runs have both a human label and a suggestion, run `python3 -m ajieval calibrate runs/`. Propose `"calibrated": true` and the thresholds in `triage.json` to the owner only when agreement among auto-accepted suggestions is high. Do not flip it yourself. +4. Run `python3 -m ajieval triage runs/ [--plan PLAN]`. For each proposal, act according to its route: + - `diagnostics`: patch the message in `src/diag.zig` and `docs/reference/error-codes.md`, add a test, open a PR. + - `agent_bundle` / `documentation`: clarify `docs/agent/`, the Quick Reference or the reference without changing meaning. Check the bundle growth (`tools/agent_bundle_tokens.py`). + - `language`: add an entry to `docs/design/open-questions.md` with the evidence (runs, tasks, agents, codes). Only the owner turns it into an RFC. + - `harness`: fix `tools/eval/`. + - `task_ambiguity`: run the task acceptance review (protocol §8). + - `model_capability`: nothing. + +## Changing the questions + +The option descriptions in `tools/eval/ajieval/jev.py` are the classifier's input. A change there changes `questions_hash`, and suggestions made under different hashes must not be mixed in `calibrate`. Keep the descriptions atomic and literal: Jev reads instructions at face value and handles multi-hop reasoning poorly. diff --git a/docs/evaluation/harness.md b/docs/evaluation/harness.md index c77c47d..e93a349 100644 --- a/docs/evaluation/harness.md +++ b/docs/evaluation/harness.md @@ -161,6 +161,20 @@ For the smoke test it also records the cause, decided before any language change - `model_capability` - `task_ambiguity` +### Advisory suggestions and improvement triage + +```sh +python3 -m ajieval classify RUN_DIR --suggest [--auto-accept] # needs TYPESAFE_API_KEY +python3 -m ajieval calibrate runs/ +python3 -m ajieval triage runs/ [--plan PLAN.json] [--json] +``` + +`classify --suggest` asks TypeSafe Jev, a System One classifier, for the category, the place the failure was caught and the cause. The answer is stored as `classification_suggestion` with per-option probabilities and confidence; it is not a classification. The questions and their option descriptions are defined once, in `ajieval/jev.py`. The state sent is minimal: task id, outcome, diagnostic codes, and the tails of the last three failing commands. Only failed runs of the `dev` and `validation` sets are sent; a `test`-set run is refused before any request, because sending it to a third party would disclose the held-out corpus (protocol §29). + +`calibrate` compares suggestions with human classifications per question: agreement overall and among the suggestions the thresholds would accept. Thresholds, proposal minimums and routes live only in `tools/eval/triage.json`. Until it says `"calibrated": true`, `--auto-accept` does nothing. After that, a suggestion whose every confidence meets its threshold becomes the classification, marked `"source": "jev"`; human labels are never overwritten. + +`triage` groups classified failures by (cause, language, category). A group becomes a proposal only when it has at least `min_events` runs across `min_tasks` tasks and `min_agents` agents, so one model struggling on one task never proposes anything (protocol §38). Each proposal is routed by cause to a layer. Diagnostic text, agent bundle, documentation and harness changes go to a reviewed patch or issue. A `language` cause goes only to an open-question entry carrying the evidence; an RFC is the owner's decision. `model_capability` is logged only. With `--plan`, proposals are withheld while that frozen plan still has cells to run, because changing Aji mid-experiment is online tuning. Triage reports; it never edits the specification, the bundle or the code. + ## Track B: native agents ```sh diff --git a/tools/eval/ajieval/cli.py b/tools/eval/ajieval/cli.py index 26b55b2..5e5b8b5 100644 --- a/tools/eval/ajieval/cli.py +++ b/tools/eval/ajieval/cli.py @@ -5,6 +5,9 @@ python3 -m ajieval matrix PLAN.json python3 -m ajieval report runs/ [--json] python3 -m ajieval classify RUN_DIR CATEGORY [--caught-by verifier|runtime|test] [--note TEXT] + python3 -m ajieval classify RUN_DIR --suggest [--auto-accept] + python3 -m ajieval triage runs/ [--plan PLAN.json] [--json] + python3 -m ajieval calibrate runs/ """ import argparse @@ -15,13 +18,12 @@ import sys import datetime -from . import freeze, languages, native, record, report, util +from . import freeze, jev, languages, native, record, report, triage, util -CATEGORIES = ["SPEC_UNDERSTANDING", "SYNTAX", "TYPE", "OWNERSHIP", "BORROW", "RESOURCE", "BOUNDS", "FUNCTIONAL", "CONCURRENCY", - "DEADLOCK", "ATOMIC_ORDERING", "PERFORMANCE", "BUDGET", "TIMEOUT", "AGENT_GAVE_UP", "TOOL_FAILURE"] -# Smoke-test causes (protocol §38): where a failure originates, before any -# language change is considered. -CAUSES = ["language", "documentation", "agent_bundle", "diagnostics", "harness", "model_capability", "task_ambiguity"] +# Protocol §27 categories and §38 causes; their descriptions (the questions +# Jev answers) are defined once, in jev.py. +CATEGORIES = list(jev.CATEGORIES) +CAUSES = list(jev.CAUSES) def load_pricing(path): @@ -124,6 +126,12 @@ def cmd_journal(a): def cmd_classify(a): path = os.path.join(a.run, "run.json") + if not os.path.isfile(path): + raise SystemExit(f"classify: {path} not found") + if a.suggest: + return suggest(a, path) + if not a.category: + raise SystemExit("classify: CATEGORY is required unless --suggest is given") rec = util.read_json(path) rec["classification"] = {"category": a.category, "caught_by": a.caught_by, "cause": a.cause, "note": a.note} if a.atomic_error: @@ -132,6 +140,31 @@ def cmd_classify(a): print(json.dumps(rec["classification"])) +def suggest(a, path): + """Stores a Jev suggestion next to (never in place of) the human + classification; with --auto-accept and a calibrated `triage.json` it + also becomes the classification when every confidence meets its + threshold, marked `source: jev`.""" + try: + s = jev.suggest(a.run) + except jev.JevError as e: + raise SystemExit(f"classify --suggest: {e}") + rec = util.read_json(path) + rec["classification_suggestion"] = s + accepted = False + if a.auto_accept: + cfg = triage.load_config(a.config) + if not cfg.get("calibrated"): + print("auto-accept disabled: triage.json is not calibrated (run `ajieval calibrate`)", file=sys.stderr) + elif rec.get("classification"): + print("auto-accept skipped: the run already has a classification", file=sys.stderr) + elif triage.confident(s, cfg): + rec["classification"] = triage.accept(s) + accepted = True + util.write_json(path, rec) + print(json.dumps({"suggestion": {k: [v["choice"], v["confidence"]] for k, v in s["answers"].items()}, "accepted": accepted})) + + def main(argv=None): p = argparse.ArgumentParser(prog="ajieval", description="Aji evaluation harness (protocol §5, §28)") sub = p.add_subparsers(dest="cmd", required=True) @@ -212,14 +245,30 @@ def main(argv=None): c = sub.add_parser("classify", help="record the primary failure category of a run (protocol §27)") c.add_argument("run") - c.add_argument("category", choices=CATEGORIES) + c.add_argument("category", nargs="?", choices=CATEGORIES) c.add_argument("--caught-by", choices=["verifier", "runtime", "test"]) c.add_argument("--cause", choices=CAUSES) c.add_argument("--note") # B1 §5: for failed runs of the atomic family. c.add_argument("--atomic-error", choices=["memory_model", "algorithmic"]) + c.add_argument("--suggest", action="store_true", help="ask Jev (TYPESAFE_API_KEY) for an advisory classification; dev/validation runs only") + c.add_argument("--auto-accept", action="store_true", help="with --suggest: record it as the classification if triage.json is calibrated and every confidence meets its threshold") + c.add_argument("--config", help="triage thresholds (default tools/eval/triage.json)") c.set_defaults(fn=cmd_classify) + tr = sub.add_parser("triage", help="protocol §38: aggregate classified failures into routed improvement proposals") + tr.add_argument("paths", nargs="+") + tr.add_argument("--plan", help="withhold proposals while this frozen plan still has cells to run") + tr.add_argument("--config") + tr.add_argument("--json", action="store_true") + tr.set_defaults(fn=triage.main_triage) + + cb = sub.add_parser("calibrate", help="agreement of Jev suggestions with human classifications, per question") + cb.add_argument("paths", nargs="+") + cb.add_argument("--config") + cb.add_argument("--json", action="store_true") + cb.set_defaults(fn=triage.main_calibrate) + v = sub.add_parser("vsr", help="B1 §6.1: verified success rate per agent × language with 95 %% Wilson intervals") v.add_argument("paths", nargs="+") v.add_argument("--tasks", help="comma-separated task ids to include (e.g. the medium ones)") diff --git a/tools/eval/ajieval/jev.py b/tools/eval/ajieval/jev.py new file mode 100644 index 0000000..0b14255 --- /dev/null +++ b/tools/eval/ajieval/jev.py @@ -0,0 +1,167 @@ +"""Advisory failure classification with a System One model (TypeSafe Jev). + +Jev answers typed questions about a small state with calibrated +probabilities. Here it suggests the protocol §27 category, the place a +failure was caught and the §38 cause of a failed run. A suggestion is never +a verdict: it is stored next to the human classification, and only +`triage.json` thresholds decide whether `triage` may count it. + +Boundaries (tools/eval only; never the verifier, CI gates or conformance): + - only runs of the `dev` and `validation` sets are sent; the held-out + `test` set never leaves the machine (protocol §29); + - the state is minimal (task id, outcome, diagnostic codes, the tails of + the last failing commands), because unrelated detail lowers accuracy; + - the questions below are the single reviewable definition. + + TYPESAFE_API_KEY bearer token (required, never recorded) + TYPESAFE_BASE_URL default https://api.typesafe.ai +""" + +import datetime +import json +import os +import urllib.error +import urllib.request + +from . import util + +MODEL = "jev-latest" +SENDABLE_SETS = ("dev", "validation") +COMMANDS = 3 +OUTPUT_TAIL = 1500 + +CATEGORIES = { + "SPEC_UNDERSTANDING": "the program solves a different problem than the task asks", + "SYNTAX": "the program does not parse", + "TYPE": "type errors: mismatched, unknown or ill-formed types", + "OWNERSHIP": "moves, use after move, missing release of an owned value", + "BORROW": "borrow conflicts, mutable aliasing, borrows that outlive their owner", + "RESOURCE": "resources (files, sockets, regions, tasks) not closed or closed twice", + "BOUNDS": "out-of-bounds index or length errors", + "FUNCTIONAL": "the program runs but its output or behaviour is wrong", + "CONCURRENCY": "data races, wrong task or channel structure", + "DEADLOCK": "tasks wait on each other forever", + "ATOMIC_ORDERING": "wrong atomic memory ordering", + "PERFORMANCE": "correct but too slow or too large for the task limits", + "BUDGET": "the agent ran out of tokens or tool calls", + "TIMEOUT": "a command or the run hit its time limit", + "AGENT_GAVE_UP": "the agent stopped without a working solution", + "TOOL_FAILURE": "the harness, sandbox or toolchain itself failed", +} +CAUGHT_BY = { + "verifier": "a verifier or compiler diagnostic rejected the program", + "runtime": "the program trapped or failed while running", + "test": "the program ran to completion but a test rejected its output", +} +CAUSES = { + "language": "the language semantics themselves make the correct program hard to express", + "documentation": "the specification or reference does not explain the needed rule clearly", + "agent_bundle": "the agent reference bundle or quick reference lacks or misstates what was needed", + "diagnostics": "a diagnostic was misleading or did not say how to fix the program", + "harness": "the evaluation harness, sandbox or evaluator misbehaved", + "model_capability": "the rules were clear and available; the model failed to apply them", + "task_ambiguity": "the task statement is ambiguous or underspecified", +} + + +class JevError(Exception): + pass + + +def questions(aji): + q = { + "category": {"type": "choice", "instructions": "Which primary failure category best describes why this run failed?", "criteria": CATEGORIES}, + "cause": {"type": "choice", "instructions": "Where does the failure originate?", "criteria": CAUSES}, + } + if aji: + q["caught_by"] = {"type": "choice", "instructions": "What first caught the failure?", "criteria": CAUGHT_BY} + return q + + +def _commands(r, run_dir): + """(command, exit code, output) for every command of the run.""" + from . import native + + if r.get("track") == "B": + path = os.path.join(run_dir, "transcript.jsonl") + return native.command_events(r["agent"]["name"], path) if os.path.isfile(path) else [] + path = os.path.join(run_dir, "events.jsonl") + if not os.path.isfile(path): + return [] + out = [] + with open(path) as f: + for line in f: + e = json.loads(line) + if e.get("event") == "command": + out.append((e.get("command") or "", e.get("exit"), e.get("output") or "")) + return out + + +def state(r, run_dir): + """The minimal state for one failed run.""" + from . import report + + cmds = _commands(r, run_dir) + failing = [c for c in cmds if c[1] not in (0, None)] or cmds + m = r.get("metrics", {}) + return { + "task": r["task"]["id"], + "language": r["language"]["name"], + "termination": m.get("termination"), + "verdict": {k: v for k, v in (r.get("verdict") or {}).items() if k in ("accepted", "gates", "error")}, + "failed_verifier_cycles": m.get("failed_verifier_cycles"), + "failed_test_cycles": m.get("failed_test_cycles"), + "diagnostic_codes": report._diagnostic_codes(r, run_dir, [c[2] for c in cmds]), + "last_failing_commands": [{"command": c[0][:300], "exit": c[1], "output_tail": c[2][-OUTPUT_TAIL:]} for c in failing[-COMMANDS:]], + } + + +def check_sendable(r): + s = r["task"].get("set", "dev") + if s not in SENDABLE_SETS: + raise JevError(f"task {r['task']['id']} is in the {s!r} set; only {', '.join(SENDABLE_SETS)} runs are sent to Jev (protocol §29)") + if r.get("accepted"): + raise JevError(f"run {r['run_id']} was accepted; only failed runs are classified (protocol §27)") + + +def ask(state_obj, qs, post=None): + """One System One request; returns the `answers` map.""" + body = {"state": state_obj, "model": os.environ.get("TYPESAFE_DEFAULT_MODEL", MODEL), "questions": qs} + resp = (post or _post)(body) + answers = resp.get("answers") + if not isinstance(answers, dict) or set(answers) != set(qs): + raise JevError(f"unexpected response: answers for {sorted(answers or {})}, asked {sorted(qs)}") + return resp.get("model"), answers + + +def _post(body): + key = os.environ.get("TYPESAFE_API_KEY") + if not key: + raise JevError("TYPESAFE_API_KEY is not set") + url = os.environ.get("TYPESAFE_BASE_URL", "https://api.typesafe.ai").rstrip("/") + "/v1/systemone" + req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", + headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}) + try: + with urllib.request.urlopen(req, timeout=60) as f: + return json.loads(f.read()) + except urllib.error.HTTPError as e: + raise JevError(f"TypeSafe API: HTTP {e.code}: {e.read()[:500].decode(errors='replace')}") from None + except urllib.error.URLError as e: + raise JevError(f"TypeSafe API: {e.reason}") from None + + +def suggest(run_dir, post=None): + """Asks Jev about one failed run; returns the suggestion record.""" + r = util.read_json(os.path.join(run_dir, "run.json")) + check_sendable(r) + st = state(r, run_dir) + qs = questions(r["language"]["name"] in ("aji_air", "aji_source")) + model, answers = ask(st, qs, post) + return { + "source": "jev", + "model": model, + "at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), + "state_hash": util.sha256_text(json.dumps(st, sort_keys=True)), + "questions_hash": util.sha256_text(json.dumps(qs, sort_keys=True)), + "answers": {k: {"choice": a.get("choice"), "confidence": a.get("confidence"), "probabilities": a.get("probabilities")} for k, a in answers.items()}, + } diff --git a/tools/eval/ajieval/record.py b/tools/eval/ajieval/record.py index 62187e0..351e6de 100644 --- a/tools/eval/ajieval/record.py +++ b/tools/eval/ajieval/record.py @@ -56,7 +56,8 @@ def evaluator_env(lang): AJIEVAL_TOOLCHAIN_PATH PATH entries of the toolchain (`:`-separated) AJIEVAL_TOOLCHAIN_DIRS directories to bind read-only (newline-separated) """ - env = dict(os.environ) + # The TypeSafe key is for `classify --suggest` only (jev.py). + env = {k: v for k, v in os.environ.items() if not k.startswith("TYPESAFE_")} try: _, binds = languages.resolve_binaries(languages.load(lang)) except SystemExit: diff --git a/tools/eval/ajieval/triage.py b/tools/eval/ajieval/triage.py new file mode 100644 index 0000000..04de69f --- /dev/null +++ b/tools/eval/ajieval/triage.py @@ -0,0 +1,170 @@ +"""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'])} |") diff --git a/tools/eval/tests/test_triage.py b/tools/eval/tests/test_triage.py new file mode 100644 index 0000000..69e7153 --- /dev/null +++ b/tools/eval/tests/test_triage.py @@ -0,0 +1,169 @@ +"""Jev suggestions and improvement triage (protocol §27, §38), offline: the +TypeSafe API is replaced by a canned response.""" + +import json +import os +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) + +from ajieval import cli, jev, triage, util # noqa: E402 + +CFG = {"calibrated": True, "min_confidence": {"category": 0.8, "cause": 0.8, "caught_by": 0.8}, + "proposal": {"min_events": 3, "min_tasks": 2, "min_agents": 2}, + "routes": {"diagnostics": {"layer": "diagnostic text", "target": "src/diag.zig", "action": "patch"}, + "model_capability": {"layer": "none", "target": None, "action": "log only"}}} + + +def answer(choice, confidence): + return {"type": "choice", "choice": choice, "confidence": confidence, "probabilities": {choice: confidence}} + + +def canned(confidence=0.9, cause="diagnostics"): + seen = [] + + def post(body): + seen.append(body) + a = {"category": answer("BORROW", confidence), "cause": answer(cause, confidence), "caught_by": answer("verifier", confidence)} + return {"model": "jev-test", "answers": {q: a[q] for q in body["questions"]}, "usage": {}} + return post, seen + + +def make_run(root, run_id, task="t1", agent="m1", task_set="dev", accepted=False, classification=None, lang="aji_air"): + d = os.path.join(root, run_id) + os.makedirs(d) + rec = {"run_id": run_id, "task": {"id": task, "set": task_set}, "language": {"name": lang}, "model": {"id": agent}, + "metrics": {"termination": "done", "failed_verifier_cycles": 2, "failed_test_cycles": 0}, + "verdict": {"accepted": accepted, "gates": {"builds": False}}, "accepted": accepted, "classification": classification} + util.write_json(os.path.join(d, "run.json"), rec) + with open(os.path.join(d, "events.jsonl"), "w") as f: + f.write(json.dumps({"event": "command", "command": "aji check main.air", "exit": 1, "output": '{"code":"E3101","reason":"x"}\n'}) + "\n") + f.write(json.dumps({"event": "command", "command": "ls", "exit": 0, "output": "main.air\n"}) + "\n") + return d + + +class Suggest(unittest.TestCase): + def test_state_is_minimal_and_questions_match_language(self): + with tempfile.TemporaryDirectory() as root: + d = make_run(root, "r1") + post, seen = canned() + s = jev.suggest(d, post) + st = seen[0]["state"] + self.assertEqual(st["diagnostic_codes"], {"E3101": 1}) + self.assertEqual([c["command"] for c in st["last_failing_commands"]], ["aji check main.air"]) + self.assertEqual(set(seen[0]["questions"]), {"category", "cause", "caught_by"}) + self.assertEqual(s["answers"]["cause"]["choice"], "diagnostics") + make_run(root, "r2", lang="rust") + jev.suggest(os.path.join(root, "r2"), post) + self.assertEqual(set(seen[1]["questions"]), {"category", "cause"}) + + def test_held_out_and_accepted_runs_are_never_sent(self): + with tempfile.TemporaryDirectory() as root: + post, seen = canned() + with self.assertRaisesRegex(jev.JevError, "§29"): + jev.suggest(make_run(root, "r1", task_set="test"), post) + with self.assertRaisesRegex(jev.JevError, "§27"): + jev.suggest(make_run(root, "r2", accepted=True), post) + self.assertEqual(seen, []) + + def test_bad_response_is_rejected(self): + with self.assertRaises(jev.JevError): + jev.ask({}, jev.questions(False), lambda body: {"answers": {"category": answer("TYPE", 1.0)}}) + + def test_categories_and_causes_have_one_definition(self): + self.assertEqual(cli.CATEGORIES, list(jev.CATEGORIES)) + self.assertEqual(cli.CAUSES, list(jev.CAUSES)) + + +class Triage(unittest.TestCase): + def label(self, cause="diagnostics", source=None): + c = {"category": "BORROW", "caught_by": "verifier", "cause": cause, "note": None} + if source: + c["source"] = source + return c + + def test_proposal_needs_events_tasks_and_agents(self): + with tempfile.TemporaryDirectory() as root: + for i, (task, agent) in enumerate([("t1", "m1"), ("t1", "m1"), ("t1", "m1")]): + make_run(root, f"r{i}", task=task, agent=agent, classification=self.label()) + t = triage.triage([root], CFG) + self.assertFalse(t["groups"][0]["proposed"], "one task, one agent: never a proposal") + make_run(root, "r3", task="t2", agent="m2", classification=self.label()) + t = triage.triage([root], CFG) + g = t["groups"][0] + self.assertTrue(g["proposed"]) + self.assertEqual(g["codes"], {"E3101": 4}) + self.assertIn("src/diag.zig", triage.render(t)) + + def test_log_only_causes_and_unconfirmed_suggestions_never_propose(self): + with tempfile.TemporaryDirectory() as root: + for i, (task, agent) in enumerate([("t1", "m1"), ("t2", "m2"), ("t3", "m3")]): + make_run(root, f"r{i}", task=task, agent=agent, classification=self.label("model_capability")) + d = make_run(root, "s1") + rec = util.read_json(os.path.join(d, "run.json")) + rec["classification_suggestion"] = {"answers": {}} + util.write_json(os.path.join(d, "run.json"), rec) + make_run(root, "ok", accepted=True) + t = triage.triage([root], CFG) + self.assertFalse(t["groups"][0]["proposed"]) + self.assertEqual(t["awaiting_review"], ["s1"]) + self.assertEqual(t["unclassified"], []) + + def test_frozen_plan_withholds_proposals(self): + with tempfile.TemporaryDirectory() as root: + runs = os.path.join(root, "runs") + for i, (task, agent) in enumerate([("t1", "m1"), ("t2", "m2"), ("t3", "m3")]): + make_run(runs, f"r{i}", task=task, agent=agent, classification=self.label()) + plan = os.path.join(root, "plan.json") + util.write_json(plan, {"out": "runs"}) + util.write_json(triage.freeze.freeze_path(plan), {"order": [{}] * 5}) + t = triage.triage([runs], CFG, plan) + self.assertTrue(t["withheld"]) + self.assertFalse(any(g["proposed"] for g in t["groups"])) + util.write_json(triage.freeze.freeze_path(plan), {"order": [{}] * 3}) + self.assertTrue(triage.triage([runs], CFG, plan)["groups"][0]["proposed"]) + + def test_auto_accept_requires_calibration_and_confidence(self): + with tempfile.TemporaryDirectory() as root: + cfg_path = os.path.join(root, "triage.json") + d = make_run(root, "r1") + post, _ = canned(0.95) + orig = jev._post + jev._post = post + try: + util.write_json(cfg_path, dict(CFG, calibrated=False)) + cli.main(["classify", d, "--suggest", "--auto-accept", "--config", cfg_path]) + self.assertIsNone(util.read_json(os.path.join(d, "run.json"))["classification"]) + util.write_json(cfg_path, CFG) + cli.main(["classify", d, "--suggest", "--auto-accept", "--config", cfg_path]) + c = util.read_json(os.path.join(d, "run.json"))["classification"] + self.assertEqual((c["cause"], c["source"]), ("diagnostics", "jev")) + d2 = make_run(root, "r2") + jev._post = canned(0.5)[0] + cli.main(["classify", d2, "--suggest", "--auto-accept", "--config", cfg_path]) + self.assertIsNone(util.read_json(os.path.join(d2, "run.json"))["classification"]) + finally: + jev._post = orig + + def test_calibration_counts_only_human_labels(self): + with tempfile.TemporaryDirectory() as root: + for i, cause in enumerate(["diagnostics", "documentation"]): + d = make_run(root, f"r{i}", classification=self.label(cause)) + rec = util.read_json(os.path.join(d, "run.json")) + rec["classification_suggestion"] = {"questions_hash": util.sha256_text(json.dumps(jev.questions(True), sort_keys=True)), + "answers": {"cause": answer("diagnostics", 0.9 - 0.2 * i)}} + util.write_json(os.path.join(d, "run.json"), rec) + make_run(root, "j", classification=self.label(source="jev")) + d = make_run(root, "old", classification=self.label("documentation")) + rec = util.read_json(os.path.join(d, "run.json")) + rec["classification_suggestion"] = {"questions_hash": "sha256:old", "answers": {"cause": answer("diagnostics", 0.9)}} + util.write_json(os.path.join(d, "run.json"), rec) + s = triage.calibration([root], CFG)["cause"] + self.assertEqual(s, {"pairs": 2, "agree": 1, "covered": 1, "covered_agree": 1}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/eval/triage.json b/tools/eval/triage.json new file mode 100644 index 0000000..ffb787a --- /dev/null +++ b/tools/eval/triage.json @@ -0,0 +1,15 @@ +{ + "_comment": "Thresholds and routing for `ajieval triage` and `classify --suggest --auto-accept`. The single reviewable place for these constants; change them by review, never during a frozen experiment.", + "calibrated": false, + "min_confidence": {"category": 0.8, "cause": 0.8, "caught_by": 0.8}, + "proposal": {"min_events": 3, "min_tasks": 2, "min_agents": 2}, + "routes": { + "diagnostics": {"layer": "diagnostic text", "target": "src/diag.zig, docs/reference/error-codes.md", "action": "patch the message and add a test; PR review"}, + "agent_bundle": {"layer": "agent bundle", "target": "docs/agent/, Quick Reference", "action": "patch; PR review; only between experiment iterations"}, + "documentation": {"layer": "documentation", "target": "docs/reference/, explanatory spec prose", "action": "clarify without changing meaning; PR review"}, + "harness": {"layer": "harness", "target": "tools/eval/", "action": "issue"}, + "language": {"layer": "language", "target": "docs/design/open-questions.md", "action": "open-question entry with the evidence below; an RFC only by owner decision (protocol §38)"}, + "task_ambiguity": {"layer": "benchmark", "target": "task statement", "action": "task acceptance review (protocol §8)"}, + "model_capability": {"layer": "none", "target": null, "action": "log only"} + } +}