Files
aji/tools/agent_bundle_tokens.py
T
dev 6eceb4405b 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
2026-10-04 15:44:26 +03:00

96 lines
3.1 KiB
Python

#!/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()