Files
aji/tools/eval/ajieval/native.py
T
dev c2c238d9b1 M checkpoints recorded; harness statuses; memory test split; P6A-12
- results note docs/evaluation/results/2026-10-06-m-checkpoints.md:
  both checkpoints, owner's assessment (IR-tax closed at the engineering
  level, layer 7 GO; cost hypothesis open); plan status and order
- P6A-12: source type-check completeness (E1001 reached the verifier
  from a source run); not a layer 7 blocker
- harness: metrics.agent_status (max_tokens for a reply cut at its
  length limit, provider_rate_limited for 429/usage limits) and
  metrics.evaluation_status (accepted/rejected/evaluator_error/
  infrastructure_failure/not_evaluated), kept apart; termination records
  max_tokens; checkpoint rows show both; evaluator contract: an
  infrastructure failure sets "infrastructure": true
- interpreter memory test: fast form (20k-320k iterations, 256 KiB
  threshold via Options.collect_threshold) in zig build test; full form
  (100k/1M/4M) in zig build test-extended; CI job 'extended' also runs
  conformance with --collect-every-step
2026-10-05 17:43:55 +03:00

545 lines
25 KiB
Python

"""Track B: native coding agents (protocol §39b).
The agent product (Codex, Claude Code, OpenCode) is the scaffold: it brings
its own system prompt, tools, context management and compaction, so these
runs are never evidence for H4. The harness only prepares the workspace,
starts the CLI with one shared task message, collects the repository and
runs the same independent evaluator.
Isolation (bubblewrap): the network is shared, because the CLI must reach
its model backend; everything else is confined:
- the workspace at /work (read-write), documentation at /docs (read-only),
the language toolchain and the agent CLI read-only;
- a fresh HOME holding only the agent's credential file and a minimal
configuration written by the harness, so user-level skills, MCP
servers, memory, custom agents and global instructions do not exist;
- neither the evaluator nor the Aji repository is visible.
Web and search tools, MCP and subagents are disabled where the CLI allows.
Shell commands never have network. Codex runs them in its own
`workspace-write` sandbox. For Claude Code and OpenCode, `/usr/bin/bash`
and `/usr/bin/sh` inside the sandbox are wrappers that run every command
in a nested bubblewrap with a fresh, empty network namespace and no
resolver socket. The CLI process itself keeps the network to reach its
model backend, and every process a tool starts through a shell is
networkless.
"""
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import time
from . import __version__, agent, context, languages, record, task as task_mod, util
PREAMBLE = """You are working alone in a fresh repository at /work (the current directory).
Implement the task below in the language named here. Use only the files in /work, the local
documentation under /docs (read-only) and the toolchain installed on PATH. Do not use the web.
Work until the public tests described in the task pass. Hidden tests will also check your solution
against the stated requirements, so implement the requirements, not just the public tests.
{language}
---
"""
class NativeAgent:
"""One CLI: how to configure and start it, and where its credentials are."""
name = ""
binary = ""
# (host path relative to the real HOME, same path inside the sandbox HOME)
credentials = []
command_network = "disabled (networkless shell wrapper)"
# Whether the harness must make the shell networkless itself.
netless_shell = True
def version(self):
r = subprocess.run([self.binary, "--version"], capture_output=True, text=True, timeout=60)
return (r.stdout + r.stderr).strip()
def account_mode(self):
return None
def configure(self, home, model, effort):
"""Writes the agent's minimal configuration into the fresh HOME."""
return {}
def argv(self, model, effort, prompt):
raise NotImplementedError
def parse(self, transcript_path):
"""Best-effort facts from the CLI's JSON event stream."""
return {}
def _jsonl(path):
out = []
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if line.startswith("{"):
try:
out.append(json.loads(line))
except json.JSONDecodeError:
pass
return out
CODEX_FEATURES_OFF = ["multi_agent", "apps", "browser_use", "browser_use_external", "browser_use_full_cdp_access", "computer_use",
"image_generation", "plugins", "remote_plugin", "plugin_sharing", "skill_search", "skill_mcp_dependency_install",
"tool_suggest", "goals", "worktrees", "in_app_browser", "realtime_conversation", "hooks"]
class Codex(NativeAgent):
name = "codex"
binary = "codex"
credentials = [".codex/auth.json"]
command_network = "disabled (Codex workspace-write sandbox)"
netless_shell = False
def account_mode(self):
try:
return "codex auth_mode=" + str(util.read_json(os.path.expanduser("~/.codex/auth.json")).get("auth_mode"))
except (OSError, ValueError):
return None
def configure(self, home, model, effort):
cfg = "\n".join([
f'model = "{model}"',
f'model_reasoning_effort = "{effort}"' if effort else "",
'approval_policy = "never"',
'sandbox_mode = "workspace-write"',
'web_search = "disabled"',
"",
"[sandbox_workspace_write]",
"network_access = false",
"",
# Product features beyond model + shell + files are off for the smoke (protocol §39b).
"[features]",
] + [f"{feat} = false" for feat in CODEX_FEATURES_OFF] + [""])
os.makedirs(os.path.join(home, ".codex"), exist_ok=True)
with open(os.path.join(home, ".codex", "config.toml"), "w") as f:
f.write(cfg)
return {".codex/config.toml": cfg}
def argv(self, model, effort, prompt):
return [self.binary, "exec", "--json", "--skip-git-repo-check", "-m", model, "-s", "workspace-write", "-C", "/work", prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {}}
for e in _jsonl(path):
t = e.get("type", "")
item = e.get("item") or {}
if t == "item.completed" and item.get("type") in ("command_execution", "file_change", "mcp_tool_call", "web_search"):
facts["tool_calls"] += 1
if t == "turn.completed" and e.get("usage"):
for k, v in e["usage"].items():
if isinstance(v, int):
facts["usage"][k] = facts["usage"].get(k, 0) + v
if e.get("model"):
facts["model"] = e["model"]
return facts
class Claude(NativeAgent):
name = "claude"
binary = "claude"
credentials = [".claude/.credentials.json"]
def account_mode(self):
p = os.path.expanduser("~/.claude/.credentials.json")
return "claude.ai OAuth credentials (subscription)" if os.path.exists(p) else None
def configure(self, home, model, effort):
settings = {"permissions": {"deny": ["WebSearch", "WebFetch"]}, "enableAllProjectMcpServers": False}
os.makedirs(os.path.join(home, ".claude"), exist_ok=True)
util.write_json(os.path.join(home, ".claude", "settings.json"), settings)
# Marks onboarding as done so the non-interactive run does not stop.
util.write_json(os.path.join(home, ".claude.json"), {"hasCompletedOnboarding": True})
return {".claude/settings.json": settings}
def argv(self, model, effort, prompt):
a = [self.binary, "-p", "--output-format", "stream-json", "--verbose", "--model", model,
"--dangerously-skip-permissions", "--strict-mcp-config", "--disable-slash-commands",
"--tools", "Bash", "Read", "Edit", "Write"]
if effort:
a += ["--effort", effort]
return a + ["--", prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {}}
for e in _jsonl(path):
if e.get("type") == "assistant":
msg = e.get("message") or {}
if msg.get("model"):
facts["model"] = msg["model"]
facts["tool_calls"] += sum(1 for b in msg.get("content", []) if b.get("type") == "tool_use")
if e.get("type") == "result":
facts["usage"] = e.get("usage") or {}
facts["cost_usd_reported"] = e.get("total_cost_usd")
facts["num_turns"] = e.get("num_turns")
facts["result_subtype"] = e.get("subtype")
if e.get("type") == "system" and e.get("model"):
facts["model"] = e["model"]
return facts
class OpenCode(NativeAgent):
name = "opencode"
binary = "opencode"
credentials = [".local/share/opencode/auth.json"]
def account_mode(self):
return "opencode provider credential (see model id prefix, e.g. zai-coding-plan = Z.AI Coding Plan)"
def configure(self, home, model, effort):
cfg = {"$schema": "https://opencode.ai/config.json", "model": model, "autoupdate": False, "share": "disabled",
"mcp": {}, "permission": {"webfetch": "deny", "websearch": "deny", "edit": "allow", "bash": "allow"},
"tools": {"webfetch": False, "websearch": False, "task": False}}
d = os.path.join(home, ".config", "opencode")
os.makedirs(d, exist_ok=True)
util.write_json(os.path.join(d, "opencode.json"), cfg)
return {".config/opencode/opencode.json": cfg}
def argv(self, model, effort, prompt):
a = [self.binary, "run", "--pure", "--auto", "--format", "json", "-m", model, "--dir", "/work"]
if effort:
a += ["--variant", effort]
return a + [prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {}}
for e in _jsonl(path):
part = e.get("part") or {}
if e.get("type") == "tool_use" or part.get("type") == "tool":
facts["tool_calls"] += 1
tokens = part.get("tokens") if part.get("type") == "step-finish" else None
if isinstance(tokens, dict):
cache = tokens.get("cache") or {}
flat = {"input": tokens.get("input", 0), "output": tokens.get("output", 0) + tokens.get("reasoning", 0),
"cache_read": cache.get("read", 0), "cache_creation": cache.get("write", 0)}
for k, v in flat.items():
facts["usage"][k] = facts["usage"].get(k, 0) + (v or 0)
for key in ("modelID", "model"):
v = part.get(key) or (e.get("info") or {}).get(key)
if isinstance(v, str):
facts["model"] = v
return facts
AGENTS = {a.name: a for a in (Codex(), Claude(), OpenCode())}
def available():
return sorted(AGENTS)
NETLESS_WRAPPER = """#!/opt/aji-real/{shell}
# Runs the command in a nested namespace without network (Track B, protocol §39b).
if [ -n "$AJI_NETLESS" ]; then exec /opt/aji-real/{shell} "$@"; fi
exec /usr/bin/bwrap --unshare-net --dev-bind / / --tmpfs /run/systemd/resolve --setenv AJI_NETLESS 1 /opt/aji-real/{shell} "$@"
"""
def netless_binds(run_dir):
"""bwrap arguments that replace the system shells by networkless wrappers.
Symlinks such as /usr/bin/sh -> bash are followed, so each real shell
binary is wrapped once, at its real path."""
d = os.path.join(run_dir, "netless")
os.makedirs(d, exist_ok=True)
out = []
for real in sorted({os.path.realpath("/usr/bin/" + s) for s in ("bash", "sh")}):
shell = os.path.basename(real)
path = os.path.join(d, shell)
with open(path, "w") as f:
f.write(NETLESS_WRAPPER.format(shell=shell))
os.chmod(path, 0o755)
out += ["--ro-bind", real, "/opt/aji-real/" + shell, "--ro-bind", path, real]
return out + ["--setenv", "SHELL", "/usr/bin/bash", "--setenv", "OPENCODE_DISABLE_LSP_DOWNLOAD", "true"]
def sandbox_argv(workspace, home, binds, path_dirs, docs, env):
a = ["bwrap", "--unshare-all", "--share-net", "--die-with-parent", "--new-session"]
for d in ("/usr", "/etc"):
a += ["--ro-bind", d, d]
for src, dst in (("usr/lib", "/lib"), ("usr/lib64", "/lib64"), ("usr/bin", "/bin"), ("usr/sbin", "/sbin")):
if os.path.exists("/" + src):
a += ["--symlink", src, dst]
if os.path.isdir("/run/systemd/resolve"):
a += ["--ro-bind", "/run/systemd/resolve", "/run/systemd/resolve"]
a += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp"]
for d in binds:
a += ["--ro-bind", d, d]
if docs:
a += ["--tmpfs", "/docs"]
for name, p in docs:
a += ["--ro-bind", p, "/docs/" + name if name else "/docs"]
a += ["--remount-ro", "/docs"]
a += ["--bind", home, "/home/agent", "--bind", workspace, "/work", "--chdir", "/work", "--clearenv"]
base = {"PATH": ":".join(path_dirs + ["/usr/bin", "/bin"]), "HOME": "/home/agent", "TMPDIR": "/tmp", "LANG": "C.UTF-8", "TERM": "dumb"}
base.update(env)
for k, v in sorted(base.items()):
a += ["--setenv", k, v]
return a
def command_events(agent_name, transcript_path):
"""(command, exit code, output) for every shell command in a transcript."""
out = []
pending = {}
for line in open(transcript_path, encoding="utf-8", errors="replace"):
line = line.strip()
if not line.startswith("{"):
continue
try:
e = json.loads(line)
except json.JSONDecodeError:
continue
if agent_name == "codex":
item = e.get("item") or {}
if e.get("type") == "item.completed" and item.get("type") == "command_execution":
out.append((item.get("command") or "", item.get("exit_code"), item.get("aggregated_output") or ""))
elif agent_name == "claude":
msg = e.get("message") or {}
for b in msg.get("content", []) if isinstance(msg.get("content"), list) else []:
if b.get("type") == "tool_use" and b.get("name") == "Bash":
pending[b.get("id")] = (b.get("input") or {}).get("command", "")
elif b.get("type") == "tool_result" and b.get("tool_use_id") in pending:
c = b.get("content")
text = c if isinstance(c, str) else "\n".join(x.get("text", "") for x in (c or []) if isinstance(x, dict))
m = re.match(r"Exit code (\d+)", text)
code = int(m.group(1)) if m else (1 if b.get("is_error") else 0)
out.append((pending.pop(b.get("tool_use_id")), code, text))
elif agent_name == "opencode":
part = e.get("part") or {}
if e.get("type") == "tool_use" and part.get("tool") == "bash":
st = part.get("state") or {}
meta = st.get("metadata") or {}
out.append(((st.get("input") or {}).get("command", ""), meta.get("exit"), st.get("output") or meta.get("output") or ""))
return out
def cycles(profile, test_command, commands):
"""Repair-loop metrics (protocol §14, §15) derived from shell commands.
A command counts as a toolchain invocation if it contains a verifier,
compiler or test command of the language profile, or the task's public
test command. A failing invocation whose output carries a diagnostic of
the language is a failed verifier cycle; any other failing invocation
with a test is a failed test cycle."""
pat = re.compile(profile.get("diagnostic_pattern") or "$^")
cls = profile.get("classify", {})
checks = [p for k in ("check", "build") for p in cls.get(k, [])]
tests = list(cls.get("test", [])) + ([test_command] if test_command else [])
m = {"toolchain_invocations": 0, "failed_verifier_cycles": 0, "failed_test_cycles": 0,
"first_check_accepted": None, "first_public_test_passed": None}
for cmd, code, output in commands:
has_check = any(p in cmd for p in checks)
has_test = any(p in cmd for p in tests)
if not (has_check or has_test):
continue
m["toolchain_invocations"] += 1
diag = bool(pat.search(output or ""))
failed = code not in (0, None) or diag
if has_check and m["first_check_accepted"] is None:
m["first_check_accepted"] = not diag and code in (0, None)
if has_test and test_command and test_command in cmd and m["first_public_test_passed"] is None:
m["first_public_test_passed"] = not failed
if failed and diag:
m["failed_verifier_cycles"] += 1
elif failed and has_test:
m["failed_test_cycles"] += 1
return m
_FINISH = re.compile(r'"(?:finish_reason|stop_reason|finish|reason)"\s*:\s*"([a-z_]+)"')
_RATE_LIMIT = re.compile(r"\b429\b|rate[ _-]?limit|usage limit|too many requests", re.IGNORECASE)
def agent_status(termination, transcript_path, stderr_path):
"""How the agent's session ended, apart from what the evaluator says
about the repository (protocol §28):
finished / exited the CLI ended normally
max_tokens the last model reply stopped at its length
limit (finish_reason length / max_tokens)
provider_rate_limited the provider refused further requests (429,
usage limit); the CLI then exited with an error
error_exit, wall_time otherwise as recorded in `termination`
"""
def tail(path, n=200_000):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()[-n:]
except OSError:
return ""
t = tail(transcript_path)
reasons = _FINISH.findall(t)
if reasons and reasons[-1] in ("length", "max_tokens"):
return "max_tokens"
if termination == "error_exit" and _RATE_LIMIT.search(tail(stderr_path) + t[-20_000:]):
return "provider_rate_limited"
return termination
def evaluation_status(verdict):
"""accepted / rejected / evaluator_error / infrastructure_failure /
not_evaluated. An evaluator reports an infrastructure failure with
`"infrastructure": true` in its verdict (harness.md, evaluator contract)."""
if verdict is None:
return "not_evaluated"
if verdict.get("infrastructure"):
return "infrastructure_failure"
if verdict.get("accepted"):
return "accepted"
if "gates" not in verdict and verdict.get("error"):
return "evaluator_error"
return "rejected"
def normalize_usage(u):
"""Input (including cached), output and cached-input tokens from the
differently named usage fields of the CLIs; None when not reported."""
if not u:
return {"input": None, "output": None, "cached_input": None}
cached = sum(v for k, v in u.items() if isinstance(v, int) and ("cache_read" in k or k in ("cached_input_tokens", "cached")))
created = sum(v for k, v in u.items() if isinstance(v, int) and "cache_creation" in k)
plain = u.get("input_tokens", u.get("input", 0)) or 0
# Codex reports cached tokens as part of input_tokens; Claude reports them separately.
total_in = plain + (0 if "cached_input_tokens" in u else cached + created)
out = u.get("output_tokens", u.get("output", 0)) or 0
return {"input": total_in, "output": out, "cached_input": cached}
def diff_tree(before, after):
r = subprocess.run(["diff", "-ruN", "-x", "target", "-x", ".zig-cache", "-x", "zig-out", os.path.basename(before), os.path.basename(after)],
capture_output=True, text=True, cwd=os.path.dirname(before))
return r.stdout
def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, seed=0, evaluator=None, evaluator_hash_path=None, label=None, limits=None):
if shutil.which("bwrap") is None:
raise SystemExit("native runs need bubblewrap")
ag = AGENTS[agent_name]
task = task_mod.Task(task_dir)
profile = languages.load(lang_name)
lang = task.language(lang_name)
lim = dict(task.limits, **(limits or {}))
stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
run_id = f"{record.slug(task.id)}.{lang_name}.{agent_name}-{record.slug(model)}.s{seed}.{stamp}"
run_dir = os.path.join(out_dir, run_id)
os.makedirs(run_dir)
workspace = os.path.join(run_dir, "workspace")
agent.copy_workspace(lang["workspace"], workspace)
pristine = os.path.join(run_dir, "initial")
agent.copy_workspace(lang["workspace"], pristine)
home = os.path.join(run_dir, "home")
os.makedirs(home)
# Credentials: bound read-write at their usual place in the fresh HOME
# (token refresh writes them); nothing else from the real HOME exists.
cred_binds = []
for rel in ag.credentials:
src = os.path.join(os.path.expanduser("~"), rel)
if not os.path.exists(src):
raise SystemExit(f"{agent_name}: credential file ~/{rel} not found; log in with the CLI first")
dst = os.path.join(home, rel)
os.makedirs(os.path.dirname(dst), exist_ok=True)
open(dst, "a").close()
cred_binds.append((src, "/home/agent/" + rel))
config = ag.configure(home, model, effort)
_, binds = languages.resolve_binaries(profile)
cli = os.path.realpath(shutil.which(ag.binary) or "")
if not cli:
raise SystemExit(f"{agent_name}: CLI {ag.binary!r} not on PATH")
cli_dir = os.path.dirname(cli)
binds = sorted(set(binds) | {os.path.dirname(cli_dir) if os.path.basename(cli_dir) == "bin" else cli_dir})
path_dirs = languages.sandbox_path(binds)
docs = languages.docs_mounts(profile)
message = PREAMBLE.format(language=profile["instructions"]) + agent.task_message(task, workspace)
argv = ag.argv(model, effort, message)
sb = sandbox_argv(workspace, home, binds, path_dirs, docs, profile.get("env", {}))
for src, dst in cred_binds:
sb[sb.index("--chdir"):sb.index("--chdir")] = ["--bind", src, dst]
if ag.netless_shell:
# Binds go before --chdir; environment variables after --clearenv.
extra = netless_binds(run_dir)
triples = [extra[i:i + 3] for i in range(0, len(extra), 3)]
at = sb.index("--chdir")
for t in triples:
if t[0] == "--ro-bind":
sb[at:at] = t
at += 3
else:
sb += t
transcript = os.path.join(run_dir, "transcript.jsonl")
started = datetime.datetime.now(datetime.timezone.utc).isoformat()
t0 = time.monotonic()
with open(transcript, "w") as out, open(os.path.join(run_dir, "stderr.log"), "w") as err:
try:
p = subprocess.run(sb + argv, stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=lim["wall_seconds"])
code, termination = p.returncode, ("exited" if p.returncode == 0 else "error_exit")
except subprocess.TimeoutExpired:
code, termination = None, "wall_time"
elapsed = round(time.monotonic() - t0, 3)
ended = datetime.datetime.now(datetime.timezone.utc).isoformat()
facts = ag.parse(transcript)
tokens = normalize_usage(facts.get("usage") or {})
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens, profile.get("doc_groups"))
cyc = cycles(profile, lang.get("test"), command_events(agent_name, transcript))
with open(os.path.join(run_dir, "patch.diff"), "w") as f:
f.write(diff_tree(pristine, workspace))
verdict = record.evaluate(evaluator, workspace, lang_name, task.dir, lim["command_timeout"] * 4, os.path.join(run_dir, "evaluator.log")) if evaluator else None
status = agent_status(termination, transcript, os.path.join(run_dir, "stderr.log"))
if status == "max_tokens":
termination = "max_tokens"
rec = {
"schema": "aji-eval-native/1",
"track": "B",
"run_id": run_id,
"started": started,
"ended": ended,
"task": {"id": task.id, "version": task.version, "set": task.set, "family": task.spec.get("family"), "hash": task.hash(), "concurrency": bool(task.spec.get("concurrency"))},
"evaluator": None if not evaluator else {"command": evaluator, "hash": util.sha256_path(evaluator_hash_path or evaluator[0])},
"language": {"name": lang_name, "profile_hash": profile["profile_hash"], "toolchain": languages.versions(profile),
"docs": [{"mount": "/docs/" + n, "path": p, "hash": util.sha256_path_cached(p)} for n, p in docs]},
"agent": {"name": agent_name, "label": label, "cli_version": ag.version(), "cli_path": cli, "requested_model": model,
"model": facts.get("model") or model, "model_source": "transcript" if facts.get("model") else "requested",
"effort": effort, "account_mode": ag.account_mode(), "configuration": config,
"command_line": [a if a != message else "<task message>" for a in argv], "command_network": ag.command_network},
"scaffold": {"version": __version__, "commit": util.git_commit(), "isolation": "bwrap, shared network, fresh HOME"},
"task_prompt_hash": util.sha256_text(message),
"limits": lim,
"hardware": util.hardware(),
"seed": seed,
"metrics": {"elapsed_seconds": elapsed, "exit_code": code, "termination": termination,
"agent_status": status, "evaluation_status": evaluation_status(verdict), "tool_calls": facts.get("tool_calls"),
"usage": facts.get("usage"), "agent_facts": {k: v for k, v in facts.items() if k not in ("usage", "tool_calls", "model")},
"input_tokens": tokens["input"], "output_tokens": tokens["output"], "cached_input_tokens": tokens["cached_input"], "context": ctx,
"toolchain_invocations": cyc["toolchain_invocations"],
"failed_verifier_cycles": cyc["failed_verifier_cycles"], "failed_test_cycles": cyc["failed_test_cycles"],
"first_check_accepted": cyc["first_check_accepted"], "first_build_accepted": None,
"first_public_test_passed": cyc["first_public_test_passed"], "cycles_source": "derived from transcript"},
"transcript": "transcript.jsonl",
"patch": "patch.diff",
"final_repository": {"path": "workspace", "files": record.file_hashes(workspace)},
"verdict": verdict,
"accepted": None if verdict is None else verdict["accepted"],
"cost_usd": None,
"classification": None,
}
util.write_json(os.path.join(run_dir, "run.json"), rec)
return run_dir, rec