E-N0: native-agent mode (Track B) and the native dev-echo gate
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.
This commit is contained in:
1 parent
2c1fdf1cc6
commit
00cbb65447
8 files changed
+521
-17
No files matched your search
@@ -140,6 +140,59 @@ For the smoke test it also records the cause, decided before any language change
|
||||
- `model_capability`
|
||||
- `task_ambiguity`
|
||||
|
||||
## Track B: native agents
|
||||
|
||||
```sh
|
||||
python3 -m ajieval native --task DIR --language aji_air --agent codex --model gpt-6.1-sol --effort high --label N1 \
|
||||
--evaluator CMD --out runs/
|
||||
```
|
||||
|
||||
In Track B the agent product is the scaffold: Codex, Claude Code or OpenCode runs with its own prompt, tools and context management (protocol §39b). The harness only:
|
||||
|
||||
- copies the pristine workspace;
|
||||
- starts the CLI with the shared task message (the same preamble as Track A plus the task);
|
||||
- collects the repository;
|
||||
- runs the same evaluator.
|
||||
|
||||
These runs are never evidence for H4.
|
||||
|
||||
**Isolation.** bubblewrap with a shared network, because the CLI must reach its model backend. The sandbox contains:
|
||||
|
||||
- `/work` (read-write), `/docs` (read-only), the language toolchain and the CLI (read-only);
|
||||
- a fresh `HOME` holding only the CLI's credential file and a minimal configuration written by the harness.
|
||||
|
||||
User-level skills, MCP servers, memory, custom agents, plugins and global instructions therefore do not exist. Neither the evaluator nor the Aji repository is visible.
|
||||
|
||||
Per agent:
|
||||
|
||||
| Agent | Configuration | Shell network |
|
||||
|---|---|---|
|
||||
| `codex` | `codex exec --json`; `approval_policy=never`; web search off; product features off (multi-agent, apps, browser, computer use, plugins, skills, goals, hooks…) | off (Codex `workspace-write` sandbox) |
|
||||
| `claude` | `claude -p --output-format stream-json`; tools limited to `Bash`, `Read`, `Edit` and `Write`; `--strict-mcp-config`; slash commands off | on |
|
||||
| `opencode` | `opencode run --pure --format json`; no MCP; `webfetch`, `websearch` and `task` off | on |
|
||||
|
||||
**Record (`aji-eval-native/1`).** The run directory holds:
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `run.json` | the record below |
|
||||
| `transcript.jsonl` | the CLI's JSON event stream |
|
||||
| `stderr.log` | the CLI's error output |
|
||||
| `patch.diff` | the diff from the initial to the final workspace |
|
||||
| `initial/`, `workspace/` | the pristine and the final repository |
|
||||
|
||||
`run.json` holds:
|
||||
|
||||
- the CLI version and path;
|
||||
- the requested model and the model from the transcript, where the CLI reports it;
|
||||
- the effort setting and the account mode (subscription or API key; only the source is recorded, never a credential);
|
||||
- the written configuration and the command line;
|
||||
- start and end time;
|
||||
- tool calls and token usage as reported by the CLI, normalized to input, output and cached input;
|
||||
- the evaluator verdict.
|
||||
|
||||
A first-generation snapshot is not available in Track B.
|
||||
|
||||
## Smoke test (E-S)
|
||||
|
||||
[`smoke-plan.example.json`](smoke-plan.example.json) is the shape of the 36-run plan (owner decision):
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"comment": "E-N native-agent smoke, Track B (protocol §39b): 2 tasks x 3 languages x 3 native agents x 1 run = 18 runs on subscriptions. Never evidence for H4. Run from tools/eval: python3 -m ajieval matrix plan.json. Model ids are the exact ids the CLIs accept, recorded per run.",
|
||||
"tasks": ["../aji-bench/tasks/<segmented-telemetry-decoder>", "../aji-bench/tasks/<bounded-fanout-aggregator>"],
|
||||
"languages": ["aji_air", "rust", "zig"],
|
||||
"models": [
|
||||
{"label": "N1", "agent": "codex", "model": "gpt-6.1-sol", "effort": "high"},
|
||||
{"label": "N2", "agent": "claude", "model": "claude-opus-5-5", "effort": "high"},
|
||||
{"label": "N3", "agent": "opencode", "model": "zai-coding-plan/glm-5.3-flash"}
|
||||
],
|
||||
"runs": 1,
|
||||
"evaluator": "../aji-bench/evaluate",
|
||||
"evaluator_hash_path": "../aji-bench/evaluators",
|
||||
"out": "runs-native-smoke"
|
||||
}
|
||||
@@ -1578,7 +1578,7 @@ Track B — native agent language × coding-agent product (each model in it
|
||||
tests the practical economics of development
|
||||
```
|
||||
|
||||
Track B measures model + system prompt + context management + tool policy + compaction + agent heuristics together, so its results are never used as evidence for H4. A first Track B run follows the smoke test: 2 tasks × 3 languages × 3 native agents × 1 run = 18 runs.
|
||||
Track B measures model + system prompt + context management + tool policy + compaction + agent heuristics together, so its results are never used as evidence for H4. Order (owner decision): the first experiment is Track B on existing subscriptions — a native dev-echo gate, then 2 tasks × 3 languages × 3 native agents × 1 run = 18 runs — and its analysis decides whether the controlled 36-run Track A (direct APIs, one scaffold) is bought next. Track B agents run with model, filesystem, shell, compiler, tests, documentation and the task statement only: web and search tools, MCP, skills, custom agents, subagents, external memory and global instructions are disabled where the product allows. Track B results never label models by capability; they describe how Aji behaves on three different agent stacks.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-1
@@ -99,7 +99,8 @@ Evaluation runs alongside the phases; each stage starts when the language featur
|
||||
| E-C | todo | Model calibration: models labelled M1–M3 run 5–10 neutral coding tasks unrelated to Aji in `tools/eval`; classes assigned from scores; live `dev-echo` per model (protocol §2, §39a) | E0-3 | calibration report; model IDs, endpoints and reasoning modes frozen |
|
||||
| E-G | todo | Smoke gates: Rust, Zig and hand-written Aji references pass the frozen evaluators; task-statement and hidden-test review (protocol §39a) | E0-2, E0-4 | all gates pass |
|
||||
| E-S | todo | Engineering smoke test, Track A: 2 families (binary/stream parser, concurrent bounded pipeline) × 3 languages × 3 models (M1–M3) × 2 runs = 36 runs on one Aji commit (protocol §39a); plan shape `docs/evaluation/smoke-plan.example.json`; failures classified by cause after the matrix, before any language change | E-C, E-G | harness, bundle sufficiency, accounting and traces verified |
|
||||
| E-N | todo | Track B native-agent run: 2 tasks × 3 languages × 3 native agents × 1 run = 18 runs (protocol §39b); never evidence for H4 | E-S | native-agent report: cost and outcome per agent product |
|
||||
| E-N0 | done | Native dev-echo gate (Aji/AIR): Codex + `gpt-6.1-sol` (effort high), Claude Code + `claude-opus-5-5` (effort high), OpenCode + `zai-coding-plan/glm-5.3-flash` all accepted; versions and model IDs in the run records | E0-3 | `ajieval native` |
|
||||
| E-N | todo | Track B native smoke, first experiment (owner decision): 2 tasks × 3 languages × 3 native agents (N1–N3) × 1 run = 18 runs on subscriptions (protocol §39b); never evidence for H4; plan shape `docs/evaluation/native-smoke-plan.example.json` | E-N0, E0-2, E-G | native-agent report; failures classified before any language change |
|
||||
| E-A | todo | Stage A pilot (condition `Aji/AIR`): T01–T04 families × Aji/Rust/Zig × 3 model classes × 3 runs = 108 runs (protocol §39); not headline evidence | E-S, basic Phase 3 | pilot report: effect size, broken tasks, cost, instrumentation |
|
||||
| E-B | todo | Stage B: T05–T07 | Phase 3 | stage report |
|
||||
| E-C | todo | Stage C: T08, litmus repair | Phase 5 | stage report |
|
||||
|
||||
+37
-10
@@ -13,7 +13,7 @@ import os
|
||||
import shlex
|
||||
import sys
|
||||
|
||||
from . import languages, record, report, util
|
||||
from . import languages, native, record, report, util
|
||||
|
||||
CATEGORIES = ["SPEC_UNDERSTANDING", "SYNTAX", "TYPE", "OWNERSHIP", "BORROW", "RESOURCE", "BOUNDS", "FUNCTIONAL", "CONCURRENCY",
|
||||
"DEADLOCK", "ATOMIC_ORDERING", "PERFORMANCE", "BUDGET", "TIMEOUT", "AGENT_GAVE_UP", "TOOL_FAILURE"]
|
||||
@@ -37,6 +37,15 @@ def cmd_run(a):
|
||||
"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; finished runs (a run.json with the same
|
||||
task, language, model and seed) are skipped, so a plan can be resumed."""
|
||||
@@ -44,7 +53,7 @@ def cmd_matrix(a):
|
||||
base = os.path.dirname(os.path.abspath(a.plan))
|
||||
out = os.path.join(base, plan.get("out", "runs"))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
done = {(r["task"]["id"], r["language"]["name"], r["model"]["id"], r["seed"]) for r in report.load([out])}
|
||||
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)
|
||||
@@ -58,15 +67,20 @@ def cmd_matrix(a):
|
||||
for lang in plan["languages"]:
|
||||
for mdl in plan["models"]:
|
||||
for seed in range(plan.get("runs", 1)):
|
||||
if (tid, lang, mdl["model"], seed) in done:
|
||||
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
|
||||
if (tid, lang, key, seed) in done:
|
||||
continue
|
||||
print(f"run {tid} {lang} {mdl['model']} seed {seed}", file=sys.stderr)
|
||||
run_dir, rec = record.run_one(
|
||||
tpath, lang, mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=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})
|
||||
print(f"run {tid} {lang} {key} seed {seed}", file=sys.stderr)
|
||||
if mdl.get("agent"):
|
||||
run_dir, rec = native.run_native(tpath, lang, mdl["agent"], mdl["model"], out, effort=mdl.get("effort"), seed=seed,
|
||||
evaluator=evaluator, evaluator_hash_path=hash_path, label=mdl.get("label"), limits=plan.get("limits"))
|
||||
else:
|
||||
run_dir, rec = record.run_one(
|
||||
tpath, lang, mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=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})
|
||||
print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr)
|
||||
report.print_report([out])
|
||||
|
||||
@@ -104,6 +118,19 @@ def main(argv=None):
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,379 @@
|
||||
"""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;
|
||||
whether shell commands themselves have network depends on the CLI and is
|
||||
recorded (`command_network`).
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from . import __version__, agent, 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 = "allowed"
|
||||
|
||||
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)"
|
||||
|
||||
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"]
|
||||
command_network = "allowed (Claude Code does not restrict Bash network here)"
|
||||
|
||||
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"]
|
||||
command_network = "allowed (OpenCode does not restrict shell network)"
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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 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]
|
||||
|
||||
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 {})
|
||||
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) if evaluator else None
|
||||
|
||||
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, "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"], "failed_verifier_cycles": None, "failed_test_cycles": None,
|
||||
"first_check_accepted": None, "first_build_accepted": None},
|
||||
"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
|
||||
@@ -14,6 +14,8 @@ def load(paths):
|
||||
runs = []
|
||||
for p in paths:
|
||||
for f in [p] if p.endswith("run.json") else glob.glob(os.path.join(p, "**", "run.json"), recursive=True):
|
||||
if "/superseded/" in f:
|
||||
continue
|
||||
runs.append(util.read_json(f))
|
||||
return runs
|
||||
|
||||
@@ -26,7 +28,11 @@ def mean(xs):
|
||||
def aggregate(runs):
|
||||
cells = {}
|
||||
for r in runs:
|
||||
key = (r["task"]["id"], r["language"]["name"], r["model"].get("class") or "-", r["model"]["id"])
|
||||
if r.get("track") == "B":
|
||||
a = r["agent"]
|
||||
key = (r["task"]["id"], r["language"]["name"], "B:" + (a.get("label") or a["name"]), a["name"] + ":" + a["model"])
|
||||
else:
|
||||
key = (r["task"]["id"], r["language"]["name"], r["model"].get("class") or "-", r["model"]["id"])
|
||||
cells.setdefault(key, []).append(r)
|
||||
rows = []
|
||||
for (task, lang, cls, model), rs in sorted(cells.items()):
|
||||
@@ -37,11 +43,11 @@ def aggregate(runs):
|
||||
"task": task, "language": lang, "class": cls, "model": model,
|
||||
"runs": len(rs), "accepted": len(acc),
|
||||
"verified_success_rate": round(len(acc) / len(rs), 3),
|
||||
"repair_cycles_accepted": mean([r["metrics"]["failed_verifier_cycles"] + r["metrics"]["failed_test_cycles"] for r in acc]),
|
||||
"context_tokens_mean": mean([r["metrics"]["input_tokens"] for r in rs]),
|
||||
"output_tokens_mean": mean([r["metrics"]["output_tokens"] for r in rs]),
|
||||
"repair_cycles_accepted": mean([r["metrics"]["failed_verifier_cycles"] + r["metrics"]["failed_test_cycles"] for r in acc if r["metrics"].get("failed_verifier_cycles") is not None]),
|
||||
"context_tokens_mean": mean([r["metrics"].get("input_tokens") for r in rs]),
|
||||
"output_tokens_mean": mean([r["metrics"].get("output_tokens") for r in rs]),
|
||||
"tool_calls_mean": mean([r["metrics"]["tool_calls"] for r in rs]),
|
||||
"first_check_accepted": sum(1 for r in rs if r["metrics"]["first_check_accepted"] or r["metrics"]["first_build_accepted"]),
|
||||
"first_check_accepted": sum(1 for r in rs if r["metrics"].get("first_check_accepted") or r["metrics"].get("first_build_accepted")),
|
||||
"cost_total_usd": total_cost,
|
||||
"cost_per_correct_usd": None if total_cost is None or not acc else round(total_cost / len(acc), 4),
|
||||
"unclassified_failures": sum(1 for r in rs if r.get("accepted") is False and not r.get("classification")),
|
||||
|
||||
@@ -205,3 +205,27 @@ class MockAPITest(unittest.TestCase):
|
||||
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)
|
||||
Reference in new issue
Block a user