P6A-8: Source Reference Bundle and harness profile aji_source

- source bundle: a /docs directory with QUICK.md (Quick Reference plus a
  where-to-read table), language/*.md, diagnostics/errors.md and the AIR
  bundle only under air/; built from docs/agent/source-bundle.txt
  (> output files, @manifest includes) by zig build agent-reference
- Quick Reference examples are checked: every aji block must be an
  excerpt of a conformance program in tests/conformance/source/quickref
  (zig build test fails otherwise); QR fixes found by the check
  (mut d = data, region not auto-borrowed, statement/borrow blocks that
  could not verify, io_error match)
- frontend: task.*/channel.*/mutex.* are not-yet-implemented, not E7006
- aji lower --stats: mechanical_air_eliminated_raw and _normalized (each
  byte-string materialization counted as one constant; spec 15 §11)
- harness: profile aji_source (doc_groups), per-file and per-group docs
  metrics on distinctive lines, profile columns (tool calls, lowered AIR
  raw/normalized, docs files read, IR-form and type-mismatch counts),
  dev-echo aji_source variant, scripted run and test, source token report
- plan: P6A-8 done, P6A-9 criteria; Q-021/Q-022 resolved; unsafe block
  deferred
This commit is contained in:
dev committed 2026-10-05 13:16:51 +03:00
1 parent 61be766634
commit 3e2d9b63a7
35 files changed
+1170 -106

No files matched your search

+83 -2
View File
@@ -11,6 +11,17 @@
reference_coverage for a single-file reference (the Aji Agent
Reference Bundle): the fraction of its
non-empty lines that appeared in those outputs
docs for a directory of documentation (the Source
Reference Bundle), per file and per group of
the profile's `doc_groups`:
<group>_tokens size of the group (e.g. quick_reference_tokens,
source_docs_tokens, air_docs_tokens)
full_source_docs_tokens every group except air_docs
read_tokens_by_group tokens of the group's lines the agent saw
coverage_by_section per file: fraction of its distinctive lines
(in no other file of the mount) seen
files_opened files whose /docs path occurs in a tool input
unique_docs_read how many files were opened
The gap between them shows where context is amplified: rereading the same
documentation, verbose tool output, or the provider resending history.
@@ -86,9 +97,76 @@ def tool_events_native(agent_name, transcript_path):
return out
def metrics(tool_events, task_message, docs, provider):
def _doc_files(docs):
"""[(path under /docs, host path)] of every file in the mounts."""
out = []
for name, p in docs:
if os.path.isfile(p):
out.append((name or os.path.basename(p), p))
continue
for d, _, files in os.walk(p):
for f in sorted(files):
hp = os.path.join(d, f)
rel = os.path.relpath(hp, p)
out.append((os.path.join(name, rel) if name else rel, hp))
return sorted(out)
def _group_of(rel, groups):
for g, prefixes in groups.items():
for pre in prefixes:
if rel == pre or (pre.endswith("/") and rel.startswith(pre)):
return g
return "other"
def doc_metrics(tool_events, docs, groups, seen, count):
"""Per-file and per-group reading of a documentation directory.
Only distinctive lines count: a line contributes to a file's coverage
only if no other file in the mount contains it, and to a group's read
tokens only if every file containing it is in that group. Table rules,
fences and sections copied into several files (the error-code table is
in diagnostics/ and in air/) would otherwise be credited to files the
agent never opened."""
files = _doc_files(docs)
inputs = "\n".join(i for i, _ in tool_events)
texts, owners = {}, {}
for rel, hp in files:
with open(hp, encoding="utf-8", errors="replace") as f:
texts[rel] = f.read()
for x in {_norm(x) for x in texts[rel].splitlines() if _norm(x)}:
owners.setdefault(x, set()).add(rel)
own = {}
for x, fs in owners.items():
if len(fs) == 1:
own.setdefault(next(iter(fs)), set()).add(x)
coverage, opened, size, read_lines = {}, [], {}, {}
for rel, _ in files:
mine = own.get(rel, set())
coverage[rel] = round(len(mine & seen) / len(mine), 4) if mine else 0.0
if "/docs/" + rel in inputs:
opened.append(rel)
g = _group_of(rel, groups)
size[g] = size.get(g, 0) + count(texts[rel])
read_lines.setdefault(g, set())
for x in seen:
gs = {_group_of(f, groups) for f in owners.get(x, ())}
if len(gs) == 1:
read_lines[gs.pop()].add(x)
out = {f"{g}_tokens": n for g, n in sorted(size.items())}
out["full_source_docs_tokens"] = sum(n for g, n in size.items() if g != "air_docs")
out["read_tokens_by_group"] = {g: (count("\n".join(sorted(ls))) if ls else 0) for g, ls in sorted(read_lines.items())}
out["coverage_by_section"] = coverage
out["files_opened"] = opened
out["unique_docs_read"] = len(opened)
return out
def metrics(tool_events, task_message, docs, provider, groups=None):
"""`docs` is [(mount name, host path)]; `provider` holds input, output,
cached_input as counted by the provider (None when unknown)."""
cached_input as counted by the provider (None when unknown); `groups` is
the profile's `doc_groups` ({name: [file or "dir/" prefix]})."""
name, count = _tokenizer()
cumulative = count(task_message) + sum(count(o) for _, o in tool_events)
seen = set()
@@ -106,6 +184,8 @@ def metrics(tool_events, task_message, docs, provider):
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")
dirs = [p for _, p in docs if os.path.isdir(p)]
extra = {"docs": doc_metrics(tool_events, docs, groups or {}, seen, count)} if dirs else {}
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")},
@@ -113,4 +193,5 @@ def metrics(tool_events, task_message, docs, provider):
"unique_reference_tokens": unique,
"reference_coverage": coverage,
"tool_outputs": len(tool_events),
**extra,
}
+1 -1
View File
@@ -451,7 +451,7 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
facts = ag.parse(transcript)
tokens = normalize_usage(facts.get("usage") or {})
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens)
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens, profile.get("doc_groups"))
cyc = cycles(profile, lang.get("test"), command_events(agent_name, transcript))
with open(os.path.join(run_dir, "patch.diff"), "w") as f:
f.write(diff_tree(pristine, workspace))
+2 -1
View File
@@ -129,7 +129,8 @@ def run_one(task_dir, lang_name, provider_name, model, out_dir, model_class=None
metrics[key + "_count"] = len(metrics[key])
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"]})
{"input": metrics["input_tokens"], "output": metrics["output_tokens"], "cached_input": metrics["cached_input_tokens"]},
profile.get("doc_groups"))
metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"])
verdict = first_verdict = None
+39 -5
View File
@@ -167,7 +167,7 @@ def _diagnostic_codes(r, run_dir):
outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l]
lang = r["language"]["name"]
for o in outputs:
if lang == "aji_air":
if lang in ("aji_air", "aji_source"):
counts.update(re.findall(r'"code":"([ET]\d{4})"', o))
elif lang == "rust":
counts.update(re.findall(r"error\[(E\d{4})\]", o))
@@ -177,14 +177,43 @@ def _diagnostic_codes(r, run_dir):
return dict(counts.most_common())
# Diagnostics about the textual form of AIR (syntax, names, module header,
# SSA, CFG): the classes the source frontend is meant to remove. Type
# mismatches (E1001 from AIR, E7005 from source) are semantic and counted
# separately, so relabeling cannot make the IR-form count look better.
IR_FORM = {"E0001", "E0002", "E0003", "E0004", "E0005", "E0006", "E5001", "E5002"}
TYPE_MISMATCH = {"E1001", "E7005"}
def _lowered_size(run_dir):
"""`aji lower --stats` summed over the workspace's .aji files: raw and
normalized lowered AIR bytes (spec 15 §11); None when nothing lowers."""
import subprocess
aji = os.path.join(util.REPO, "zig-out", "bin", "aji")
raw = norm = 0
found = False
for root, dirs, names in os.walk(os.path.join(run_dir, "workspace")):
dirs[:] = [d for d in dirs if d not in ("zig-out", ".zig-cache", ".git")]
for n in names:
if not n.endswith(".aji"):
continue
r = subprocess.run([aji, "lower", "--stats", os.path.join(root, n)], capture_output=True, text=True)
if r.returncode != 0:
continue
st = json.loads(r.stdout)
raw, norm, found = raw + st["air_bytes"], norm + st["air_bytes_normalized"], True
return (raw, norm) if found else None
def profile(paths):
"""Per-run cost profile for failure and cost analysis (protocol §27,
§38): termination, output tokens, solution size and diagnostic codes.
Shareable: numbers and diagnostic codes only."""
from . import languages
out = ["| task | language | agent | termination | output tokens | source files / lines / bytes | diagnostic codes (count) |",
"|---|---|---|---|---|---|---|"]
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) |",
"|---|---|---|---|---|---|---|---|---|---|---|---|"]
for p in paths:
for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)):
if "/superseded/" in f:
@@ -195,6 +224,11 @@ def profile(paths):
files, lines, nbytes = _source_size(d, exts)
codes = _diagnostic_codes(r, d)
m = r["metrics"]
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | "
f"{files} / {lines} / {nbytes} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
lowered = _lowered_size(d) if r["language"]["name"] == "aji_source" else None
docs = (m.get("context") or {}).get("docs") or {}
ir = sum(v for k, v in codes.items() if k in IR_FORM)
ty = sum(v for k, v in codes.items() if k in TYPE_MISMATCH)
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | {m.get('tool_calls')} | "
f"{files} / {lines} / {nbytes} | {f'{lowered[0]} / {lowered[1]}' if lowered else '-'} | "
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
return "\n".join(out)
+38
View File
@@ -0,0 +1,38 @@
{
"name": "aji_source",
"display": "Aji (condition Aji/source: .aji source language 0.1)",
"toolchain": {
"binaries": [
"${REPO}/zig-out/bin/aji"
],
"version": [
[
"${REPO}/zig-out/bin/aji",
"features"
]
]
},
"docs": {
"env": "AJI_EVAL_AJI_SOURCE_DOCS",
"default": "${REPO}/zig-out/agent/source"
},
"doc_groups": {
"quick_reference": ["QUICK.md"],
"source_docs": ["language/", "diagnostics/"],
"air_docs": ["air/"]
},
"source_extensions": [
".aji"
],
"instructions": "Language: Aji, written as `.aji` source (Aji source language 0.1).\nToolchain: `aji check FILE.aji` verifies a module and prints diagnostics as JSON lines that point at your source; `aji run [--grant P=KIND[:SCOPE]]... [--stdin TEXT] FILE.aji` verifies and runs `main` in the deterministic profile and prints one JSON run record; `aji --help` lists all commands.\nDocumentation: /docs (read-only). Start with /docs/QUICK.md: it covers most programs and says which file under /docs/language or /docs/diagnostics to open for details. /docs/air is the reference for AIR, the language `.aji` lowers to; you do not need it to write `.aji`.",
"classify": {
"check": [
"aji check"
],
"build": [],
"test": [
"aji run"
]
},
"diagnostic_pattern": "\"severity\":\"error\""
}
+63
View File
@@ -0,0 +1,63 @@
[
[
{
"text": "Reading the interface."
},
{
"tool": "read_file",
"input": {
"path": "README.md"
}
}
],
[
{
"tool": "read_file",
"input": {
"path": "/docs/QUICK.md"
}
}
],
[
{
"tool": "write_file",
"input": {
"path": "main.aji",
"content": "broken"
}
}
],
[
{
"tool": "run",
"input": {
"command": "aji check main.aji"
}
}
],
[
{
"tool": "write_file",
"input": {
"path": "main.aji",
"content": "module demo.echo\n\nfn main(input: cap<io.read>, out: cap<io.write>) -> void\neffects [io.read, io.write]\n{\n var buf: [u8; 64] = zero;\n loop {\n let n = io.stdin_read(input, mut buf) or trap;\n if n == 0 { return; }\n io.stdout_write(out, ref buf[0..n]) or trap;\n }\n}\n"
}
}
],
[
{
"tool": "run",
"input": {
"command": "sh test.sh"
}
}
],
[
{
"tool": "finish",
"input": {
"summary": "done"
}
}
]
]
+15
View File
@@ -102,6 +102,21 @@ class RunTest(unittest.TestCase):
self.assertEqual(len(rows), len(languages.available()))
self.assertTrue(all(r["verified_success_rate"] == 1.0 for r in rows))
@unittest.skipUnless(SANDBOX == "bwrap", "bubblewrap unavailable")
def test_source_docs_metrics(self):
# The Source Reference Bundle is a directory: reading is measured per file and per group.
_, rec = self.run_lang("aji_source")
self.assertTrue(rec["accepted"], rec["verdict"])
d = rec["metrics"]["context"]["docs"]
self.assertEqual(d["files_opened"], ["QUICK.md"])
self.assertEqual(d["unique_docs_read"], 1)
self.assertGreater(d["coverage_by_section"]["QUICK.md"], 0.9)
self.assertEqual(d["coverage_by_section"]["air/reference.md"], 0.0)
for g in ("quick_reference_tokens", "source_docs_tokens", "air_docs_tokens", "full_source_docs_tokens"):
self.assertGreater(d[g], 0)
self.assertEqual(d["full_source_docs_tokens"], d["quick_reference_tokens"] + d["source_docs_tokens"])
self.assertEqual(d["read_tokens_by_group"]["air_docs"], 0)
def test_tool_budget(self):
_, rec = self.run_lang("aji_air", limits={"tool_calls": 3})
self.assertEqual(rec["metrics"]["termination"], "budget_tool_calls")