Track B: networkless shell, context metrics, freeze, journal

- Claude Code and OpenCode: system shells replaced inside the sandbox by
  wrappers that run every command in a nested bubblewrap with an empty
  network namespace and no resolver socket; the CLI keeps its backend
  connection. dev-netprobe (new dev task) passes for all three agents:
  no network, no DNS from the shell
- context metrics for both tracks: provider input (cached/uncached),
  cumulative context through the tool loop, unique reference tokens and
  bundle coverage; report shows them; no dollar cost for Track B
- ajieval freeze: frozen state (clean Aji commit, binary, bundle,
  toolchains, docs, CLI versions and config fingerprints, tasks,
  evaluator, limits) and a shuffled cell order; matrix verifies it and
  runs cells sequentially in that order; ajieval journal
- docs: benchmark-authoring.md (roles, clean-context brief, E-G
  checklist); harness.md, protocol §39b, plan updated
This commit is contained in:
dev committed 2026-10-04 17:58:32 +03:00
1 parent 00cbb65447
commit 8b7911669d
16 files changed
+564 -33

No files matched your search

+1
View File
@@ -4,6 +4,7 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](..
| Document | Purpose | | Document | Purpose |
|---|---| |---|---|
| [benchmark-authoring.md](benchmark-authoring.md) | Separation of roles for E0-2 and E-G: benchmark author and reference writers in clean contexts; brief; gate checklist |
| [harness.md](harness.md) | Agent scaffold and run recorder (E0-3): task format, evaluator contract, run record, commands | | [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 | | [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 | | [../agent/README.md](../agent/README.md) | Agent Reference Bundle: contents, measurement, growth policy, milestones |
+81
View File
@@ -0,0 +1,81 @@
# Benchmark Authoring and References (E0-2, E-G)
Non-normative. How the private tasks and reference implementations for the Track B smoke (E-N) and later experiments are produced without contaminating them with knowledge of Aji's development.
## Separation of roles
| Role | Context | Sees | Produces |
|---|---|---|---|
| Language developer (the agent working in this repository) | the whole development history | this public repository | language, harness |
| Benchmark author | a fresh agent context in the private benchmark repository | only the brief below and [`harness.md`](harness.md) (task format, evaluator contract) | tasks, public and hidden tests, evaluator, manifest, reviewer notes |
| Reference writer, one per language | a fresh agent context per language | one task statement, its language's starter workspace and the documentation a smoke participant gets (for Aji exactly the frozen Agent Reference Bundle) | a reference solution |
| Owner | everything private | everything | reviews, freezes, runs |
Rules:
- The private repository is never shown to the language developer's conversation. Hidden tests, task designs and evaluator code are never pasted into it.
- The benchmark author writes the evaluator from the task statement and does **not** tune it to reference implementations.
- If a reference fails the evaluator because the task is ambiguous, the statement or evaluator is corrected and its `version` is increased, and the references are rerun. Then everything is frozen. After the freeze no change is allowed until the last run of the experiment.
- The Aji reference is written by a separate agent, never by the language developer.
Reference writers can run through the harness itself, which gives them exactly the participants' environment: `ajieval native` with the task, the language and generous limits. The runs live in the private repository, and their records are not shared with the language developer.
## Brief for the benchmark author
> You are designing a private held-out benchmark for comparing AI agents writing systems software in three languages: Aji/AIR, Rust and Zig. You have no role in Aji language design and must not optimize tasks for Aji.
>
> Create two benchmark tasks:
>
> 1. A memory-safety-heavy streaming/binary-processing systems task.
> 2. A concurrency-heavy bounded-processing task.
>
> The tasks must belong to these broad families, but must NOT reproduce public examples such as a simple length-prefixed frame decoder, append-only log, basic producer/consumer pipeline, or simple fan-out example.
>
> For each task produce:
>
> - a language-neutral task statement;
> - deterministic acceptance criteria;
> - public tests;
> - private hidden tests;
> - fuzz/property tests where applicable;
> - resource limits;
> - a machine evaluator implementing `CMD WORKSPACE LANGUAGE TASK_DIR` and returning the required JSON verdict;
> - a task manifest containing version and hashes;
> - reviewer notes explaining possible ambiguities;
> - no reference to Aji-specific constructs in the task statement.
>
> Requirements:
>
> - More than one implementation strategy must be valid.
> - Hidden tests must test only stated requirements.
> - Do not introduce arbitrary requirements that favor one language.
> - Include malformed/error cases.
> - The concurrency task must exercise boundedness, ownership/lifetime of work, termination and at least one failure/cancellation scenario.
> - The memory task must exercise incremental input, malformed data, integer/bounds edge cases and constrained memory.
> - Avoid task structures already described in public Aji documentation.
> - Do not reveal the hidden tests or concrete hidden task design outside this private benchmark repository.
>
> Task directory and evaluator format: see `harness.md` (task directory, evaluator contract). Each language gets a starter workspace with a README describing the program's interface and a public test command. The Aji/AIR workspace describes the entry point and the `aji run` invocation (grants, inputs), the way `docs/evaluation/dev-tasks/dev-echo/lang/aji_air/README.md` does.
## Gate E-G (before the 18 runs)
All of the following must hold:
```text
networkless shell for all native agents (verified: dev-netprobe)
native configurations frozen (ajieval freeze)
2 private tasks reviewed
evaluator frozen
task/evaluator hashes frozen
Rust references PASS
Zig references PASS
Aji/AIR references PASS
Aji compiler commit frozen
Agent Reference Bundle hash frozen
Rust/Zig toolchains + docs frozen
```
`ajieval freeze PLAN.json` records the frozen state and a random cell order. `ajieval matrix PLAN.json` refuses to run if anything changed. Observations during the runs go to `ajieval journal PLAN.json "…"` and are acted on only after the last run.
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Dev evaluator for dev-netprobe: accepted iff the agent's shell had no
network (net.txt says NETWORK_BLOCKED) and probe.sh was left unchanged.
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR
"""
import json, os, sys
ws, task_dir = sys.argv[1], sys.argv[3]
try:
out = open(os.path.join(ws, "net.txt")).read()
except OSError:
out = ""
pristine = open(os.path.join(task_dir, "lang", "any", "probe.sh")).read() == open(os.path.join(ws, "probe.sh")).read()
gates = {"probe_ran": "NETWORK_" in out, "probe_unchanged": pristine, "network_blocked": "NETWORK_BLOCKED" in out and "NETWORK_REACHABLE" not in out, "no_dns": "DNS_RESOLVES" not in out}
print(json.dumps({"accepted": all(gates.values()), "gates": gates, "net_txt": out[-500:]}))
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Reports whether this shell can reach the network.
reach=0
if command -v curl >/dev/null 2>&1; then
curl -sS -m 8 -o /dev/null https://example.com 2>/dev/null && reach=1
fi
python3 - <<'PY' && reach=1
import socket, sys
try:
socket.create_connection(("1.1.1.1", 443), 5).close()
except OSError:
sys.exit(1)
PY
getent hosts example.com >/dev/null 2>&1 && echo "DNS_RESOLVES"
if [ "$reach" = 1 ]; then echo "NETWORK_REACHABLE"; else echo "NETWORK_BLOCKED"; fi
@@ -0,0 +1,5 @@
# Task: environment probe
Harness development task (dev set): it checks the isolation of the agent's shell. Do not evaluate anything with it.
Run the command `sh probe.sh` in the repository exactly once, using your shell tool, and save its complete output into the file `net.txt` in the repository (for example `sh probe.sh > net.txt 2>&1`). Do not modify `probe.sh`. Then stop.
@@ -0,0 +1,14 @@
{
"id": "dev-netprobe",
"version": "1",
"set": "dev",
"family": "harness-dev",
"prompt": "prompt.md",
"languages": {
"aji_air": {"workspace": "lang/any", "test": "sh probe.sh"},
"rust": {"workspace": "lang/any", "test": "sh probe.sh"},
"zig": {"workspace": "lang/any", "test": "sh probe.sh"}
},
"limits": {"tool_calls": 10, "total_tokens": 200000, "wall_seconds": 300, "command_timeout": 60},
"concurrency": false
}
+36 -3
View File
@@ -168,8 +168,10 @@ Per agent:
| Agent | Configuration | Shell network | | Agent | Configuration | Shell network |
|---|---|---| |---|---|---|
| `codex` | `codex exec --json`; `approval_policy=never`; web search off; product features off (multi-agent, apps, browser, computer use, plugins, skills, goals, hooks…) | off (Codex `workspace-write` sandbox) | | `codex` | `codex exec --json`; `approval_policy=never`; web search off; product features off (multi-agent, apps, browser, computer use, plugins, skills, goals, hooks…) | off (Codex `workspace-write` sandbox) |
| `claude` | `claude -p --output-format stream-json`; tools limited to `Bash`, `Read`, `Edit` and `Write`; `--strict-mcp-config`; slash commands off | on | | `claude` | `claude -p --output-format stream-json`; tools limited to `Bash`, `Read`, `Edit` and `Write`; `--strict-mcp-config`; slash commands off | off (networkless shell wrapper) |
| `opencode` | `opencode run --pure --format json`; no MCP; `webfetch`, `websearch` and `task` off | on | | `opencode` | `opencode run --pure --format json`; no MCP; `webfetch`, `websearch` and `task` off; no LSP downloads | off (networkless shell wrapper) |
**Networkless shell.** Inside the sandbox, the real shell binaries (`/usr/bin/bash`; `sh` follows its symlink) are replaced by wrappers. Each wrapper runs the command in a nested bubblewrap with a fresh, empty network namespace and without the resolver socket. The CLI process keeps the network to reach its backend. Every process a tool starts through a shell, `python3` sockets included, has neither network nor DNS. The live check is the dev task [`dev-netprobe`](dev-tasks/dev-netprobe/), which all three agents pass.
**Record (`aji-eval-native/1`).** The run directory holds: **Record (`aji-eval-native/1`).** The run directory holds:
@@ -191,7 +193,38 @@ Per agent:
- tool calls and token usage as reported by the CLI, normalized to input, output and cached input; - tool calls and token usage as reported by the CLI, normalized to input, output and cached input;
- the evaluator verdict. - the evaluator verdict.
A first-generation snapshot is not available in Track B. A first-generation snapshot is not available in Track B. There is no cost in dollars either: on subscriptions there is no honest cost per solution, so Track B reports success, time, tool calls and context. Economics stays with Track A.
## Context metrics (both tracks, `metrics.context`)
| Metric | Measures |
|---|---|
| `provider_input_tokens` | what the provider counted: total, cached and uncached input, and output |
| `cumulative_context_tokens` | the text returned to the agent through its tool loop (every tool output, plus the task message), counted each time it was returned |
| `unique_reference_tokens` | the distinct documentation text the agent saw: distinct lines in the outputs of tool calls that touched `/docs` |
| `reference_coverage` | for a single-file reference (the Aji bundle), the fraction of its lines that the agent saw |
The gap between provider input and cumulative context is history resending, mostly cached. The gap between cumulative context and unique reference is rereading and verbose output. The tokenizer is `cl100k_base` if tiktoken is installed, otherwise bytes / 4. Each record names the one it used.
## Freezing and running an experiment
```sh
python3 -m ajieval freeze PLAN.json # PLAN.freeze.json: frozen state + random cell order
python3 -m ajieval matrix PLAN.json # verifies the freeze, runs cells sequentially in frozen order
python3 -m ajieval journal PLAN.json "observation" [--run RUN_ID]
```
The freeze records:
- the Aji commit (the repository must be clean), the `aji` binary and the bundle hash;
- the language profiles, toolchain versions and documentation hashes;
- for each native agent: the CLI version and binary hash, and a fingerprint of its configuration (config, command line template, task preamble, shell wrapper);
- the harness commit, the task hashes, the evaluator hash and the limits;
- the shuffled order of all cells.
If any of it changes, `matrix` stops. Problems seen during the runs go to the journal (`<out>/journal.md`) and are acted on only after the last run.
How tasks and references are produced without contamination: [`benchmark-authoring.md`](benchmark-authoring.md).
## Smoke test (E-S) ## Smoke test (E-S)
+1 -1
View File
@@ -1578,7 +1578,7 @@ Track B — native agent language × coding-agent product (each model in it
tests the practical economics of development tests the practical economics of development
``` ```
Track B measures model + system prompt + context management + tool policy + compaction + agent heuristics together, so its results are never used as evidence for H4. Order (owner decision): the first experiment is Track B on existing subscriptions — a native dev-echo gate, then 2 tasks × 3 languages × 3 native agents × 1 run = 18 runs — and its analysis decides whether the controlled 36-run Track A (direct APIs, one scaffold) is bought next. Track B agents run with model, filesystem, shell, compiler, tests, documentation and the task statement only: web and search tools, MCP, skills, custom agents, subagents, external memory and global instructions are disabled where the product allows. Track B results never label models by capability; they describe how Aji behaves on three different agent stacks. Track B measures model + system prompt + context management + tool policy + compaction + agent heuristics together, so its results are never used as evidence for H4. Order (owner decision): the first experiment is Track B on existing subscriptions — a native dev-echo gate, then 2 tasks × 3 languages × 3 native agents × 1 run = 18 runs — and its analysis decides whether the controlled 36-run Track A (direct APIs, one scaffold) is bought next. Track B agents run with model, filesystem, shell, compiler, tests, documentation and the task statement only: web and search tools, MCP, skills, custom agents, subagents, external memory and global instructions are disabled where the product allows. Track B results never label models by capability; they describe how Aji behaves on three different agent stacks. Shell commands run without network in every agent. Track B reports success, time, tool calls and context, but no cost in dollars: on subscriptions there is no honest cost per solution, so H5 economics stays with Track A. The 18 cells run sequentially, in an order shuffled once at freeze time, each with a fresh HOME and workspace; nothing is changed until the last result, and observations go to a journal. The first question afterwards is vertical: does the same native agent become more reliable, or need less, moving from Rust/Zig to Aji/AIR — with the cheapest stack (GLM) as the earliest indicator of Model Capability Compression.
--- ---
+3 -3
View File
@@ -93,13 +93,13 @@ Evaluation runs alongside the phases; each stage starts when the language featur
| ID | Status | Task | Depends | Done when | | ID | Status | Task | Depends | Done when |
|---|---|---|---|---| |---|---|---|---|---|
| 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-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-2 | todo | (owner, outside this repository and outside the language developer's conversation) Private benchmark repository: a benchmark-authoring agent in a clean context designs the two smoke tasks from the brief in `docs/evaluation/benchmark-authoring.md`; later T01–T04; dev/validation/test split | — | evaluator hashes published; nothing hidden in this repository |
| 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-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 | | E0-4 | todo | Rust and Zig baseline solutions and pinned local documentation | E0-2 | baselines pass the hidden tests |
| E-C | todo | Model calibration: models labelled M1–M3 run 5–10 neutral coding tasks unrelated to Aji in `tools/eval`; classes assigned from scores; live `dev-echo` per model (protocol §2, §39a) | E0-3 | calibration report; model IDs, endpoints and reasoning modes frozen | | E-C | todo | Model calibration: models labelled M1–M3 run 5–10 neutral coding tasks unrelated to Aji in `tools/eval`; classes assigned from scores; live `dev-echo` per model (protocol §2, §39a) | E0-3 | calibration report; model IDs, endpoints and reasoning modes frozen |
| E-G | todo | Smoke gates: Rust, Zig and hand-written Aji references pass the frozen evaluators; task-statement and hidden-test review (protocol §39a) | E0-2, E0-4 | all gates pass | | E-G | todo | Gate before E-N (and later E-S): private tasks reviewed; evaluator, task and evaluator hashes frozen; Rust, Zig and Aji/AIR references written by separate clean agents pass; Aji commit, bundle, toolchains and docs frozen with `ajieval freeze` (checklist in `docs/evaluation/benchmark-authoring.md`) | E0-2, E0-4 | all gates pass |
| E-S | todo | Engineering smoke test, Track A: 2 families (binary/stream parser, concurrent bounded pipeline) × 3 languages × 3 models (M1–M3) × 2 runs = 36 runs on one Aji commit (protocol §39a); plan shape `docs/evaluation/smoke-plan.example.json`; failures classified by cause after the matrix, before any language change | E-C, E-G | harness, bundle sufficiency, accounting and traces verified | | E-S | todo | Engineering smoke test, Track A: 2 families (binary/stream parser, concurrent bounded pipeline) × 3 languages × 3 models (M1–M3) × 2 runs = 36 runs on one Aji commit (protocol §39a); plan shape `docs/evaluation/smoke-plan.example.json`; failures classified by cause after the matrix, before any language change | E-C, E-G | harness, bundle sufficiency, accounting and traces verified |
| E-N0 | done | Native dev-echo gate (Aji/AIR): Codex + `gpt-6.1-sol` (effort high), Claude Code + `claude-opus-5-5` (effort high), OpenCode + `zai-coding-plan/glm-5.3-flash` all accepted; versions and model IDs in the run records | E0-3 | `ajieval native` | | E-N0 | done | Native dev-echo gate (Aji/AIR): Codex + `gpt-6.1-sol` (effort high), Claude Code + `claude-opus-5-5` (effort high), OpenCode + `zai-coding-plan/glm-5.3-flash` all accepted; networkless shell for all three verified by `dev-netprobe`; context metrics (provider / cumulative / unique reference) | E0-3 | `ajieval native`, `ajieval freeze`, `ajieval journal` |
| E-N | todo | Track B native smoke, first experiment (owner decision): 2 tasks × 3 languages × 3 native agents (N1–N3) × 1 run = 18 runs on subscriptions (protocol §39b); never evidence for H4; plan shape `docs/evaluation/native-smoke-plan.example.json` | E-N0, E0-2, E-G | native-agent report; failures classified before any language change | | E-N | todo | Track B native smoke, first experiment (owner decision): 2 tasks × 3 languages × 3 native agents (N1–N3) × 1 run = 18 runs on subscriptions (protocol §39b); never evidence for H4; plan shape `docs/evaluation/native-smoke-plan.example.json` | E-N0, E0-2, E-G | native-agent report; failures classified before any language change |
| E-A | todo | Stage A pilot (condition `Aji/AIR`): T01–T04 families × Aji/Rust/Zig × 3 model classes × 3 runs = 108 runs (protocol §39); not headline evidence | E-S, basic Phase 3 | pilot report: effect size, broken tasks, cost, instrumentation | | E-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-B | todo | Stage B: T05–T07 | Phase 3 | stage report |
+52 -15
View File
@@ -13,7 +13,9 @@ import os
import shlex import shlex
import sys import sys
from . import languages, native, record, report, util import datetime
from . import freeze, languages, native, record, report, util
CATEGORIES = ["SPEC_UNDERSTANDING", "SYNTAX", "TYPE", "OWNERSHIP", "BORROW", "RESOURCE", "BOUNDS", "FUNCTIONAL", "CONCURRENCY", CATEGORIES = ["SPEC_UNDERSTANDING", "SYNTAX", "TYPE", "OWNERSHIP", "BORROW", "RESOURCE", "BOUNDS", "FUNCTIONAL", "CONCURRENCY",
"DEADLOCK", "ATOMIC_ORDERING", "PERFORMANCE", "BUDGET", "TIMEOUT", "AGENT_GAVE_UP", "TOOL_FAILURE"] "DEADLOCK", "ATOMIC_ORDERING", "PERFORMANCE", "BUDGET", "TIMEOUT", "AGENT_GAVE_UP", "TOOL_FAILURE"]
@@ -47,12 +49,21 @@ def cmd_native(a):
def cmd_matrix(a): def cmd_matrix(a):
"""Runs every cell of a plan; finished runs (a run.json with the same """Runs every cell of a plan sequentially; finished runs (a run.json with
task, language, model and seed) are skipped, so a plan can be resumed.""" the same task, language, model and seed) are skipped, so a plan can be
resumed. With a freeze file (`ajieval freeze`) the frozen state is
verified first and the cells run in the frozen random order."""
plan = util.read_json(a.plan) plan = util.read_json(a.plan)
base = os.path.dirname(os.path.abspath(a.plan)) base = os.path.dirname(os.path.abspath(a.plan))
out = os.path.join(base, plan.get("out", "runs")) out = os.path.join(base, plan.get("out", "runs"))
os.makedirs(out, exist_ok=True) os.makedirs(out, exist_ok=True)
if os.path.exists(freeze.freeze_path(a.plan)):
order = freeze.check(a.plan)["order"]
print(f"frozen plan: {len(order)} cells in frozen order", file=sys.stderr)
elif plan.get("require_freeze"):
raise SystemExit(f"{a.plan} requires a freeze file; run `ajieval freeze {a.plan}` first")
else:
order = freeze.cells(plan, base)
done = {(r["task"]["id"], r["language"]["name"], (r["agent"]["name"] + ":" + r["agent"]["requested_model"]) if r.get("track") == "B" else r["model"]["id"], r["seed"]) for r in report.load([out])} done = {(r["task"]["id"], r["language"]["name"], (r["agent"]["name"] + ":" + r["agent"]["requested_model"]) if r.get("track") == "B" else r["model"]["id"], r["seed"]) for r in report.load([out])}
pricing = load_pricing(os.path.join(base, plan["pricing"])) if plan.get("pricing") else None 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 evaluator = shlex.split(plan["evaluator"]) if plan.get("evaluator") else None
@@ -60,31 +71,46 @@ def cmd_matrix(a):
if evaluator: if evaluator:
evaluator[0] = rel(evaluator[0]) evaluator[0] = rel(evaluator[0])
hash_path = rel(plan["evaluator_hash_path"]) if plan.get("evaluator_hash_path") else None hash_path = rel(plan["evaluator_hash_path"]) if plan.get("evaluator_hash_path") else None
from . import task as task_mod models = {((m["agent"] + ":" + m["model"]) if m.get("agent") else m["model"]): m for m in plan["models"]}
for tdir in plan["tasks"]: for i, cell in enumerate(order):
tpath = os.path.join(base, tdir) if (cell["task_id"], cell["language"], cell["model"], cell["seed"]) in done:
tid = task_mod.Task(tpath).id
for lang in plan["languages"]:
for mdl in plan["models"]:
for seed in range(plan.get("runs", 1)):
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
if (tid, lang, key, seed) in done:
continue continue
print(f"run {tid} {lang} {key} seed {seed}", file=sys.stderr) mdl = models[cell["model"]]
tpath = os.path.join(base, cell["task"])
print(f"[{i + 1}/{len(order)}] {cell['task_id']} {cell['language']} {cell['model']} seed {cell['seed']}", file=sys.stderr)
if mdl.get("agent"): if mdl.get("agent"):
run_dir, rec = native.run_native(tpath, lang, mdl["agent"], mdl["model"], out, effort=mdl.get("effort"), seed=seed, run_dir, rec = native.run_native(tpath, cell["language"], mdl["agent"], mdl["model"], out, effort=mdl.get("effort"), seed=cell["seed"],
evaluator=evaluator, evaluator_hash_path=hash_path, label=mdl.get("label"), limits=plan.get("limits")) evaluator=evaluator, evaluator_hash_path=hash_path, label=mdl.get("label"), limits=plan.get("limits"))
else: else:
run_dir, rec = record.run_one( run_dir, rec = record.run_one(
tpath, lang, mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=seed, tpath, cell["language"], mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=cell["seed"],
sandbox_kind=plan.get("sandbox", "bwrap"), evaluator=evaluator, evaluator_hash_path=hash_path, 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"), pricing=pricing, base_url=mdl.get("base_url"), max_tokens=mdl.get("max_tokens", 8192), temperature=mdl.get("temperature"),
limits=plan.get("limits"), limits=plan.get("limits"),
provider_options={k: mdl[k] for k in ("extra", "key_env", "key_file", "token_param") if k in mdl}) provider_options={k: mdl[k] for k in ("extra", "key_env", "key_file", "token_param") if k in mdl})
rec["cell"] = {"index": i, "of": len(order)}
util.write_json(os.path.join(run_dir, "run.json"), rec)
print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr) print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr)
report.print_report([out]) report.print_report([out])
def cmd_freeze(a):
path, frozen = freeze.write(a.plan, a.order_seed)
print(json.dumps({"freeze": path, "cells": len(frozen["order"]), "order_seed": frozen["order_seed"], "aji_commit": frozen["state"]["aji_commit"]}))
def cmd_journal(a):
"""Appends an observation to the plan's journal. During a frozen
experiment problems are recorded here and acted on only afterwards."""
plan = util.read_json(a.plan)
out = os.path.join(os.path.dirname(os.path.abspath(a.plan)), plan.get("out", "runs"))
os.makedirs(out, exist_ok=True)
stamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
with open(os.path.join(out, "journal.md"), "a") as f:
f.write(f"- {stamp}" + (f" [{a.run}]" if a.run else "") + f" {a.text}\n")
print(os.path.join(out, "journal.md"))
def cmd_classify(a): def cmd_classify(a):
path = os.path.join(a.run, "run.json") path = os.path.join(a.run, "run.json")
rec = util.read_json(path) rec = util.read_json(path)
@@ -135,6 +161,17 @@ def main(argv=None):
m.add_argument("plan") m.add_argument("plan")
m.set_defaults(fn=cmd_matrix) m.set_defaults(fn=cmd_matrix)
fz = sub.add_parser("freeze", help="freeze a plan: record its state and a random cell order")
fz.add_argument("plan")
fz.add_argument("--order-seed", type=int)
fz.set_defaults(fn=cmd_freeze)
jn = sub.add_parser("journal", help="record an observation during a frozen experiment")
jn.add_argument("plan")
jn.add_argument("text")
jn.add_argument("--run")
jn.set_defaults(fn=cmd_journal)
rp = sub.add_parser("report", help="aggregate run records") rp = sub.add_parser("report", help="aggregate run records")
rp.add_argument("paths", nargs="+") rp.add_argument("paths", nargs="+")
rp.add_argument("--json", action="store_true") rp.add_argument("--json", action="store_true")
+116
View File
@@ -0,0 +1,116 @@
"""Context metrics (protocol §16), the same for both tracks.
provider_input_tokens what the model provider counted: input,
cached and uncached separately
cumulative_context_tokens the text returned to the agent through its
tool loop (every tool output, plus the task
message), counted each time it was returned
unique_reference_tokens the distinct documentation text the agent
actually saw: distinct lines in the outputs
of tool calls that touched /docs
reference_coverage for a single-file reference (the Aji Agent
Reference Bundle): the fraction of its
non-empty lines that appeared in those outputs
The gap between them shows where context is amplified: rereading the same
documentation, verbose tool output, or the provider resending history.
Tokens are counted with tiktoken `cl100k_base` when it is installed,
otherwise estimated as bytes / 4; the record says which.
"""
import json
import os
import re
from . import util
_PREFIX = re.compile(r"^\s*\d+\s*[:\t→│|]\s?")
def _tokenizer():
try:
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
return "cl100k_base", lambda s: len(enc.encode(s, disallowed_special=()))
except Exception:
return "estimate(bytes/4)", lambda s: util.estimate_tokens(len(s.encode()))
def _norm(line):
return _PREFIX.sub("", line).strip()
def tool_events_track_a(events_path):
"""(input text, output text) per tool call from a Track A event log."""
out = []
for line in open(events_path, encoding="utf-8"):
e = json.loads(line)
if e["event"] == "command":
out.append((e["command"], e.get("output") or ""))
elif e["event"] == "tool" and e["name"] != "run":
out.append((json.dumps(e.get("input")), e.get("output") or ""))
return out
def tool_events_native(agent_name, transcript_path):
"""(input text, output text) per tool call from a native CLI transcript."""
out = []
pending = {}
for line in open(transcript_path, encoding="utf-8", errors="replace"):
line = line.strip()
if not line.startswith("{"):
continue
try:
e = json.loads(line)
except json.JSONDecodeError:
continue
if agent_name == "codex":
item = e.get("item") or {}
if e.get("type") == "item.completed" and item.get("type") == "command_execution":
out.append((item.get("command") or "", item.get("aggregated_output") or ""))
elif agent_name == "claude":
msg = e.get("message") or {}
for b in msg.get("content", []) if isinstance(msg.get("content"), list) else []:
if b.get("type") == "tool_use":
pending[b.get("id")] = json.dumps(b.get("input"))
elif b.get("type") == "tool_result":
c = b.get("content")
text = c if isinstance(c, str) else "\n".join(x.get("text", "") for x in (c or []) if isinstance(x, dict))
out.append((pending.pop(b.get("tool_use_id"), ""), text))
elif agent_name == "opencode":
part = e.get("part") or {}
if e.get("type") == "tool_use":
st = part.get("state") or {}
out.append((json.dumps(st.get("input")), st.get("output") or ""))
return out
def metrics(tool_events, task_message, docs, provider):
"""`docs` is [(mount name, host path)]; `provider` holds input, output,
cached_input as counted by the provider (None when unknown)."""
name, count = _tokenizer()
cumulative = count(task_message) + sum(count(o) for _, o in tool_events)
seen = set()
for inp, outp in tool_events:
if "/docs" in inp:
for line in outp.splitlines():
n = _norm(line)
if n:
seen.add(n)
unique = count("\n".join(sorted(seen)))
coverage = None
files = [p for _, p in docs if os.path.isfile(p)]
if len(files) == 1 and len(docs) == 1:
with open(files[0], encoding="utf-8", errors="replace") as f:
ref = {_norm(x) for x in f.read().splitlines() if _norm(x)}
coverage = round(len(ref & seen) / len(ref), 4) if ref else None
inp, cached = provider.get("input"), provider.get("cached_input")
return {
"tokenizer": name,
"provider_input_tokens": {"total": inp, "cached": cached, "uncached": None if inp is None or cached is None else inp - cached, "output": provider.get("output")},
"cumulative_context_tokens": cumulative,
"unique_reference_tokens": unique,
"reference_coverage": coverage,
"tool_outputs": len(tool_events),
}
+139
View File
@@ -0,0 +1,139 @@
"""Freezing an experiment (protocol §39a, §39b).
`ajieval freeze PLAN.json` writes PLAN.freeze.json. It records everything
that must not change until the last run of the plan:
- the Aji commit (the repository must be clean), the `aji` binary and the
Agent Reference Bundle;
- each language profile, toolchain version and documentation hash;
- each native agent's CLI version and binary hash, and a fingerprint of
its configuration: written config, command line template, task
preamble, networkless shell wrapper;
- the harness commit, the task hashes and the evaluator hash;
- the cell order: every cell (task × language × model × run) shuffled
once with a recorded seed.
`ajieval matrix` refuses to run a plan whose freeze file no longer matches,
and runs the cells sequentially in the frozen order.
"""
import json
import os
import random
import shutil
import subprocess
import tempfile
from . import languages, native, task as task_mod, util
def _agent_fingerprint(mdl):
ag = native.AGENTS[mdl["agent"]]
home = tempfile.mkdtemp()
try:
config = ag.configure(home, mdl["model"], mdl.get("effort"))
finally:
shutil.rmtree(home, ignore_errors=True)
material = {
"config": config,
"argv": ag.argv(mdl["model"], mdl.get("effort"), "<task message>"),
"preamble": native.PREAMBLE,
"netless_wrapper": native.NETLESS_WRAPPER if ag.netless_shell else None,
"codex_features_off": native.CODEX_FEATURES_OFF if mdl["agent"] == "codex" else None,
"credentials": ag.credentials,
}
cli = os.path.realpath(shutil.which(ag.binary) or ag.binary)
return {
"cli_version": ag.version(),
"cli_hash": util.sha256_path(cli) if os.path.exists(cli) else None,
"configuration_hash": util.sha256_text(json.dumps(material, sort_keys=True)),
}
def snapshot(plan, base):
"""The current state of everything a plan depends on."""
commit = util.git_commit()
aji = os.path.join(util.REPO, "zig-out", "bin", "aji")
bundle = os.path.join(util.REPO, "zig-out", "agent", "reference-bundle.md")
langs = {}
for name in plan["languages"]:
prof = languages.load(name)
langs[name] = {
"profile_hash": prof["profile_hash"],
"toolchain": [v.get("output") for v in languages.versions(prof)],
"docs": {("/docs/" + n): util.sha256_path_cached(p) for n, p in languages.docs_mounts(prof)},
}
tasks = {}
for t in plan["tasks"]:
tk = task_mod.Task(os.path.join(base, t))
tasks[tk.id] = {"version": tk.version, "hash": tk.hash()}
evaluator = None
if plan.get("evaluator"):
ev = plan["evaluator"].split()[0]
ev = ev if os.path.isabs(ev) else os.path.join(base, ev)
hp = plan.get("evaluator_hash_path")
hp = (hp if os.path.isabs(hp) else os.path.join(base, hp)) if hp else ev
evaluator = util.sha256_path(hp)
models = {}
for mdl in plan["models"]:
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
models[key] = _agent_fingerprint(mdl) if mdl.get("agent") else {"provider": mdl["provider"], "options": {k: mdl.get(k) for k in ("extra", "base_url", "token_param", "max_tokens", "temperature")}}
return {
"aji_commit": commit,
"aji_binary": util.sha256_path(aji) if os.path.exists(aji) else None,
"agent_reference_bundle": util.sha256_path(bundle) if os.path.exists(bundle) else None,
"harness_commit": commit,
"languages": langs,
"tasks": tasks,
"evaluator": evaluator,
"models": models,
"limits": plan.get("limits"),
}
def cells(plan, base):
out = []
for t in plan["tasks"]:
tid = task_mod.Task(os.path.join(base, t)).id
for lang in plan["languages"]:
for mdl in plan["models"]:
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
for seed in range(plan.get("runs", 1)):
out.append({"task": t, "task_id": tid, "language": lang, "model": key, "seed": seed})
return out
def freeze_path(plan_path):
return os.path.splitext(plan_path)[0] + ".freeze.json"
def write(plan_path, order_seed=None):
plan = util.read_json(plan_path)
base = os.path.dirname(os.path.abspath(plan_path))
snap = snapshot(plan, base)
if snap["aji_commit"] is None or snap["aji_commit"].endswith("+dirty"):
raise SystemExit("freeze needs a clean, committed repository (no +dirty)")
seed = order_seed if order_seed is not None else random.SystemRandom().randrange(2 ** 32)
order = cells(plan, base)
random.Random(seed).shuffle(order)
frozen = {"schema": "aji-eval-freeze/1", "plan_hash": util.sha256_path(plan_path), "state": snap, "order_seed": seed, "order": order}
util.write_json(freeze_path(plan_path), frozen)
return freeze_path(plan_path), frozen
def check(plan_path):
"""Returns the frozen record, or exits naming what changed."""
path = freeze_path(plan_path)
frozen = util.read_json(path)
plan = util.read_json(plan_path)
base = os.path.dirname(os.path.abspath(plan_path))
problems = []
if util.sha256_path(plan_path) != frozen["plan_hash"]:
problems.append("plan file")
now = snapshot(plan, base)
for key, value in frozen["state"].items():
if now.get(key) != value:
problems.append(key)
if problems:
raise SystemExit(f"{plan_path}: frozen state changed ({', '.join(problems)}); a frozen experiment cannot continue")
return frozen
+51 -8
View File
@@ -14,9 +14,15 @@ its model backend; everything else is confined:
configuration written by the harness, so user-level skills, MCP configuration written by the harness, so user-level skills, MCP
servers, memory, custom agents and global instructions do not exist; servers, memory, custom agents and global instructions do not exist;
- neither the evaluator nor the Aji repository is visible. - neither the evaluator nor the Aji repository is visible.
Web and search tools, MCP and subagents are disabled where the CLI allows; Web and search tools, MCP and subagents are disabled where the CLI allows.
whether shell commands themselves have network depends on the CLI and is
recorded (`command_network`). Shell commands never have network. Codex runs them in its own
`workspace-write` sandbox. For Claude Code and OpenCode, `/usr/bin/bash`
and `/usr/bin/sh` inside the sandbox are wrappers that run every command
in a nested bubblewrap with a fresh, empty network namespace and no
resolver socket. The CLI process itself keeps the network to reach its
model backend, and every process a tool starts through a shell is
networkless.
""" """
import datetime import datetime
@@ -27,7 +33,7 @@ import subprocess
import sys import sys
import time import time
from . import __version__, agent, languages, record, task as task_mod, util from . import __version__, agent, context, languages, record, task as task_mod, util
PREAMBLE = """You are working alone in a fresh repository at /work (the current directory). PREAMBLE = """You are working alone in a fresh repository at /work (the current directory).
Implement the task below in the language named here. Use only the files in /work, the local Implement the task below in the language named here. Use only the files in /work, the local
@@ -49,7 +55,9 @@ class NativeAgent:
binary = "" binary = ""
# (host path relative to the real HOME, same path inside the sandbox HOME) # (host path relative to the real HOME, same path inside the sandbox HOME)
credentials = [] credentials = []
command_network = "allowed" command_network = "disabled (networkless shell wrapper)"
# Whether the harness must make the shell networkless itself.
netless_shell = True
def version(self): def version(self):
r = subprocess.run([self.binary, "--version"], capture_output=True, text=True, timeout=60) r = subprocess.run([self.binary, "--version"], capture_output=True, text=True, timeout=60)
@@ -93,6 +101,7 @@ class Codex(NativeAgent):
binary = "codex" binary = "codex"
credentials = [".codex/auth.json"] credentials = [".codex/auth.json"]
command_network = "disabled (Codex workspace-write sandbox)" command_network = "disabled (Codex workspace-write sandbox)"
netless_shell = False
def account_mode(self): def account_mode(self):
try: try:
@@ -142,7 +151,6 @@ class Claude(NativeAgent):
name = "claude" name = "claude"
binary = "claude" binary = "claude"
credentials = [".claude/.credentials.json"] credentials = [".claude/.credentials.json"]
command_network = "allowed (Claude Code does not restrict Bash network here)"
def account_mode(self): def account_mode(self):
p = os.path.expanduser("~/.claude/.credentials.json") p = os.path.expanduser("~/.claude/.credentials.json")
@@ -186,7 +194,6 @@ class OpenCode(NativeAgent):
name = "opencode" name = "opencode"
binary = "opencode" binary = "opencode"
credentials = [".local/share/opencode/auth.json"] credentials = [".local/share/opencode/auth.json"]
command_network = "allowed (OpenCode does not restrict shell network)"
def account_mode(self): def account_mode(self):
return "opencode provider credential (see model id prefix, e.g. zai-coding-plan = Z.AI Coding Plan)" return "opencode provider credential (see model id prefix, e.g. zai-coding-plan = Z.AI Coding Plan)"
@@ -233,6 +240,30 @@ def available():
return sorted(AGENTS) return sorted(AGENTS)
NETLESS_WRAPPER = """#!/opt/aji-real/{shell}
# Runs the command in a nested namespace without network (Track B, protocol §39b).
if [ -n "$AJI_NETLESS" ]; then exec /opt/aji-real/{shell} "$@"; fi
exec /usr/bin/bwrap --unshare-net --dev-bind / / --tmpfs /run/systemd/resolve --setenv AJI_NETLESS 1 /opt/aji-real/{shell} "$@"
"""
def netless_binds(run_dir):
"""bwrap arguments that replace the system shells by networkless wrappers.
Symlinks such as /usr/bin/sh -> bash are followed, so each real shell
binary is wrapped once, at its real path."""
d = os.path.join(run_dir, "netless")
os.makedirs(d, exist_ok=True)
out = []
for real in sorted({os.path.realpath("/usr/bin/" + s) for s in ("bash", "sh")}):
shell = os.path.basename(real)
path = os.path.join(d, shell)
with open(path, "w") as f:
f.write(NETLESS_WRAPPER.format(shell=shell))
os.chmod(path, 0o755)
out += ["--ro-bind", real, "/opt/aji-real/" + shell, "--ro-bind", path, real]
return out + ["--setenv", "SHELL", "/usr/bin/bash", "--setenv", "OPENCODE_DISABLE_LSP_DOWNLOAD", "true"]
def sandbox_argv(workspace, home, binds, path_dirs, docs, env): def sandbox_argv(workspace, home, binds, path_dirs, docs, env):
a = ["bwrap", "--unshare-all", "--share-net", "--die-with-parent", "--new-session"] a = ["bwrap", "--unshare-all", "--share-net", "--die-with-parent", "--new-session"]
for d in ("/usr", "/etc"): for d in ("/usr", "/etc"):
@@ -325,6 +356,17 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
sb = sandbox_argv(workspace, home, binds, path_dirs, docs, profile.get("env", {})) sb = sandbox_argv(workspace, home, binds, path_dirs, docs, profile.get("env", {}))
for src, dst in cred_binds: for src, dst in cred_binds:
sb[sb.index("--chdir"):sb.index("--chdir")] = ["--bind", src, dst] sb[sb.index("--chdir"):sb.index("--chdir")] = ["--bind", src, dst]
if ag.netless_shell:
# Binds go before --chdir; environment variables after --clearenv.
extra = netless_binds(run_dir)
triples = [extra[i:i + 3] for i in range(0, len(extra), 3)]
at = sb.index("--chdir")
for t in triples:
if t[0] == "--ro-bind":
sb[at:at] = t
at += 3
else:
sb += t
transcript = os.path.join(run_dir, "transcript.jsonl") transcript = os.path.join(run_dir, "transcript.jsonl")
started = datetime.datetime.now(datetime.timezone.utc).isoformat() started = datetime.datetime.now(datetime.timezone.utc).isoformat()
@@ -340,6 +382,7 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
facts = ag.parse(transcript) facts = ag.parse(transcript)
tokens = normalize_usage(facts.get("usage") or {}) tokens = normalize_usage(facts.get("usage") or {})
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens)
with open(os.path.join(run_dir, "patch.diff"), "w") as f: with open(os.path.join(run_dir, "patch.diff"), "w") as f:
f.write(diff_tree(pristine, workspace)) f.write(diff_tree(pristine, workspace))
verdict = record.evaluate(evaluator, workspace, lang_name, task.dir, lim["command_timeout"] * 4) if evaluator else None verdict = record.evaluate(evaluator, workspace, lang_name, task.dir, lim["command_timeout"] * 4) if evaluator else None
@@ -365,7 +408,7 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
"seed": seed, "seed": seed,
"metrics": {"elapsed_seconds": elapsed, "exit_code": code, "termination": termination, "tool_calls": facts.get("tool_calls"), "metrics": {"elapsed_seconds": elapsed, "exit_code": code, "termination": termination, "tool_calls": facts.get("tool_calls"),
"usage": facts.get("usage"), "agent_facts": {k: v for k, v in facts.items() if k not in ("usage", "tool_calls", "model")}, "usage": facts.get("usage"), "agent_facts": {k: v for k, v in facts.items() if k not in ("usage", "tool_calls", "model")},
"input_tokens": tokens["input"], "output_tokens": tokens["output"], "cached_input_tokens": tokens["cached_input"], "failed_verifier_cycles": None, "failed_test_cycles": None, "input_tokens": tokens["input"], "output_tokens": tokens["output"], "cached_input_tokens": tokens["cached_input"], "context": ctx, "failed_verifier_cycles": None, "failed_test_cycles": None,
"first_check_accepted": None, "first_build_accepted": None}, "first_check_accepted": None, "first_build_accepted": None},
"transcript": "transcript.jsonl", "transcript": "transcript.jsonl",
"patch": "patch.diff", "patch": "patch.diff",
+3 -1
View File
@@ -9,7 +9,7 @@ import subprocess
import sys import sys
import time import time
from . import __version__, agent, languages, providers, sandbox, task as task_mod, util from . import __version__, agent, context, languages, providers, sandbox, task as task_mod, util
class Recorder: class Recorder:
@@ -104,6 +104,8 @@ def run_one(task_dir, lang_name, provider_name, model, out_dir, model_class=None
for key in ("files_opened",): for key in ("files_opened",):
metrics[key + "_count"] = len(metrics[key]) metrics[key + "_count"] = len(metrics[key])
metrics["documentation_tokens_estimate"] = util.estimate_tokens(metrics["documentation_bytes_read"]) metrics["documentation_tokens_estimate"] = util.estimate_tokens(metrics["documentation_bytes_read"])
metrics["context"] = context.metrics(context.tool_events_track_a(os.path.join(run_dir, "events.jsonl")), message, docs,
{"input": metrics["input_tokens"], "output": metrics["output_tokens"], "cached_input": metrics["cached_input_tokens"]})
metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"]) metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"])
verdict = first_verdict = None verdict = first_verdict = None
+13 -2
View File
@@ -45,6 +45,11 @@ def aggregate(runs):
"verified_success_rate": round(len(acc) / len(rs), 3), "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 if r["metrics"].get("failed_verifier_cycles") is not None]), "repair_cycles_accepted": mean([r["metrics"]["failed_verifier_cycles"] + r["metrics"]["failed_test_cycles"] for r in acc if r["metrics"].get("failed_verifier_cycles") is not None]),
"context_tokens_mean": mean([r["metrics"].get("input_tokens") for r in rs]), "context_tokens_mean": mean([r["metrics"].get("input_tokens") for r in rs]),
"uncached_input_tokens_mean": mean([((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]),
"cumulative_context_tokens_mean": mean([(r["metrics"].get("context") or {}).get("cumulative_context_tokens") for r in rs]),
"unique_reference_tokens_mean": mean([(r["metrics"].get("context") or {}).get("unique_reference_tokens") for r in rs]),
"reference_coverage_mean": mean([(r["metrics"].get("context") or {}).get("reference_coverage") for r in rs]),
"elapsed_seconds_mean": mean([r["metrics"].get("elapsed_seconds") for r in rs]),
"output_tokens_mean": mean([r["metrics"].get("output_tokens") for r in rs]), "output_tokens_mean": mean([r["metrics"].get("output_tokens") for r in rs]),
"tool_calls_mean": mean([r["metrics"]["tool_calls"] for r in rs]), "tool_calls_mean": mean([r["metrics"]["tool_calls"] for r in rs]),
"first_check_accepted": sum(1 for r in rs if r["metrics"].get("first_check_accepted") or r["metrics"].get("first_build_accepted")), "first_check_accepted": sum(1 for r in rs if r["metrics"].get("first_check_accepted") or r["metrics"].get("first_build_accepted")),
@@ -57,10 +62,16 @@ def aggregate(runs):
def markdown(rows): def markdown(rows):
head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "context tokens", "cost/correct USD", "unclassified failures"] head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "tool calls",
"provider input (uncached)", "cumulative context", "unique reference", "ref. coverage", "seconds", "cost/correct USD", "unclassified failures"]
out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)] out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
for r in rows: 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"]]) + " |") # Track B runs on subscriptions: no honest cost per solution (protocol §39b).
cost = "n/a (Track B)" if r["class"].startswith("B:") else r["cost_per_correct_usd"]
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["tool_calls_mean"], f"{r['context_tokens_mean']} ({r['uncached_input_tokens_mean']})", r["cumulative_context_tokens_mean"],
r["unique_reference_tokens_mean"], r["reference_coverage_mean"], r["elapsed_seconds_mean"], cost, r["unclassified_failures"]]) + " |")
return "\n".join(out) return "\n".join(out)
+18
View File
@@ -114,6 +114,24 @@ class RunTest(unittest.TestCase):
self.assertAlmostEqual(rec["cost_usd"], (m["input_tokens"] + 10 * m["output_tokens"]) / 1e6, places=6) self.assertAlmostEqual(rec["cost_usd"], (m["input_tokens"] + 10 * m["output_tokens"]) / 1e6, places=6)
class FreezeTest(unittest.TestCase):
@unittest.skipIf((util.git_commit() or "+dirty").endswith("+dirty"), "repository has uncommitted changes")
def test_freeze_order_and_check(self):
from ajieval import freeze
d = tempfile.mkdtemp()
plan = {"tasks": [TASK], "languages": ["rust", "zig"], "runs": 2, "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)
_, frozen = freeze.write(path, order_seed=7)
self.assertEqual(len(frozen["order"]), 4)
self.assertEqual(freeze.check(path)["order"], frozen["order"])
plan["runs"] = 3
util.write_json(path, plan)
with self.assertRaises(SystemExit):
freeze.check(path)
class MatrixTest(unittest.TestCase): class MatrixTest(unittest.TestCase):
def test_resume(self): def test_resume(self):
d = tempfile.mkdtemp() d = tempfile.mkdtemp()