From b49003bdb923c9534379d22e8dffb10cf30fd38e Mon Sep 17 00:00:00 2001 From: "A.Shakhmatov" Date: Sun, 4 Oct 2026 17:17:43 +0300 Subject: [PATCH] E0-3: language-neutral agent scaffold and run recorder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .github/workflows/ci.yml | 2 + .gitignore | 4 + CONTRIBUTING.md | 1 + docs/evaluation/README.md | 5 +- .../dev-tasks/dev-echo/evaluator.py | 37 +++ .../dev-tasks/dev-echo/lang/aji_air/README.md | 5 + .../dev-tasks/dev-echo/lang/aji_air/test.sh | 7 + .../dev-tasks/dev-echo/lang/rust/Cargo.toml | 6 + .../dev-tasks/dev-echo/lang/rust/README.md | 4 + .../dev-tasks/dev-echo/lang/rust/src/main.rs | 1 + .../dev-tasks/dev-echo/lang/rust/test.sh | 5 + .../dev-tasks/dev-echo/lang/zig/README.md | 4 + .../dev-tasks/dev-echo/lang/zig/main.zig | 1 + .../dev-tasks/dev-echo/lang/zig/test.sh | 5 + docs/evaluation/dev-tasks/dev-echo/prompt.md | 7 + docs/evaluation/dev-tasks/dev-echo/task.json | 14 + docs/evaluation/harness.md | 140 ++++++++++ docs/evaluation/protocol.md | 2 +- docs/evaluation/smoke-plan.example.json | 16 ++ docs/plan/README.md | 4 +- tools/eval/ajieval/__init__.py | 15 + tools/eval/ajieval/__main__.py | 3 + tools/eval/ajieval/agent.py | 256 ++++++++++++++++++ tools/eval/ajieval/cli.py | 123 +++++++++ tools/eval/ajieval/languages.py | 104 +++++++ tools/eval/ajieval/providers.py | 209 ++++++++++++++ tools/eval/ajieval/record.py | 147 ++++++++++ tools/eval/ajieval/report.py | 63 +++++ tools/eval/ajieval/sandbox.py | 73 +++++ tools/eval/ajieval/task.py | 45 +++ tools/eval/ajieval/util.py | 78 ++++++ tools/eval/languages/aji_air.json | 12 + tools/eval/languages/rust.json | 13 + tools/eval/languages/zig.json | 12 + tools/eval/tests/scripts/aji_air.json | 63 +++++ tools/eval/tests/scripts/rust.json | 63 +++++ tools/eval/tests/scripts/zig.json | 63 +++++ tools/eval/tests/test_harness.py | 128 +++++++++ 38 files changed, 1735 insertions(+), 5 deletions(-) create mode 100755 docs/evaluation/dev-tasks/dev-echo/evaluator.py create mode 100644 docs/evaluation/dev-tasks/dev-echo/lang/aji_air/README.md create mode 100755 docs/evaluation/dev-tasks/dev-echo/lang/aji_air/test.sh create mode 100644 docs/evaluation/dev-tasks/dev-echo/lang/rust/Cargo.toml create mode 100644 docs/evaluation/dev-tasks/dev-echo/lang/rust/README.md create mode 100644 docs/evaluation/dev-tasks/dev-echo/lang/rust/src/main.rs create mode 100755 docs/evaluation/dev-tasks/dev-echo/lang/rust/test.sh create mode 100644 docs/evaluation/dev-tasks/dev-echo/lang/zig/README.md create mode 100644 docs/evaluation/dev-tasks/dev-echo/lang/zig/main.zig create mode 100755 docs/evaluation/dev-tasks/dev-echo/lang/zig/test.sh create mode 100644 docs/evaluation/dev-tasks/dev-echo/prompt.md create mode 100644 docs/evaluation/dev-tasks/dev-echo/task.json create mode 100644 docs/evaluation/harness.md create mode 100644 docs/evaluation/smoke-plan.example.json create mode 100644 tools/eval/ajieval/__init__.py create mode 100644 tools/eval/ajieval/__main__.py create mode 100644 tools/eval/ajieval/agent.py create mode 100644 tools/eval/ajieval/cli.py create mode 100644 tools/eval/ajieval/languages.py create mode 100644 tools/eval/ajieval/providers.py create mode 100644 tools/eval/ajieval/record.py create mode 100644 tools/eval/ajieval/report.py create mode 100644 tools/eval/ajieval/sandbox.py create mode 100644 tools/eval/ajieval/task.py create mode 100644 tools/eval/ajieval/util.py create mode 100644 tools/eval/languages/aji_air.json create mode 100644 tools/eval/languages/rust.json create mode 100644 tools/eval/languages/zig.json create mode 100644 tools/eval/tests/scripts/aji_air.json create mode 100644 tools/eval/tests/scripts/rust.json create mode 100644 tools/eval/tests/scripts/zig.json create mode 100644 tools/eval/tests/test_harness.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2624ddf..378f8f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,8 @@ jobs: - run: zig build && python3 tests/hosted/smoke.py - run: zig-out/bin/aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air - run: zig build agent-reference + - name: Evaluation harness self-tests + run: cd tools/eval && python3 -m unittest discover tests - name: Agent Reference Bundle tokens (non-blocking) continue-on-error: true run: pip install --quiet tiktoken tokenizers && python3 tools/agent_bundle_tokens.py diff --git a/.gitignore b/.gitignore index 3389c86..84a9a24 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,6 @@ .zig-cache/ zig-out/ +__pycache__/ +*.pyc +runs/ +runs-*/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c20f2aa..ad2c902 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,6 +15,7 @@ zig build conformance # conformance suite, see tests/conformance/README.m zig build run -- check f.air # verify a text AIR module zig build run -- run f.air # verify and execute @main (deterministic profile) python3 tests/hosted/smoke.py # hosted profile against the real OS +(cd tools/eval && python3 -m unittest discover tests) # evaluation harness self-tests zig fmt --check build.zig src tools ``` diff --git a/docs/evaluation/README.md b/docs/evaluation/README.md index 9794d11..6b50f36 100644 --- a/docs/evaluation/README.md +++ b/docs/evaluation/README.md @@ -4,6 +4,7 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](.. | Document | Purpose | |---|---| +| [harness.md](harness.md) | Agent scaffold and run recorder (E0-3): task format, evaluator contract, run record, commands | | [protocol.md](protocol.md) | Agent Language Evaluation Protocol 0.2: variables, benchmark families T01–T10, conditions `Aji/AIR` and `Aji/source`, maintenance and seeded-bug benchmarks, metrics, statistics, stages A–E, success and falsification criteria | | [../agent/README.md](../agent/README.md) | Agent Reference Bundle: contents, measurement, growth policy, milestones | @@ -18,8 +19,8 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](.. | Stage | Tasks | Requires | Status | |---|---|---|---| -| A — Phase 2 validation | T01–T04 | Phase 2 (heap, regions, resources, capabilities, effects, deterministic I/O) | language ready; infrastructure pending (plan E0) | -| B — Phase 3 validation | T05–T07 | Phase 3 (structured concurrency, schedule exploration) | blocked on Phase 3 | +| A — Phase 2 validation | T01–T04 | Phase 2 (heap, regions, resources, capabilities, effects, deterministic I/O) | language ready; harness done (E0-3); tasks and baselines pending (E0-2, E0-4) | +| B — Phase 3 validation | T05–T07 | Phase 3 (structured concurrency, schedule exploration) | language ready; infrastructure: harness done (E0-3), tasks pending (E0-2) | | C — Atomic validation | T08, litmus repair | Phase 5 (atomics, memory model) | blocked on Phase 5 | | D — Systems integration | T09, T10 | Phases 3–5; stable features | blocked | | E — Maintenance campaign | M1–M8 on T03, T07, T09, T10 | D | blocked | diff --git a/docs/evaluation/dev-tasks/dev-echo/evaluator.py b/docs/evaluation/dev-tasks/dev-echo/evaluator.py new file mode 100755 index 0000000..ad4e0f2 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/evaluator.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Dev evaluator for dev-echo (public because the task is dev-set; real +evaluators live in the private benchmark repository and sandbox the code +they run). + +usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout +""" +import json, os, subprocess, sys + +ws, lang = sys.argv[1], sys.argv[2] +REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) +AJI = os.path.join(REPO, "zig-out", "bin", "aji") +cases = ["", "hello", "x" * 64, "line one\nline two\n"] +gates = {} + +def build(): + if lang == "rust": + return subprocess.run(["cargo", "build", "-q", "--offline"], cwd=ws, capture_output=True).returncode == 0 + if lang == "zig": + return subprocess.run(["zig", "build-exe", "main.zig"], cwd=ws, capture_output=True).returncode == 0 + return subprocess.run([AJI, "check", "main.air"], cwd=ws, capture_output=True).returncode == 0 + +def run(inp): + if lang == "aji_air": + p = subprocess.run([AJI, "run", "--grant", "in=io.read", "--grant", "out=io.write", "--stdin", inp, "main.air"], cwd=ws, capture_output=True, text=True, timeout=60) + try: + rec = json.loads(p.stdout) + except json.JSONDecodeError: + return None + return rec.get("stdout") if rec.get("status") == "returned" else None + exe = "./target/debug/echo" if lang == "rust" else "./main" + p = subprocess.run([exe], cwd=ws, input=inp, capture_output=True, text=True, timeout=60) + return p.stdout if p.returncode == 0 else None + +gates["builds"] = build() +gates["functional"] = gates["builds"] and all(run(c) == c for c in cases) +print(json.dumps({"accepted": all(gates.values()), "gates": gates})) diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/aji_air/README.md b/docs/evaluation/dev-tasks/dev-echo/lang/aji_air/README.md new file mode 100644 index 0000000..66a4857 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/aji_air/README.md @@ -0,0 +1,5 @@ +# Interface + +- Source: `main.air`, a text AIR module. +- Entry point: `@main(%in: cap, %out: cap)`; any return type. +- The program is run as `aji run --grant in=io.read --grant out=io.write --stdin TEXT main.air`; the bytes written to standard output appear in the run record's `stdout` field. diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/aji_air/test.sh b/docs/evaluation/dev-tasks/dev-echo/lang/aji_air/test.sh new file mode 100755 index 0000000..a01d8ad --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/aji_air/test.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Public test: one input. +out=$(aji run --grant in=io.read --grant out=io.write --stdin 'hello' main.air) || { echo "FAIL: aji run failed"; echo "$out"; exit 1; } +case "$out" in + *'"stdout":"hello"'*) echo "PASS";; + *) echo "FAIL: unexpected run record: $out"; exit 1;; +esac diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/rust/Cargo.toml b/docs/evaluation/dev-tasks/dev-echo/lang/rust/Cargo.toml new file mode 100644 index 0000000..51d5eb6 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/rust/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "echo" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/rust/README.md b/docs/evaluation/dev-tasks/dev-echo/lang/rust/README.md new file mode 100644 index 0000000..fc0f4f2 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/rust/README.md @@ -0,0 +1,4 @@ +# Interface + +- Cargo package `echo` in this directory; the binary is `target/debug/echo`. +- The program reads standard input and writes standard output. diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/rust/src/main.rs b/docs/evaluation/dev-tasks/dev-echo/lang/rust/src/main.rs new file mode 100644 index 0000000..f328e4d --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/rust/src/main.rs @@ -0,0 +1 @@ +fn main() {} diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/rust/test.sh b/docs/evaluation/dev-tasks/dev-echo/lang/rust/test.sh new file mode 100755 index 0000000..19a3768 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/rust/test.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# Public test: one input. +cargo build -q --offline || { echo "FAIL: build"; exit 1; } +out=$(printf 'hello' | ./target/debug/echo) +[ "$out" = "hello" ] && echo PASS || { echo "FAIL: got '$out'"; exit 1; } diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/zig/README.md b/docs/evaluation/dev-tasks/dev-echo/lang/zig/README.md new file mode 100644 index 0000000..7244538 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/zig/README.md @@ -0,0 +1,4 @@ +# Interface + +- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`. +- The program reads standard input and writes standard output. diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/zig/main.zig b/docs/evaluation/dev-tasks/dev-echo/lang/zig/main.zig new file mode 100644 index 0000000..902b554 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/zig/main.zig @@ -0,0 +1 @@ +pub fn main() void {} diff --git a/docs/evaluation/dev-tasks/dev-echo/lang/zig/test.sh b/docs/evaluation/dev-tasks/dev-echo/lang/zig/test.sh new file mode 100755 index 0000000..e2a39e0 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/lang/zig/test.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# Public test: one input. +zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; } +out=$(printf 'hello' | ./main) +[ "$out" = "hello" ] && echo PASS || { echo "FAIL: got '$out'"; exit 1; } diff --git a/docs/evaluation/dev-tasks/dev-echo/prompt.md b/docs/evaluation/dev-tasks/dev-echo/prompt.md new file mode 100644 index 0000000..2e2cc17 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/prompt.md @@ -0,0 +1,7 @@ +# Task: echo + +Harness development task (dev set; not a benchmark family). Do not use it to evaluate anything. + +Write a program that reads all of its standard input and writes exactly the same bytes to its standard output. The input is at most 64 bytes long and may be empty. + +The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. diff --git a/docs/evaluation/dev-tasks/dev-echo/task.json b/docs/evaluation/dev-tasks/dev-echo/task.json new file mode 100644 index 0000000..08502a1 --- /dev/null +++ b/docs/evaluation/dev-tasks/dev-echo/task.json @@ -0,0 +1,14 @@ +{ + "id": "dev-echo", + "version": "1", + "set": "dev", + "family": "harness-dev", + "prompt": "prompt.md", + "languages": { + "aji_air": {"workspace": "lang/aji_air", "test": "sh test.sh"}, + "rust": {"workspace": "lang/rust", "test": "sh test.sh"}, + "zig": {"workspace": "lang/zig", "test": "sh test.sh"} + }, + "limits": {"tool_calls": 40, "total_tokens": 400000, "wall_seconds": 900, "command_timeout": 120}, + "concurrency": false +} diff --git a/docs/evaluation/harness.md b/docs/evaluation/harness.md new file mode 100644 index 0000000..775b0c8 --- /dev/null +++ b/docs/evaluation/harness.md @@ -0,0 +1,140 @@ +# Evaluation Harness + +Non-normative. The language-neutral agent scaffold and run recorder of plan item E0-3 (protocol §3–§5, §13–§17, §27–§29). Code: [`tools/eval/`](../../tools/eval/). Python standard library only. + +```sh +cd tools/eval +python3 -m ajieval run --task DIR --language aji_air --provider anthropic --model MODEL --class frontier \ + --evaluator CMD --out runs/ +python3 -m ajieval matrix PLAN.json # every cell of a plan; resumable +python3 -m ajieval report runs/ [--json] # VSR, repair cycles, context, cost per correct solution +python3 -m ajieval classify RUN_DIR CATEGORY [--caught-by verifier|runtime|test] [--cause CAUSE] +python3 -m unittest discover tests # harness self-tests (needs `zig build`, Rust, Zig) +``` + +## One run + +One model + one language + one task + one fresh workspace + one fresh agent context (protocol §3). The task's starter workspace for the language is copied into `RUN/workspace`, and the agent loop runs until the model calls `finish`, ends its turn without a tool call, or a budget runs out. Then the evaluator judges the final workspace and the first-generation snapshot. + +**One loop for every language.** The system prompt, the tools and the termination rules are the same for Aji, Rust and Zig. A language contributes only its profile ([`tools/eval/languages/`](../../tools/eval/languages/)): how to invoke the toolchain, where its pinned documentation is, and which commands count as verifier, compiler or test runs. Profiles carry no solution hints (protocol §5). + +**Tools.** `list_files`, `read_file`, `write_file`, `edit_file`, `run` (a shell command in the workspace) and `finish`. Paths are confined to `/work` (the repository, writable) and `/docs` (documentation, read-only). + +**Sandbox.** `bwrap` (bubblewrap) is the default: + +- no network (protocol §4); +- read-only system and toolchain; +- the workspace at `/work`; +- documentation at `/docs`; +- a fresh `/tmp` and `HOME`; +- a clean environment. + +`--sandbox none` is for harness development only and is recorded. + +**Termination.** One of: + +| Reason | Meaning | +|---|---| +| `finished` | the model called `finish` | +| `model_end` | the model ended its turn without a tool call; the scaffold does not nudge, so stopping early is part of the measurement | +| `max_tokens` | the reply hit the output-token limit | +| `budget_tool_calls`, `budget_tokens`, `wall_time` | a task limit ran out | +| `provider_error` | the model provider failed | + +**Providers.** Each provider has a fixed role: + +| Provider | Use | +|---|---| +| `anthropic` | Anthropic Messages API (`ANTHROPIC_API_KEY`) | +| `openai` | OpenAI-compatible chat completions (`OPENAI_API_KEY`); also local servers such as vLLM, llama.cpp or Ollama via `base_url` | +| `scripted` | replays fixed turns (self-tests) | + +## Task directory (the interface to the private benchmark repository) + +```text +/task.json id, version, set (dev|validation|test), family, prompt, + languages {lang: {workspace, test}}, limits, concurrency +/prompt.md language-neutral statement +// starter repository per language: README with the + interface, public tests, build files +``` + +`limits` may set: + +| Limit | Default | +|---|---| +| `tool_calls` | 150 | +| `total_tokens` | 3 000 000 | +| `wall_seconds` | 3 600 | +| `command_timeout` | 300 | +| `output_chars` | 20 000 | + +The `test` command is the public test. Invoking it counts as a test run. + +Hidden tests, evaluators and reference implementations never enter this repository (protocol §29). The only task kept here is the harness development task [`dev-tasks/dev-echo`](dev-tasks/dev-echo/), which belongs to no benchmark family. + +## Evaluator contract + +The harness calls `CMD WORKSPACE LANGUAGE TASK_DIR` outside the agent's sandbox. The evaluator must print one JSON object: + +```json +{"accepted": true, "gates": {"verifier": true, "public_tests": true, "hidden_functional": true, "hidden_regression": true, "fuzz": true, "resources": true, "deterministic_runs": true, "schedule_exploration": true}} +``` + +`accepted` follows protocol §13: all mandatory gates pass, with no partial success. The evaluator runs untrusted code, so it must sandbox that code itself. The record stores the hash of the evaluator, or of `--evaluator-hash-path`, and the full verdict. + +## Run record (`RUN/run.json`, protocol §28) + +Every run directory contains: + +| Path | Contents | +|---|---| +| `run.json` | the record below | +| `events.jsonl` | every model reply (content and token usage), tool call and result, patch (unified diff), and command (exit code, output) | +| `workspace/` | the final repository | +| `first_generation/` | the workspace before the first toolchain invocation (protocol §14) | + +`run.json` holds: + +- **Identity:** + - task id, version, set and hash; + - evaluator command and hash; + - language, profile hash, toolchain versions, docs path and hash; + - model provider, id, class and parameters; + - scaffold version, commit and sandbox; + - system prompt hash and task prompt hash; + - limits, hardware, seed. +- **Metrics:** + - model and tool calls; + - input, output and cached tokens; + - patches, commands, check/build/test runs; + - failed verifier cycles and failed test cycles (§15); + - first check, build, public test and hidden test results (§14); + - files opened, repository and documentation bytes read (§16); + - elapsed time, termination. +- **Outcome:** `cost_usd` from an optional pricing table (USD per million tokens, §17), `verdict`, `first_generation_verdict`, `accepted`, the hashes of the final repository, and `classification`. + +## Failure classification + +`ajieval classify` records the primary category of a failed run (protocol §27). For Aji runs it also records where the failure was caught: verifier, runtime or test. + +For the smoke test it also records the cause, decided before any language change is considered (protocol §38): + +- `language` +- `documentation` +- `agent_bundle` +- `diagnostics` +- `harness` +- `model_capability` +- `task_ambiguity` + +## Smoke test (E-S) + +[`smoke-plan.example.json`](smoke-plan.example.json) is the shape of the 36-run plan (owner decision): + +- families: a binary/stream parser and a concurrent bounded pipeline; +- languages: Aji/AIR, Rust and Zig; +- model classes: frontier, mid and small/local; +- runs: 2 independent runs per cell. + +The tasks, evaluators and baselines come from E0-2 and E0-4. The smoke test checks infrastructure, not the hypothesis. Its headline numbers are still read: Verified Success Rate, repair cycles, context consumed and cost per correct solution. diff --git a/docs/evaluation/protocol.md b/docs/evaluation/protocol.md index 9e20116..e5fe20a 100644 --- a/docs/evaluation/protocol.md +++ b/docs/evaluation/protocol.md @@ -1534,7 +1534,7 @@ Do not add syntax or instructions merely because one model struggled with one ta Before the pilot, a small run checks the infrastructure, not the hypothesis: ```text -2 families (e.g. binary frame decoding, append log) +2 families (binary/stream parsing; concurrent bounded pipeline — owner decision after Phase 3) × 3 languages (Aji/AIR, Rust, Zig) × 3 model classes × 2 runs diff --git a/docs/evaluation/smoke-plan.example.json b/docs/evaluation/smoke-plan.example.json new file mode 100644 index 0000000..388468b --- /dev/null +++ b/docs/evaluation/smoke-plan.example.json @@ -0,0 +1,16 @@ +{ + "comment": "E-S engineering smoke test (protocol §39a): 2 tasks x 3 languages x 3 model classes x 2 runs = 36 runs. Copy next to the private task checkout, fill in task paths, models and the evaluator, then: python3 -m ajieval matrix plan.json (from tools/eval, with PYTHONPATH or cwd there). Infrastructure check only; no result is evidence.", + "tasks": ["../aji-bench/tasks/", "../aji-bench/tasks/"], + "languages": ["aji_air", "rust", "zig"], + "models": [ + {"class": "frontier", "provider": "anthropic", "model": ""}, + {"class": "mid", "provider": "openai", "model": "", "base_url": ""}, + {"class": "small", "provider": "openai", "model": "", "base_url": "http://127.0.0.1:8000/v1"} + ], + "runs": 2, + "sandbox": "bwrap", + "evaluator": "../aji-bench/evaluate", + "evaluator_hash_path": "../aji-bench/evaluators", + "pricing": "pricing.json", + "out": "runs-smoke" +} diff --git a/docs/plan/README.md b/docs/plan/README.md index f583a94..89a5fc4 100644 --- a/docs/plan/README.md +++ b/docs/plan/README.md @@ -94,9 +94,9 @@ Evaluation runs alongside the phases; each stage starts when the language featur |---|---|---|---|---| | E0-1 | done | Define the Agent Reference Bundle (spec 14 §3.7) and a deterministic size measurement (bytes and tokens) recorded per release | — | `docs/agent/bundle.txt`, `zig build agent-reference`, `tools/agent_bundle_tokens.py`; Phase 2 baseline recorded; measured in CI | | E0-2 | todo | (owner; in parallel with Phase 3, outside this repository) Private benchmark repository: task specs, evaluators, reference implementations, hidden tests for T01–T04; dev/validation/test split | — | evaluator hashes published; nothing hidden in this repository | -| E0-3 | todo | (after basic Phase 3) Language-neutral agent scaffold and run recorder (protocol §5, §28) | — | identical loop drives Aji, Rust and Zig; every run record complete | +| E0-3 | done | Language-neutral agent scaffold and run recorder (protocol §5, §28) | — | `tools/eval/`, `docs/evaluation/harness.md`; one loop drives Aji, Rust and Zig (self-tests on `dev-echo`); every run record complete | | E0-4 | todo | Rust and Zig baseline solutions and pinned local documentation | E0-2 | baselines pass the hidden tests | -| E-S | todo | Engineering smoke test: 2 families × 3 languages × 3 model classes × 2 runs = 36 runs (protocol §39a); infrastructure only | E0-2, E0-3, E0-4 | harness, bundle sufficiency, accounting and traces verified | +| E-S | todo | Engineering smoke test: 2 families (binary/stream parser, concurrent bounded pipeline) × 3 languages × 3 model classes × 2 runs = 36 runs (protocol §39a); plan shape `docs/evaluation/smoke-plan.example.json`; failures classified by cause before any language change | E0-2, E0-3, E0-4 | harness, bundle sufficiency, accounting and traces verified | | 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 | diff --git a/tools/eval/ajieval/__init__.py b/tools/eval/ajieval/__init__.py new file mode 100644 index 0000000..2348e94 --- /dev/null +++ b/tools/eval/ajieval/__init__.py @@ -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" diff --git a/tools/eval/ajieval/__main__.py b/tools/eval/ajieval/__main__.py new file mode 100644 index 0000000..4e28416 --- /dev/null +++ b/tools/eval/ajieval/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +main() diff --git a/tools/eval/ajieval/agent.py b/tools/eval/ajieval/agent.py new file mode 100644 index 0000000..5ccc6c3 --- /dev/null +++ b/tools/eval/ajieval/agent.py @@ -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) diff --git a/tools/eval/ajieval/cli.py b/tools/eval/ajieval/cli.py new file mode 100644 index 0000000..16d9e20 --- /dev/null +++ b/tools/eval/ajieval/cli.py @@ -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() diff --git a/tools/eval/ajieval/languages.py b/tools/eval/ajieval/languages.py new file mode 100644 index 0000000..89f9258 --- /dev/null +++ b/tools/eval/ajieval/languages.py @@ -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: `/bin` where it exists, else ``.""" + 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 diff --git a/tools/eval/ajieval/providers.py b/tools/eval/ajieval/providers.py new file mode 100644 index 0000000..6301439 --- /dev/null +++ b/tools/eval/ajieval/providers.py @@ -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) diff --git a/tools/eval/ajieval/record.py b/tools/eval/ajieval/record.py new file mode 100644 index 0000000..b100e10 --- /dev/null +++ b/tools/eval/ajieval/record.py @@ -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 diff --git a/tools/eval/ajieval/report.py b/tools/eval/ajieval/report.py new file mode 100644 index 0000000..0bf427d --- /dev/null +++ b/tools/eval/ajieval/report.py @@ -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)) diff --git a/tools/eval/ajieval/sandbox.py b/tools/eval/ajieval/sandbox.py new file mode 100644 index 0000000..bf1e249 --- /dev/null +++ b/tools/eval/ajieval/sandbox.py @@ -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 diff --git a/tools/eval/ajieval/task.py b/tools/eval/ajieval/task.py new file mode 100644 index 0000000..a79849e --- /dev/null +++ b/tools/eval/ajieval/task.py @@ -0,0 +1,45 @@ +"""Benchmark task directories (provided at run time; hidden material never +lives in the public repository). + + /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) diff --git a/tools/eval/ajieval/util.py b/tools/eval/ajieval/util.py new file mode 100644 index 0000000..a2aefba --- /dev/null +++ b/tools/eval/ajieval/util.py @@ -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): + """`` or `+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 diff --git a/tools/eval/languages/aji_air.json b/tools/eval/languages/aji_air.json new file mode 100644 index 0000000..983e6ff --- /dev/null +++ b/tools/eval/languages/aji_air.json @@ -0,0 +1,12 @@ +{ + "name": "aji_air", + "display": "Aji (condition Aji/AIR: text AIR format 0)", + "toolchain": { + "binaries": ["${REPO}/zig-out/bin/aji"], + "version": [["${REPO}/zig-out/bin/aji", "features"]] + }, + "docs": {"env": "AJI_EVAL_AJI_DOCS", "default": "${REPO}/zig-out/agent/reference-bundle.md"}, + "source_extensions": [".air"], + "instructions": "Language: Aji, written directly as text AIR format 0 (`.air` files).\nToolchain: `aji check FILE.air` verifies a module and prints diagnostics as JSON lines; `aji run [--grant P=KIND[:SCOPE]]... [--stdin TEXT] FILE.air` verifies and runs `@main` in the deterministic profile and prints one JSON run record; `aji features` lists the supported AIR features; `aji --help` lists all commands.\nDocumentation: the Aji Agent Reference Bundle is in /docs (read-only). It is the complete reference for writing AIR.", + "classify": {"check": ["aji check"], "build": [], "test": ["aji run"]} +} diff --git a/tools/eval/languages/rust.json b/tools/eval/languages/rust.json new file mode 100644 index 0000000..6d86a85 --- /dev/null +++ b/tools/eval/languages/rust.json @@ -0,0 +1,13 @@ +{ + "name": "rust", + "display": "Rust", + "toolchain": { + "bind_command": ["rustc", "--print", "sysroot"], + "version": [["rustc", "--version"], ["cargo", "--version"]] + }, + "docs": {"env": "AJI_EVAL_RUST_DOCS", "default": ""}, + "source_extensions": [".rs"], + "instructions": "Language: Rust (stable toolchain, standard library only; no network, so no crates.io dependencies).\nToolchain: `cargo build`, `cargo test`, `cargo run`, `rustc`. Cargo works offline (`--offline` is implied by the environment).\nDocumentation: pinned local Rust documentation is in /docs (read-only), if present.", + "env": {"CARGO_NET_OFFLINE": "true"}, + "classify": {"check": ["cargo check"], "build": ["cargo build", "rustc"], "test": ["cargo test", "cargo run"]} +} diff --git a/tools/eval/languages/zig.json b/tools/eval/languages/zig.json new file mode 100644 index 0000000..59871f4 --- /dev/null +++ b/tools/eval/languages/zig.json @@ -0,0 +1,12 @@ +{ + "name": "zig", + "display": "Zig", + "toolchain": { + "binaries": ["zig"], + "version": [["zig", "version"]] + }, + "docs": {"env": "AJI_EVAL_ZIG_DOCS", "default": ""}, + "source_extensions": [".zig"], + "instructions": "Language: Zig (the pinned toolchain below; standard library only; no network).\nToolchain: `zig build`, `zig build test`, `zig build run`, `zig run FILE.zig`, `zig test FILE.zig`.\nDocumentation: pinned local Zig documentation is in /docs (read-only), if present.", + "classify": {"check": ["zig ast-check"], "build": ["zig build-exe", "zig build"], "test": ["zig build test", "zig test", "zig build run", "zig run"]} +} diff --git a/tools/eval/tests/scripts/aji_air.json b/tools/eval/tests/scripts/aji_air.json new file mode 100644 index 0000000..2b7aee1 --- /dev/null +++ b/tools/eval/tests/scripts/aji_air.json @@ -0,0 +1,63 @@ +[ + [ + { + "text": "Reading the interface." + }, + { + "tool": "read_file", + "input": { + "path": "README.md" + } + } + ], + [ + { + "tool": "list_files", + "input": { + "path": "/docs" + } + } + ], + [ + { + "tool": "write_file", + "input": { + "path": "main.air", + "content": "broken" + } + } + ], + [ + { + "tool": "run", + "input": { + "command": "aji check main.air" + } + } + ], + [ + { + "tool": "write_file", + "input": { + "path": "main.air", + "content": "module echo\nair 0\nlang 0.1\nfeatures [arrays, capabilities, effects, ownership, resources]\n\nfn @main(%in: cap, %out: cap) -> void\neffects [io.read, io.write]\nentry:\n %b = local.alloc array\n local.zero %b\n %m = borrow.mut %b\n %s = slice.make %m\n intrinsic io.stdin_read(%in, %s), ok -> @got, err -> @fail\ngot(%n: usize):\n %z = const.usize 0\n %part = slice.sub %s, %z, %n\n %pr = borrow.ref %part\n intrinsic io.stdout_write(%out, %pr), ok -> @done, err -> @fail2\ndone:\n borrow.end %pr\n borrow.end %part\n borrow.end %s\n borrow.end %m\n ret\nfail(%e: io_error):\n trap\nfail2(%e2: io_error):\n trap\n" + } + } + ], + [ + { + "tool": "run", + "input": { + "command": "sh test.sh" + } + } + ], + [ + { + "tool": "finish", + "input": { + "summary": "done" + } + } + ] +] \ No newline at end of file diff --git a/tools/eval/tests/scripts/rust.json b/tools/eval/tests/scripts/rust.json new file mode 100644 index 0000000..8fafa2d --- /dev/null +++ b/tools/eval/tests/scripts/rust.json @@ -0,0 +1,63 @@ +[ + [ + { + "text": "Reading the interface." + }, + { + "tool": "read_file", + "input": { + "path": "README.md" + } + } + ], + [ + { + "tool": "list_files", + "input": { + "path": "/docs" + } + } + ], + [ + { + "tool": "write_file", + "input": { + "path": "src/main.rs", + "content": "broken" + } + } + ], + [ + { + "tool": "run", + "input": { + "command": "cargo build" + } + } + ], + [ + { + "tool": "write_file", + "input": { + "path": "src/main.rs", + "content": "use std::io::{Read, Write};\n\nfn main() {\n let mut buf = Vec::new();\n std::io::stdin().read_to_end(&mut buf).unwrap();\n std::io::stdout().write_all(&buf).unwrap();\n}\n" + } + } + ], + [ + { + "tool": "run", + "input": { + "command": "sh test.sh" + } + } + ], + [ + { + "tool": "finish", + "input": { + "summary": "done" + } + } + ] +] \ No newline at end of file diff --git a/tools/eval/tests/scripts/zig.json b/tools/eval/tests/scripts/zig.json new file mode 100644 index 0000000..fc53059 --- /dev/null +++ b/tools/eval/tests/scripts/zig.json @@ -0,0 +1,63 @@ +[ + [ + { + "text": "Reading the interface." + }, + { + "tool": "read_file", + "input": { + "path": "README.md" + } + } + ], + [ + { + "tool": "list_files", + "input": { + "path": "/docs" + } + } + ], + [ + { + "tool": "write_file", + "input": { + "path": "main.zig", + "content": "broken" + } + } + ], + [ + { + "tool": "run", + "input": { + "command": "zig build-exe main.zig" + } + } + ], + [ + { + "tool": "write_file", + "input": { + "path": "main.zig", + "content": "const std = @import(\"std\");\n\npub fn main(init: std.process.Init) !void {\n const io = init.io;\n var in_buf: [128]u8 = undefined;\n var fr: std.Io.File.Reader = .init(.stdin(), io, &in_buf);\n const data = try fr.interface.allocRemaining(init.arena.allocator(), .limited(1024));\n var out_buf: [128]u8 = undefined;\n var fw: std.Io.File.Writer = .init(.stdout(), io, &out_buf);\n try fw.interface.writeAll(data);\n try fw.interface.flush();\n}\n" + } + } + ], + [ + { + "tool": "run", + "input": { + "command": "sh test.sh" + } + } + ], + [ + { + "tool": "finish", + "input": { + "summary": "done" + } + } + ] +] \ No newline at end of file diff --git a/tools/eval/tests/test_harness.py b/tools/eval/tests/test_harness.py new file mode 100644 index 0000000..8685f28 --- /dev/null +++ b/tools/eval/tests/test_harness.py @@ -0,0 +1,128 @@ +"""Harness self-tests: sandbox isolation, path confinement, budgets, the +complete run record (protocol §28) and resumable matrices. + + cd tools/eval && python3 -m unittest discover tests + +Requires zig-out/bin/aji (`zig build`) and the Rust and Zig toolchains; +sandbox tests are skipped where bubblewrap cannot create namespaces. +""" + +import json +import os +import shutil +import subprocess +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, os.path.dirname(HERE)) + +from ajieval import agent, languages, record, report, sandbox, util # noqa: E402 + +TASK = os.path.join(util.REPO, "docs", "evaluation", "dev-tasks", "dev-echo") +EVALUATOR = [os.path.join(TASK, "evaluator.py")] + + +def bwrap_works(): + if shutil.which("bwrap") is None: + return False + return subprocess.run(["bwrap", "--unshare-all", "--ro-bind", "/", "/", "true"], capture_output=True).returncode == 0 + + +SANDBOX = "bwrap" if bwrap_works() else "none" + + +class SandboxTest(unittest.TestCase): + @unittest.skipUnless(SANDBOX == "bwrap", "bubblewrap unavailable") + def test_isolation(self): + ws = tempfile.mkdtemp() + sb = sandbox.Sandbox("bwrap", ws, [], [], docs=TASK) + code, out, _ = sb.run("echo hi > f && cat f", 30, 1000) + self.assertEqual((code, out.strip()), (0, "hi")) + code, out, _ = sb.run("getent hosts example.com || echo NO_NET", 30, 1000) + self.assertIn("NO_NET", out) + code, _, _ = sb.run("touch /docs/x", 30, 1000) + self.assertNotEqual(code, 0) + code, out, _ = sb.run("ls " + os.path.expanduser("~") + " 2>&1 || echo NO_HOME", 30, 1000) + self.assertIn("NO_HOME", out) + self.assertTrue(os.path.exists(os.path.join(ws, "f"))) + + def test_output_limit_and_timeout(self): + sb = sandbox.Sandbox(SANDBOX, tempfile.mkdtemp(), [], []) + code, out, truncated = sb.run("yes | head -c 5000", 30, 100) + self.assertTrue(truncated) + self.assertLess(len(out), 200) + code, _, _ = sb.run("sleep 5", 1, 100) + self.assertIsNone(code) + + +class PathTest(unittest.TestCase): + def test_confinement(self): + ws = tempfile.mkdtemp() + a = agent.Agent(None, {"instructions": ""}, None, {}, None, ws, None, None, {"tool_calls": 1, "total_tokens": 1, "output_chars": 100}) + for bad in ["/etc/passwd", "../x", "/work/../etc/passwd", "/docs/x"]: + with self.assertRaises(agent.ToolError): + a.host_path(bad) + with self.assertRaises(agent.ToolError): + a.host_path("/docs", write=True) + self.assertEqual(a.host_path("a/b")[0], os.path.join(os.path.realpath(ws), "a", "b")) + + +class RunTest(unittest.TestCase): + def setUp(self): + self.out = tempfile.mkdtemp() + + def run_lang(self, lang, **kw): + return record.run_one(TASK, lang, "scripted", os.path.join(HERE, "scripts", lang + ".json"), self.out, + model_class="test", sandbox_kind=SANDBOX, evaluator=EVALUATOR, **kw) + + def test_all_languages_complete_record(self): + for lang in languages.available(): + with self.subTest(lang=lang): + run_dir, rec = self.run_lang(lang) + self.assertTrue(rec["accepted"], rec["verdict"]) + self.assertEqual(rec["metrics"]["termination"], "finished") + for key in ["task", "evaluator", "language", "model", "scaffold", "system_prompt_hash", "task_prompt_hash", + "limits", "hardware", "seed", "metrics", "final_repository", "verdict", "cost_usd"]: + self.assertIn(key, rec) + self.assertTrue(rec["evaluator"]["hash"].startswith("sha256:")) + m = rec["metrics"] + self.assertEqual(m["patches"], 2) + self.assertEqual(m["failed_verifier_cycles"], 1) + self.assertFalse(m["first_check_accepted"] or m["first_build_accepted"]) + self.assertTrue(m["first_public_test_passed"]) + self.assertFalse(m["first_hidden_test_passed"]) # the snapshot holds the broken file + kinds = [json.loads(l)["event"] for l in open(os.path.join(run_dir, "events.jsonl"))] + for k in ["start", "model", "tool", "patch", "command"]: + self.assertIn(k, kinds) + rows = report.aggregate(report.load([self.out])) + self.assertEqual(len(rows), len(languages.available())) + self.assertTrue(all(r["verified_success_rate"] == 1.0 for r in rows)) + + def test_tool_budget(self): + _, rec = self.run_lang("aji_air", limits={"tool_calls": 3}) + self.assertEqual(rec["metrics"]["termination"], "budget_tool_calls") + self.assertFalse(rec["accepted"]) + + def test_cost(self): + pricing = {os.path.join(HERE, "scripts", "zig.json"): {"input": 1.0, "output": 10.0}} + _, rec = self.run_lang("zig", pricing=pricing) + m = rec["metrics"] + self.assertAlmostEqual(rec["cost_usd"], (m["input_tokens"] + 10 * m["output_tokens"]) / 1e6, places=6) + + +class MatrixTest(unittest.TestCase): + def test_resume(self): + d = tempfile.mkdtemp() + plan = {"tasks": [TASK], "languages": ["rust"], "runs": 1, "sandbox": SANDBOX, "evaluator": EVALUATOR[0], + "models": [{"provider": "scripted", "model": os.path.join(HERE, "scripts", "rust.json"), "class": "test"}]} + path = os.path.join(d, "plan.json") + util.write_json(path, plan) + for _ in range(2): + subprocess.run([sys.executable, "-m", "ajieval", "matrix", path], cwd=os.path.dirname(HERE), check=True, capture_output=True) + self.assertEqual(len(report.load([os.path.join(d, "runs")])), 1) + + +if __name__ == "__main__": + unittest.main()