E0-3: language-neutral agent scaffold and run recorder

tools/eval (stdlib Python): one agent loop, system prompt and tool set
(list/read/write/edit files, run, finish) for every language; language
profiles for aji_air, rust, zig carry only toolchain invocation, docs
location and command classification; bubblewrap sandbox without
network, read-only toolchain and /docs; providers: Anthropic Messages,
OpenAI-compatible (incl. local servers), scripted; run record per
protocol §28 (hashes, versions, limits, hardware, seed, all events,
patches, commands, final repository, first-generation snapshot,
evaluator verdicts, cost); metrics §14-§17; resumable matrix plans;
report (VSR, repair cycles, context, cost per correct solution);
classify (§27 categories, caught-by, smoke-test causes).

docs/evaluation/harness.md (task format for the private benchmark
repository, evaluator contract, record schema); dev-tasks/dev-echo
(harness development task, no benchmark family); smoke plan shape for
the owner's E-S choice (binary/stream parser, bounded pipeline);
self-tests in CI
This commit is contained in:
dev committed 2026-10-04 17:17:43 +03:00
1 parent d2932bd75a
commit b49003bdb9
38 files changed
+1735 -5

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
"""Language-neutral agent scaffold and run recorder for the Aji evaluation
protocol (docs/evaluation/protocol.md §3–§5, §13–§17, §27–§29).
One run = one model + one language + one task + one fresh workspace + one
fresh agent context. The same loop, tools and system prompt drive every
language; only the language profile (toolchain invocation, local docs)
differs, and it carries no solution hints.
Integrity (protocol §29): hidden tests and evaluators are never part of this
repository. A task directory and an evaluator command are given at run time;
the evaluator runs outside the agent's sandbox and only its hash and verdict
are recorded.
"""
__version__ = "0.1.0"
+3
View File
@@ -0,0 +1,3 @@
from .cli import main
main()
+256
View File
@@ -0,0 +1,256 @@
"""The agent loop and its tools (protocol §5): one loop for every language.
Tools: list_files, read_file, write_file, edit_file, run, finish. Paths are
`/work/...` (the repository, writable) or `/docs/...` (local documentation,
read-only); relative paths are under /work.
The model ending its turn without a tool call ends the run (`model_end`);
the scaffold does not nudge, so stopping early is part of what is measured.
"""
import difflib
import json
import os
import shutil
import time
from . import languages, util
TOOLS = [
{"name": "list_files", "description": "List files under a directory (default /work), recursively.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": []}},
{"name": "read_file", "description": "Read a text file. Optional 1-based `offset` line and `limit` lines.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}}, "required": ["path"]}},
{"name": "write_file", "description": "Create or overwrite a file under /work.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
{"name": "edit_file", "description": "Replace the single exact occurrence of `old` with `new` in a file under /work.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"}}, "required": ["path", "old", "new"]}},
{"name": "run", "description": "Run a shell command in /work (no network). Returns the exit code and combined output.",
"parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
{"name": "finish", "description": "End the task when your solution is complete.",
"parameters": {"type": "object", "properties": {"summary": {"type": "string"}}, "required": []}},
]
SYSTEM = """You are a software engineer working alone in a fresh repository at /work.
Implement the task described in the first message, in the language named below.
Tools: list, read, write and edit files; run shell commands in /work (no network access); finish.
Local documentation is under /docs (read-only). Nothing else is available.
Work until the public tests described in the task pass, then call `finish`. Hidden tests will also check
your solution against the stated requirements, so implement the requirements, not just the public tests.
Limits: at most {tool_calls} tool calls and {total_tokens} total tokens.
{language}"""
class ToolError(Exception):
pass
class Agent:
def __init__(self, provider, profile, task, lang, sandbox, workspace, docs, recorder, limits):
self.provider, self.profile, self.task, self.lang = provider, profile, task, lang
self.sandbox, self.workspace, self.docs, self.rec, self.limits = sandbox, workspace, docs, recorder, limits
self.system = SYSTEM.format(language=profile["instructions"], **limits)
self.m = {
"model_calls": 0, "tool_calls": 0, "input_tokens": 0, "output_tokens": 0, "cached_input_tokens": 0,
"patches": 0, "files_opened": [], "repository_bytes_read": 0, "documentation_bytes_read": 0,
"commands": 0, "check_runs": 0, "build_runs": 0, "test_runs": 0,
"failed_verifier_cycles": 0, "failed_test_cycles": 0,
"first_check_accepted": None, "first_build_accepted": None, "first_public_test_passed": None,
}
self.first_snapshot = None
# ---------------------------------------------------------------- paths
def host_path(self, path, write=False):
p = path or "/work"
if not p.startswith("/"):
p = "/work/" + p
p = os.path.normpath(p)
if p == "/work" or p.startswith("/work/"):
base, rel, kind = self.workspace, p[len("/work"):].lstrip("/"), "repository"
elif p == "/docs" or p.startswith("/docs/"):
if write:
raise ToolError("/docs is read-only")
if not self.docs:
raise ToolError("no documentation is mounted")
rel = p[len("/docs"):].lstrip("/")
if os.path.isfile(self.docs):
if rel not in ("", os.path.basename(self.docs)):
raise ToolError(f"no such file: {p}")
return self.docs, "documentation"
base, kind = self.docs, "documentation"
else:
raise ToolError("paths must be under /work or /docs")
full = os.path.realpath(os.path.join(base, rel))
if full != os.path.realpath(base) and not full.startswith(os.path.realpath(base) + os.sep):
raise ToolError("path escapes its root")
return full, kind
# ---------------------------------------------------------------- tools
def tool_list_files(self, inp):
full, kind = self.host_path(inp.get("path"))
if os.path.isfile(full):
return os.path.basename(full)
root_virtual = "/docs" if kind == "documentation" else "/work"
base = self.docs if kind == "documentation" else self.workspace
out = []
for root, dirs, files in os.walk(full):
dirs[:] = sorted(d for d in dirs if d not in (".git", "target", "zig-cache", ".zig-cache", "zig-out"))
for name in sorted(files):
out.append(root_virtual + "/" + os.path.relpath(os.path.join(root, name), base))
if len(out) > 2000:
out.append("... (truncated)")
break
return "\n".join(out) or "(empty)"
def tool_read_file(self, inp):
full, kind = self.host_path(inp["path"])
if not os.path.isfile(full):
raise ToolError(f"no such file: {inp['path']}")
with open(full, encoding="utf-8", errors="replace") as f:
lines = f.read().split("\n")
start = max(int(inp.get("offset") or 1), 1) - 1
count = int(inp.get("limit") or len(lines))
text = "\n".join(lines[start:start + count])
if len(text) > self.limits["output_chars"] * 4:
text = text[: self.limits["output_chars"] * 4] + "\n... (truncated; use offset/limit)"
self.m[kind + "_bytes_read"] += len(text.encode())
if inp["path"] not in self.m["files_opened"]:
self.m["files_opened"].append(inp["path"])
return text
def _write(self, path, content, before):
full, _ = self.host_path(path, write=True)
os.makedirs(os.path.dirname(full), exist_ok=True)
with open(full, "w", encoding="utf-8") as f:
f.write(content)
rel = os.path.relpath(full, self.workspace)
diff = "".join(difflib.unified_diff((before or "").splitlines(True), content.splitlines(True), "a/" + rel, "b/" + rel))
self.m["patches"] += 1
self.rec.event("patch", path=rel, diff=diff)
return f"wrote {rel} ({len(content.encode())} bytes)"
def tool_write_file(self, inp):
full, _ = self.host_path(inp["path"], write=True)
before = None
if os.path.isfile(full):
with open(full, encoding="utf-8", errors="replace") as f:
before = f.read()
return self._write(inp["path"], inp["content"], before)
def tool_edit_file(self, inp):
full, _ = self.host_path(inp["path"], write=True)
if not os.path.isfile(full):
raise ToolError(f"no such file: {inp['path']}")
with open(full, encoding="utf-8", errors="replace") as f:
before = f.read()
n = before.count(inp["old"])
if n != 1:
raise ToolError(f"`old` occurs {n} times; it must occur exactly once")
return self._write(inp["path"], before.replace(inp["old"], inp["new"], 1), before)
def tool_run(self, inp):
command = inp["command"]
kind = languages.classify(self.profile, command)
if kind is None and self.lang.get("test") and command.strip().startswith(self.lang["test"]):
kind = "test"
if kind and self.first_snapshot is None:
# First-generation state (protocol §14): before the first
# toolchain invocation, i.e. before any compiler-driven repair.
self.first_snapshot = self.rec.snapshot(self.workspace, "first_generation")
t0 = time.monotonic()
code, out, truncated = self.sandbox.run(command, self.limits["command_timeout"], self.limits["output_chars"])
self.m["commands"] += 1
ok = code == 0
if kind in ("check", "build"):
self.m[kind + "_runs"] += 1
key = "first_" + kind + "_accepted"
if self.m[key] is None:
self.m[key] = ok
if not ok:
self.m["failed_verifier_cycles"] += 1
elif kind == "test":
self.m["test_runs"] += 1
if self.m["first_public_test_passed"] is None:
self.m["first_public_test_passed"] = ok
if not ok:
self.m["failed_test_cycles"] += 1
self.rec.event("command", command=command, kind=kind, exit=code, seconds=round(time.monotonic() - t0, 3), output=out, truncated=truncated)
status = "timed out" if code is None else f"exit code {code}"
return f"[{status}]\n{out}"
# ---------------------------------------------------------------- loop
def run(self, task_prompt):
messages = [{"role": "user", "content": [{"type": "text", "text": task_prompt}]}]
t0 = time.monotonic()
reason = None
while reason is None:
if self.m["tool_calls"] >= self.limits["tool_calls"]:
reason = "budget_tool_calls"
break
if self.m["input_tokens"] + self.m["output_tokens"] >= self.limits["total_tokens"]:
reason = "budget_tokens"
break
if time.monotonic() - t0 >= self.limits["wall_seconds"]:
reason = "wall_time"
break
try:
reply = self.provider.complete(self.system, messages, TOOLS)
except Exception as e: # provider errors end the run and are recorded
self.rec.event("provider_error", error=f"{type(e).__name__}: {e}")
reason = "provider_error"
break
self.m["model_calls"] += 1
u = reply["usage"]
self.m["input_tokens"] += u["input"]
self.m["output_tokens"] += u["output"]
self.m["cached_input_tokens"] += u["cached_input"]
self.rec.event("model", model=reply.get("model"), stop=reply["stop"], usage=u, content=reply["content"])
messages.append({"role": "assistant", "content": reply["content"]})
calls = [b for b in reply["content"] if b["type"] == "tool_call"]
if not calls:
reason = "max_tokens" if reply["stop"] == "max_tokens" else "model_end"
break
results = []
for c in calls:
self.m["tool_calls"] += 1
if c["name"] == "finish":
reason = "finished"
self.rec.event("tool", name="finish", input=c["input"], output="", is_error=False)
results.append({"type": "tool_result", "id": c["id"], "output": "ok", "is_error": False})
continue
fn = getattr(self, "tool_" + c["name"], None)
try:
if fn is None:
raise ToolError(f"unknown tool {c['name']!r}")
out, err = fn(c["input"]), False
except ToolError as e:
out, err = str(e), True
except (KeyError, TypeError, ValueError) as e:
out, err = f"invalid arguments: {e}", True
self.rec.event("tool", name=c["name"], input=c["input"], output=out if c["name"] != "run" else None, is_error=err)
results.append({"type": "tool_result", "id": c["id"], "output": out, "is_error": err})
messages.append({"role": "user", "content": results})
self.m["elapsed_seconds"] = round(time.monotonic() - t0, 3)
self.m["termination"] = reason
return self.m
def initial_listing(workspace):
out = []
for root, dirs, files in os.walk(workspace):
dirs.sort()
for name in sorted(files):
out.append("/work/" + os.path.relpath(os.path.join(root, name), workspace))
return "\n".join(out) or "(empty)"
def task_message(task, workspace):
return task.prompt.rstrip() + "\n\nThe repository /work initially contains:\n" + initial_listing(workspace) + "\n"
def copy_workspace(src, dst):
shutil.copytree(src, dst, symlinks=False)
+123
View File
@@ -0,0 +1,123 @@
"""Command line: run, matrix, report, classify.
python3 -m ajieval run --task DIR --language aji_air --provider anthropic \\
--model claude-... --class frontier --out runs/ [--evaluator CMD ...]
python3 -m ajieval matrix PLAN.json
python3 -m ajieval report runs/ [--json]
python3 -m ajieval classify RUN_DIR CATEGORY [--caught-by verifier|runtime|test] [--note TEXT]
"""
import argparse
import json
import os
import shlex
import sys
from . import languages, 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"]
# Smoke-test causes (protocol §38): where a failure originates, before any
# language change is considered.
CAUSES = ["language", "documentation", "agent_bundle", "diagnostics", "harness", "model_capability", "task_ambiguity"]
def load_pricing(path):
return util.read_json(path) if path else None
def cmd_run(a):
run_dir, rec = record.run_one(
a.task, a.language, a.provider, a.model, a.out, model_class=a.model_class, seed=a.seed, sandbox_kind=a.sandbox,
evaluator=shlex.split(a.evaluator) if a.evaluator else None, evaluator_hash_path=a.evaluator_hash_path,
pricing=load_pricing(a.pricing), base_url=a.base_url, max_tokens=a.max_tokens, temperature=a.temperature)
m = rec["metrics"]
print(json.dumps({"run": run_dir, "termination": m["termination"], "accepted": rec["accepted"], "tool_calls": m["tool_calls"],
"input_tokens": m["input_tokens"], "output_tokens": m["output_tokens"], "cost_usd": rec["cost_usd"]}))
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."""
plan = util.read_json(a.plan)
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])}
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)
if evaluator:
evaluator[0] = rel(evaluator[0])
hash_path = rel(plan["evaluator_hash_path"]) if plan.get("evaluator_hash_path") else None
from . import task as task_mod
for tdir in plan["tasks"]:
tpath = os.path.join(base, tdir)
tid = task_mod.Task(tpath).id
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:
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"))
print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr)
report.print_report([out])
def cmd_classify(a):
path = os.path.join(a.run, "run.json")
rec = util.read_json(path)
rec["classification"] = {"category": a.category, "caught_by": a.caught_by, "cause": a.cause, "note": a.note}
util.write_json(path, rec)
print(json.dumps(rec["classification"]))
def main(argv=None):
p = argparse.ArgumentParser(prog="ajieval", description="Aji evaluation harness (protocol §5, §28)")
sub = p.add_subparsers(dest="cmd", required=True)
r = sub.add_parser("run", help="one run: one model, one language, one task, fresh workspace and context")
r.add_argument("--task", required=True)
r.add_argument("--language", required=True, choices=languages.available())
r.add_argument("--provider", required=True)
r.add_argument("--model", required=True)
r.add_argument("--class", dest="model_class")
r.add_argument("--seed", type=int, default=0)
r.add_argument("--out", default="runs")
r.add_argument("--sandbox", default="bwrap", choices=["bwrap", "none"])
r.add_argument("--evaluator", help="command run as: CMD WORKSPACE LANGUAGE TASK_DIR; prints a JSON verdict")
r.add_argument("--evaluator-hash-path", help="file or directory hashed into the record (default: the evaluator executable)")
r.add_argument("--pricing", help="JSON: model -> {input, output, cached_input} USD per million tokens")
r.add_argument("--base-url")
r.add_argument("--max-tokens", type=int, default=8192)
r.add_argument("--temperature", type=float)
r.set_defaults(fn=cmd_run)
m = sub.add_parser("matrix", help="run every cell of a plan file (resumable)")
m.add_argument("plan")
m.set_defaults(fn=cmd_matrix)
rp = sub.add_parser("report", help="aggregate run records")
rp.add_argument("paths", nargs="+")
rp.add_argument("--json", action="store_true")
rp.set_defaults(fn=lambda a: report.print_report(a.paths, a.json))
c = sub.add_parser("classify", help="record the primary failure category of a run (protocol §27)")
c.add_argument("run")
c.add_argument("category", choices=CATEGORIES)
c.add_argument("--caught-by", choices=["verifier", "runtime", "test"])
c.add_argument("--cause", choices=CAUSES)
c.add_argument("--note")
c.set_defaults(fn=cmd_classify)
a = p.parse_args(argv)
a.fn(a)
if __name__ == "__main__":
main()
+104
View File
@@ -0,0 +1,104 @@
"""Language profiles (tools/eval/languages/*.json).
A profile says how to invoke a toolchain and where its pinned local
documentation is. It MUST NOT contain solution hints (protocol §5).
Fields:
name language id used in task directories and records
display human name
toolchain {"binaries": [...], "version": [argv, ...], "bind": [paths]}
binaries are resolved on the host and bound read-only into
the sandbox; "version" commands are recorded (§28)
docs {"env": VAR, "default": path}: directory or file mounted at
/docs (read-only)
instructions text appended to the shared system prompt
classify {"check": [prefix, ...], "build": [...], "test": [...]}:
command prefixes counted as verifier/compiler and test runs
for the repair metrics (§14, §15)
"""
import glob
import os
import shutil
import subprocess
from . import util
HERE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "languages")
def available():
return sorted(os.path.splitext(os.path.basename(p))[0] for p in glob.glob(os.path.join(HERE, "*.json")))
def load(name):
path = os.path.join(HERE, name + ".json")
if not os.path.exists(path):
raise SystemExit(f"unknown language profile {name!r}; available: {', '.join(available())}")
prof = util.read_json(path)
prof["profile_hash"] = util.sha256_path(path)
return prof
def expand(s):
return os.path.expandvars(os.path.expanduser(s.replace("${REPO}", util.REPO)))
def resolve_binaries(prof):
"""Host paths of the toolchain binaries and the directories to bind."""
found, binds = {}, set()
cmd = prof["toolchain"].get("bind_command")
if cmd:
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode != 0 or not os.path.isdir(r.stdout.strip()):
raise SystemExit(f"{prof['name']}: {' '.join(cmd)} did not print a directory")
binds.add(os.path.realpath(r.stdout.strip()))
for b in prof["toolchain"].get("binaries", []):
path = shutil.which(expand(b)) if os.sep not in b else expand(b)
if path is None or not os.path.exists(path):
raise SystemExit(f"{prof['name']}: toolchain binary {b!r} not found")
real = os.path.realpath(path)
found[os.path.basename(b)] = real
binds.add(os.path.dirname(real))
for extra in prof["toolchain"].get("bind", []):
for p in glob.glob(expand(extra)):
binds.add(os.path.realpath(p))
# A rustc sysroot or a zig installation is self-contained: bind the
# directory above `bin` so libraries and the standard library resolve.
out = set()
for d in binds:
out.add(os.path.dirname(d) if os.path.basename(d) == "bin" else d)
return found, sorted(out)
def sandbox_path(binds):
"""PATH inside the sandbox: `<dir>/bin` where it exists, else `<dir>`."""
return [os.path.join(d, "bin") if os.path.isdir(os.path.join(d, "bin")) else d for d in binds]
def versions(prof, env=None):
out = []
for argv in prof["toolchain"].get("version", []):
try:
r = subprocess.run([expand(a) for a in argv], capture_output=True, text=True, timeout=60, env=env)
out.append({"argv": argv, "output": (r.stdout + r.stderr).strip()})
except OSError as e:
out.append({"argv": argv, "error": str(e)})
return out
def docs_path(prof):
d = prof.get("docs") or {}
path = os.environ.get(d.get("env", ""), "") or d.get("default", "")
path = expand(path) if path else ""
return path if path and os.path.exists(path) else None
def classify(prof, command):
"""'check', 'build', 'test' or None for a shell command line."""
c = command.strip()
for kind in ("test", "check", "build"):
for prefix in prof.get("classify", {}).get(kind, []):
if c == prefix or c.startswith(prefix + " "):
return kind
return None
+209
View File
@@ -0,0 +1,209 @@
"""Model providers behind one interface.
reply = provider.complete(system, messages, tools)
`messages` and the reply use one neutral shape:
{"role": "user"|"assistant", "content": [block, ...]}
block: {"type": "text", "text": ...}
| {"type": "tool_call", "id": ..., "name": ..., "input": {...}}
| {"type": "tool_result", "id": ..., "output": ..., "is_error": bool}
The reply adds "usage": {"input": n, "output": n, "cached_input": n} and
"stop": "tool_use"|"end"|"max_tokens".
anthropic Anthropic Messages API (ANTHROPIC_API_KEY)
openai OpenAI-compatible chat completions (OPENAI_API_KEY, base URL);
also local servers (vLLM, llama.cpp, Ollama) via --base-url
scripted replays a JSON list of assistant turns (harness tests)
"""
import json
import os
import time
import urllib.error
import urllib.request
class ProviderError(Exception):
pass
def _post(url, headers, body, timeout, retries=4):
data = json.dumps(body).encode()
for attempt in range(retries + 1):
req = urllib.request.Request(url, data=data, headers={"content-type": "application/json", **headers})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
except urllib.error.HTTPError as e:
detail = e.read().decode(errors="replace")[:500]
if e.code in (429, 500, 502, 503, 529) and attempt < retries:
time.sleep(2 ** attempt * 5)
continue
raise ProviderError(f"HTTP {e.code}: {detail}")
except (urllib.error.URLError, TimeoutError) as e:
if attempt < retries:
time.sleep(2 ** attempt * 5)
continue
raise ProviderError(str(e))
class Anthropic:
name = "anthropic"
def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=600):
self.model, self.max_tokens, self.temperature, self.timeout = model, max_tokens, temperature, timeout
self.url = (base_url or "https://api.anthropic.com") + "/v1/messages"
self.key = os.environ.get("ANTHROPIC_API_KEY")
if not self.key:
raise SystemExit("ANTHROPIC_API_KEY is not set")
def params(self):
return {"max_tokens": self.max_tokens, "temperature": self.temperature}
def complete(self, system, messages, tools):
msgs = []
for m in messages:
blocks = []
for b in m["content"]:
if b["type"] == "text":
blocks.append({"type": "text", "text": b["text"]})
elif b["type"] == "tool_call":
blocks.append({"type": "tool_use", "id": b["id"], "name": b["name"], "input": b["input"]})
elif b["type"] == "tool_result":
blocks.append({"type": "tool_result", "tool_use_id": b["id"], "content": b["output"], "is_error": b["is_error"]})
msgs.append({"role": m["role"], "content": blocks})
body = {
"model": self.model,
"max_tokens": self.max_tokens,
"system": [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}],
"messages": msgs,
"tools": [{"name": t["name"], "description": t["description"], "input_schema": t["parameters"]} for t in tools],
}
if self.temperature is not None:
body["temperature"] = self.temperature
r = _post(self.url, {"x-api-key": self.key, "anthropic-version": "2023-06-01"}, body, self.timeout)
content = []
for b in r.get("content", []):
if b["type"] == "text":
content.append({"type": "text", "text": b["text"]})
elif b["type"] == "tool_use":
content.append({"type": "tool_call", "id": b["id"], "name": b["name"], "input": b["input"]})
u = r.get("usage", {})
stop = {"tool_use": "tool_use", "max_tokens": "max_tokens"}.get(r.get("stop_reason"), "end")
return {
"role": "assistant",
"content": content,
"stop": stop,
"model": r.get("model", self.model),
"usage": {
"input": u.get("input_tokens", 0) + u.get("cache_read_input_tokens", 0) + u.get("cache_creation_input_tokens", 0),
"output": u.get("output_tokens", 0),
"cached_input": u.get("cache_read_input_tokens", 0),
},
}
class OpenAICompatible:
name = "openai"
def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=600):
self.model, self.max_tokens, self.temperature, self.timeout = model, max_tokens, temperature, timeout
self.url = (base_url or "https://api.openai.com/v1").rstrip("/") + "/chat/completions"
self.key = os.environ.get("OPENAI_API_KEY", "")
def params(self):
return {"max_tokens": self.max_tokens, "temperature": self.temperature}
def complete(self, system, messages, tools):
msgs = [{"role": "system", "content": system}]
for m in messages:
texts = [b["text"] for b in m["content"] if b["type"] == "text"]
calls = [b for b in m["content"] if b["type"] == "tool_call"]
results = [b for b in m["content"] if b["type"] == "tool_result"]
if m["role"] == "assistant":
msg = {"role": "assistant", "content": "\n".join(texts) or None}
if calls:
msg["tool_calls"] = [{"id": c["id"], "type": "function", "function": {"name": c["name"], "arguments": json.dumps(c["input"])}} for c in calls]
msgs.append(msg)
else:
for r in results:
msgs.append({"role": "tool", "tool_call_id": r["id"], "content": r["output"]})
if texts:
msgs.append({"role": "user", "content": "\n".join(texts)})
body = {
"model": self.model,
"max_tokens": self.max_tokens,
"messages": msgs,
"tools": [{"type": "function", "function": {"name": t["name"], "description": t["description"], "parameters": t["parameters"]}} for t in tools],
}
if self.temperature is not None:
body["temperature"] = self.temperature
headers = {"authorization": f"Bearer {self.key}"} if self.key else {}
r = _post(self.url, headers, body, self.timeout)
choice = r["choices"][0]
msg = choice["message"]
content = []
if msg.get("content"):
content.append({"type": "text", "text": msg["content"]})
for c in msg.get("tool_calls") or []:
try:
args = json.loads(c["function"]["arguments"] or "{}")
except json.JSONDecodeError:
args = {"_unparsable_arguments": c["function"]["arguments"]}
content.append({"type": "tool_call", "id": c["id"], "name": c["function"]["name"], "input": args})
u = r.get("usage") or {}
details = u.get("prompt_tokens_details") or {}
stop = "tool_use" if msg.get("tool_calls") else ("max_tokens" if choice.get("finish_reason") == "length" else "end")
return {
"role": "assistant",
"content": content,
"stop": stop,
"model": r.get("model", self.model),
"usage": {"input": u.get("prompt_tokens", 0), "output": u.get("completion_tokens", 0), "cached_input": details.get("cached_tokens", 0)},
}
class Scripted:
"""Replays assistant turns from a JSON file: a list of lists of blocks
(`{"text": ...}` or `{"tool": name, "input": {...}}`). Usage is counted
as characters / 4 so accounting paths are exercised."""
name = "scripted"
def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=0):
self.model = model
with open(model) as f:
self.turns = json.load(f)
self.i = 0
def params(self):
return {}
def complete(self, system, messages, tools):
if self.i >= len(self.turns):
return {"role": "assistant", "content": [{"type": "text", "text": "done"}], "stop": "end", "model": "scripted", "usage": {"input": 0, "output": 0, "cached_input": 0}}
turn = self.turns[self.i]
self.i += 1
content = []
for n, b in enumerate(turn):
if "tool" in b:
content.append({"type": "tool_call", "id": f"call_{self.i}_{n}", "name": b["tool"], "input": b["input"]})
else:
content.append({"type": "text", "text": b["text"]})
prompt_chars = len(system) + len(json.dumps(messages))
return {
"role": "assistant",
"content": content,
"stop": "tool_use" if any(b["type"] == "tool_call" for b in content) else "end",
"model": "scripted",
"usage": {"input": prompt_chars // 4, "output": len(json.dumps(turn)) // 4, "cached_input": 0},
}
PROVIDERS = {"anthropic": Anthropic, "openai": OpenAICompatible, "scripted": Scripted}
def make(name, model, **kw):
if name not in PROVIDERS:
raise SystemExit(f"unknown provider {name!r}; available: {', '.join(PROVIDERS)}")
return PROVIDERS[name](model, **kw)
+147
View File
@@ -0,0 +1,147 @@
"""Run recorder and the orchestration of one run (protocol §3, §28)."""
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import time
from . import __version__, agent, languages, providers, sandbox, task as task_mod, util
class Recorder:
def __init__(self, run_dir):
self.dir = run_dir
self.f = open(os.path.join(run_dir, "events.jsonl"), "w")
self.seq = 0
self.t0 = time.monotonic()
def event(self, kind, /, **fields):
self.seq += 1
self.f.write(json.dumps({"seq": self.seq, "t": round(time.monotonic() - self.t0, 3), "event": kind, **fields}) + "\n")
self.f.flush()
def snapshot(self, workspace, name):
dst = os.path.join(self.dir, name)
shutil.copytree(workspace, dst, ignore=shutil.ignore_patterns("target", ".zig-cache", "zig-cache", "zig-out"))
return dst
def close(self):
self.f.close()
def slug(s):
return re.sub(r"[^A-Za-z0-9._-]+", "-", s).strip("-")[:60]
def file_hashes(root):
out = {}
for r, dirs, files in os.walk(root):
dirs[:] = sorted(d for d in dirs if d not in ("target", ".zig-cache", "zig-cache", "zig-out"))
for name in sorted(files):
full = os.path.join(r, name)
out[os.path.relpath(full, root)] = util.sha256_path(full)
return out
def evaluate(evaluator, workspace, lang, task_dir, timeout):
"""Runs the (external, hidden) evaluator; returns its JSON verdict."""
try:
p = subprocess.run(evaluator + [workspace, lang, task_dir], capture_output=True, text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return {"accepted": False, "error": "evaluator timed out"}
try:
verdict = json.loads(p.stdout)
except json.JSONDecodeError:
return {"accepted": False, "error": f"evaluator printed no JSON (exit {p.returncode})", "stderr": p.stderr[-2000:]}
verdict["accepted"] = bool(verdict.get("accepted"))
return verdict
def cost(pricing, model, m):
"""Cost in USD from a pricing table (USD per million tokens), or None."""
price = (pricing or {}).get(model)
if not price:
return None
cached = m["cached_input_tokens"]
return round(((m["input_tokens"] - cached) * price["input"] + cached * price.get("cached_input", price["input"]) + m["output_tokens"] * price["output"]) / 1e6, 6)
def run_one(task_dir, lang_name, provider_name, model, out_dir, model_class=None, seed=0, sandbox_kind="bwrap",
evaluator=None, evaluator_hash_path=None, pricing=None, base_url=None, max_tokens=8192, temperature=None, limits=None):
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"{slug(task.id)}.{lang_name}.{slug(os.path.basename(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)
_, binds = languages.resolve_binaries(profile)
docs = languages.docs_path(profile)
docs_src = docs
if docs is None:
print(f"warning: no local documentation for {lang_name} (set {profile.get('docs', {}).get('env')}); protocol §4 requires pinned docs", file=sys.stderr)
if docs and os.path.isfile(docs):
# A single documentation file is staged into a directory so that
# /docs is a read-only mount as a whole.
staged = os.path.join(run_dir, "docs")
os.makedirs(staged)
shutil.copy(docs, staged)
docs = staged
sb = sandbox.Sandbox(sandbox_kind, workspace, binds, languages.sandbox_path(binds), docs, profile.get("env"))
kw = {"max_tokens": max_tokens, "temperature": temperature, "base_url": base_url}
prov = providers.make(provider_name, model, **kw)
rec = Recorder(run_dir)
a = agent.Agent(prov, profile, task, lang, sb, workspace, docs, rec, lim)
message = agent.task_message(task, workspace)
rec.event("start", system=a.system, task_message=message)
started = datetime.datetime.now(datetime.timezone.utc).isoformat()
metrics = a.run(message)
rec.close()
for key in ("files_opened",):
metrics[key + "_count"] = len(metrics[key])
metrics["documentation_tokens_estimate"] = util.estimate_tokens(metrics["documentation_bytes_read"])
metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"])
verdict = first_verdict = None
if evaluator:
verdict = evaluate(evaluator, workspace, lang_name, task.dir, lim["command_timeout"] * 4)
if a.first_snapshot:
first_verdict = evaluate(evaluator, a.first_snapshot, lang_name, task.dir, lim["command_timeout"] * 4)
metrics["first_hidden_test_passed"] = None if first_verdict is None else first_verdict["accepted"]
record = {
"schema": "aji-eval-run/1",
"run_id": run_id,
"started": started,
"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": docs_src, "docs_hash": util.sha256_path(docs) if docs else None},
"model": {"provider": provider_name, "id": model, "class": model_class, "params": prov.params(), "base_url": base_url},
"scaffold": {"version": __version__, "commit": util.git_commit(), "sandbox": sb.describe()},
"system_prompt_hash": util.sha256_text(a.system),
"task_prompt_hash": util.sha256_text(message),
"limits": lim,
"hardware": util.hardware(),
"seed": seed,
"metrics": metrics,
"cost_usd": cost(pricing, model, metrics),
"final_repository": {"path": "workspace", "files": file_hashes(workspace)},
"first_generation": None if not a.first_snapshot else "first_generation",
"verdict": verdict,
"first_generation_verdict": first_verdict,
"accepted": None if verdict is None else verdict["accepted"],
"classification": None,
}
util.write_json(os.path.join(run_dir, "run.json"), record)
return run_dir, record
+63
View File
@@ -0,0 +1,63 @@
"""Aggregates run records into the protocol's headline numbers (§13, §15,
§16, §17): Verified Success Rate, repair cycles to an accepted solution,
context consumed and expected cost per correct solution."""
import glob
import json
import os
import statistics
from . import util
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):
runs.append(util.read_json(f))
return runs
def mean(xs):
xs = [x for x in xs if x is not None]
return round(statistics.mean(xs), 2) if xs else None
def aggregate(runs):
cells = {}
for r in runs:
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()):
acc = [r for r in rs if r.get("accepted")]
costs = [r.get("cost_usd") for r in rs]
total_cost = None if any(c is None for c in costs) else round(sum(costs), 4)
rows.append({
"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]),
"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"]),
"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")),
"terminations": sorted({r["metrics"]["termination"] for r in rs}),
})
return rows
def markdown(rows):
head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "context tokens", "cost/correct USD", "unclassified failures"]
out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
for r in rows:
out.append("| " + " | ".join(str(x) for x in [r["task"], r["language"], r["class"], r["model"], r["runs"], r["accepted"], r["verified_success_rate"], r["repair_cycles_accepted"], r["context_tokens_mean"], r["cost_per_correct_usd"], r["unclassified_failures"]]) + " |")
return "\n".join(out)
def print_report(paths, as_json=False):
rows = aggregate(load(paths))
print(json.dumps(rows, indent=2) if as_json else markdown(rows))
+73
View File
@@ -0,0 +1,73 @@
"""Command execution for the agent's shell tool.
`bwrap` (bubblewrap): no network (protocol §4: no public internet), a
read-only system, the toolchain bound read-only, the workspace at /work
read-write, local documentation at /docs read-only, a fresh /tmp and HOME,
and a clean environment. `none` runs on the host and is for harness
development only; it is recorded in the run record.
"""
import os
import shutil
import subprocess
SYSTEM_RO = ["/usr", "/etc"]
LINKS = [("usr/lib", "/lib"), ("usr/lib64", "/lib64"), ("usr/bin", "/bin"), ("usr/sbin", "/sbin")]
class Sandbox:
def __init__(self, kind, workspace, toolchain_binds, path_dirs, docs=None, env=None):
if kind == "bwrap" and shutil.which("bwrap") is None:
raise SystemExit("sandbox bwrap requested but bubblewrap is not installed")
self.kind = kind
self.workspace = os.path.realpath(workspace)
self.binds = toolchain_binds
self.path = ":".join(path_dirs + ["/usr/bin", "/bin"])
self.docs = os.path.realpath(docs) if docs else None
self.env = dict(env or {})
def describe(self):
return {"kind": self.kind, "network": self.kind != "bwrap", "toolchain_binds": self.binds, "docs": self.docs}
def argv(self, command):
if self.kind == "none":
return ["sh", "-c", command]
a = ["bwrap", "--unshare-all", "--die-with-parent", "--new-session"]
for d in SYSTEM_RO:
if os.path.exists(d):
a += ["--ro-bind", d, d]
for src, dst in LINKS:
if os.path.exists("/" + src):
a += ["--symlink", src, dst]
a += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp"]
for d in self.binds:
a += ["--ro-bind", d, d]
if self.docs:
target = "/docs" if os.path.isdir(self.docs) else "/docs/" + os.path.basename(self.docs)
a += ["--ro-bind", self.docs, target]
a += ["--bind", self.workspace, "/work", "--chdir", "/work", "--clearenv"]
env = {"PATH": self.path, "HOME": "/tmp", "TMPDIR": "/tmp", "LANG": "C.UTF-8"}
env.update(self.env)
for k, v in sorted(env.items()):
a += ["--setenv", k, v]
return a + ["sh", "-c", command]
def run(self, command, timeout, output_limit):
"""Runs `command`; returns (exit code or None on timeout, output, truncated)."""
env = None
cwd = self.workspace
if self.kind == "none":
env = {"PATH": self.path + ":" + os.environ.get("PATH", ""), "HOME": os.environ.get("HOME", "/tmp"), "LANG": "C.UTF-8"}
env.update(self.env)
try:
p = subprocess.run(self.argv(command), cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout)
code = p.returncode
out = p.stdout
except subprocess.TimeoutExpired as e:
code, out = None, (e.stdout or b"")
text = out.decode("utf-8", errors="replace")
truncated = len(text) > output_limit
if truncated:
half = output_limit // 2
text = text[:half] + f"\n... [{len(text) - output_limit} characters omitted] ...\n" + text[-half:]
return code, text, truncated
+45
View File
@@ -0,0 +1,45 @@
"""Benchmark task directories (provided at run time; hidden material never
lives in the public repository).
<task>/task.json
id, version, set ("dev" | "validation" | "test"), family,
prompt language-neutral statement (file, relative)
languages {lang: {"workspace": dir, "test": command}}
`workspace` is copied fresh into every run; `test` is
the public test command, counted as a test run
limits tool_calls, total_tokens, wall_seconds,
command_timeout, output_chars (defaults below)
concurrency bool (schedule exploration gate, protocol §13)
"""
import os
from . import util
DEFAULT_LIMITS = {"tool_calls": 150, "total_tokens": 3_000_000, "wall_seconds": 3600, "command_timeout": 300, "output_chars": 20_000}
class Task:
def __init__(self, path):
self.dir = os.path.realpath(path)
spec = util.read_json(os.path.join(self.dir, "task.json"))
for key in ("id", "version", "prompt", "languages"):
if key not in spec:
raise SystemExit(f"{path}/task.json: missing {key!r}")
self.spec = spec
self.id = spec["id"]
self.version = str(spec["version"])
self.set = spec.get("set", "dev")
with open(os.path.join(self.dir, spec["prompt"]), encoding="utf-8") as f:
self.prompt = f.read()
self.limits = dict(DEFAULT_LIMITS, **spec.get("limits", {}))
def language(self, name):
if name not in self.spec["languages"]:
raise SystemExit(f"task {self.id} has no variant for language {name!r}")
lang = self.spec["languages"][name]
return {"workspace": os.path.join(self.dir, lang["workspace"]), "test": lang.get("test")}
def hash(self):
"""Hash of the public task material (statement and starter workspaces)."""
return util.sha256_path(self.dir)
+78
View File
@@ -0,0 +1,78 @@
"""Hashing, environment facts and small helpers shared by the harness."""
import hashlib
import json
import os
import platform
import subprocess
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
def sha256_bytes(data):
return "sha256:" + hashlib.sha256(data).hexdigest()
def sha256_text(text):
return sha256_bytes(text.encode("utf-8"))
def sha256_path(path):
"""Hash of a file, or of a directory tree (sorted relative paths and contents)."""
h = hashlib.sha256()
if os.path.isfile(path):
with open(path, "rb") as f:
h.update(f.read())
return "sha256:" + h.hexdigest()
for root, dirs, files in os.walk(path):
dirs[:] = sorted(d for d in dirs if d not in (".git", "__pycache__"))
for name in sorted(files):
full = os.path.join(root, name)
rel = os.path.relpath(full, path)
h.update(rel.encode() + b"\0")
with open(full, "rb") as f:
h.update(f.read())
h.update(b"\0")
return "sha256:" + h.hexdigest()
def git_commit(path=REPO):
"""`<commit>` or `<commit>+dirty` for the repository containing `path`."""
try:
rev = subprocess.run(["git", "-C", path, "rev-parse", "HEAD"], capture_output=True, text=True, check=True).stdout.strip()
dirty = subprocess.run(["git", "-C", path, "status", "--porcelain"], capture_output=True, text=True, check=True).stdout.strip()
return rev + ("+dirty" if dirty else "")
except (OSError, subprocess.CalledProcessError):
return None
def hardware():
info = {"machine": platform.machine(), "system": platform.system(), "release": platform.release(), "cpus": os.cpu_count()}
try:
with open("/proc/cpuinfo") as f:
for line in f:
if line.startswith("model name"):
info["cpu"] = line.split(":", 1)[1].strip()
break
with open("/proc/meminfo") as f:
info["mem_kb"] = int(f.readline().split()[1])
except OSError:
pass
return info
def write_json(path, obj):
with open(path, "w") as f:
json.dump(obj, f, indent=2, sort_keys=True)
f.write("\n")
def read_json(path):
with open(path) as f:
return json.load(f)
def estimate_tokens(nbytes):
"""Rough token estimate for byte counts the provider does not report
(documentation inspected); flagged as an estimate in records."""
return (nbytes + 3) // 4