P6A-8: Source Reference Bundle and harness profile aji_source

- 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
This commit is contained in:
dev committed 2026-10-05 13:16:51 +03:00
1 parent 61be766634
commit 3e2d9b63a7
35 files changed
+1170 -106

No files matched your search

+6
View File
@@ -82,4 +82,10 @@ pub fn build(b: *std.Build) void {
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);
// Every Quick Reference example is an excerpt of a checked program.
const check_quickref = b.addRunArtifact(bundle);
check_quickref.setCwd(b.path("."));
check_quickref.addArgs(&.{ "--check", "." });
check_quickref.has_side_effects = true;
test_step.dependOn(&check_quickref.step);
}
+30 -1
View File
@@ -50,6 +50,35 @@ Growth never blocks a merge automatically; a complex feature can be justified, b
RFC 0011 crossed the 10 % warning line (its own estimate said "below 10 %"): four new sections in spec 04 (tasks, loans, `Send`/`Share` table, scheduler). Below the 20 % review threshold. RFC 0012 (+15.8 %, estimate 12–16 %): five sections in spec 04 (waits and cancellation, channels, select, mutex, critical-section rule). Implementation-time spec corrections (mutex linearity, `mutex.take` rules): +0.6 %. Phase 3 total since the Phase 2 baseline: +29.2 %. Next measurement: after the E-S smoke test, or with the next RFC.
## Source Reference Bundle (condition `Aji/source`)
The `.aji` condition does not get the AIR bundle as its documentation. It gets a directory mounted at `/docs` with a small front door, and the agent reads the rest only when it needs it. That tests a second hypothesis: a model can work from a small reference and selective reading.
| Path | Contents | cl100k tokens |
|---|---|---:|
| `QUICK.md` | the Quick Reference, then a table of which file to open for what | ~4.4k |
| `language/syntax.md` | grammar, spec 15 §1, §2, §4–§6 | ~5.4k |
| `language/types.md` | spec 15 §3, integer semantics, type properties, traps | ~1.0k |
| `language/ownership.md` | spec 15 §9, aliasing, borrow lifetime, stack storage, slices, initialization (spec 03) | ~1.0k |
| `language/memory.md` | `Own<T>`, regions, allocation authority (spec 03) | ~1.4k |
| `language/effects-capabilities.md` | spec 05 §2–§5, §9–§10, effect and capability registries | ~4.4k |
| `language/io-resources.md` | spec 15 §8, spec 06 §1–§3, §7, intrinsic registry | ~3.0k |
| `language/concurrency.md` | implementation status, spec 15 §7, `Send`/`Share`, scheduler | ~2.2k |
| `language/tooling.md` | spec 15 §11, execution limits and profiles (spec 11) | ~2.2k |
| `diagnostics/errors.md` | spec 15 §10, stable codes, repair loop, error-code registry | ~1.9k |
| `air/reference.md` | the whole AIR bundle, for reading `aji lower` output only | ~35.7k |
Without `air/` it comes to about 26.8k tokens. The manifest is [`source-bundle.txt`](source-bundle.txt): the `bundle.txt` syntax, plus `> path` to start an output file and `@manifest` to include another bundle. Text that exists only for this bundle (navigation, implementation status) is in [`source-notes.md`](source-notes.md).
```sh
zig build agent-reference # also writes zig-out/agent/source/ and source-report.json
uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source
```
The groups `quick_reference`, `source_docs` and `air_docs` come from the `doc_groups` of the language profile `tools/eval/languages/aji_source.json`. The harness reports reading per group with the same definition (`docs/evaluation/harness.md`, context metrics). An agent writing `.aji` that reads much of `air/` is a signal: either the source documentation is not self-sufficient, or diagnostics are still too AIR-centric.
## Quick Reference (`.aji`)
[`quick-reference.md`](quick-reference.md) is the agent's first entry for the condition `Aji/source`. It is 4–6k tokens (currently about 3.6k, cl100k), covers most programs and has an index into the full reference (owner decision after the native smoke). It is kept consistent with spec 15. Its size and the `unique_reference_tokens` that agents actually read are measured alongside the bundle. The source-condition bundle, with the semantic rules restated in source terms, follows once the frontend exists.
[`quick-reference.md`](quick-reference.md) is the front door of the Source Reference Bundle (`QUICK.md`). It targets 4–6k tokens (about 4.4k with the navigation table, cl100k), covers most programs, and is kept consistent with spec 15.
**Its examples are checked.** Every ```aji block must be an excerpt of a program in `tests/conformance/source/quickref/`. Comments and whitespace are ignored, and `…` matches any text. Those programs are conformance tests, so each example is part of a program that verifies and runs. `zig build test` and `zig build agent-reference` fail on an example that is not. The concurrency programs (§7) are PENDING until layers 7–8 exist.
+28 -31
View File
@@ -1,6 +1,6 @@
# Aji Quick Reference (`.aji` 0.1)
Read this first; it covers most programs. The full rules live in the reference index at the end. `aji check file.aji` verifies, `aji run file.aji` verifies and runs, `aji lower file.aji` prints the AIR it becomes. Diagnostics are JSON lines; fix the first one first.
Read this first; it covers most programs. Where to find the full rules is at the end. Every example below is part of a program the conformance suite checks. `aji check file.aji` verifies, `aji run file.aji` verifies and runs, `aji lower file.aji` prints the AIR it becomes. Diagnostics are JSON lines; fix the first one first.
Aji makes every significant action explicit — moves, borrows, allocation, closing, authority, effects, tasks, channel transfers, locking, cancellation, every failure outcome — and checks them all before running. The compiler writes the mechanics: SSA, control flow, borrow ends, frame storage, the feature header.
@@ -50,15 +50,16 @@ var i: usize = 0; // variable; reassign with i = i + 1;
var buf: [u8; 16] = zero; // zero-initialized storage
if c { … } else if d { … } else { … }
while i < n { … }
for i in 0..n { … } // 0 ≤ i < n
for k in 0..n { … } // 0 ≤ k < n
loop { … break; … continue; … }
return v; trap; assert(c);
let y = if c { 1 } else { 2 }; // value-producing if/match: tail expression without `;`
let w: u64 = match m { // enum match: exhaustive, one arm per variant
Message::Stop => 0,
Message::Value(x) => x, // x exists only in this arm
Message::Value(v) => v, // v exists only in this arm
};
match d { 0 => { … } 1 => { … } _ => { … } } // integer match: `_` required
match t { 0 => { … } 1 => { … } _ => { … } } // integer match: `_` required
assert(c); // traps T0002 when false
return x + y + w; // also: `trap;`
```
| Operation | Meaning |
@@ -80,14 +81,19 @@ There is one spelling per construct: no `+=`, no alternative syntax.
```aji
var data: [u64; 8] = zero;
data[0] = 7; // element write (array variables get frame storage automatically)
mut s = data; // bind an exclusive borrow (an array is borrowed as slice_mut<u64>)
s[1] = s[0] + 1; // checked index; out of range traps T0008
let n = s.len;
if i < s.len { s[i] = 0; } // no runtime check here: the verifier proves i < s.len
let (l, r) = s.split_at(4); // two disjoint halves of s
{
mut s = data; // exclusive borrow to the end of this block (an array is borrowed as slice_mut<u64>)
s[1] = s[0] + 1; // checked index; out of range traps T0008
let n = s.len;
if i < s.len { s[i] = 0; } // no runtime check here: the verifier proves i < s.len
let (l, r) = s.split_at(4); // two disjoint halves of s
…
}
slice.copy(mut out[0..4], ref data[4..8]); // borrows as arguments end after the call
…
ref q = p; // shared borrow of a struct; q.a reads a field
*c = *c + 1; // through mut<u64>
…
*c = *c + 1; // through c: mut<u64>
```
Rules (checked by the verifier):
@@ -103,9 +109,10 @@ Rules (checked by the verifier):
```aji
match fs.open_read(c, b"/data/in.txt") {
ok(f) => { … use f … ; fs.close(move f) or trap; }
ok(f) => { …; fs.close(move f) or trap; }
err(e) => { return 1u8; }
}
…
let n = net.recv(conn, mut buf) or trap; // any non-ok outcome traps
```
@@ -134,6 +141,7 @@ A region allocation needs an explicit borrow of the region that outlives the all
ref arena = r;
let item = region.new(arena, 1u64) or trap; // item: mut<u64>, ends with this block
*item = *item + 1;
…
}
region.reset(r);
```
@@ -141,19 +149,22 @@ region.reset(r);
`err(e)` binds a real value: `match e { alloc_error::budget_exceeded => …, alloc_error::out_of_memory => … }`.
- **Narrowing:** `cap.narrow.prefix(c, b"/data")` and `cap.narrow.budget(heap, 4096)`, each giving `ok(c2) / err(e)`.
- Resource operands (`f`, `s`, `l`, `r`, endpoints) are borrowed automatically for an operation; data borrows (`mut buf`, `ref bytes`) are always written.
- Resource operands (`f`, `s`, `l`, endpoints) are borrowed automatically for an operation; a region is not (bind `ref arena = r;`); data borrows (`mut buf`, `ref bytes`) are always written.
- Memory budgets count live bytes, so freeing returns them. In the deterministic profile `mem.alloc` needs a grant with a budget: `--grant heap=mem.alloc:4096`.
## 7. Concurrency
Not implemented in the source frontend yet (layers 7–8): `aji check` reports these constructs as not implemented (exit code 3). They are shown as specified.
```aji
let d = mut data; // data: [u64; 8]
mut d = data; // data: [u64; 8]
scope s { // every task spawned in s must be joined before the block ends (E4301)
let (l, r) = d.split_at(4);
let a = task.spawn(s, square, l); // borrows are lent to the task until its join
let b = task.spawn(s, square, r);
let x = task.join(move a);
let y = task.join(move b);
…
}
```
@@ -174,11 +185,12 @@ scope s { // every task spawned in s must
```aji
match channel.make<u64>(2, heap) { // effect mem.alloc
ok(tx, rx) => {
let tx2 = channel.dup(tx);
let tx2 = channel.dup(tx); // another sender; close it too
…
match channel.send(tx, v) { ok => {} closed(v) => { … } cancelled(v) => { … } } // a linear v: `move v`
match channel.recv(rx) { ok(v) => { … } closed => { … } cancelled => { … } }
channel.close_sender(move tx);
match channel.close_receiver(move rx) { ok => {} pending(rx) => { … receive until closed, close again … } }
match channel.close_receiver(move rx) { ok => {} pending(rx) => { … } } // drain, then close again
}
err(e) => { trap; }
}
@@ -231,18 +243,3 @@ scope s { // every task spawned in s must
| E4301 | task not joined at scope end | `task.join(move t)` before the `scope` block ends |
| E4304 | wait inside `lock` | move the wait out of the `lock` block |
| T0001–T0009 | runtime trap | see `kind` and `source_location` |
## 9. Index into the full reference
| Topic | Section |
|---|---|
| source language, every construct | spec 15 |
| types, Send/Share | spec 02 §6; spec 04 §35 |
| borrows, frame storage | spec 08 §11; spec 15 §5, §9 |
| heap, regions, budgets | spec 03 §18–§20 |
| effects, capabilities, narrowing | spec 05 §9–§11; `reference/capabilities.md` |
| resources, I/O errors | spec 06 §6–§7; `reference/intrinsics.md` |
| tasks, loans, scheduler | spec 04 §33–§36 |
| waits, cancellation, channels, select, mutex | spec 04 §37–§41 |
| determinism, run records, profiles | spec 11 §7–§8 |
| all codes | `reference/error-codes.md` |
+78
View File
@@ -0,0 +1,78 @@
# Source Reference Bundle manifest (condition Aji/source, spec 14 §3.7).
#
# A directory mounted at /docs. QUICK.md is the front door: it covers most
# programs and says which file to open for the rest. The agent reads the
# other files only when it needs them; air/ is the AIR reference, for
# reading the output of `aji lower` only. Entry syntax: bundle.txt, plus
# > <path> starts the output file <path>
# @<manifest> the single output of another manifest
> QUICK.md
docs/agent/quick-reference.md
docs/agent/source-notes.md :: ## 9. Where to read more
> language/syntax.md
docs/reference/grammar.ebnf
docs/spec/15-source-language.md :: ## 1. Principle
docs/spec/15-source-language.md :: ## 2. Modules and declarations
docs/spec/15-source-language.md :: ## 4. Statements and control flow
docs/spec/15-source-language.md :: ## 5. Expressions
docs/spec/15-source-language.md :: ## 6. Fallible operations and `match`
> language/types.md
docs/spec/15-source-language.md :: ## 3. Types
docs/spec/02-types-and-values.md :: ## 2. Integer semantics
docs/reference/type-properties.md
docs/spec/01-language-overview.md :: ## 6. Trap
> language/ownership.md
docs/spec/15-source-language.md :: ## 9. Frame storage, borrow scopes and features
docs/spec/03-memory-model.md :: ## 3. Safe-reference aliasing rule
docs/spec/03-memory-model.md :: ## 4. Borrow lifetime
docs/spec/03-memory-model.md :: ## 6. Stack storage
docs/spec/03-memory-model.md :: ## 9. Slices
docs/spec/03-memory-model.md :: ## 10. Initialization policy
> language/memory.md
docs/spec/03-memory-model.md :: ## 7. Own<T>
docs/spec/03-memory-model.md :: ## 8. Regions
docs/spec/03-memory-model.md :: ## 18. Allocation authority in AIR
> language/effects-capabilities.md
docs/spec/05-effects-and-capabilities.md :: ## 2. Effects
docs/spec/05-effects-and-capabilities.md :: ## 3. Capabilities
docs/spec/05-effects-and-capabilities.md :: ## 4. Narrowing
docs/spec/05-effects-and-capabilities.md :: ## 5. Capability transfer
docs/spec/05-effects-and-capabilities.md :: ## 9. Effects in AIR
docs/spec/05-effects-and-capabilities.md :: ## 10. Capabilities in AIR
docs/reference/effects.md
docs/reference/capabilities.md
> language/io-resources.md
docs/spec/15-source-language.md :: ## 8. Allocation, resources and intrinsics
docs/spec/06-resources-and-errors.md :: ## 1. Linear resources
docs/spec/06-resources-and-errors.md :: ## 2. Typestate
docs/spec/06-resources-and-errors.md :: ## 3. Cleanup
docs/spec/06-resources-and-errors.md :: ## 7. I/O errors
docs/reference/intrinsics.md
> language/concurrency.md
docs/agent/source-notes.md :: ## Concurrency status
docs/spec/15-source-language.md :: ## 7. Tasks, cancellation, channels, select and mutex
docs/spec/04-concurrency-and-atomics.md :: ## 35. Send and Share in AIR
docs/spec/04-concurrency-and-atomics.md :: ## 36. The deterministic scheduler
> language/tooling.md
docs/spec/15-source-language.md :: ## 11. Tooling
docs/spec/11-determinism-and-replay.md :: ## 7. Execution limits
docs/spec/11-determinism-and-replay.md :: ## 8. Execution profiles
> diagnostics/errors.md
docs/spec/15-source-language.md :: ## 10. Diagnostics
docs/spec/10-diagnostics-and-agent-protocol.md :: ## 2. Stable codes
docs/spec/10-diagnostics-and-agent-protocol.md :: ## 5. Expected repair loop
docs/reference/error-codes.md
> air/reference.md
docs/agent/source-notes.md :: ## The AIR reference
@docs/agent/bundle.txt
+30
View File
@@ -0,0 +1,30 @@
# Source Reference Bundle notes
Text that exists only for the Source Reference Bundle (`source-bundle.txt`). Non-normative: it points at the normative files and states which source layers are implemented.
## 9. Where to read more
The other files in `/docs` hold the full rules. Open one only when this page is not enough.
| Need | Read |
|---|---|
| exact syntax, every construct, `match` and outcomes | `/docs/language/syntax.md` |
| integer semantics, conversions, Copy/Send/Share, traps | `/docs/language/types.md` |
| borrows, scopes, frame storage, slices, initialization | `/docs/language/ownership.md` |
| `own`, regions, allocation budgets | `/docs/language/memory.md` |
| effects, capabilities, grants, narrowing | `/docs/language/effects-capabilities.md` |
| files, streams, stdin/stdout, intrinsic operand tables, `io_error` | `/docs/language/io-resources.md` |
| tasks, channels, select, mutex, cancellation | `/docs/language/concurrency.md` |
| `aji` commands, run records, fuel, profiles | `/docs/language/tooling.md` |
| a diagnostic code (`E2101`, `T0008`, …) | `/docs/diagnostics/errors.md` |
| the AIR printed by `aji lower`, `air_line`/`air_col` in a diagnostic | `/docs/air/reference.md` |
You write `.aji`; you never need to write AIR. Diagnostics point at your source (`file`, `line`, `col`).
## Concurrency status
The source frontend implements layers 1–6 of spec 15. Layers 7 (tasks, channels) and 8 (`lock`, `select`, cancellation, shields) are not implemented yet: a program that uses `scope`, `task.*`, `channel.*`, `mutex.*`, `lock`, `select` or `shield` is reported as not implemented (exit code 3). The rules below describe the language as specified.
## The AIR reference
This file is the reference for text AIR format 0, the language `.aji` lowers to. You do not need it to write `.aji`. It explains what `aji lower` prints and the `air_line`/`air_col` fields of diagnostics.
+4
View File
@@ -149,6 +149,10 @@ Frame storage is bounded (`max_local_frame`, spec 08 §11.5), but an SSA value o
Parameter names are preserved by lowering and are the binding points for grants (spec 15 §2). An AIR program whose `@main` has a parameter named after a `.aji` keyword (`%in` in `tests/conformance/phase2/run/echo_stdin.air`) has no source equivalent with the same instantiation contract, so a grant `in=io.read` cannot target a `.aji` program. Options: accept the restriction (keywords are not parameter names; AIR programs meant to have a source twin avoid them), or a raw-identifier spelling for this position. Not urgent; noted when the source/AIR equivalence test for `echo_stdin` had to drop its `equivalent:` reference.
**Resolved (owner decision):** no language change. For runtime grants the source parameter name is what matters, not identity with a hand-written AIR program: the source program names the parameter `input` and is run with `--grant input=…`, and that AIR test simply has no `equivalent:` twin. Escaped identifiers (`` `in` ``) are deferred until there is a real need, because they grow the grammar for a rare case.
## Q-022 — Byte strings dominate the source/AIR size metric
A byte string lowers to one `local.zero`, then a borrow, index, store and end per non-zero byte, because format 0 has no byte-array constant. In the Layer 6 programs this makes up most of the AIR (`hello`: `mechanical_air_eliminated` 0.94). The metric then measures a representation cost of format 0 more than the mechanics an agent would otherwise write. Options for P6A-9: report the metric both with and without byte-string materialization, or count each byte string as one AIR construct. A byte-array constant in AIR would be a format change (spec 07 §8.7) and is out of scope for 6A.
**Resolved (owner decision):** report both. `mechanical_air_eliminated_raw` counts all AIR actually generated and stays the main engineering metric. `mechanical_air_eliminated_normalized` counts each byte-string materialization as one logical constant operation, under one fixed rule for every program (spec 15 §11).
@@ -18,11 +18,14 @@ def build():
return subprocess.run(["cargo", "build", "-q", "--offline"], cwd=ws, capture_output=True).returncode == 0
if lang == "zig":
return subprocess.run(["zig", "build-exe", "main.zig"], cwd=ws, capture_output=True).returncode == 0
return subprocess.run([AJI, "check", "main.air"], cwd=ws, capture_output=True).returncode == 0
src = "main.aji" if lang == "aji_source" else "main.air"
return subprocess.run([AJI, "check", src], cwd=ws, capture_output=True).returncode == 0
def run(inp):
if lang == "aji_air":
p = subprocess.run([AJI, "run", "--grant", "in=io.read", "--grant", "out=io.write", "--stdin", inp, "main.air"], cwd=ws, capture_output=True, text=True, timeout=60)
if lang in ("aji_air", "aji_source"):
# `in` is a keyword in .aji, so the source entry point names it `input`.
argv = ["--grant", "in=io.read", "main.air"] if lang == "aji_air" else ["--grant", "input=io.read", "main.aji"]
p = subprocess.run([AJI, "run", argv[0], argv[1], "--grant", "out=io.write", "--stdin", inp, argv[2]], cwd=ws, capture_output=True, text=True, timeout=60)
try:
rec = json.loads(p.stdout)
except json.JSONDecodeError:
@@ -0,0 +1,5 @@
# Interface
- Source: `main.aji`, an `.aji` module.
- Entry point: `main(input: cap<io.read>, out: cap<io.write>)`; any return type.
- The program is run as `aji run --grant input=io.read --grant out=io.write --stdin TEXT main.aji`; the bytes written to standard output appear in the run record's `stdout` field.
@@ -0,0 +1,7 @@
#!/bin/sh
# Public test: one input.
out=$(aji run --grant input=io.read --grant out=io.write --stdin 'hello' main.aji) || { echo "FAIL: aji run failed"; echo "$out"; exit 1; }
case "$out" in
*'"stdout":"hello"'*) echo "PASS";;
*) echo "FAIL: unexpected run record: $out"; exit 1;;
esac
@@ -6,6 +6,7 @@
"prompt": "prompt.md",
"languages": {
"aji_air": {"workspace": "lang/aji_air", "test": "sh test.sh"},
"aji_source": {"workspace": "lang/aji_source", "test": "sh test.sh"},
"rust": {"workspace": "lang/rust", "test": "sh test.sh"},
"zig": {"workspace": "lang/zig", "test": "sh test.sh"}
},
+17 -2
View File
@@ -99,7 +99,7 @@ The harness calls `CMD WORKSPACE LANGUAGE TASK_DIR` outside the agent's sandbox.
| Variable | Contents |
|---|---|
| `AJIEVAL_LANGUAGE` | `aji_air`, `rust` or `zig` |
| `AJIEVAL_LANGUAGE` | `aji_air`, `aji_source`, `rust` or `zig` |
| `AJIEVAL_TOOLCHAIN_PATH` | the toolchain's PATH entries, `:`-separated |
| `AJIEVAL_TOOLCHAIN_DIRS` | the directories to bind read-only, one per line |
@@ -224,6 +224,21 @@ A first-generation snapshot is not available in Track B. There is no cost in dol
| `cumulative_context_tokens` | the text returned to the agent through its tool loop (every tool output, plus the task message), counted each time it was returned |
| `unique_reference_tokens` | the distinct documentation text the agent saw: distinct lines in the outputs of tool calls that touched `/docs` |
| `reference_coverage` | for a single-file reference (the Aji bundle), the fraction of its lines that the agent saw |
| `docs` | for a documentation directory (the Source Reference Bundle of `aji_source`), per file and per group of the profile's `doc_groups`; see below |
**Directory documentation (`metrics.context.docs`).**
| Field | Meaning |
|---|---|
| `quick_reference_tokens`, `source_docs_tokens`, `air_docs_tokens` | size of each group (`<group>_tokens`) |
| `full_source_docs_tokens` | every group except `air_docs` |
| `read_tokens_by_group` | tokens of the group's lines that the agent saw |
| `coverage_by_section` | per file: the fraction of its distinctive lines that the agent saw |
| `files_opened`, `unique_docs_read` | the files whose `/docs/…` path occurs in a tool input, and how many there are |
A line is *distinctive* when no other file of the mount contains it. A line seen in a tool output counts toward a group only if every file containing it belongs to that group. This keeps table rules, fences and sections copied into several files out of the attribution: the error-code table, for instance, is in both `diagnostics/` and `air/`.
**Task variants for `aji_source`.** A task supports the condition through a `languages.aji_source` entry: a starter workspace whose README names `main.aji` and the `main` signature, and a public test. `in` is a keyword in `.aji`, so a source entry point names that capability `input`, and the grant becomes `--grant input=io.read`. Example: [`dev-tasks/dev-echo/lang/aji_source/`](dev-tasks/dev-echo/lang/aji_source/). The evaluator gets `AJIEVAL_LANGUAGE=aji_source` and runs `aji check`/`aji run` on `main.aji`.
The gap between provider input and cumulative context is history resending, mostly cached. The gap between cumulative context and unique reference is rereading and verbose output. The tokenizer is `cl100k_base` if tiktoken is installed, otherwise bytes / 4. Each record names the one it used.
@@ -234,7 +249,7 @@ python3 -m ajieval freeze PLAN.json # PLAN.freeze.json: frozen state + rand
python3 -m ajieval matrix PLAN.json # verifies the freeze, runs cells sequentially in frozen order
python3 -m ajieval journal PLAN.json "observation" [--run RUN_ID]
python3 -m ajieval summary RUNS_DIR # shareable: PASS/FAIL matrix, per-cell metrics, aggregates
python3 -m ajieval profile RUNS_DIR # shareable: termination, output tokens, solution size, diagnostic-code occurrences
python3 -m ajieval profile RUNS_DIR # shareable: termination, output tokens, tool calls, solution size, lowered AIR size (aji_source), docs files read, IR-form and type-mismatch diagnostic counts, diagnostic-code occurrences
```
In Track B the repair metrics are derived from the transcript's shell commands, with their exit codes and outputs:
@@ -0,0 +1,14 @@
{
"comment": "P6A-9 dev regression, Track B: the dev tasks M and C (former smoke tasks) in Aji/source x 3 native agents x 1 run = 6 runs, compared with the frozen Aji/AIR smoke runs of the same agents. Dev material only, never evidence for H4. The tasks need an `aji_source` variant first (harness.md, task variants). Run from tools/eval: python3 -m ajieval matrix plan.json; then python3 -m ajieval profile on both run directories.",
"tasks": ["../aji-bench/tasks/<task-M>", "../aji-bench/tasks/<task-C>"],
"languages": ["aji_source"],
"models": [
{"label": "N1", "agent": "codex", "model": "gpt-6.1-sol", "effort": "high"},
{"label": "N2", "agent": "claude", "model": "claude-opus-5-5", "effort": "high"},
{"label": "N3", "agent": "opencode", "model": "zai-coding-plan/glm-5.3-flash"}
],
"runs": 1,
"evaluator": "../aji-bench/evaluate",
"evaluator_hash_path": "../aji-bench/evaluators",
"out": "runs-source-regression"
}
+33 -2
View File
@@ -30,10 +30,41 @@ Targets and the evaluation order are in `README.md`. Phase 6A is specified by RF
| P6A-5 | done | Source spans on lowered AIR; verifier diagnostics and trap records carry `source_location` and `air_location` | P6A-4 | `src/frontend/spans.zig`, `src/diag.zig` | every diagnostic of a `.aji` file points at source |
| P6A-6 | done | CLI: `aji check/run/lower file.aji` | P6A-4 | `src/main.zig` | same flags and run record as for `.air` |
| P6A-7 | todo | `.aji` twins for the Phase 0–3 conformance tests (same outcome or code) and the reference programs | P6A-5 | `tests/conformance/*/source/` | twins pass; the reference programs in `.aji` pass `--stress` |
| P6A-8 | todo | Source bundle and harness profile `aji_source` (Quick Reference first, full material indexed) | P6A-6 | `docs/agent/`, `tools/eval/languages/aji_source.json` | bundle measured |
| P6A-9 | todo | Dev regression on tasks M and C: `Aji/AIR` vs `Aji/source` (size, output tokens, tool calls, bundle use, diagnostics) | P6A-8 | results note | targets checked (≤ 1.5× Rust size, ≤ 2× output tokens, no SSA/CFG or `E0006` diagnostics) |
| P6A-8 | done | Source Reference Bundle (directory, `QUICK.md` front door, AIR reference only under `air/`), harness profile `aji_source` with per-group documentation metrics, Quick Reference examples checked against conformance programs, raw and normalized size metrics | P6A-6 | `docs/agent/source-bundle.txt`, `tools/eval/languages/aji_source.json` | bundle measured; every Quick Reference example is an excerpt of a checked program |
| P6A-9 | todo | Dev regression on tasks M and C: the frozen `Aji/AIR` runs vs new `Aji/source` runs, same agents (all three native agents) | P6A-8 | results note | criteria below reported |
| P6A-10 | todo | Phase 6A exit review | all | plan status | targets reported |
### P6A-9 criteria (owner decision, fixed before the runs)
Compared per agent with the frozen `Aji/AIR` run of the same task:
| Measure | Criterion |
|---|---|
| IR-form diagnostics (`E0001`–`E0006`, `E5001`, `E5002`; `ajieval profile`) | decrease ≥ 80 % |
| agent output tokens | decrease ≥ 50 % |
| tool calls | decrease materially |
| Aji semantic guarantees | unchanged (same verifier, same evaluator gates) |
| VSR | no regression |
| uncached provider input (strong agents) | substantial decrease |
| weakest agent (GLM) | an earlier `Aji/AIR` failure becomes a PASS, or repair cycles drop sharply |
Also reported:
- wall time;
- `unique_docs_read` and reading per group (`quick_reference`, `source_docs`, `air_docs`);
- diagnostic classes;
- source bytes, lowered AIR bytes (raw and normalized);
- type mismatches (`E1001` + `E7005`), counted apart from the IR-form classes so that relabeling cannot improve them.
Order:
1. source bundle and harness profile (P6A-8);
2. Quick Reference examples checked automatically (P6A-8);
3. M/C `Aji/source` dev runs;
4. comparison with the frozen AIR results;
5. Phase 6A review;
6. only then any decision about further frontend changes.
Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) and verifier-caught tests in `tests/conformance/source/`:
| Layer | Content | Status |
+8 -2
View File
@@ -66,7 +66,7 @@ effects [io.read, io.write]
- **Grants are not source semantics.** A program only declares `main`'s capability parameters. Granting them is instantiation after the module is lowered and verified (`aji run --grant …`, `aji.toml`, spec 12 §1). A missing grant is `not_instantiated` at run time, never a source or verifier diagnostic.
- **One source for every profile.** The frontend does not know the execution profile. The same `.aji` runs in the deterministic and the hosted profile (spec 11).
- **`trusted` is not available.** It is the boundary of runtime, std and toolchain modules (spec 13 §6.3), not something a program declares about its own code. The word is reserved and a `trusted` clause is `E7006`.
- **Unsafe operations** are the format-0 ones and nothing else: `ref unchecked s[i]` / `mut unchecked s[i]` (also bound: `ref unchecked e = s[i];`) lower to `borrow.index.unchecked`, and `assume(c)` to `assume`. Their boundary is the AIR one: the function declares `effects [unsafe]`, which propagates to its callers. Outside it the verifier reports `E6001`. There is no `unsafe { … }` block, because AIR has no block-level unsafe boundary. There is no FFI, raw address or syscall surface in format 0, so none exists in source.
- **Unsafe operations** are the format-0 ones and nothing else: `ref unchecked s[i]` / `mut unchecked s[i]` (also bound: `ref unchecked e = s[i];`) lower to `borrow.index.unchecked`, and `assume(c)` to `assume`. Their boundary is the AIR one: the function declares `effects [unsafe]`, which propagates to its callers. Outside it the verifier reports `E6001`. There is no `unsafe { … }` block, because AIR has no block-level unsafe boundary (owner decision: deferred; localizing unsafe inside a function would be an AIR change through its own RFC). There is no FFI, raw address or syscall surface in format 0, so none exists in source.
## 3. Types
@@ -377,7 +377,13 @@ A byte string or array used where a `slice<u8>` is expected is materialized in f
| `aji check file.aji` | parse, lower, verify |
| `aji run file.aji` | the same, then run (same flags and run record as for `.air`) |
| `aji lower file.aji` | print the canonical AIR |
| `aji lower --stats file.aji` | source and AIR size and the expansion ratio (bytes, non-empty lines): how much mechanical work the frontend took over |
| `aji lower --stats file.aji` | source and AIR size, expansion ratios and the two `mechanical_air_eliminated` metrics below |
| `aji lower --annotate file.aji` | the same with `; line:col-line:col` source spans before each instruction (not canonical; for debugging) |
Lowering is deterministic: the same source and compiler give byte-identical AIR, and the lowered AIR is canonical (parse → print reproduces it). The conformance runner checks both for every accepted `.aji` test.
**Size metrics** (`--stats`, non-normative tooling with a fixed definition):
- Sizes count code only: non-empty lines that are not comments (`//` in source, `;` in AIR), each with its newline.
- `mechanical_air_eliminated_raw` = 1 − `source_bytes` / `air_bytes`: how much of the AIR text the author did not write. This is the main engineering metric.
- `mechanical_air_eliminated_normalized` = 1 − `source_bytes` / `air_bytes_normalized`: the same against AIR in which every byte-string materialization counts as one logical constant operation. Such a materialization is the instructions from the string's `local.zero` to its final `borrow.end`, a store per non-zero byte, because format 0 has no byte-array constant. It is replaced by the single notional line ` const.bytes %<storage>, <literal>`, where `<literal>` is the canonical spelling: printable ASCII as is, otherwise the escapes `\n \r \t \0 \\ \" \xNN`. The storage's `local.alloc` is real frame storage and stays. No other instruction is normalized. The rule is the same for every program, and `byte_string_constants` reports how many were replaced.
+55
View File
@@ -69,3 +69,58 @@ test {
_ = parse;
_ = lower_mod;
}
pub const Size = struct { bytes: usize, lines: usize };
/// AIR size with every byte-string materialization (the instructions from
/// its `local.zero` to its final `borrow.end`) replaced by one notional
/// line ` const.bytes %<storage>, b"<canonical literal>"` (spec 15 §11).
/// Blank lines are not counted, as for the raw size.
pub fn normalizedSize(arena: std.mem.Allocator, o: lower_mod.Output) std.mem.Allocator.Error!Size {
var size: Size = .{ .bytes = 0, .lines = 0 };
var it = std.mem.splitScalar(u8, o.air, '\n');
var i: usize = 0;
var last: u32 = 0;
while (it.next()) |ln| : (i += 1) {
const k: u32 = if (i < o.constant_of.len) o.constant_of[i] else 0;
if (k != 0) {
if (k != last) {
const c = o.constants[k - 1];
const text = try std.fmt.allocPrint(arena, " const.bytes %{s}, {s}", .{ c.storage, try canonicalBytes(arena, c.bytes) });
size.bytes += text.len + 1;
size.lines += 1;
}
last = k;
continue;
}
last = 0;
if (std.mem.trim(u8, ln, " \t\r").len == 0) continue;
size.bytes += ln.len + 1;
size.lines += 1;
}
return size;
}
/// `b"…"` with printable ASCII as is and `\n \r \t \0 \\ \" \xNN` otherwise.
pub fn canonicalBytes(arena: std.mem.Allocator, bytes: []const u8) std.mem.Allocator.Error![]const u8 {
var out: std.ArrayList(u8) = .empty;
try out.appendSlice(arena, "b\"");
for (bytes) |c| switch (c) {
'\n' => try out.appendSlice(arena, "\\n"),
'\r' => try out.appendSlice(arena, "\\r"),
'\t' => try out.appendSlice(arena, "\\t"),
0 => try out.appendSlice(arena, "\\0"),
'\\' => try out.appendSlice(arena, "\\\\"),
'"' => try out.appendSlice(arena, "\\\""),
0x20...0x21, 0x23...0x5b, 0x5d...0x7e => try out.append(arena, c),
else => try out.print(arena, "\\x{x:0>2}", .{c}),
};
try out.append(arena, '"');
return out.items;
}
test canonicalBytes {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
try std.testing.expectEqualStrings("b\"hi\\n\\\"\\x01\"", try canonicalBytes(a.allocator(), "hi\n\"\x01"));
}
+36 -4
View File
@@ -123,6 +123,13 @@ pub const Output = struct {
/// The same AIR with `; line:col-line:col` comments before each
/// instruction (not canonical; `aji lower --annotate`).
annotated: []const u8,
/// Byte-string materializations, for the normalized size metric
/// (spec 15 §11): `constant_of[i]` is 0, or `k` when AIR line `i + 1`
/// belongs to the materialization of `constants[k - 1]`.
constant_of: []const u32,
constants: []const Constant,
pub const Constant = struct { storage: []const u8, bytes: []const u8 };
};
pub const Result = union(enum) {
@@ -142,10 +149,12 @@ pub fn lower(arena: Allocator, m: ast.Module) Allocator.Error!Result {
error.Unimplemented => return .{ .unimplemented = l.unimpl.? },
error.OutOfMemory => return error.OutOfMemory,
};
return .{ .ok = .{ .air = l.out.items, .lines = l.lines.items, .annotated = l.annotated.items } };
return .{ .ok = .{ .air = l.out.items, .lines = l.lines.items, .annotated = l.annotated.items, .constant_of = l.constant_of.items, .constants = l.constants.items } };
}
const Inst = struct { text: []const u8, span: ?Span };
/// `constant`: 0, or the 1-based index of the byte-string constant whose
/// materialization the instruction belongs to.
const Inst = struct { text: []const u8, span: ?Span, constant: u32 = 0 };
const Block = struct {
name: []const u8,
@@ -213,6 +222,10 @@ const Lowerer = struct {
out: std.ArrayList(u8) = .empty,
annotated: std.ArrayList(u8) = .empty,
lines: std.ArrayList(?Span) = .empty,
constant_of: std.ArrayList(u32) = .empty,
constants: std.ArrayList(Output.Constant) = .empty,
/// Set while a byte string is materialized: the tag for its instructions.
in_constant: u32 = 0,
problem: ?Problem = null,
unimpl: ?@FieldType(Result, "unimplemented") = null,
sigs: std.StringHashMapUnmanaged(FnSig) = .empty,
@@ -302,6 +315,11 @@ const Lowerer = struct {
// ------------------------------------------------------------ output
fn line(l: *Lowerer, text: []const u8, span: ?Span) Error!void {
try l.lineTagged(text, span, 0);
}
fn lineTagged(l: *Lowerer, text: []const u8, span: ?Span, constant: u32) Error!void {
try l.constant_of.append(l.arena, constant);
try l.out.appendSlice(l.arena, text);
try l.out.append(l.arena, '\n');
try l.lines.append(l.arena, span);
@@ -539,7 +557,7 @@ const Lowerer = struct {
}
try head.appendSlice(l.arena, ":");
try l.line(head.items, null);
for (b.insts.items) |inst| try l.line(try l.fmt(" {s}", .{inst.text}), inst.span);
for (b.insts.items) |inst| try l.lineTagged(try l.fmt(" {s}", .{inst.text}), inst.span, inst.constant);
}
}
@@ -564,7 +582,7 @@ const Lowerer = struct {
fn emit(l: *Lowerer, text: []const u8, span: Span) Error!void {
const b = &l.blocks.items[l.cur.?];
try b.insts.append(l.arena, .{ .text = text, .span = span });
try b.insts.append(l.arena, .{ .text = text, .span = span, .constant = l.in_constant });
}
/// Emits `%name = text` and returns the value.
@@ -1574,6 +1592,11 @@ const Lowerer = struct {
if (bytes.len == 0) return l.fail("E7006", span, "an empty byte string has no array type", &.{});
const ty = try l.arrayOf(.{ .int = "u8" }, bytes.len);
const st = try l.storageFor("bytes", ty, span);
// Everything from here to the final `borrow.end` is the constant's
// initialization; the `local.alloc` is real frame storage.
try l.constants.append(l.arena, .{ .storage = st, .bytes = bytes });
l.in_constant = @intCast(l.constants.items.len);
defer l.in_constant = 0;
try l.emit(try l.fmt("local.zero %{s}", .{st}), span);
const b = try l.def("w", try l.wrap(.mut, ty), try l.fmt("borrow.mut %{s}", .{st}), span);
for (bytes, 0..) |byte, i| {
@@ -2020,6 +2043,7 @@ const Lowerer = struct {
fn lowerFallible(l: *Lowerer, e: ast.Expr) Error!Fallible {
if (e.kind != .call) return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
if (laterLayer(e.kind.call.callee.*)) return l.notYet(e.span, "this operation (layers 7–8)");
const path = pathOf(e.kind.call.callee.*) orelse return l.fail("E7006", e.span, "outcome arms (`ok`, `err`, …) belong to a fallible operation", &.{});
const args = e.kind.call.args;
const want = struct {
@@ -2254,6 +2278,14 @@ fn elemOf(t: Ty) ?Ty {
};
}
/// `task.*`, `channel.*`, `mutex.*`: operations of layers 7–8.
fn laterLayer(e: ast.Expr) bool {
var buf: [64]u8 = undefined;
const text = dotted(e, &buf) orelse return false;
for ([_][]const u8{ "task.", "channel.", "mutex." }) |p| if (std.mem.startsWith(u8, text, p)) return true;
return false;
}
/// The built-in operation named by a callee such as `own.new` or
/// `cap.narrow.budget`; null for anything else.
fn pathOf(e: ast.Expr) ?[]const u8 {
+15 -3
View File
@@ -117,16 +117,28 @@ fn run(io: std.Io, arena: std.mem.Allocator, args: []const [:0]const u8, out: *s
}.count;
const sc = code(source);
const ac = code(o.air);
const nc = try aji.frontend.normalizedSize(arena, o);
const ratio = struct {
fn f(a: usize, b: usize) f64 {
return @as(f64, @floatFromInt(a)) / @as(f64, @floatFromInt(@max(b, 1)));
}
}.f;
var s: std.json.Stringify = .{ .writer = out };
try s.write(.{
.source_bytes = sc.bytes,
.source_lines = sc.lines,
.air_bytes = ac.bytes,
.air_lines = ac.lines,
.expansion_bytes = @as(f64, @floatFromInt(ac.bytes)) / @as(f64, @floatFromInt(@max(sc.bytes, 1))),
.expansion_lines = @as(f64, @floatFromInt(ac.lines)) / @as(f64, @floatFromInt(@max(sc.lines, 1))),
.air_bytes_normalized = nc.bytes,
.air_lines_normalized = nc.lines,
.byte_string_constants = o.constants.len,
.expansion_bytes = ratio(ac.bytes, sc.bytes),
.expansion_lines = ratio(ac.lines, sc.lines),
// 1 − source/AIR: the share of AIR text the frontend writes for the author.
.mechanical_air_eliminated = 1.0 - @as(f64, @floatFromInt(sc.bytes)) / @as(f64, @floatFromInt(@max(ac.bytes, 1))),
.mechanical_air_eliminated_raw = 1.0 - ratio(sc.bytes, ac.bytes),
// The same against AIR with each byte-string materialization counted
// as one logical constant operation (spec 15 §11).
.mechanical_air_eliminated_normalized = 1.0 - ratio(sc.bytes, nc.bytes),
});
try out.writeByte('\n');
return .accepted;
@@ -0,0 +1,46 @@
// Quick Reference §4: borrows and moves.
// expect: run
// result: 36
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.borrows
struct P {
a: u64,
b: u64,
}
fn main() -> u64
effects []
{
let i = 2usize;
var out: [u64; 4] = zero;
var total: u64 = 0;
var data: [u64; 8] = zero;
data[0] = 7; // element write (array variables get frame storage automatically)
{
mut s = data; // exclusive borrow to the end of this block
s[1] = s[0] + 1; // checked index; out of range traps T0008
let n = s.len;
if i < s.len { s[i] = 0; } // no runtime check here: the verifier proves i < s.len
let (l, r) = s.split_at(4); // two disjoint halves of s
l[3] = n as! u64;
r[0] = 9;
}
slice.copy(mut out[0..4], ref data[4..8]); // borrows as arguments end after the call
total = total + out[0];
var p: P = P { a: 1, b: 2 };
{
ref q = p; // shared borrow of a struct; q.a reads a field
total = total + q.a + q.b;
}
var count: u64 = 0;
bump(mut count);
total + count + data[0] + data[1] + data[3]
}
fn bump(c: mut<u64>) -> void
effects []
{
*c = *c + 1; // through c: mut<u64>
}
@@ -0,0 +1,26 @@
// Quick Reference §7: a bounded channel, every outcome handled (layer 7).
// expect: run
// grant: heap=mem.alloc:1024
// result: 5
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.qrchannels
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
let v = 5u64;
var got: u64 = 0;
match channel.make<u64>(2, heap) { // effect mem.alloc
ok(tx, rx) => {
let tx2 = channel.dup(tx);
channel.close_sender(move tx2);
match channel.send(tx, v) { ok => {} closed(v) => { trap; } cancelled(v) => { trap; } } // a linear v: `move v`
match channel.recv(rx) { ok(v) => { got = v; } closed => { trap; } cancelled => { trap; } }
channel.close_sender(move tx);
match channel.close_receiver(move rx) { ok => {} pending(rx) => { trap; } } // drain, then close again
}
err(e) => { trap; }
}
got
}
@@ -0,0 +1,21 @@
// Quick Reference §1: the skeleton program.
// expect: run
// grant: input=io.read
// grant: out=io.write
// stdin: hi
// result: null
// stdout: hi
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.echo
fn main(input: cap<io.read>, out: cap<io.write>) -> void
effects [io.read, io.write]
{
var buf: [u8; 64] = zero;
loop {
let n = io.stdin_read(input, mut buf) or trap;
if n == 0 { return; }
io.stdout_write(out, ref buf[0..n]) or trap;
}
}
@@ -0,0 +1,30 @@
// Quick Reference §5: every outcome is a match arm.
// expect: run
// grant: c=fs.read:/data
// grant: listen=net.listen
// grant: connect=net.connect
// vfs: /data/in.txt=abc
// result: 3
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.failure
fn main(c: cap<fs.read>, listen: cap<net.listen>, connect: cap<net.connect>) -> u8
effects [fs.read, net.listen, net.connect, net.read, net.write]
{
var buf: [u8; 8] = zero;
var got: usize = 0;
match fs.open_read(c, b"/data/in.txt") {
ok(f) => { got = fs.read(f, mut buf) or trap; fs.close(move f) or trap; }
err(e) => { return 1u8; }
}
let l = net.listen(listen, b"127.0.0.1:7") or trap;
let peer = net.connect(connect, b"127.0.0.1:7") or trap;
let conn = net.accept(l) or trap;
net.send_all(peer, ref buf[0..got]) or trap;
let n = net.recv(conn, mut buf) or trap; // any non-ok outcome traps
net.close_stream(move conn) or trap;
net.close_stream(move peer) or trap;
net.close_listener(move l) or trap;
n as! u8
}
@@ -0,0 +1,17 @@
// Quick Reference §7: a mutex, a lock block and mutex.take (layer 8).
// expect: run
// result: 1
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.qrmutex
fn main() -> u64
effects [task.wait]
{
let m = mutex.make(0u64);
lock ref m as count { // count: mut<u64>; unlocked at every exit of the block
*count = *count + 1;
} cancelled { trap; }
let total = mutex.take(move m); // needs no live borrow of m
total
}
@@ -0,0 +1,23 @@
// Quick Reference §6: allocation in a region with an explicit region borrow.
// expect: run
// grant: heap=mem.alloc:256
// result: 2
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.qrregion
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc]
{
let r = region.create(heap) or trap;
var v: u64 = 0;
{
ref arena = r;
let item = region.new(arena, 1u64) or trap; // item: mut<u64>, ends with this block
*item = *item + 1;
v = *item;
}
region.reset(r);
region.destroy(move r);
v
}
@@ -0,0 +1,35 @@
// Quick Reference §7: select over a receive and a send (layer 8).
// expect: run
// grant: heap=mem.alloc:1024
// result: 1
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.qrselect
fn main(heap: cap<mem.alloc>) -> u64
effects [mem.alloc, task.wait]
{
let job = 9u64;
var which: u64 = 0;
match channel.make<u64>(1, heap) {
ok(tx_a, rx_a) => {
match channel.make<u64>(1, heap) {
ok(tx_b, rx_b) => {
channel.close_sender(move tx_a);
select {
recv(rx_a) { ok(x) => { which = 2; } closed => { which = 1; } }
send(tx_b, move job) { ok => { which = 1; } closed(job) => { which = 3; } }
cancelled(job) => { trap; }
}
channel.close_sender(move tx_b);
match channel.close_receiver(move rx_a) { ok => {} pending(rx_a) => { trap; } }
match channel.recv(rx_b) { ok(v) => {} closed => {} cancelled => { trap; } }
match channel.close_receiver(move rx_b) { ok => {} pending(rx_b) => { trap; } }
}
err(e) => { trap; }
}
}
err(e) => { trap; }
}
which
}
@@ -0,0 +1,44 @@
// Quick Reference §3: statements and expressions.
// expect: run
// result: 50
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.statements
enum Message {
Stop,
Value(u64),
}
fn main() -> u64
effects []
{
let a = 20u64;
let b = 22u64;
let c = a < b;
let d = false;
let t = 1u8;
let n = 4usize;
let m = Message::Value(7);
var acc: u64 = 0;
let x = a + b; // immutable
var i: usize = 0; // variable; reassign with i = i + 1;
var buf: [u8; 16] = zero; // zero-initialized storage
if c { acc = acc + 1; } else if d { acc = acc + 2; } else { acc = acc + 3; }
while i < n { i = i + 1; buf[0] = 1; }
for k in 0..n { acc = acc + k as! u64; }
loop {
i = i + 1;
if i > 6 { break; }
if i == 5 { continue; }
acc = acc + 1;
}
let y = if c { 1 } else { 2 };
let w: u64 = match m {
Message::Stop => 0,
Message::Value(v) => v,
};
match t { 0 => { acc = acc + 100; } 1 => { assert(acc + buf[0] as u64 == 9); } _ => { trap; } }
assert(c);
return x + y + w;
}
@@ -0,0 +1,40 @@
// Quick Reference §7: a scope with two tasks over disjoint halves (layer 7).
// expect: run
// result: 30
// phase: 6
// spec: docs/agent/quick-reference.md
module demo.qrtasks
fn square(s: slice_mut<u64>) -> u64
effects []
{
var sum: u64 = 0;
for i in 0..s.len {
s[i] = s[i] * s[i];
sum = sum + s[i];
}
sum
}
fn main() -> u64
effects [task.spawn, task.wait]
{
var data: [u64; 8] = [1; 8];
data[4] = 2;
data[5] = 2;
data[6] = 2;
data[7] = 4;
var total: u64 = 0;
{
mut d = data; // data: [u64; 8]
scope s { // every task spawned in s must be joined before the block ends (E4301)
let (l, r) = d.split_at(4);
let a = task.spawn(s, square, l); // borrows are lent to the task until its join
let b = task.spawn(s, square, r);
let x = task.join(move a);
let y = task.join(move b);
total = x + y;
}
}
total
}
+242 -49
View File
@@ -1,86 +1,160 @@
//! Builds the Agent Reference Bundle (spec 14 §3.7) from docs/agent/bundle.txt
//! and reports its size. Deterministic: same sources, same bytes.
//! 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>
//! writes <output dir>/reference-bundle.md and <output dir>/report.json
//! aji-agent-bundle --check <repo root>
const std = @import("std");
const aji = @import("aji");
const Error = error{ BadManifest, SectionNotFound };
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>\n", .{});
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], .{});
const manifest = try root.readFileAlloc(io, "docs/agent/bundle.txt", arena, .limited(1 << 20));
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], .{});
var bundle: std.ArrayList(u8) = .empty;
var files: std.ArrayList([]const u8) = .empty;
// 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 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 });
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(text, h) orelse {
std.debug.print("bundle.txt:{d}: no heading starting with \"{s}\" in {s}\n", .{ line_no, h, path });
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 text;
try bundle.print(arena, "<!-- source: {s}{s}{s} -->\n", .{ path, if (heading != null) " :: " else "", heading orelse "" });
try bundle.appendSlice(arena, std.mem.trimEnd(u8, part, "\n"));
try bundle.appendSlice(arena, "\n\n");
} 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 (files.items) |f| known = known or std.mem.eql(u8, f, path);
if (!known) try files.append(arena, path);
for (sources.items) |f| known = known or std.mem.eql(u8, f, path);
if (!known) try sources.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();
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
@@ -110,6 +184,115 @@ fn section(text: []const u8, prefix: []const u8) ?[]const u8 {
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.").?);
@@ -119,3 +302,13 @@ test section {
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));
}
+32
View File
@@ -4,6 +4,11 @@
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
@@ -23,6 +28,30 @@ 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):
@@ -46,6 +75,9 @@ def count_tokens(text):
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:
+83 -2
View File
@@ -11,6 +11,17 @@
reference_coverage for a single-file reference (the Aji Agent
Reference Bundle): the fraction of its
non-empty lines that appeared in those outputs
docs for a directory of documentation (the Source
Reference Bundle), per file and per group of
the profile's `doc_groups`:
<group>_tokens size of the group (e.g. quick_reference_tokens,
source_docs_tokens, air_docs_tokens)
full_source_docs_tokens every group except air_docs
read_tokens_by_group tokens of the group's lines the agent saw
coverage_by_section per file: fraction of its distinctive lines
(in no other file of the mount) seen
files_opened files whose /docs path occurs in a tool input
unique_docs_read how many files were opened
The gap between them shows where context is amplified: rereading the same
documentation, verbose tool output, or the provider resending history.
@@ -86,9 +97,76 @@ def tool_events_native(agent_name, transcript_path):
return out
def metrics(tool_events, task_message, docs, provider):
def _doc_files(docs):
"""[(path under /docs, host path)] of every file in the mounts."""
out = []
for name, p in docs:
if os.path.isfile(p):
out.append((name or os.path.basename(p), p))
continue
for d, _, files in os.walk(p):
for f in sorted(files):
hp = os.path.join(d, f)
rel = os.path.relpath(hp, p)
out.append((os.path.join(name, rel) if name else rel, hp))
return sorted(out)
def _group_of(rel, groups):
for g, prefixes in groups.items():
for pre in prefixes:
if rel == pre or (pre.endswith("/") and rel.startswith(pre)):
return g
return "other"
def doc_metrics(tool_events, docs, groups, seen, count):
"""Per-file and per-group reading of a documentation directory.
Only distinctive lines count: a line contributes to a file's coverage
only if no other file in the mount contains it, and to a group's read
tokens only if every file containing it is in that group. Table rules,
fences and sections copied into several files (the error-code table is
in diagnostics/ and in air/) would otherwise be credited to files the
agent never opened."""
files = _doc_files(docs)
inputs = "\n".join(i for i, _ in tool_events)
texts, owners = {}, {}
for rel, hp in files:
with open(hp, encoding="utf-8", errors="replace") as f:
texts[rel] = f.read()
for x in {_norm(x) for x in texts[rel].splitlines() if _norm(x)}:
owners.setdefault(x, set()).add(rel)
own = {}
for x, fs in owners.items():
if len(fs) == 1:
own.setdefault(next(iter(fs)), set()).add(x)
coverage, opened, size, read_lines = {}, [], {}, {}
for rel, _ in files:
mine = own.get(rel, set())
coverage[rel] = round(len(mine & seen) / len(mine), 4) if mine else 0.0
if "/docs/" + rel in inputs:
opened.append(rel)
g = _group_of(rel, groups)
size[g] = size.get(g, 0) + count(texts[rel])
read_lines.setdefault(g, set())
for x in seen:
gs = {_group_of(f, groups) for f in owners.get(x, ())}
if len(gs) == 1:
read_lines[gs.pop()].add(x)
out = {f"{g}_tokens": n for g, n in sorted(size.items())}
out["full_source_docs_tokens"] = sum(n for g, n in size.items() if g != "air_docs")
out["read_tokens_by_group"] = {g: (count("\n".join(sorted(ls))) if ls else 0) for g, ls in sorted(read_lines.items())}
out["coverage_by_section"] = coverage
out["files_opened"] = opened
out["unique_docs_read"] = len(opened)
return out
def metrics(tool_events, task_message, docs, provider, groups=None):
"""`docs` is [(mount name, host path)]; `provider` holds input, output,
cached_input as counted by the provider (None when unknown)."""
cached_input as counted by the provider (None when unknown); `groups` is
the profile's `doc_groups` ({name: [file or "dir/" prefix]})."""
name, count = _tokenizer()
cumulative = count(task_message) + sum(count(o) for _, o in tool_events)
seen = set()
@@ -106,6 +184,8 @@ def metrics(tool_events, task_message, docs, provider):
ref = {_norm(x) for x in f.read().splitlines() if _norm(x)}
coverage = round(len(ref & seen) / len(ref), 4) if ref else None
inp, cached = provider.get("input"), provider.get("cached_input")
dirs = [p for _, p in docs if os.path.isdir(p)]
extra = {"docs": doc_metrics(tool_events, docs, groups or {}, seen, count)} if dirs else {}
return {
"tokenizer": name,
"provider_input_tokens": {"total": inp, "cached": cached, "uncached": None if inp is None or cached is None else inp - cached, "output": provider.get("output")},
@@ -113,4 +193,5 @@ def metrics(tool_events, task_message, docs, provider):
"unique_reference_tokens": unique,
"reference_coverage": coverage,
"tool_outputs": len(tool_events),
**extra,
}
+1 -1
View File
@@ -451,7 +451,7 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
facts = ag.parse(transcript)
tokens = normalize_usage(facts.get("usage") or {})
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens)
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens, profile.get("doc_groups"))
cyc = cycles(profile, lang.get("test"), command_events(agent_name, transcript))
with open(os.path.join(run_dir, "patch.diff"), "w") as f:
f.write(diff_tree(pristine, workspace))
+2 -1
View File
@@ -129,7 +129,8 @@ def run_one(task_dir, lang_name, provider_name, model, out_dir, model_class=None
metrics[key + "_count"] = len(metrics[key])
metrics["documentation_tokens_estimate"] = util.estimate_tokens(metrics["documentation_bytes_read"])
metrics["context"] = context.metrics(context.tool_events_track_a(os.path.join(run_dir, "events.jsonl")), message, docs,
{"input": metrics["input_tokens"], "output": metrics["output_tokens"], "cached_input": metrics["cached_input_tokens"]})
{"input": metrics["input_tokens"], "output": metrics["output_tokens"], "cached_input": metrics["cached_input_tokens"]},
profile.get("doc_groups"))
metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"])
verdict = first_verdict = None
+39 -5
View File
@@ -167,7 +167,7 @@ def _diagnostic_codes(r, run_dir):
outputs = [json.loads(l).get("output") or "" for l in open(os.path.join(run_dir, "events.jsonl")) if '"event": "command"' in l]
lang = r["language"]["name"]
for o in outputs:
if lang == "aji_air":
if lang in ("aji_air", "aji_source"):
counts.update(re.findall(r'"code":"([ET]\d{4})"', o))
elif lang == "rust":
counts.update(re.findall(r"error\[(E\d{4})\]", o))
@@ -177,14 +177,43 @@ def _diagnostic_codes(r, run_dir):
return dict(counts.most_common())
# Diagnostics about the textual form of AIR (syntax, names, module header,
# SSA, CFG): the classes the source frontend is meant to remove. Type
# mismatches (E1001 from AIR, E7005 from source) are semantic and counted
# separately, so relabeling cannot make the IR-form count look better.
IR_FORM = {"E0001", "E0002", "E0003", "E0004", "E0005", "E0006", "E5001", "E5002"}
TYPE_MISMATCH = {"E1001", "E7005"}
def _lowered_size(run_dir):
"""`aji lower --stats` summed over the workspace's .aji files: raw and
normalized lowered AIR bytes (spec 15 §11); None when nothing lowers."""
import subprocess
aji = os.path.join(util.REPO, "zig-out", "bin", "aji")
raw = norm = 0
found = False
for root, dirs, names in os.walk(os.path.join(run_dir, "workspace")):
dirs[:] = [d for d in dirs if d not in ("zig-out", ".zig-cache", ".git")]
for n in names:
if not n.endswith(".aji"):
continue
r = subprocess.run([aji, "lower", "--stats", os.path.join(root, n)], capture_output=True, text=True)
if r.returncode != 0:
continue
st = json.loads(r.stdout)
raw, norm, found = raw + st["air_bytes"], norm + st["air_bytes_normalized"], True
return (raw, norm) if found else None
def profile(paths):
"""Per-run cost profile for failure and cost analysis (protocol §27,
§38): termination, output tokens, solution size and diagnostic codes.
Shareable: numbers and diagnostic codes only."""
from . import languages
out = ["| task | language | agent | termination | output tokens | source files / lines / bytes | diagnostic codes (count) |",
"|---|---|---|---|---|---|---|"]
out = ["| task | language | agent | termination | output tokens | tool calls | source files / lines / bytes | lowered AIR bytes raw / normalized | docs files read | IR-form diagnostics | type mismatches | diagnostic codes (count) |",
"|---|---|---|---|---|---|---|---|---|---|---|---|"]
for p in paths:
for f in sorted(glob.glob(os.path.join(p, "**", "run.json"), recursive=True)):
if "/superseded/" in f:
@@ -195,6 +224,11 @@ def profile(paths):
files, lines, nbytes = _source_size(d, exts)
codes = _diagnostic_codes(r, d)
m = r["metrics"]
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | "
f"{files} / {lines} / {nbytes} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
lowered = _lowered_size(d) if r["language"]["name"] == "aji_source" else None
docs = (m.get("context") or {}).get("docs") or {}
ir = sum(v for k, v in codes.items() if k in IR_FORM)
ty = sum(v for k, v in codes.items() if k in TYPE_MISMATCH)
out.append(f"| {r['task']['id']} | {r['language']['name']} | {_agent_key(r)} | {m.get('termination')} | {m.get('output_tokens')} | {m.get('tool_calls')} | "
f"{files} / {lines} / {nbytes} | {f'{lowered[0]} / {lowered[1]}' if lowered else '-'} | "
f"{docs.get('unique_docs_read', '-')} | {ir} | {ty} | {', '.join(f'{k} {v}' for k, v in codes.items()) or '-'} |")
return "\n".join(out)
+38
View File
@@ -0,0 +1,38 @@
{
"name": "aji_source",
"display": "Aji (condition Aji/source: .aji source language 0.1)",
"toolchain": {
"binaries": [
"${REPO}/zig-out/bin/aji"
],
"version": [
[
"${REPO}/zig-out/bin/aji",
"features"
]
]
},
"docs": {
"env": "AJI_EVAL_AJI_SOURCE_DOCS",
"default": "${REPO}/zig-out/agent/source"
},
"doc_groups": {
"quick_reference": ["QUICK.md"],
"source_docs": ["language/", "diagnostics/"],
"air_docs": ["air/"]
},
"source_extensions": [
".aji"
],
"instructions": "Language: Aji, written as `.aji` source (Aji source language 0.1).\nToolchain: `aji check FILE.aji` verifies a module and prints diagnostics as JSON lines that point at your source; `aji run [--grant P=KIND[:SCOPE]]... [--stdin TEXT] FILE.aji` verifies and runs `main` in the deterministic profile and prints one JSON run record; `aji --help` lists all commands.\nDocumentation: /docs (read-only). Start with /docs/QUICK.md: it covers most programs and says which file under /docs/language or /docs/diagnostics to open for details. /docs/air is the reference for AIR, the language `.aji` lowers to; you do not need it to write `.aji`.",
"classify": {
"check": [
"aji check"
],
"build": [],
"test": [
"aji run"
]
},
"diagnostic_pattern": "\"severity\":\"error\""
}
+63
View File
@@ -0,0 +1,63 @@
[
[
{
"text": "Reading the interface."
},
{
"tool": "read_file",
"input": {
"path": "README.md"
}
}
],
[
{
"tool": "read_file",
"input": {
"path": "/docs/QUICK.md"
}
}
],
[
{
"tool": "write_file",
"input": {
"path": "main.aji",
"content": "broken"
}
}
],
[
{
"tool": "run",
"input": {
"command": "aji check main.aji"
}
}
],
[
{
"tool": "write_file",
"input": {
"path": "main.aji",
"content": "module demo.echo\n\nfn main(input: cap<io.read>, out: cap<io.write>) -> void\neffects [io.read, io.write]\n{\n var buf: [u8; 64] = zero;\n loop {\n let n = io.stdin_read(input, mut buf) or trap;\n if n == 0 { return; }\n io.stdout_write(out, ref buf[0..n]) or trap;\n }\n}\n"
}
}
],
[
{
"tool": "run",
"input": {
"command": "sh test.sh"
}
}
],
[
{
"tool": "finish",
"input": {
"summary": "done"
}
}
]
]
+15
View File
@@ -102,6 +102,21 @@ class RunTest(unittest.TestCase):
self.assertEqual(len(rows), len(languages.available()))
self.assertTrue(all(r["verified_success_rate"] == 1.0 for r in rows))
@unittest.skipUnless(SANDBOX == "bwrap", "bubblewrap unavailable")
def test_source_docs_metrics(self):
# The Source Reference Bundle is a directory: reading is measured per file and per group.
_, rec = self.run_lang("aji_source")
self.assertTrue(rec["accepted"], rec["verdict"])
d = rec["metrics"]["context"]["docs"]
self.assertEqual(d["files_opened"], ["QUICK.md"])
self.assertEqual(d["unique_docs_read"], 1)
self.assertGreater(d["coverage_by_section"]["QUICK.md"], 0.9)
self.assertEqual(d["coverage_by_section"]["air/reference.md"], 0.0)
for g in ("quick_reference_tokens", "source_docs_tokens", "air_docs_tokens", "full_source_docs_tokens"):
self.assertGreater(d[g], 0)
self.assertEqual(d["full_source_docs_tokens"], d["quick_reference_tokens"] + d["source_docs_tokens"])
self.assertEqual(d["read_tokens_by_group"]["air_docs"], 0)
def test_tool_budget(self):
_, rec = self.run_lang("aji_air", limits={"tool_calls": 3})
self.assertEqual(rec["metrics"]["termination"], "budget_tool_calls")