"""Harness self-tests: sandbox isolation, path confinement, budgets, the complete run record (protocol §28) and resumable matrices. cd tools/eval && python3 -m unittest discover tests Requires zig-out/bin/aji (`zig build`) and the Rust and Zig toolchains; sandbox tests are skipped where bubblewrap cannot create namespaces. """ import json import os import shutil import subprocess 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 agent, languages, record, report, sandbox, util # noqa: E402 TASK = os.path.join(util.REPO, "docs", "evaluation", "dev-tasks", "dev-echo") EVALUATOR = [os.path.join(TASK, "evaluator.py")] def bwrap_works(): if shutil.which("bwrap") is None: return False return subprocess.run(["bwrap", "--unshare-all", "--ro-bind", "/", "/", "true"], capture_output=True).returncode == 0 SANDBOX = "bwrap" if bwrap_works() else "none" class SandboxTest(unittest.TestCase): @unittest.skipUnless(SANDBOX == "bwrap", "bubblewrap unavailable") def test_isolation(self): ws = tempfile.mkdtemp() sb = sandbox.Sandbox("bwrap", ws, [], [], docs=[("", TASK), ("prompt.md", os.path.join(TASK, "prompt.md"))]) code, out, _ = sb.run("echo hi > f && cat f", 30, 1000) self.assertEqual((code, out.strip()), (0, "hi")) code, out, _ = sb.run("getent hosts example.com || echo NO_NET", 30, 1000) self.assertIn("NO_NET", out) code, _, _ = sb.run("touch /docs/x", 30, 1000) self.assertNotEqual(code, 0) code, out, _ = sb.run("cat /docs/prompt.md/../task.json >/dev/null 2>&1; head -c 6 /docs/prompt.md", 30, 1000) self.assertIn("# Task", out) code, out, _ = sb.run("ls " + os.path.expanduser("~") + " 2>&1 || echo NO_HOME", 30, 1000) self.assertIn("NO_HOME", out) self.assertTrue(os.path.exists(os.path.join(ws, "f"))) def test_output_limit_and_timeout(self): sb = sandbox.Sandbox(SANDBOX, tempfile.mkdtemp(), [], []) code, out, truncated = sb.run("yes | head -c 5000", 30, 100) self.assertTrue(truncated) self.assertLess(len(out), 200) code, _, _ = sb.run("sleep 5", 1, 100) self.assertIsNone(code) class PathTest(unittest.TestCase): def test_confinement(self): ws = tempfile.mkdtemp() a = agent.Agent(None, {"instructions": ""}, None, {}, None, ws, [], None, {"tool_calls": 1, "total_tokens": 1, "output_chars": 100}) for bad in ["/etc/passwd", "../x", "/work/../etc/passwd", "/docs/x"]: with self.assertRaises(agent.ToolError): a.host_path(bad) with self.assertRaises(agent.ToolError): a.host_path("/docs", write=True) self.assertEqual(a.host_path("a/b")[0], os.path.join(os.path.realpath(ws), "a", "b")) class RunTest(unittest.TestCase): def setUp(self): self.out = tempfile.mkdtemp() def run_lang(self, lang, **kw): return record.run_one(TASK, lang, "scripted", os.path.join(HERE, "scripts", lang + ".json"), self.out, model_class="test", sandbox_kind=SANDBOX, evaluator=EVALUATOR, **kw) def test_all_languages_complete_record(self): for lang in languages.available(): with self.subTest(lang=lang): run_dir, rec = self.run_lang(lang) self.assertTrue(rec["accepted"], rec["verdict"]) self.assertEqual(rec["metrics"]["termination"], "finished") for key in ["task", "evaluator", "language", "model", "scaffold", "system_prompt_hash", "task_prompt_hash", "limits", "hardware", "seed", "metrics", "final_repository", "verdict", "cost_usd"]: self.assertIn(key, rec) self.assertTrue(rec["evaluator"]["hash"].startswith("sha256:")) m = rec["metrics"] self.assertEqual(m["patches"], 2) self.assertEqual(m["failed_verifier_cycles"], 1) self.assertFalse(m["first_check_accepted"] or m["first_build_accepted"]) self.assertTrue(m["first_public_test_passed"]) self.assertFalse(m["first_hidden_test_passed"]) # the snapshot holds the broken file kinds = [json.loads(l)["event"] for l in open(os.path.join(run_dir, "events.jsonl"))] for k in ["start", "model", "tool", "patch", "command"]: self.assertIn(k, kinds) rows = report.aggregate(report.load([self.out])) self.assertEqual(len(rows), len(languages.available())) self.assertTrue(all(r["verified_success_rate"] == 1.0 for r in rows)) @unittest.skipUnless(SANDBOX == "bwrap", "bubblewrap unavailable") def test_source_docs_metrics(self): # The Source Reference Bundle is a directory: reading is measured per file and per group. _, rec = self.run_lang("aji_source") self.assertTrue(rec["accepted"], rec["verdict"]) d = rec["metrics"]["context"]["docs"] self.assertEqual(d["files_opened"], ["QUICK.md"]) self.assertEqual(d["unique_docs_read"], 1) self.assertGreater(d["coverage_by_section"]["QUICK.md"], 0.9) self.assertEqual(d["coverage_by_section"]["air/reference.md"], 0.0) for g in ("quick_reference_tokens", "source_docs_tokens", "air_docs_tokens", "full_source_docs_tokens"): self.assertGreater(d[g], 0) self.assertEqual(d["full_source_docs_tokens"], d["quick_reference_tokens"] + d["source_docs_tokens"]) self.assertEqual(d["read_tokens_by_group"]["air_docs"], 0) def test_tool_budget(self): _, rec = self.run_lang("aji_air", limits={"tool_calls": 3}) self.assertEqual(rec["metrics"]["termination"], "budget_tool_calls") self.assertFalse(rec["accepted"]) def test_cost(self): pricing = {os.path.join(HERE, "scripts", "zig.json"): {"input": 1.0, "output": 10.0}} _, rec = self.run_lang("zig", pricing=pricing) m = rec["metrics"] self.assertAlmostEqual(rec["cost_usd"], (m["input_tokens"] + 10 * m["output_tokens"]) / 1e6, places=6) class FreezeTest(unittest.TestCase): @unittest.skipIf((util.git_commit() or "+dirty").endswith("+dirty"), "repository has uncommitted changes") def test_freeze_order_and_check(self): from ajieval import freeze d = tempfile.mkdtemp() plan = {"tasks": [TASK], "languages": ["rust", "zig"], "runs": 2, "sandbox": SANDBOX, "evaluator": EVALUATOR[0], "models": [{"provider": "scripted", "model": os.path.join(HERE, "scripts", "rust.json"), "class": "test"}]} path = os.path.join(d, "plan.json") util.write_json(path, plan) _, frozen = freeze.write(path, order_seed=7) self.assertEqual(len(frozen["order"]), 4) self.assertEqual(freeze.check(path)["order"], frozen["order"]) plan["runs"] = 3 util.write_json(path, plan) with self.assertRaises(SystemExit): freeze.check(path) class MatrixTest(unittest.TestCase): def test_resume(self): d = tempfile.mkdtemp() plan = {"tasks": [TASK], "languages": ["rust"], "runs": 1, "sandbox": SANDBOX, "evaluator": EVALUATOR[0], "models": [{"provider": "scripted", "model": os.path.join(HERE, "scripts", "rust.json"), "class": "test"}]} path = os.path.join(d, "plan.json") util.write_json(path, plan) for _ in range(2): subprocess.run([sys.executable, "-m", "ajieval", "matrix", path], cwd=os.path.dirname(HERE), check=True, capture_output=True) self.assertEqual(len(report.load([os.path.join(d, "runs")])), 1) if __name__ == "__main__": unittest.main() class MockAPITest(unittest.TestCase): """The API providers against a local mock server: request translation (tools, extras, token parameter, auth from a key file) and the tool loop, without any external call.""" def serve(self, reply_fn): import http.server import threading seen = [] class H(http.server.BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["content-length"]))) seen.append({"path": self.path, "headers": {k.lower(): v for k, v in self.headers.items()}, "body": body}) data = json.dumps(reply_fn(len(seen), body)).encode() self.send_response(200) self.send_header("content-type", "application/json") self.send_header("content-length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *a): pass srv = http.server.HTTPServer(("127.0.0.1", 0), H) threading.Thread(target=srv.serve_forever, daemon=True).start() self.addCleanup(srv.shutdown) return f"http://127.0.0.1:{srv.server_address[1]}", seen def key_file(self): f = tempfile.NamedTemporaryFile("w", delete=False, suffix=".key") f.write("test-secret-123\n") f.close() return f.name def test_openai_compatible(self): steps = [("write_file", {"path": "src/main.rs", "content": open(os.path.join(HERE, "scripts", "rust.json")).read() and json.load(open(os.path.join(HERE, "scripts", "rust.json")))[4][0]["input"]["content"]}), ("run", {"command": "sh test.sh"}), ("finish", {})] def reply(n, body): name, args = steps[min(n, len(steps)) - 1] return {"model": "mock", "usage": {"prompt_tokens": 100, "completion_tokens": 10, "prompt_tokens_details": {"cached_tokens": 40}}, "choices": [{"finish_reason": "tool_calls", "message": {"role": "assistant", "content": None, "tool_calls": [{"id": f"c{n}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}]}}]} url, seen = self.serve(reply) out = tempfile.mkdtemp() _, rec = record.run_one(TASK, "rust", "openai", "mock-model", out, sandbox_kind=SANDBOX, evaluator=EVALUATOR, base_url=url + "/v1", provider_options={"extra": {"reasoning_effort": "medium"}, "key_file": self.key_file()}) self.assertTrue(rec["accepted"], rec["verdict"]) self.assertEqual(rec["metrics"]["cached_input_tokens"], 120) first = seen[0] self.assertEqual(first["path"], "/v1/chat/completions") self.assertEqual(first["headers"]["authorization"], "Bearer test-secret-123") self.assertEqual(first["body"]["reasoning_effort"], "medium") self.assertIn("max_tokens", first["body"]) self.assertEqual({t["function"]["name"] for t in first["body"]["tools"]}, {"list_files", "read_file", "write_file", "edit_file", "run", "finish"}) self.assertEqual(seen[1]["body"]["messages"][-1]["role"], "tool") self.assertNotIn("test-secret-123", json.dumps(rec)) def test_anthropic(self): def reply(n, body): blocks = [{"type": "tool_use", "id": f"t{n}", "name": "list_files", "input": {}}] if n == 1 else [{"type": "tool_use", "id": f"t{n}", "name": "finish", "input": {}}] return {"model": "mock", "stop_reason": "tool_use", "content": blocks, "usage": {"input_tokens": 50, "output_tokens": 5, "cache_read_input_tokens": 20}} url, seen = self.serve(reply) _, rec = record.run_one(TASK, "zig", "anthropic", "mock-model", tempfile.mkdtemp(), sandbox_kind=SANDBOX, base_url=url, provider_options={"key_file": self.key_file(), "extra": {"thinking": {"type": "enabled", "budget_tokens": 1024}}}) self.assertEqual(rec["metrics"]["termination"], "finished") self.assertEqual(seen[0]["path"], "/v1/messages") self.assertEqual(seen[0]["headers"]["x-api-key"], "test-secret-123") self.assertEqual(seen[0]["body"]["thinking"]["budget_tokens"], 1024) self.assertEqual(seen[1]["body"]["messages"][-1]["content"][0]["type"], "tool_result") self.assertEqual(rec["metrics"]["input_tokens"], 140) class NativeTest(unittest.TestCase): """Track B adapters without starting a CLI: configuration and usage normalization.""" def test_configs_disable_extras(self): from ajieval import native home = tempfile.mkdtemp() cfg = native.AGENTS["codex"].configure(home, "m", "high")[".codex/config.toml"] self.assertIn('web_search = "disabled"', cfg) self.assertIn("multi_agent = false", cfg) self.assertIn("network_access = false", cfg) argv = native.AGENTS["claude"].argv("m", "high", "PROMPT") self.assertEqual(argv[argv.index("--tools") + 1:argv.index("--tools") + 5], ["Bash", "Read", "Edit", "Write"]) self.assertIn("--strict-mcp-config", argv) oc = native.AGENTS["opencode"].configure(home, "p/m", None)[".config/opencode/opencode.json"] self.assertFalse(oc["tools"]["webfetch"] or oc["tools"]["task"]) def test_gobang_adapter(self): """gobang: configuration by model id, the key only in the environment, and the facts and toolchain commands of its journal.""" from ajieval import context, native g = native.AGENTS["gobang"] home = tempfile.mkdtemp() cfg = g.configure(home, "glm-5.3-flash", "high")[".config/gobang/gobang.toml"] self.assertIn('provider = "openai"', cfg) self.assertIn('key_env = "ZAI_API_KEY"', cfg) self.assertIn('mode = "required"', cfg) self.assertIn('docs = "/docs"', cfg) self.assertIn('reasoning_effort = "high"', cfg) self.assertIn('key_env = "ANTHROPIC_API_KEY"', g.configure(home, "claude-opus-5-5", None)[".config/gobang/gobang.toml"]) scenario = os.path.join(home, "s.jsonl") open(scenario, "w").write("{}\n") self.assertIn('provider = "fixture"', g.configure(home, "fixture:" + scenario, None)[".config/gobang/gobang.toml"]) self.assertTrue(os.path.exists(os.path.join(home, ".config", "gobang", "scenario.jsonl"))) self.assertEqual(g.env("fixture:" + scenario), {}) old = os.environ.pop("ZAI_API_KEY", None) try: with self.assertRaises(SystemExit): g.env("glm-5.3-flash") os.environ["ZAI_API_KEY"] = "zk-test" self.assertEqual(g.env("glm-5.3-flash"), {"ZAI_API_KEY": "zk-test"}) self.assertNotIn("zk-test", json.dumps(g.configure(home, "glm-5.3-flash", None))) finally: os.environ.pop("ZAI_API_KEY", None) if old is not None: os.environ["ZAI_API_KEY"] = old argv = g.argv("m", None, "PROMPT") self.assertEqual(argv[:3], ["gobang", "run", "--json-events"]) self.assertEqual(argv[-2:], ["--task", "PROMPT"]) self.assertFalse(g.netless_shell) def ev(seq, t, data): return json.dumps({"v": 1, "session": "g", "seq": seq, "ts": "", "state": "S", "type": t, "data": data}) # gobang writes compact JSON, as aji does. check_rejected = json.dumps({"ok": True, "outcome": "rejected", "groups": [{"code": "E3101", "severity": "error"}]}, separators=(",", ":")) lines = [ ev(1, "SESSION_CREATED", {"prompt_sha256": "sha256:p"}), ev(2, "CONFIG_RESOLVED", {"test_command_argv": ["sh test.sh"]}), ev(3, "MODEL_RESPONDED", {"response": {"model_reported": "glm-5.3-flash", "finish_reason": "tool_use", "usage": {"input": 1000, "output": 50, "cache_read": 600}}}), ev(4, "TOOL_REQUESTED", {"call_id": "c1", "tool": "aji_check", "arguments": "{}"}), ev(5, "TOOL_COMPLETED", {"call_id": "c1", "tool": "aji_check", "output": check_rejected}), ev(6, "TOOL_REQUESTED", {"call_id": "c2", "tool": "docs_read", "arguments": "{\"section\":\"QUICK.md#1-skeleton\"}"}), ev(7, "TOOL_COMPLETED", {"call_id": "c2", "tool": "docs_read", "output": json.dumps({"ok": True, "text": "3\tEvery function lists its effects.\n"})}), ev(8, "TOOL_REQUESTED", {"call_id": "c3", "tool": "run_tests", "arguments": "{}"}), ev(9, "TOOL_COMPLETED", {"call_id": "c3", "tool": "run_tests", "output": json.dumps({"ok": True, "passed": 0, "failed": 1, "errors": 0})}), ev(10, "MODEL_RESPONDED", {"response": {"finish_reason": "stop", "usage": {"input": 1200, "output": 10, "cache_read": 1000}}}), ev(11, "SESSION_FINISHED", {"state": "FAILED", "reason": "verification_failed"}), ] tr = os.path.join(home, "transcript.jsonl") open(tr, "w").write("\n".join(lines) + "\n") facts = g.parse(tr) self.assertEqual(facts["tool_calls"], 3) self.assertEqual(facts["model"], "glm-5.3-flash") self.assertEqual(facts["gobang_state"], "FAILED") self.assertEqual(native.normalize_usage(facts["usage"]), {"input": 2200, "output": 60, "cached_input": 1600}) cmds = native.command_events("gobang", tr) self.assertEqual([(c, code) for c, code, _ in cmds], [("aji check", 1), ("aji run; sh test.sh", 1)]) prof = {"diagnostic_pattern": '"severity":"error"', "classify": {"check": ["aji check"], "test": ["aji run"]}} m = native.cycles(prof, "sh test.sh", cmds) self.assertEqual((m["first_check_accepted"], m["first_public_test_passed"], m["failed_verifier_cycles"], m["failed_test_cycles"]), (False, False, 1, 1)) events = context.tool_events_native("gobang", tr) self.assertIn(("/docs/QUICK.md", "3\tEvery function lists its effects.\n"), events) def test_usage_normalization(self): from ajieval import native self.assertEqual(native.normalize_usage({"input_tokens": 100, "cached_input_tokens": 60, "output_tokens": 5}), {"input": 100, "output": 5, "cached_input": 60}) self.assertEqual(native.normalize_usage({"input_tokens": 10, "cache_read_input_tokens": 60, "cache_creation_input_tokens": 30, "output_tokens": 5}), {"input": 100, "output": 5, "cached_input": 60}) self.assertEqual(native.normalize_usage({"input": 40, "cache_read": 60, "cache_creation": 0, "output": 5})["input"], 100) class CheckpointTest(unittest.TestCase): def test_diagnostic_buckets(self): b = report._diagnostic_buckets({"E0001": 2, "E0006": 1, "E5001": 3, "E5002": 1, "E1001": 4, "E7005": 2, "E7003": 1, "E2001": 1, "E2101": 2, "E2104": 1, "E3002": 1, "E4304": 1, "T0001": 1, "E3101": 5}) self.assertEqual(b["E0001-E0006"], 3) self.assertEqual(b["ir_form_total"], 7) self.assertEqual((b["E1001"], b["E7005"], b["other_E7xxx"]), (4, 2, 1)) self.assertEqual((b["ownership"], b["borrow"], b["resource"], b["concurrency"], b["runtime_traps"]), (1, 3, 1, 1, 1)) self.assertEqual(b["other"], 5) # effects and capabilities are not dropped class DocsReadTest(unittest.TestCase): def test_files_opened_by_relative_path(self): from ajieval import context with tempfile.TemporaryDirectory() as d: os.makedirs(os.path.join(d, "language")) for rel in ("QUICK.md", "language/syntax.md", "language/types.md", "language/memory.md"): with open(os.path.join(d, rel), "w") as f: f.write(f"only in {rel}\n") events = [('{"command": "cat /docs/QUICK.md"}', "only in QUICK.md"), ('{"command": "cd /docs/language && cat syntax.md"}', "only in language/syntax.md"), ('{"command": "cat language/types.md"}', "only in language/types.md"), ('{"command": "cat mysyntax.md types.mdx"}', "")] seen = {o for _, o in events if o} m = context.doc_metrics(events, [("", d)], {}, seen, len) self.assertEqual(m["files_opened"], ["QUICK.md", "language/syntax.md", "language/types.md"]) self.assertEqual(m["coverage_by_section"]["language/memory.md"], 0.0) class StatusTest(unittest.TestCase): def test_agent_and_evaluation_status(self): from ajieval import native with tempfile.TemporaryDirectory() as d: tr, err = os.path.join(d, "t.jsonl"), os.path.join(d, "e.log") def write(t, e=""): open(tr, "w").write(t) open(err, "w").write(e) write('{"part":{"reason":"tool-calls"}}\n{"part":{"reason":"length"}}\n') self.assertEqual(native.agent_status("exited", tr, err), "max_tokens") write('{"stop_reason":"max_tokens"}\n{"stop_reason":"end_turn"}\n') self.assertEqual(native.agent_status("exited", tr, err), "exited") write('{"part":{"reason":"stop"}}\n', "Error: 429 Too Many Requests: usage limit reached") self.assertEqual(native.agent_status("error_exit", tr, err), "provider_rate_limited") self.assertEqual(native.agent_status("exited", tr, err), "exited") self.assertEqual(native.evaluation_status(None), "not_evaluated") self.assertEqual(native.evaluation_status({"accepted": True, "gates": {}}), "accepted") self.assertEqual(native.evaluation_status({"accepted": False, "gates": {"builds": False}, "error": "build_failed"}), "rejected") self.assertEqual(native.evaluation_status({"accepted": False, "error": "evaluator timed out"}), "evaluator_error") self.assertEqual(native.evaluation_status({"accepted": False, "infrastructure": True}), "infrastructure_failure") class GrepReadTest(unittest.TestCase): def test_grep_output_counts_as_read(self): from ajieval import context with tempfile.TemporaryDirectory() as d: os.makedirs(os.path.join(d, "language")) with open(os.path.join(d, "language", "syntax.md"), "w") as f: f.write("alpha rule one\nbeta rule two\n") events = [('{"command": "grep -rn rule /docs/language"}', "/docs/language/syntax.md:1:alpha rule one\n/docs/language/syntax.md-2-beta rule two"), ('{"pattern": "x", "path": "/docs"}', "language/syntax.md:alpha rule one")] seen = {context._norm(l) for _, o in events for l in o.splitlines() if context._norm(l)} m = context.doc_metrics(events, [("", d)], {}, seen, len) self.assertEqual(m["coverage_by_section"]["language/syntax.md"], 1.0) # Ordinary text with a colon is left alone. self.assertEqual(context._norm("Note: keep this"), "Note: keep this") self.assertEqual(context._norm(" 12→text"), "text") class CyclesTest(unittest.TestCase): def test_repair_cycles_from_commands(self): from ajieval import native prof = languages.load("aji_air") cmds = [("cat README.md", 0, "x"), ("aji check main.air", 1, '{"code":"E0001","severity":"error"}'), ("aji check main.air && sh test.sh", 1, "FAIL: unexpected"), ("aji check main.air && sh test.sh", 0, "PASS")] m = native.cycles(prof, "sh test.sh", cmds) self.assertEqual((m["toolchain_invocations"], m["failed_verifier_cycles"], m["failed_test_cycles"]), (3, 1, 1)) self.assertFalse(m["first_check_accepted"]) self.assertFalse(m["first_public_test_passed"])