ajieval native: Codex, Claude Code and OpenCode in bubblewrap with a shared network (backend only matters), a fresh HOME holding only the credential file and a harness-written minimal config (no user skills, MCP, memory, agents, plugins, global instructions), /work, read-only /docs and toolchain; evaluator and Aji repository invisible. Codex: workspace-write sandbox (shell without network), web search and product features off. Claude Code: tools Bash/Read/Edit/Write, strict MCP, slash commands off. OpenCode: pure, no MCP, webfetch/websearch/task off. Record aji-eval-native/1: CLI version, requested/transcript model, effort, account mode, config, command line, times, transcript, usage (normalized), patch, final repository, verdict. Gate on dev-echo (Aji/AIR) accepted for all three: codex 0.160.0 + gpt-6.1-sol (high), Claude Code 2.1.288 + claude-opus-5-5 (high), OpenCode 1.18.34 + zai-coding-plan/glm-5.3-flash. Protocol §39b and plan: Track B first (E-N0 done, E-N 18 runs), Track A after analysis.
232 lines
12 KiB
Python
232 lines
12 KiB
Python
"""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))
|
|
|
|
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 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_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)
|