Files
aji/tools/eval/ajieval/record.py
T
dev b49003bdb9 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
2026-10-04 17:17:43 +03:00

148 lines
6.4 KiB
Python

"""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