- 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
315 lines
13 KiB
Zig
315 lines
13 KiB
Zig
//! 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>
|
|
//! aji-agent-bundle --check <repo root>
|
|
|
|
const std = @import("std");
|
|
const aji = @import("aji");
|
|
|
|
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> | --check <repo root>\n", .{});
|
|
std.process.exit(2);
|
|
}
|
|
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], .{});
|
|
|
|
// 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 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(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 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 (sources.items) |f| known = known or std.mem.eql(u8, f, path);
|
|
if (!known) try sources.append(arena, path);
|
|
}
|
|
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
|
|
/// 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;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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.").?);
|
|
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.").?);
|
|
}
|
|
|
|
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));
|
|
}
|