eval: advisory Jev failure classification and improvement triage
`classify --suggest` asks TypeSafe Jev for the protocol §27 category, where the failure was caught and the §38 cause, and stores the answer beside the human classification. Only failed dev/validation runs are sent; test-set runs are refused before any request (§29). `--auto-accept` acts only when triage.json is calibrated and every confidence meets its threshold. `calibrate` measures agreement with human labels per question. `triage` groups classified failures and proposes a routed change only across enough runs, tasks and agents, and withholds proposals while a frozen plan is incomplete. It reports; it never edits spec, bundle or code. The evaluator environment no longer carries TYPESAFE_* variables. The aji-jev skill records where Jev may and may not be used.
This commit is contained in:
1 parent
ba2cb1340a
commit
f733f7c7bb
8 files changed
+626
-8
No files matched your search
@@ -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)")
|
||||
|
||||
@@ -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()},
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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'])} |")
|
||||
@@ -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()
|
||||
@@ -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"}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user