E0-1: Agent Reference Bundle and Phase 2 baseline
- docs/agent/bundle.txt: minimal AIR reference by file and section (grammar, instructions, types, traps, verifier rules, resources, effects, capabilities, intrinsics, heap/regions, unsafe, runtime contract, diagnostics and registries); syntax-example.air verifies and runs - zig build agent-reference: deterministic bundle and report (files, sections, bytes, lines, words); section extraction ignores fenced code - tools/agent_bundle_tokens.py: cl100k_base, o200k_base and Qwen2.5 BPE counts; growth warnings >10 % and review >20 % against history.json - baseline after Phase 2: 104 250 bytes, 16 197 words, ~27.3k tokens - CI builds the bundle and counts tokens (non-blocking) - evaluation protocol 0.2: benchmark families, Aji/AIR and Aji/source conditions, 36-run engineering smoke test, order of work - RFC template and AGENTS.md: report bundle growth
This commit is contained in:
1 parent
72192c2331
commit
6eceb4405b
13 files changed
+470
-11
No files matched your search
@@ -0,0 +1,121 @@
|
||||
//! Builds the Agent Reference Bundle (spec 14 §3.7) from docs/agent/bundle.txt
|
||||
//! and reports its size. Deterministic: same sources, same bytes.
|
||||
//!
|
||||
//! usage: aji-agent-bundle <repo root> <output dir>
|
||||
//! writes <output dir>/reference-bundle.md and <output dir>/report.json
|
||||
|
||||
const std = @import("std");
|
||||
const aji = @import("aji");
|
||||
|
||||
const Error = error{ BadManifest, SectionNotFound };
|
||||
|
||||
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) {
|
||||
std.debug.print("usage: aji-agent-bundle <repo root> <output dir>\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));
|
||||
|
||||
var bundle: std.ArrayList(u8) = .empty;
|
||||
var files: std.ArrayList([]const u8) = .empty;
|
||||
var sections: usize = 0;
|
||||
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;
|
||||
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 });
|
||||
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 });
|
||||
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");
|
||||
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);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/// The Markdown section whose heading starts with `prefix`, up to the next
|
||||
/// heading of the same or a higher level.
|
||||
fn section(text: []const u8, prefix: []const u8) ?[]const u8 {
|
||||
const level = std.mem.indexOfNone(u8, prefix, "#") orelse return null;
|
||||
var pos: usize = 0;
|
||||
var start: ?usize = null;
|
||||
var in_code = false;
|
||||
while (pos < text.len) {
|
||||
const end = std.mem.indexOfScalarPos(u8, text, pos, '\n') orelse text.len;
|
||||
const line = text[pos..end];
|
||||
// Lines starting with `#` inside fenced code are not headings.
|
||||
if (std.mem.startsWith(u8, line, "```")) in_code = !in_code;
|
||||
if (in_code) {
|
||||
pos = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (start) |st| {
|
||||
const l = std.mem.indexOfNone(u8, line, "#") orelse 0;
|
||||
if (l > 0 and l <= level and l < line.len and line[l] == ' ') return text[st..pos];
|
||||
} else if (std.mem.startsWith(u8, line, prefix)) {
|
||||
start = pos;
|
||||
}
|
||||
pos = end + 1;
|
||||
}
|
||||
return if (start) |st| text[st..] else null;
|
||||
}
|
||||
|
||||
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.").?);
|
||||
try std.testing.expectEqualStrings("### 1.1 B\nb\n", section(doc, "### 1.1").?);
|
||||
try std.testing.expectEqualStrings("## 2. C\nc\n", section(doc, "## 2.").?);
|
||||
try std.testing.expect(section(doc, "## 3.") == null);
|
||||
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.").?);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Token counts and growth check for the Agent Reference Bundle (spec 14 §3.7).
|
||||
|
||||
Run after `zig build agent-reference`:
|
||||
|
||||
uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py [--record LABEL]
|
||||
|
||||
Tokenizers: OpenAI `cl100k_base` and `o200k_base` (tiktoken) and the
|
||||
byte-level BPE of Qwen2.5 (Hugging Face `tokenizers`) as an independent
|
||||
vocabulary. The trend matters more than any single count.
|
||||
|
||||
Growth is compared with the last entry of docs/agent/history.json:
|
||||
warning above 10 %, review required above 20 % (per spec 14 §3.7 the size
|
||||
is a complexity metric; growth does not block a merge but an RFC must
|
||||
explain it). With --record LABEL the measurement is appended to the history.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
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")
|
||||
|
||||
|
||||
def count_tokens(text):
|
||||
tokens = {}
|
||||
try:
|
||||
import tiktoken
|
||||
|
||||
for name in ("cl100k_base", "o200k_base"):
|
||||
tokens[name] = len(tiktoken.get_encoding(name).encode(text, disallowed_special=()))
|
||||
except Exception as e: # missing package or offline
|
||||
print(f"warning: tiktoken unavailable: {e}", file=sys.stderr)
|
||||
try:
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
tokens["qwen2.5"] = len(Tokenizer.from_pretrained("Qwen/Qwen2.5-0.5B").encode(text).ids)
|
||||
except Exception as e:
|
||||
print(f"warning: tokenizers unavailable: {e}", file=sys.stderr)
|
||||
return tokens
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
label = None
|
||||
if args[:1] == ["--record"] and len(args) == 2:
|
||||
label = args[1]
|
||||
elif args:
|
||||
print(__doc__)
|
||||
sys.exit(2)
|
||||
|
||||
with open(REPORT) as f:
|
||||
report = json.load(f)
|
||||
with open(BUNDLE, encoding="utf-8") as f:
|
||||
text = f.read()
|
||||
report["tokens"] = count_tokens(text)
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
history = []
|
||||
if os.path.exists(HISTORY):
|
||||
with open(HISTORY) as f:
|
||||
history = json.load(f)
|
||||
if history:
|
||||
prev = history[-1]
|
||||
for metric in ("bytes", "words"):
|
||||
check(metric, prev.get(metric), report[metric], prev["label"])
|
||||
for name, value in report["tokens"].items():
|
||||
check(f"tokens.{name}", prev.get("tokens", {}).get(name), value, prev["label"])
|
||||
|
||||
if label:
|
||||
history.append({"label": label, **report})
|
||||
with open(HISTORY, "w") as f:
|
||||
json.dump(history, f, indent=2)
|
||||
f.write("\n")
|
||||
print(f"recorded as {label!r} in docs/agent/history.json")
|
||||
|
||||
|
||||
def check(metric, before, after, prev_label):
|
||||
if not before:
|
||||
return
|
||||
growth = (after - before) / before
|
||||
msg = f"Agent Reference Bundle {metric}: {before} -> {after} ({growth:+.1%}) since {prev_label}"
|
||||
if growth > 0.20:
|
||||
print(f"::warning title=Agent Reference Bundle::review required: {msg}")
|
||||
elif growth > 0.10:
|
||||
print(f"::warning title=Agent Reference Bundle::{msg}")
|
||||
else:
|
||||
print(msg)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user