"""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()