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

+242 -49
View File
@@ -1,86 +1,160 @@
//! Builds the Agent Reference Bundle (spec 14 §3.7) from docs/agent/bundle.txt
//! and reports its size. Deterministic: same sources, same bytes.
//! Builds the Agent Reference Bundles (spec 14 §3.7) and reports their size.
//! Deterministic: same sources, same bytes.
//!
//! docs/agent/bundle.txt → <out>/reference-bundle.md, <out>/report.json
//! (condition Aji/AIR: one file)
//! docs/agent/source-bundle.txt → <out>/source/… , <out>/source-report.json
//! (condition Aji/source: a directory with
//! QUICK.md as the front door)
//!
//! Every ```aji block of the Quick Reference must be an excerpt of a program
//! in tests/conformance/source/quickref/ (`…` matches anything), so the
//! examples an agent copies are parts of programs the conformance suite
//! checks. `--check` runs only that check.
//!
//! usage: aji-agent-bundle <repo root> <output dir>
//! writes <output dir>/reference-bundle.md and <output dir>/report.json
//! aji-agent-bundle --check <repo root>
const std = @import("std");
const aji = @import("aji");
const Error = error{ BadManifest, SectionNotFound };
const quick_reference = "docs/agent/quick-reference.md";
const quickref_programs = "tests/conformance/source/quickref";
pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();
const io = init.io;
const args = try init.minimal.args.toSlice(arena);
if (args.len == 3 and std.mem.eql(u8, args[1], "--check")) {
const root = try std.Io.Dir.cwd().openDir(io, args[2], .{ .iterate = true });
try checkQuickReference(arena, io, root);
return;
}
if (args.len != 3) {
std.debug.print("usage: aji-agent-bundle <repo root> <output dir>\n", .{});
std.debug.print("usage: aji-agent-bundle <repo root> <output dir> | --check <repo root>\n", .{});
std.process.exit(2);
}
const root = try std.Io.Dir.cwd().openDir(io, args[1], .{});
const manifest = try root.readFileAlloc(io, "docs/agent/bundle.txt", arena, .limited(1 << 20));
const root = try std.Io.Dir.cwd().openDir(io, args[1], .{ .iterate = true });
try checkQuickReference(arena, io, root);
const out_dir = try std.Io.Dir.cwd().createDirPathOpen(io, args[2], .{});
var bundle: std.ArrayList(u8) = .empty;
var files: std.ArrayList([]const u8) = .empty;
// Condition Aji/AIR: one file.
const air = try build(arena, io, root, "docs/agent/bundle.txt");
const air_text = air[0].text;
try out_dir.writeFile(io, .{ .sub_path = "reference-bundle.md", .data = air_text });
var report: std.Io.Writer.Allocating = .init(arena);
var s: std.json.Stringify = .{ .writer = &report.writer, .options = .{ .whitespace = .indent_2 } };
const m = measure(air_text);
try s.write(.{
.language = "aji",
.air = aji.air.format_version,
.phase = aji.implemented_phase,
.files = air[0].sources,
.sections = air[0].sections,
.bytes = m.bytes,
.lines = m.lines,
.words = m.words,
});
try report.writer.writeByte('\n');
try out_dir.writeFile(io, .{ .sub_path = "report.json", .data = report.written() });
// Condition Aji/source: a directory. Rebuilt from scratch so a file
// dropped from the manifest does not linger.
out_dir.deleteTree(io, "source") catch {};
const src_dir = try out_dir.createDirPathOpen(io, "source", .{});
const files = try build(arena, io, root, "docs/agent/source-bundle.txt");
var src_report: std.Io.Writer.Allocating = .init(arena);
var rs: std.json.Stringify = .{ .writer = &src_report.writer, .options = .{ .whitespace = .indent_2 } };
try rs.beginObject();
try rs.objectField("files");
try rs.beginArray();
for (files) |f| {
if (std.fs.path.dirname(f.path)) |d| _ = try src_dir.createDirPathOpen(io, d, .{});
try src_dir.writeFile(io, .{ .sub_path = f.path, .data = f.text });
const fm = measure(f.text);
try rs.write(.{ .path = f.path, .sections = f.sections, .bytes = fm.bytes, .lines = fm.lines, .words = fm.words });
}
try rs.endArray();
try rs.endObject();
try src_report.writer.writeByte('\n');
try out_dir.writeFile(io, .{ .sub_path = "source-report.json", .data = src_report.written() });
var stdout_buf: [256]u8 = undefined;
var fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf);
try fw.interface.writeAll(report.written());
try fw.interface.flush();
}
const Measure = struct { bytes: usize, lines: usize, words: usize };
fn measure(text: []const u8) Measure {
var lines: usize = 0;
for (text) |c| lines += @intFromBool(c == '\n');
var words: usize = 0;
var it = std.mem.tokenizeAny(u8, text, " \t\r\n");
while (it.next()) |_| words += 1;
return .{ .bytes = text.len, .lines = lines, .words = words };
}
const OutFile = struct { path: []const u8, text: []const u8, sections: usize, sources: usize };
/// Builds the files of a manifest. Entries:
/// > <output path> starts the next output file (without one,
/// the manifest has a single unnamed output)
/// <path> the whole file
/// <path> :: <heading prefix> one Markdown section
/// @<manifest> the single output of another manifest
fn build(arena: std.mem.Allocator, io: std.Io, root: std.Io.Dir, manifest_path: []const u8) ![]const OutFile {
const manifest = try root.readFileAlloc(io, manifest_path, arena, .limited(1 << 20));
var out: std.ArrayList(OutFile) = .empty;
var text: std.ArrayList(u8) = .empty;
var sources: std.ArrayList([]const u8) = .empty;
var sections: usize = 0;
var current: ?[]const u8 = null;
var lines = std.mem.splitScalar(u8, manifest, '\n');
var line_no: usize = 0;
while (lines.next()) |raw| {
line_no += 1;
const line = std.mem.trim(u8, raw, " \t\r");
if (line.len == 0 or line[0] == '#') continue;
if (line[0] == '>') {
if (current) |c| try out.append(arena, .{ .path = c, .text = text.items, .sections = sections, .sources = sources.items.len });
current = std.mem.trim(u8, line[1..], " ");
text = .empty;
sources = .empty;
sections = 0;
continue;
}
if (line[0] == '@') {
const inner = try build(arena, io, root, line[1..]);
try text.appendSlice(arena, inner[0].text);
sections += inner[0].sections;
continue;
}
var path = line;
var heading: ?[]const u8 = null;
if (std.mem.indexOf(u8, line, " :: ")) |sep| {
path = line[0..sep];
heading = line[sep + 4 ..];
}
const text = root.readFileAlloc(io, path, arena, .limited(16 << 20)) catch |err| {
std.debug.print("bundle.txt:{d}: cannot read {s}: {t}\n", .{ line_no, path, err });
const file = root.readFileAlloc(io, path, arena, .limited(16 << 20)) catch |err| {
std.debug.print("{s}:{d}: cannot read {s}: {t}\n", .{ manifest_path, line_no, path, err });
std.process.exit(1);
};
const part = if (heading) |h| section(text, h) orelse {
std.debug.print("bundle.txt:{d}: no heading starting with \"{s}\" in {s}\n", .{ line_no, h, path });
const part = if (heading) |h| section(file, h) orelse {
std.debug.print("{s}:{d}: no heading starting with \"{s}\" in {s}\n", .{ manifest_path, line_no, h, path });
std.process.exit(1);
} else text;
try bundle.print(arena, "<!-- source: {s}{s}{s} -->\n", .{ path, if (heading != null) " :: " else "", heading orelse "" });
try bundle.appendSlice(arena, std.mem.trimEnd(u8, part, "\n"));
try bundle.appendSlice(arena, "\n\n");
} else file;
try text.print(arena, "<!-- source: {s}{s}{s} -->\n", .{ path, if (heading != null) " :: " else "", heading orelse "" });
try text.appendSlice(arena, std.mem.trimEnd(u8, part, "\n"));
try text.appendSlice(arena, "\n\n");
sections += 1;
var known = false;
for (files.items) |f| known = known or std.mem.eql(u8, f, path);
if (!known) try files.append(arena, path);
for (sources.items) |f| known = known or std.mem.eql(u8, f, path);
if (!known) try sources.append(arena, path);
}
const text = bundle.items;
var line_count: usize = 0;
for (text) |c| line_count += @intFromBool(c == '\n');
var words: usize = 0;
var it = std.mem.tokenizeAny(u8, text, " \t\r\n");
while (it.next()) |_| words += 1;
const out_dir = try std.Io.Dir.cwd().createDirPathOpen(io, args[2], .{});
try out_dir.writeFile(io, .{ .sub_path = "reference-bundle.md", .data = text });
var report: std.Io.Writer.Allocating = .init(arena);
var s: std.json.Stringify = .{ .writer = &report.writer, .options = .{ .whitespace = .indent_2 } };
try s.write(.{
.language = "aji",
.air = aji.air.format_version,
.phase = aji.implemented_phase,
.files = files.items.len,
.sections = sections,
.bytes = text.len,
.lines = line_count,
.words = words,
});
try report.writer.writeByte('\n');
try out_dir.writeFile(io, .{ .sub_path = "report.json", .data = report.written() });
var stdout_buf: [256]u8 = undefined;
var fw: std.Io.File.Writer = .init(.stdout(), io, &stdout_buf);
try fw.interface.writeAll(report.written());
try fw.interface.flush();
try out.append(arena, .{ .path = current orelse "", .text = text.items, .sections = sections, .sources = sources.items.len });
return out.items;
}
/// The Markdown section whose heading starts with `prefix`, up to the next
@@ -110,6 +184,115 @@ fn section(text: []const u8, prefix: []const u8) ?[]const u8 {
return if (start) |st| text[st..] else null;
}
// ---------------------------------------------------------------- Quick Reference examples
/// Fails the build when a ```aji block of the Quick Reference is not an
/// excerpt of a program in `quickref_programs`.
fn checkQuickReference(arena: std.mem.Allocator, io: std.Io, root: std.Io.Dir) !void {
const qr = try root.readFileAlloc(io, quick_reference, arena, .limited(1 << 20));
var programs: std.ArrayList(struct { name: []const u8, text: []const u8 }) = .empty;
var dir = try root.openDir(io, quickref_programs, .{ .iterate = true });
var it = dir.iterate();
while (try it.next(io)) |e| {
if (e.kind != .file or !std.mem.endsWith(u8, e.name, ".aji")) continue;
const t = try dir.readFileAlloc(io, e.name, arena, .limited(1 << 20));
try programs.append(arena, .{ .name = try arena.dupe(u8, e.name), .text = try normalize(arena, t) });
}
var failed = false;
const blocks = try codeBlocks(arena, qr);
for (blocks.items) |b| {
const n = try normalize(arena, b.text);
const found = for (programs.items) |p| {
if (excerptOf(n, p.text)) break true;
} else false;
if (!found) {
std.debug.print("{s}:{d}: this ```aji block is not an excerpt of any program in {s}/\n", .{ quick_reference, b.line, quickref_programs });
failed = true;
}
}
if (failed) std.process.exit(1);
}
const CodeBlock = struct { line: usize, text: []const u8 };
fn codeBlocks(arena: std.mem.Allocator, md: []const u8) !std.ArrayList(CodeBlock) {
var out: std.ArrayList(CodeBlock) = .empty;
var lines = std.mem.splitScalar(u8, md, '\n');
var n: usize = 0;
var start: ?usize = null;
var body: std.ArrayList(u8) = .empty;
while (lines.next()) |raw| {
n += 1;
const l = std.mem.trim(u8, raw, " ");
if (start == null) {
if (std.mem.eql(u8, l, "```aji")) {
start = n;
body = .empty;
}
} else if (std.mem.eql(u8, l, "```")) {
try out.append(arena, .{ .line = start.?, .text = body.items });
start = null;
} else {
try body.appendSlice(arena, raw);
try body.append(arena, '\n');
}
}
return out;
}
/// `//` comments removed (outside byte strings), every run of whitespace
/// one space.
fn normalize(arena: std.mem.Allocator, t: []const u8) ![]const u8 {
var out: std.ArrayList(u8) = .empty;
var i: usize = 0;
var in_bytes = false;
var space = false;
while (i < t.len) : (i += 1) {
const c = t[i];
if (in_bytes) {
try out.append(arena, c);
if (c == '\\' and i + 1 < t.len) {
i += 1;
try out.append(arena, t[i]);
} else if (c == '"') in_bytes = false;
continue;
}
if (c == '/' and i + 1 < t.len and t[i + 1] == '/') {
while (i < t.len and t[i] != '\n') i += 1;
space = true;
continue;
}
if (c == ' ' or c == '\t' or c == '\n' or c == '\r') {
space = true;
continue;
}
if (space and out.items.len != 0) try out.append(arena, ' ');
space = false;
if (c == 'b' and i + 1 < t.len and t[i + 1] == '"') {
try out.appendSlice(arena, "b\"");
i += 1;
in_bytes = true;
continue;
}
try out.append(arena, c);
}
return out.items;
}
/// Whether `fragment` occurs in `program`, with every `…` in the fragment
/// matching any text (pieces in order, the first and last anywhere).
fn excerptOf(fragment: []const u8, program: []const u8) bool {
var pieces = std.mem.splitSequence(u8, fragment, "…");
var pos: usize = 0;
while (pieces.next()) |raw| {
const piece = std.mem.trim(u8, raw, " ");
if (piece.len == 0) continue;
const at = std.mem.indexOfPos(u8, program, pos, piece) orelse return false;
pos = at + piece.len;
}
return true;
}
test section {
const doc = "# T\n## 1. A\na\n### 1.1 B\nb\n## 2. C\nc\n";
try std.testing.expectEqualStrings("## 1. A\na\n### 1.1 B\nb\n", section(doc, "## 1.").?);
@@ -119,3 +302,13 @@ test section {
const fenced = "## 1. A\n```sh\n# not a heading\n```\nmore\n## 2. B\n";
try std.testing.expectEqualStrings("## 1. A\n```sh\n# not a heading\n```\nmore\n", section(fenced, "## 1.").?);
}
test excerptOf {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
const prog = try normalize(a.allocator(), "fn f() {\n let x = 1; // one\n if x == 1 { return; }\n let s = b\"// not a comment\";\n}\n");
try std.testing.expect(excerptOf(try normalize(a.allocator(), "let x = 1;\nif x == 1 { … }"), prog));
try std.testing.expect(excerptOf(try normalize(a.allocator(), "b\"// not a comment\""), prog));
try std.testing.expect(!excerptOf(try normalize(a.allocator(), "if x == 2 { … }"), prog));
try std.testing.expect(!excerptOf(try normalize(a.allocator(), "return; … let x = 1;"), prog));
}
+32
View File
@@ -4,6 +4,11 @@
Run after `zig build agent-reference`:
uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py [--record LABEL]
uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source
`--source` measures the Source Reference Bundle (zig-out/agent/source/, the
condition Aji/source) per file and per group of the `aji_source` language
profile's `doc_groups` (the same groups the harness reports).
Tokenizers: OpenAI `cl100k_base` and `o200k_base` (tiktoken) and the
byte-level BPE of Qwen2.5 (Hugging Face `tokenizers`) as an independent
@@ -23,6 +28,30 @@ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REPORT = os.path.join(ROOT, "zig-out", "agent", "report.json")
BUNDLE = os.path.join(ROOT, "zig-out", "agent", "reference-bundle.md")
HISTORY = os.path.join(ROOT, "docs", "agent", "history.json")
SOURCE = os.path.join(ROOT, "zig-out", "agent", "source")
SOURCE_PROFILE = os.path.join(ROOT, "tools", "eval", "languages", "aji_source.json")
def source_report():
with open(SOURCE_PROFILE) as f:
groups = json.load(f)["doc_groups"]
files, totals = {}, {}
for d, _, names in os.walk(SOURCE):
for n in sorted(names):
path = os.path.join(d, n)
rel = os.path.relpath(path, SOURCE)
with open(path, encoding="utf-8") as f:
files[rel] = count_tokens(f.read())
g = next((g for g, pres in groups.items() for p in pres if rel == p or (p.endswith("/") and rel.startswith(p))), "other")
for k, v in files[rel].items():
totals.setdefault(g, {}).setdefault(k, 0)
totals[g][k] += v
full = {}
for g, t in totals.items():
if g != "air_docs":
for k, v in t.items():
full[k] = full.get(k, 0) + v
print(json.dumps({"files": dict(sorted(files.items())), "groups": totals, "full_source_docs": full}, indent=2))
def count_tokens(text):
@@ -46,6 +75,9 @@ def count_tokens(text):
def main():
args = sys.argv[1:]
label = None
if args == ["--source"]:
source_report()
return
if args[:1] == ["--record"] and len(args) == 2:
label = args[1]
elif args:
+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")