- 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
128 lines
4.5 KiB
Python
128 lines
4.5 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]
|
|
uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source
|
|
|
|
`--source` measures the Source Reference Bundle (zig-out/agent/source/, the
|
|
condition Aji/source) per file and per group of the `aji_source` language
|
|
profile's `doc_groups` (the same groups the harness reports).
|
|
|
|
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")
|
|
SOURCE = os.path.join(ROOT, "zig-out", "agent", "source")
|
|
SOURCE_PROFILE = os.path.join(ROOT, "tools", "eval", "languages", "aji_source.json")
|
|
|
|
|
|
def source_report():
|
|
with open(SOURCE_PROFILE) as f:
|
|
groups = json.load(f)["doc_groups"]
|
|
files, totals = {}, {}
|
|
for d, _, names in os.walk(SOURCE):
|
|
for n in sorted(names):
|
|
path = os.path.join(d, n)
|
|
rel = os.path.relpath(path, SOURCE)
|
|
with open(path, encoding="utf-8") as f:
|
|
files[rel] = count_tokens(f.read())
|
|
g = next((g for g, pres in groups.items() for p in pres if rel == p or (p.endswith("/") and rel.startswith(p))), "other")
|
|
for k, v in files[rel].items():
|
|
totals.setdefault(g, {}).setdefault(k, 0)
|
|
totals[g][k] += v
|
|
full = {}
|
|
for g, t in totals.items():
|
|
if g != "air_docs":
|
|
for k, v in t.items():
|
|
full[k] = full.get(k, 0) + v
|
|
print(json.dumps({"files": dict(sorted(files.items())), "groups": totals, "full_source_docs": full}, indent=2))
|
|
|
|
|
|
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 == ["--source"]:
|
|
source_report()
|
|
return
|
|
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()
|