Files
aji/tools/eval/ajieval/cli.py
T
dev f733f7c7bb 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.
2026-10-07 22:21:47 +03:00

290 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Command line: run, matrix, report, classify.
python3 -m ajieval run --task DIR --language aji_air --provider anthropic \\
--model claude-... --class frontier --out runs/ [--evaluator CMD ...]
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
import json
import os
import shlex
import sys
import datetime
from . import freeze, jev, languages, native, record, report, triage, util
# 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):
return util.read_json(path) if path else None
def cmd_run(a):
run_dir, rec = record.run_one(
a.task, a.language, a.provider, a.model, a.out, model_class=a.model_class, seed=a.seed, sandbox_kind=a.sandbox,
evaluator=shlex.split(a.evaluator) if a.evaluator else None, evaluator_hash_path=a.evaluator_hash_path,
pricing=load_pricing(a.pricing), base_url=a.base_url, max_tokens=a.max_tokens, temperature=a.temperature,
provider_options={k: v for k, v in {"extra": json.loads(a.extra) if a.extra else None, "key_env": a.key_env, "key_file": a.key_file, "token_param": a.token_param}.items() if v})
m = rec["metrics"]
print(json.dumps({"run": run_dir, "termination": m["termination"], "accepted": rec["accepted"], "tool_calls": m["tool_calls"],
"input_tokens": m["input_tokens"], "output_tokens": m["output_tokens"], "cost_usd": rec["cost_usd"]}))
def cmd_native(a):
run_dir, rec = native.run_native(a.task, a.language, a.agent, a.model, a.out, effort=a.effort, seed=a.seed,
evaluator=shlex.split(a.evaluator) if a.evaluator else None, evaluator_hash_path=a.evaluator_hash_path, label=a.label)
m = rec["metrics"]
print(json.dumps({"run": run_dir, "termination": m["termination"], "exit_code": m["exit_code"], "accepted": rec["accepted"],
"model": rec["agent"]["model"], "model_source": rec["agent"]["model_source"], "tool_calls": m["tool_calls"],
"input_tokens": m["input_tokens"], "output_tokens": m["output_tokens"], "seconds": m["elapsed_seconds"]}))
def cmd_matrix(a):
"""Runs every cell of a plan sequentially; finished runs (a run.json with
the same task, language, model and seed) are skipped, so a plan can be
resumed. With a freeze file (`ajieval freeze`) the frozen state is
verified first and the cells run in the frozen random order."""
plan = util.read_json(a.plan)
base = os.path.dirname(os.path.abspath(a.plan))
out = os.path.join(base, plan.get("out", "runs"))
os.makedirs(out, exist_ok=True)
if os.path.exists(freeze.freeze_path(a.plan)):
order = freeze.check(a.plan)["order"]
print(f"frozen plan: {len(order)} cells in frozen order", file=sys.stderr)
elif plan.get("require_freeze"):
raise SystemExit(f"{a.plan} requires a freeze file; run `ajieval freeze {a.plan}` first")
else:
order = freeze.cells(plan, base)
done = {(r["task"]["id"], r["language"]["name"], (r["agent"]["name"] + ":" + r["agent"]["requested_model"]) if r.get("track") == "B" else r["model"]["id"], r["seed"]) for r in report.load([out])}
pricing = load_pricing(os.path.join(base, plan["pricing"])) if plan.get("pricing") else None
evaluator = shlex.split(plan["evaluator"]) if plan.get("evaluator") else None
rel = lambda p: p if os.path.isabs(p) or not os.path.exists(os.path.join(base, p)) else os.path.join(base, p)
if evaluator:
evaluator[0] = rel(evaluator[0])
hash_path = rel(plan["evaluator_hash_path"]) if plan.get("evaluator_hash_path") else None
models = {((m["agent"] + ":" + m["model"]) if m.get("agent") else m["model"]): m for m in plan["models"]}
for i, cell in enumerate(order):
if (cell["task_id"], cell["language"], cell["model"], cell["seed"]) in done:
continue
mdl = models[cell["model"]]
tpath = os.path.join(base, cell["task"])
print(f"[{i + 1}/{len(order)}] {cell['task_id']} {cell['language']} {cell['model']} seed {cell['seed']}", file=sys.stderr)
if mdl.get("agent"):
run_dir, rec = native.run_native(tpath, cell["language"], mdl["agent"], mdl["model"], out, effort=mdl.get("effort"), seed=cell["seed"],
evaluator=evaluator, evaluator_hash_path=hash_path, label=mdl.get("label"), limits=plan.get("limits"))
else:
run_dir, rec = record.run_one(
tpath, cell["language"], mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=cell["seed"],
sandbox_kind=plan.get("sandbox", "bwrap"), evaluator=evaluator, evaluator_hash_path=hash_path,
pricing=pricing, base_url=mdl.get("base_url"), max_tokens=mdl.get("max_tokens", 8192), temperature=mdl.get("temperature"),
limits=plan.get("limits"),
provider_options={k: mdl[k] for k in ("extra", "key_env", "key_file", "token_param") if k in mdl})
rec["cell"] = {"index": i, "of": len(order)}
util.write_json(os.path.join(run_dir, "run.json"), rec)
print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr)
report.print_report([out])
def cmd_evaluate(a):
"""Runs an evaluator on a workspace exactly as the harness does (same
arguments and environment), to debug evaluator integration without an
agent run."""
from . import task as task_mod
t = task_mod.Task(a.task)
lim = t.limits
verdict = record.evaluate(shlex.split(a.evaluator), os.path.realpath(a.workspace), a.language, t.dir, lim["command_timeout"] * 4, a.log)
print(json.dumps(verdict, indent=2))
def cmd_freeze(a):
path, frozen = freeze.write(a.plan, a.order_seed)
print(json.dumps({"freeze": path, "cells": len(frozen["order"]), "order_seed": frozen["order_seed"], "aji_commit": frozen["state"]["aji_commit"]}))
def cmd_journal(a):
"""Appends an observation to the plan's journal. During a frozen
experiment problems are recorded here and acted on only afterwards."""
plan = util.read_json(a.plan)
out = os.path.join(os.path.dirname(os.path.abspath(a.plan)), plan.get("out", "runs"))
os.makedirs(out, exist_ok=True)
stamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
with open(os.path.join(out, "journal.md"), "a") as f:
f.write(f"- {stamp}" + (f" [{a.run}]" if a.run else "") + f" {a.text}\n")
print(os.path.join(out, "journal.md"))
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:
rec["classification"]["atomic_error"] = a.atomic_error
util.write_json(path, rec)
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)
r = sub.add_parser("run", help="one run: one model, one language, one task, fresh workspace and context")
r.add_argument("--task", required=True)
r.add_argument("--language", required=True, choices=languages.available())
r.add_argument("--provider", required=True)
r.add_argument("--model", required=True)
r.add_argument("--class", dest="model_class")
r.add_argument("--seed", type=int, default=0)
r.add_argument("--out", default="runs")
r.add_argument("--sandbox", default="bwrap", choices=["bwrap", "none"])
r.add_argument("--evaluator", help="command run as: CMD WORKSPACE LANGUAGE TASK_DIR; prints a JSON verdict")
r.add_argument("--evaluator-hash-path", help="file or directory hashed into the record (default: the evaluator executable)")
r.add_argument("--pricing", help="JSON: model -> {input, output, cached_input} USD per million tokens")
r.add_argument("--base-url")
r.add_argument("--max-tokens", type=int, default=8192)
r.add_argument("--temperature", type=float)
r.add_argument("--extra", help='JSON merged into every request body, e.g. {"reasoning_effort": "medium"}')
r.add_argument("--key-env", help="name of the environment variable holding the API key (openai provider)")
r.add_argument("--key-file", help="file whose first line is the API key (never recorded)")
r.add_argument("--token-param", help="max_tokens or max_completion_tokens (openai provider)")
r.set_defaults(fn=cmd_run)
n = sub.add_parser("native", help="Track B: one run of a native coding agent (Codex, Claude Code, OpenCode)")
n.add_argument("--task", required=True)
n.add_argument("--language", required=True, choices=languages.available())
n.add_argument("--agent", required=True, choices=native.available())
n.add_argument("--model", required=True, help="exact model id as the CLI expects it")
n.add_argument("--effort", help="the CLI's reasoning/effort setting, recorded")
n.add_argument("--label", help="neutral label, e.g. N1")
n.add_argument("--seed", type=int, default=0)
n.add_argument("--out", default="runs")
n.add_argument("--evaluator")
n.add_argument("--evaluator-hash-path")
n.set_defaults(fn=cmd_native)
m = sub.add_parser("matrix", help="run every cell of a plan file (resumable)")
m.add_argument("plan")
m.set_defaults(fn=cmd_matrix)
ev = sub.add_parser("evaluate", help="run an evaluator on a workspace exactly as the harness does")
ev.add_argument("--task", required=True)
ev.add_argument("--language", required=True, choices=languages.available())
ev.add_argument("--workspace", required=True)
ev.add_argument("--evaluator", required=True)
ev.add_argument("--log", help="write the evaluator's full stdout/stderr here")
ev.set_defaults(fn=cmd_evaluate)
fz = sub.add_parser("freeze", help="freeze a plan: record its state and a random cell order")
fz.add_argument("plan")
fz.add_argument("--order-seed", type=int)
fz.set_defaults(fn=cmd_freeze)
jn = sub.add_parser("journal", help="record an observation during a frozen experiment")
jn.add_argument("plan")
jn.add_argument("text")
jn.add_argument("--run")
jn.set_defaults(fn=cmd_journal)
rp = sub.add_parser("report", help="aggregate run records")
rp.add_argument("paths", nargs="+")
rp.add_argument("--json", action="store_true")
rp.set_defaults(fn=lambda a: report.print_report(a.paths, a.json))
sm = sub.add_parser("summary", help="shareable summary: PASS/FAIL matrix, per-cell metrics, aggregates by language and agent")
sm.add_argument("paths", nargs="+")
sm.set_defaults(fn=lambda a: print(report.summary(a.paths)))
pf = sub.add_parser("profile", help="per-run cost profile: termination, output tokens, solution size, diagnostic codes")
pf.add_argument("paths", nargs="+")
pf.set_defaults(fn=lambda a: print(report.profile(a.paths)))
cp = sub.add_parser("checkpoint", help="per-run rows for the M checkpoint and P6A-9: results, cost, docs by group, diagnostic buckets, program size; n/a where a record lacks a field")
cp.add_argument("paths", nargs="+")
cp.add_argument("--json", action="store_true")
cp.set_defaults(fn=lambda a: print(report.checkpoint(a.paths, a.json)))
c = sub.add_parser("classify", help="record the primary failure category of a run (protocol §27)")
c.add_argument("run")
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)")
v.add_argument("--json", action="store_true")
v.set_defaults(fn=lambda a: print(report.vsr_table(a.paths, set(a.tasks.split(",")) if a.tasks else None, a.json)))
cs = sub.add_parser("costs", help="B1 §5: cost proxies per agent × language (totals over all runs per accepted run; per-run medians)")
cs.add_argument("paths", nargs="+")
cs.add_argument("--tasks", help="comma-separated task ids to include")
cs.add_argument("--json", action="store_true")
cs.set_defaults(fn=lambda a: print(report.cost_proxies(a.paths, set(a.tasks.split(",")) if a.tasks else None, a.json)))
a = p.parse_args(argv)
a.fn(a)
if __name__ == "__main__":
main()