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