diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a00fbcc..cded2ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,4 +19,9 @@ jobs: - run: zig build test --summary all - run: zig build conformance - run: zig build && python3 tests/hosted/smoke.py + - run: zig-out/bin/aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air + - run: zig build agent-reference + - name: Agent Reference Bundle tokens (non-blocking) + continue-on-error: true + run: pip install --quiet tiktoken tokenizers && python3 tools/agent_bundle_tokens.py - run: zig-out/bin/aji run --manifest examples/packages/hello/aji.toml | grep -q '"stdout":"hello, aji\\n"' diff --git a/AGENTS.md b/AGENTS.md index 02d71c1..c0a8058 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,7 @@ Any change involving ownership, aliasing, atomics, tasks, cancellation, resource ## RFCs -Every RFC introducing a semantic feature includes `## Agent complexity impact` (spec 14 §6): new concepts, new verifier state, new syntax or instructions, interactions, effect on repairability, and whether existing primitives suffice. +Every RFC introducing a semantic feature includes `## Agent complexity impact` (spec 14 §6): new concepts, new verifier state, new syntax or instructions, interactions, effect on repairability, whether existing primitives suffice, and the Agent Reference Bundle growth (`zig build agent-reference`, `docs/agent/README.md`). Normative text an agent needs to write AIR enters the bundle through `docs/agent/bundle.txt`. ## Changes to AIR diff --git a/build.zig b/build.zig index 7ea4eac..9c81d28 100644 --- a/build.zig +++ b/build.zig @@ -65,4 +65,21 @@ pub fn build(b: *std.Build) void { run_conformance.addPassthruArgs(); b.step("conformance", "Run the conformance suite").dependOn(&run_conformance.step); test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = conformance.root_module })).step); + + // Agent Reference Bundle (spec 14 §3.7): zig-out/agent/{reference-bundle.md,report.json}. + const bundle = b.addExecutable(.{ + .name = "aji-agent-bundle", + .root_module = b.createModule(.{ + .root_source_file = b.path("tools/agent_bundle.zig"), + .target = target, + .optimize = optimize, + .imports = &.{.{ .name = "aji", .module = mod }}, + }), + }); + const run_bundle = b.addRunArtifact(bundle); + run_bundle.setCwd(b.path(".")); + run_bundle.addArgs(&.{ ".", "zig-out/agent" }); + run_bundle.has_side_effects = true; + b.step("agent-reference", "Build the Agent Reference Bundle and report its size").dependOn(&run_bundle.step); + test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = bundle.root_module })).step); } diff --git a/docs/agent/README.md b/docs/agent/README.md new file mode 100644 index 0000000..2570c5c --- /dev/null +++ b/docs/agent/README.md @@ -0,0 +1,47 @@ +# Agent Reference Bundle + +Non-normative tooling for spec 14 §3.7. The bundle is the minimal material a model must receive to write correct AIR without access to the rest of the repository. Its size is a language complexity metric. + +| File | Purpose | +|---|---| +| [bundle.txt](bundle.txt) | manifest: files and sections in bundle order | +| [syntax-example.air](syntax-example.air) | the one example in the bundle: a minimal syntax reference that verifies and runs | +| [history.json](history.json) | recorded measurements, one entry per milestone | + +## Contents + +Included: AIR text grammar and format rules, instruction set, type and integer semantics, traps, verifier rules (limits, borrows, facts, initialization, stage order), resources, effects, capabilities, intrinsics, heap and regions, unsafe boundaries, the deterministic runtime contract, the diagnostic format and all registries (codes, features, effects, capabilities, intrinsics). + +Excluded: RFC rationale, plans and roadmap, design history, README prose, benchmark descriptions, examples other than the syntax reference. + +A section enters the bundle through `bundle.txt` only. When a semantic RFC adds normative text an agent needs, the RFC adds the corresponding entry. + +## Measuring + +```sh +zig build agent-reference # zig-out/agent/reference-bundle.md, report.json +uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py +uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --record "" +``` + +Counted: files, sections, bytes, lines, words, and tokens with OpenAI `cl100k_base` and `o200k_base` and the independent byte-level BPE of Qwen2.5. The trend matters more than any single tokenizer. + +## Growth policy + +Compared with the last recorded milestone: + +| Growth per semantic RFC | Consequence | +|---|---| +| ≤ 10 % | none | +| > 10 % | CI warning | +| > 20 % | review required: the RFC explains the growth in its *Agent complexity impact* section | + +Growth never blocks a merge automatically; a complex feature can be justified, but not silently. + +## Milestones + +| Milestone | Files | Sections | Bytes | Words | cl100k | o200k | Qwen2.5 | +|---|---:|---:|---:|---:|---:|---:|---:| +| Phase 2 baseline (AIR format 0) | 18 | 29 | 104 250 | 16 197 | 27 347 | 27 445 | 28 230 | + +Next measurement: after Phase 3 (structured concurrency). diff --git a/docs/agent/bundle.txt b/docs/agent/bundle.txt new file mode 100644 index 0000000..bf28fe8 --- /dev/null +++ b/docs/agent/bundle.txt @@ -0,0 +1,63 @@ +# Agent Reference Bundle manifest (spec 14 §3.7). +# +# The minimal material a model must receive to write correct AIR without the +# rest of the repository. One entry per line: +# the whole file +# :: one section: the heading that starts with the +# prefix and everything up to the next heading +# of the same or a higher level +# Order is the order of the bundle. Rationale (RFCs), plans, design history, +# README prose and benchmark descriptions are deliberately absent. + +# Minimal syntax reference +docs/agent/syntax-example.air + +# AIR text grammar and format rules +docs/reference/air-text.ebnf +docs/spec/07-air.md :: ## 8. Text AIR + +# Instruction set, run results, canonical record +docs/spec/07a-air-instructions.md + +# Types and integer semantics +docs/spec/02-types-and-values.md :: ## 2. Integer semantics + +# Traps +docs/spec/01-language-overview.md :: ## 6. Trap + +# Verifier: limits and accounted sizes, borrows, facts, initialization, stage order +docs/spec/08-verifier.md :: ## 7. Bounded analysis +docs/spec/08-verifier.md :: ## 11. Borrow verification +docs/spec/08-verifier.md :: ## 12. Bounds facts +docs/spec/08-verifier.md :: ## 13. Initialization +docs/spec/08-verifier.md :: ## 14. Stage order + +# Effects, capabilities, intrinsics +docs/spec/05-effects-and-capabilities.md :: ## 9. Effects in AIR +docs/spec/05-effects-and-capabilities.md :: ## 10. Capabilities in AIR +docs/spec/05-effects-and-capabilities.md :: ## 11. Intrinsic calls +docs/spec/05-effects-and-capabilities.md :: ## 12. Runtime + +# Resources and I/O errors +docs/spec/06-resources-and-errors.md :: ## 6. Resources in AIR +docs/spec/06-resources-and-errors.md :: ## 7. I/O errors + +# Heap, regions, budgets +docs/spec/03-memory-model.md :: ## 18. Allocation authority in AIR +docs/spec/03-memory-model.md :: ## 19. Heap in AIR +docs/spec/03-memory-model.md :: ## 20. Regions in AIR + +# Unsafe boundaries +docs/spec/13-contracts-and-unsafe.md :: ## 6. Unsafe code in AIR + +# Deterministic runtime contract: fuel, profiles, PRNG +docs/spec/11-determinism-and-replay.md :: ## 7. Execution limits +docs/spec/11-determinism-and-replay.md :: ## 8. Execution profiles + +# Diagnostics format and registries +docs/spec/10-diagnostics-and-agent-protocol.md :: ## 2. Stable codes +docs/reference/error-codes.md +docs/reference/air-features.md +docs/reference/effects.md +docs/reference/capabilities.md +docs/reference/intrinsics.md diff --git a/docs/agent/history.json b/docs/agent/history.json new file mode 100644 index 0000000..cf4d379 --- /dev/null +++ b/docs/agent/history.json @@ -0,0 +1,18 @@ +[ + { + "label": "phase-2 baseline (AIR format 0)", + "language": "aji", + "air": 0, + "phase": 2, + "files": 18, + "sections": 29, + "bytes": 104250, + "lines": 1630, + "words": 16197, + "tokens": { + "cl100k_base": 27347, + "o200k_base": 27445, + "qwen2.5": 28230 + } + } +] diff --git a/docs/agent/syntax-example.air b/docs/agent/syntax-example.air new file mode 100644 index 0000000..e3381d8 --- /dev/null +++ b/docs/agent/syntax-example.air @@ -0,0 +1,38 @@ +; Minimal syntax reference for text AIR format 0 (part of the Agent Reference Bundle). +; Run: aji run --grant out=io.write --grant heap=mem.alloc:64 docs/agent/syntax-example.air +module example.syntax +air 0 +lang 0.1 +features [arrays, capabilities, effects, heap, ownership, resources] + +type @Pair = struct { a: u8, b: u8 } + +; Entry point: capabilities arrive as named parameters. +fn @main(%out: cap, %heap: cap) -> u8 +effects [io.write, mem.alloc] +entry: + %msg = local.alloc array ; frame storage, only in entry + %c = const.u8 104 ; 'h' + %arr = array.splat array %c + local.store %msg, %arr ; initializes the local + %r = borrow.ref %msg ; second-class borrow + %s = slice.make %r + intrinsic io.stdout_write(%out, %s), ok -> @written, err -> @io_failed +written: + borrow.end %s ; every borrow ends on every path + borrow.end %r + %one = const.u8 1 + %two = const.u8 2 + %p = struct.make @Pair(%one, %two) + own.new %p, %heap, ok -> @owned, err -> @no_memory +owned(%o: own<@Pair>): ; results arrive as block parameters + %v = own.take %o ; linear owner consumed + %b = struct.get @Pair.b, %v + %sum = add.checked.u8 %b, %one ; traps T0003 on overflow + br @done(%sum) +done(%result: u8): + ret %result +io_failed(%e: io_error): + trap +no_memory(%a: alloc_error): + trap diff --git a/docs/evaluation/README.md b/docs/evaluation/README.md index 600b161..9794d11 100644 --- a/docs/evaluation/README.md +++ b/docs/evaluation/README.md @@ -4,7 +4,8 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](.. | Document | Purpose | |---|---| -| [protocol.md](protocol.md) | Agent Language Evaluation Protocol 0.1: variables, tasks T01–T10, 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 | ## Integrity rules (protocol §7, §29; spec 14 §12) @@ -23,4 +24,6 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](.. | D — Systems integration | T09, T10 | Phases 3–5; stable features | blocked | | E — Maintenance campaign | M1–M8 on T03, T07, T09, T10 | D | blocked | -Until the source language (Phase 6) exists, an Aji run means an agent writing text AIR directly. Stage A therefore measures AIR as the agent-facing language; results must say so. +Until the source language (Phase 6) exists, Aji runs use the condition `Aji/AIR`: the agent writes text AIR directly. This is a deliberate experiment, not a stopgap: if AIR alone helps weaker models, that is strong evidence, and after Phase 6 `Aji/source` is compared against `Aji/AIR`. + +Order (protocol §30a): bundle baseline (done) → Phase 3 → second bundle measurement → private benchmark repository (in parallel) → harness → 36-run smoke test (§39a) → 108-run Stage A pilot. diff --git a/docs/evaluation/protocol.md b/docs/evaluation/protocol.md index ce2ca73..9e20116 100644 --- a/docs/evaluation/protocol.md +++ b/docs/evaluation/protocol.md @@ -1,7 +1,8 @@ # Aji Agent Language Evaluation Protocol -Version: 0.1 +Version: 0.2 Status: Proposed +Changes in 0.2: T01–T10 are benchmark families (§9); Aji conditions `Aji/AIR` and `Aji/source` (§2); engineering smoke test before the pilot (§39a); stage order (§30a). Purpose: empirical validation of the Aji language hypothesis (spec 14) # 1. Goal @@ -48,6 +49,15 @@ C C is useful as a low-level baseline but is not required for every experiment. +Aji is evaluated as two separate conditions: + +```text +Aji/AIR the agent writes text AIR directly +Aji/source the agent writes .aji source lowered to AIR (from Phase 6) +``` + +Results MUST be labelled with the condition. Comparing the two answers whether an agent needs a high-level source language at all, or whether AIR is the better agent-facing interface while `.aji` serves humans. + ## Model capability At least four capability classes: @@ -241,7 +251,9 @@ Broken tasks are removed before results are examined. --- -# 9. Task classes +# 9. Benchmark families + +T01–T10 below are **benchmark families**, not concrete tasks. Each family names the properties it exercises and gives an illustrative task. The private corpus contains concrete tasks that instantiate a family with different wire formats, storage models, requirements and hidden mutations (for example a family T03 task might be "A17 Segmented Journal"). The published descriptions are therefore never the evaluated tasks, which keeps this protocol public without disclosing the held-out corpus (§7, §29). ## T01 — Binary Frame Decoder @@ -1309,6 +1321,28 @@ No claims about concurrency yet. --- +# 30a. Order of work + +```text +E0-1 Agent Reference Bundle, baseline after Phase 2 + ↓ +Phase 3 structured concurrency + ↓ +second bundle measurement + ↓ +private benchmark repository (in parallel, outside this repository) + ↓ +E0-3 harness + ↓ +engineering smoke test (§39a) + ↓ +Stage A pilot on Aji/AIR (§39) +``` + +The full Stage A is deliberately run after the basic Phase 3, so that early benchmark work does not start shaping the language before its concurrency model exists. + +--- + # 31. Stage B — Phase 3 validation After structured concurrency: @@ -1495,9 +1529,25 @@ Do not add syntax or instructions merely because one model struggled with one ta --- +# 39a. Engineering smoke test + +Before the pilot, a small run checks the infrastructure, not the hypothesis: + +```text +2 families (e.g. binary frame decoding, append log) +× 3 languages (Aji/AIR, Rust, Zig) +× 3 model classes +× 2 runs += 36 runs +``` + +It verifies that task statements are equivalent across languages, the harness works, the Agent Reference Bundle is sufficient, token and cost accounting is right, traces are stored completely and prompts carry no bias. No result of the smoke test is reported as evidence. + +--- + # 39. First concrete experiment -As soon as RFC 0008 is implemented, run a pilot: +After the smoke test (§39a), run a pilot: ```text tasks: diff --git a/docs/plan/README.md b/docs/plan/README.md index 5d41273..5a04467 100644 --- a/docs/plan/README.md +++ b/docs/plan/README.md @@ -92,18 +92,19 @@ Evaluation runs alongside the phases; each stage starts when the language featur | ID | Status | Task | Depends | Done when | |---|---|---|---|---| -| E0-1 | todo | Define the Agent Reference Bundle (spec 14 §3.7) and a deterministic size measurement (bytes and tokens) recorded per release | — | bundle manifest in the repository; size reported in CI | -| E0-2 | todo | 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-3 | todo | Language-neutral agent scaffold and run recorder (protocol §5, §28) | — | identical loop drives Aji, Rust and Zig; every run record complete | +| 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-3 | todo | (after basic Phase 3) Language-neutral agent scaffold and run recorder (protocol §5, §28) | — | identical loop drives Aji, Rust and Zig; every run record complete | | E0-4 | todo | Rust and Zig baseline solutions and pinned local documentation | E0-2 | baselines pass the hidden tests | -| E-A | todo | Stage A pilot: T01–T04 × Aji/Rust/Zig × 3 model classes × 3 runs = 108 runs (protocol §39); not headline evidence | E0-1…E0-4, Phase 2 | pilot report: effect size, broken tasks, cost, instrumentation | +| E-S | todo | Engineering smoke test: 2 families × 3 languages × 3 model classes × 2 runs = 36 runs (protocol §39a); infrastructure only | E0-2, E0-3, E0-4 | harness, bundle sufficiency, accounting and traces verified | +| 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-C | todo | Stage C: T08, litmus repair | Phase 5 | stage report | | E-D | todo | Stage D: T09, T10 | Phases 3–5, stable features | stage report | | E-E | todo | Stage E: maintenance campaign M1–M8 | E-D | stage report | | E-1 | todo | First confirmatory experiment: 8 held-out tasks × 3 languages × 4 model classes × 6 runs = 576 runs (protocol §40); thresholds frozen beforehand (§35) | E-A fixes | published evaluation | -Until Phase 6 delivers the source language, agents write text AIR directly; Stage A results must state this. +Until Phase 6 delivers the source language, Aji runs use the condition `Aji/AIR`; after Phase 6, `Aji/source` is evaluated as a separate condition. Every Phase 3+ semantic RFC re-measures the Agent Reference Bundle (`docs/agent/README.md`). ## Task conventions diff --git a/docs/rfcs/0000-template.md b/docs/rfcs/0000-template.md index e54196d..91ae05b 100644 --- a/docs/rfcs/0000-template.md +++ b/docs/rfcs/0000-template.md @@ -68,6 +68,7 @@ Required for semantic features (spec 14 §6): - Interaction with existing features: - Expected effect on repairability: - Could existing primitives express it? +- Agent Reference Bundle growth (`zig build agent-reference` + `tools/agent_bundle_tokens.py`, tokens before → after; > 20 % needs a justification): ## Alternatives considered diff --git a/tools/agent_bundle.zig b/tools/agent_bundle.zig new file mode 100644 index 0000000..917377f --- /dev/null +++ b/tools/agent_bundle.zig @@ -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 +//! writes /reference-bundle.md and /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 \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, "\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.").?); +} diff --git a/tools/agent_bundle_tokens.py b/tools/agent_bundle_tokens.py new file mode 100644 index 0000000..3021e38 --- /dev/null +++ b/tools/agent_bundle_tokens.py @@ -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()