Compare commits

...
131 Commits
Author SHA1 Message Date
dev e3fc896a0a wip: shield index relations, dev evaluation tasks, Q-063 audit notes
Verifier borrow/provenance work, new phase3 shield_index conformance cases,
dev-intervals/dev-lru/dev-shards tasks with evaluate.py harness, and agent skill/hook config.
2026-10-17 12:30:37 +03:00
dev 2d750a0525 cli: index loop-exit edges and reuse negative After queries; fix loop-exit diagnostics (Q-063, Q-064) 2026-10-14 18:26:44 +03:00
dev 2fb882c704 docs: Q-063 profiling audit and harness, record Q-064 2026-10-14 15:31:35 +03:00
dev 17cbe3eb4e docs: record deep nested loop probe under Q-061 and Q-063 2026-10-14 13:41:33 +03:00
dev ac17e84aeb docs: record that the original Q-060 process was stopped 2026-10-14 12:30:03 +03:00
dev 0d6566632c conformance: gc skip header and sampled per-step siblings for vector suites 2026-10-14 11:28:26 +03:00
dev 3f1dc84676 docs: close Q-060 with full per-step GC validation of all 1,793 tests 2026-10-14 07:47:03 +03:00
dev 6974d60771 ci: run only on manual dispatch 2026-10-13 17:25:29 +03:00
dev c4735f7ace docs: attribute the depth probe battery correctly
ci / build (ubuntu-latest) (push) Failing after 31m48s
ci / build (macos-latest) (push) Canceled after 0s
ci / extended (push) Failing after 3h0m3s
2026-10-13 14:10:59 +03:00
dev f00f50f45b docs: close Q-061 native-stack defect, record Q-063 superlinear lowering 2026-10-13 14:10:50 +03:00
dev 3154588490 docs: simplify license statement
ci / build (ubuntu-latest) (push) Failing after 11m55s
ci / build (macos-latest) (push) Canceled after 0s
ci / extended (push) Failing after 16m54s
2026-10-13 13:08:09 +03:00
dev 0078d451f7 Add MIT license
ci / extended (push) Failing after 36m46s
ci / build (ubuntu-latest) (push) Failing after 41m55s
ci / build (macos-latest) (push) Canceled after 0s
2026-10-13 13:02:06 +03:00
dev 4bf92b23d6 docs: refine P6-7 scope and same-code breakdown
ci / build (ubuntu-latest) (push) Failing after 37m5s
ci / build (macos-latest) (push) Canceled after 0s
ci / extended (push) Failing after 42m4s
2026-10-13 12:38:03 +03:00
dev 18d2976f24 docs: close Phase 6 with owner-confirmed deferral of contracts and literal twins 2026-10-13 09:46:29 +03:00
dev a3224ea44e docs: mark P6-6/P6-7 split as pending owner confirmation 2026-10-13 00:16:48 +03:00
dev b472d33273 docs: provisional Phase 6 exit review, defer contracts and literal twins 2026-10-13 00:16:26 +03:00
dev f419063e86 cli: lower block, if, match and select control iteratively 2026-10-13 00:15:13 +03:00
dev 5c883ace54 cli: query SSA liveness with iterative continuations 2026-10-11 23:44:20 +03:00
dev b2c551047c cli: parse control flow with shared continuations 2026-10-11 22:18:21 +03:00
dev 9534359595 cli: lower place bases iteratively 2026-10-11 20:23:34 +03:00
dev dc314ddf8a docs: record current per-step GC validation evidence 2026-10-11 19:32:45 +03:00
dev 29c1928aa1 cli: lower scalar index operands iteratively 2026-10-11 19:15:23 +03:00
dev 7ccded2b59 cli: lower mutex value operands iteratively 2026-10-11 18:41:13 +03:00
dev c5d0d09a81 cli: lower task spawn arguments iteratively 2026-10-11 17:34:08 +03:00
dev b85df6777e cli: lower task join operands iteratively 2026-10-11 16:22:31 +03:00
dev 8d6792d4f1 cli: lower atomic value operands iteratively 2026-10-11 15:54:37 +03:00
dev 062fce5cfd cli: lower consuming ownership builtin operands iteratively 2026-10-11 15:09:00 +03:00
dev 5cc69393e4 cli: lower boolean builtin operands iteratively 2026-10-11 14:43:00 +03:00
dev 627ad8f857 cli: lower enum payloads iteratively 2026-10-11 13:23:36 +03:00
dev 8c34a4d64d cli: lower array initializers iteratively 2026-10-11 11:29:24 +03:00
dev 6d2c4d40a8 cli: lower struct fields iteratively 2026-10-11 00:22:18 +03:00
dev 0791a50eb9 cli: lower ordinary call arguments iteratively 2026-10-10 22:53:35 +03:00
dev bda43d2ecb cli: parse nested expression contexts iteratively 2026-10-10 22:13:08 +03:00
dev 371329f3f0 cli: parse qualified constructor paths iteratively 2026-10-10 19:23:50 +03:00
dev d39a422b2b cli: transform generic source ASTs iteratively 2026-10-10 19:07:06 +03:00
dev 50a7575efb cli: propagate host allocation errors from source queries 2026-10-10 18:32:23 +03:00
dev 6945b511a4 cli: lower scalar binary operands iteratively 2026-10-10 17:55:46 +03:00
dev e3f4695efe cli: search expected source types iteratively 2026-10-10 17:34:57 +03:00
dev e862e03f2b cli: query expression types and callee paths iteratively 2026-10-10 17:21:30 +03:00
dev dd73b84085 cli: lower unary spines and mark storage iteratively 2026-10-10 16:55:37 +03:00
dev c36b269289 cli: parse unary prefix chains iteratively 2026-10-10 16:32:29 +03:00
dev fb80413b37 interp: release execution heaps on allocation failure 2026-10-10 16:21:10 +03:00
dev 0387405d48 tests: flush conformance progress and correct live GC evidence 2026-10-10 16:07:19 +03:00
dev 46bd29953f cli: query field annotations iteratively and close type-depth audit 2026-10-10 15:46:46 +03:00
dev d98ddbc073 cli: write composed specialization identities iteratively 2026-10-10 15:30:28 +03:00
dev f5e2af15e8 cli: emit source SSA zero iteratively 2026-10-10 15:14:49 +03:00
dev c1bf99af83 cli: inspect source linear queries iteratively 2026-10-10 15:01:42 +03:00
dev 232f93f188 cli: compare source types iteratively 2026-10-10 14:51:29 +03:00
dev 936d65359c cli: convert source types to AIR iteratively 2026-10-10 14:44:48 +03:00
dev f18b41dd3d cli: print source types iteratively and propagate allocation errors 2026-10-10 14:31:50 +03:00
dev 4aad95c4a8 cli: evaluate source nominal properties with continuations 2026-10-10 14:18:14 +03:00
dev 53907ecf25 cli: inspect anonymous source properties iteratively 2026-10-10 13:30:10 +03:00
dev b23f3e678e cli: resolve source annotations with explicit continuations 2026-10-10 13:13:32 +03:00
dev 24a3876003 cli: inspect generic uses with an explicit worklist 2026-10-10 13:04:58 +03:00
dev b2a0251376 docs: record nominal property review and query guidance 2026-10-10 12:46:42 +03:00
dev cef944d30e cli: parse nested source types with explicit continuations 2026-10-10 12:41:41 +03:00
dev 35635603f9 air: query cache-free nominal properties without recursion 2026-10-10 12:13:49 +03:00
dev 897f538840 interp: evaluate cache-free nominal sizes without recursion 2026-10-10 11:05:22 +03:00
dev c9064418bd interp: serialize runtime values without recursive JSON nesting 2026-10-10 00:01:40 +03:00
dev 6353ab5f5d interp: calculate runtime value sizes without recursion 2026-10-09 22:55:04 +03:00
dev f92817b127 interp: trace collector values with explicit continuations 2026-10-09 22:31:05 +03:00
dev afc40f8502 interp: copy aggregate value trees without native recursion 2026-10-09 21:52:08 +03:00
dev b1b9b4cf03 interp: materialize zero values with explicit continuations 2026-10-09 21:38:59 +03:00
dev 9549a3dec6 diag: guide parameter mutability and explicit array slice arguments 2026-10-09 21:12:26 +03:00
dev 6a02659f31 diag: explain pointer-sized cast restrictions in source advice 2026-10-09 21:01:58 +03:00
dev 8a714ba6de report: collect capability kinds without recursive type walks 2026-10-09 20:25:47 +03:00
dev 53030efcea air: compare and print nested types without recursion 2026-10-09 20:09:00 +03:00
dev d0fcc3d473 air: evaluate anonymous type properties iteratively 2026-10-09 19:59:36 +03:00
dev b0cd7d74ff verifier: traverse type validity and layouts iteratively 2026-10-09 19:51:03 +03:00
dev 3906ce5a9b verifier: evaluate type sizes with explicit continuations 2026-10-09 19:28:03 +03:00
dev c94e5a0868 air: parse anonymous type constructors iteratively 2026-10-09 19:04:54 +03:00
dev ba99ad6727 tests: audit source rejections before AIR lowering 2026-10-09 18:49:28 +03:00
dev a491eba193 tests: add nested-size source rejection twins 2026-10-09 18:43:18 +03:00
dev b3051f161c docs: map contract source errors and compatibility rejections 2026-10-09 18:36:04 +03:00
dev c633f23952 docs: specify contract runtime continuations and failure context 2026-10-09 18:27:55 +03:00
dev 2db752dba9 docs: define contract AIR bindings and access diagnostics 2026-10-09 17:00:38 +03:00
dev 5ed0d86e36 docs: specify contract names and diagnostic witnesses 2026-10-09 16:44:08 +03:00
dev 8df6cacf12 docs: refine checked-type properties and invariant audit inventory 2026-10-09 16:18:56 +03:00
dev 4cda44823d frontend: collect independent source diagnostics without cascades 2026-10-09 16:01:18 +03:00
dev 2c6c7a3dcd frontend: provide contextual source repair advice 2026-10-09 14:04:40 +03:00
dev 008867fe48 docs: plan structured source advice and independent errors 2026-10-09 13:28:09 +03:00
dev 111a3861f9 verifier: account finite anonymous type sizes exactly 2026-10-09 13:26:17 +03:00
dev 03614c9bef rfc: define rooted module state and source contract elaboration 2026-10-09 11:29:55 +03:00
dev 8260d3521e rfc: specify closed contract proof and report rules 2026-10-09 10:32:54 +03:00
dev a4181f2d8d rfc: define contract accounting and audit status candidate 2026-10-09 10:06:40 +03:00
dev 9a3e135f43 rfc: investigate explicit invariant updates and stable observations 2026-10-09 09:29:00 +03:00
dev d041c07ad2 rfc: define shared enum and nested owner observation candidate 2026-10-09 09:03:12 +03:00
dev a5f84eb170 rfc: define predicate purity and shared observation gate 2026-10-09 08:28:31 +03:00
dev 8cd933538b rfc: specify contract prefix and invariant publication constraints 2026-10-09 07:14:41 +03:00
dev 11725ad1c3 rfc: open executable contracts spec gate 2026-10-09 00:26:37 +03:00
dev 94414dac3c docs: align source overview with specified extensions 2026-10-09 00:12:05 +03:00
dev edfef82cc6 diag: preserve factual source atomic-access diagnostics 2026-10-09 00:04:12 +03:00
dev ee09a7a290 tests: audit swap leak and remaining source rule boundaries 2026-10-08 22:25:42 +03:00
dev 03305f0957 tests: audit feature-header context and rejection boundaries 2026-10-08 22:12:04 +03:00
dev fe63ae9586 tests: preserve audited CFG loan handoff contexts 2026-10-08 21:57:27 +03:00
dev 50d1bb2c4b tests: audit source boundaries and cancellation join twins 2026-10-08 21:35:58 +03:00
dev 5371eb7a2f tests: audit buffer and error-value rejection twins 2026-10-08 21:21:42 +03:00
dev 2742867ef7 tests: audit task argument identities and source error boundaries 2026-10-08 20:57:51 +03:00
dev fd92604f36 tests: preserve rejection contexts and normalize callee effects 2026-10-08 19:41:01 +03:00
dev 06d8a1a76a tests: extend rejection twins across public semantic features 2026-10-08 19:14:12 +03:00
dev 272aebfd32 tests: extend audited rejection twins through tasks and locks 2026-10-08 18:12:53 +03:00
dev e4aacef48c tests: inventory and verify source rejection twins 2026-10-08 18:01:58 +03:00
dev 09fbf8a5bc verifier: preserve resource obligations across CFG handoff 2026-10-08 17:17:08 +03:00
devandClaude Opus 5.5 0e98638bc6 eval: gobang as a Track B native agent
gobang, the Aji-native harness, joins Codex, Claude Code and OpenCode in
ajieval native. Like them it is an agent product: its runs are never
evidence for H4. Model ids choose the provider: claude-* the Anthropic
API, any other GLM via z.ai, fixture:PATH a scenario without network
(self-tests).

gobang reaches the model over its API, so the key's variable is passed
into the sandbox environment; NativeAgent.env supplies it, its value
never enters the run record, and a missing key stops the run before
anything is created. Tool processes run in gobang's own networkless
bubblewrap sandbox, so no shell wrapper is used. The transcript is
gobang's journal: usage, tool calls and the model come from its events,
the repair metrics from its toolchain tools (aji_check, aji_run,
run_tests with aji's exit codes), and its documentation tools count as
reads of /docs files.

Checked end to end on dev-echo (aji_source) with a fixture model: the
dev evaluator accepts the solution, the workspace holds only the
solution, and the first-check and first-test metrics are exact. With a
fake key the run reaches z.ai from the sandbox and ends INFRA_FAILED
(auth) without the key in any file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:00:36 +03:00
dev 762c5abe7b frontend: validate unknown effect names before body lowering 2026-10-08 14:49:49 +03:00
dev 4c9c5626c9 frontend: align source grammar and reject empty enum payload lists 2026-10-08 14:14:45 +03:00
dev 48b9b42fed verifier: cache structural properties and nominal size queries 2026-10-08 13:33:24 +03:00
dev 41f3afbf05 cli: validate exclusive source places before AIR 2026-10-08 12:37:22 +03:00
dev dcd5f1f702 cli: reject non-value operands without aborting lowering 2026-10-08 12:17:15 +03:00
dev bc5412dadd cli: validate inferred allocation content before AIR 2026-10-08 10:31:10 +03:00
dev 1bbfed24a8 cli: check inferred array elements before AIR 2026-10-08 09:26:33 +03:00
dev cfbe01a16f cli: validate Copy content of source owning arrays 2026-10-08 09:01:58 +03:00
dev caf3b86e80 cli: validate structural source type positions before AIR 2026-10-07 23:54:55 +03:00
dev 5f76e92ff3 cli: parse dereferenced places in inline borrow arguments 2026-10-07 22:55:10 +03:00
dev 65e7a0a97c eval: advisory instruction feedback from Claude Code sessions
`ajieval sessions` pairs each human prompt with what the assistant did
just before it, and asks Jev whether the prompt was a correction and which
repository rule (AGENTS.md, the aji-jev skill, commit memory) the corrected
behaviour broke. Excerpts are truncated and credential-like strings
redacted; answers stay in a local log, and each prompt is sent once.

`sessions report` proposes clarifying a rule only when corrections pointing
to it recur across sessions (thresholds in triage.json); it never edits
instructions. `sessions hook` is meant for a personal SessionEnd hook: it
returns at once and scans in the background, and does nothing without a
TypeSafe key, which may now also come from ~/.config/typesafe/api_key.
2026-10-07 22:37:24 +03:00
dev dde801c653 cli: preserve whole-array arguments for explicit array parameters 2026-10-07 22:29:45 +03:00
dev f733f7c7bb eval: advisory Jev failure classification and improvement triage
`classify --suggest` asks TypeSafe Jev for the protocol §27 category, where
the failure was caught and the §38 cause, and stores the answer beside the
human classification. Only failed dev/validation runs are sent; test-set
runs are refused before any request (§29). `--auto-accept` acts only when
triage.json is calibrated and every confidence meets its threshold.

`calibrate` measures agreement with human labels per question. `triage`
groups classified failures and proposes a routed change only across enough
runs, tasks and agents, and withholds proposals while a frozen plan is
incomplete. It reports; it never edits spec, bundle or code.

The evaluator environment no longer carries TYPESAFE_* variables. The
aji-jev skill records where Jev may and may not be used.
2026-10-07 22:21:47 +03:00
dev ba2cb1340a cli: capture complete source parser ranges 2026-10-07 21:58:18 +03:00
dev 1a80c42289 cli: map block diagnostics to their source constructs 2026-10-07 21:45:57 +03:00
dev 1495650587 cli: resolve struct len fields by receiver type
Use ordinary field lowering and declared field types for nominal receivers while preserving array and slice lengths. Make array field type hints available to chained access. Missing struct len now reports E7002 instead of the builtin-length E7005.

Add 15 source regressions and imported generic CLI checks. Unit tests, all 1201 conformance cases, per-instruction collection for new cases, formatter corpus and original public check/lower compatibility pass.
2026-10-07 20:50:48 +03:00
dev 184cb7b321 examples: complete source ports and run the corpus in CI 2026-10-07 20:37:02 +03:00
dev b1629a59fd cli: preserve keyword spacing in unpack and grouped ranges 2026-10-07 20:36:27 +03:00
dev 9001e56325 cli: restrict source scope names to lexical task operands 2026-10-07 19:50:49 +03:00
dev 364eb57bbc diag: preserve envelope fields and reject JSON key collisions in tests 2026-10-07 19:28:36 +03:00
dev 8ee0f4c2bf diag: add factual related borrow and task locations 2026-10-07 19:12:58 +03:00
dev dbd9763713 diag: add stable source reasons and diagnostic incidence reporting 2026-10-07 18:52:36 +03:00
dev 911982dd1c cli: disambiguate block statement boundaries 2026-10-07 18:21:07 +03:00
dev 462ddd2c5c cli: add deterministic source formatter 2026-10-07 18:21:06 +03:00
dev d901d5227b docs: assess language review and propose diagnostic extensions 2026-10-07 18:21:06 +03:00
dev a9a0d63f27 cli: implement explicit source borrow returns 2026-10-07 18:20:45 +03:00
dev 715a8be491 Merge intermediate standard library foundation
Integrate feat/std-bootstrap through STD-7: nineteen safe pinned modules,
explicit owning collections, bytes/text/encoding/formatting, bounded and
buffered I/O, and caller-buffer lexical paths. Include source modules,
generics, linear aggregates/buffers and exact static operation contracts.

All 1079 conformance cases pass. New path cases pass per-step collection
and schedule stress; source/std CLI, hosted smoke, unit, formatting,
reference budgets and source coverage gates pass. Remaining Std 0.1 and
service work stays in the backlog; resume Phase 6 with Q-034/P6-11.
2026-10-07 13:43:25 +03:00
1020 changed files with 49974 additions and 3390 deletions

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
---
name: aji-jev
description: Use when classifying failed Aji evaluation runs, deciding whether a spec, diagnostic, agent-bundle or documentation improvement is warranted, or when TypeSafe/Jev comes up in this repository. Covers `ajieval classify --suggest`, `calibrate` and `triage`, and the hard limits on where Jev may be used.
---
# Jev in Aji: advisory triage only
Jev (TypeSafe) is a System One classifier. It answers typed questions (`choice`, `score`, `noul`) about a small state and returns calibrated probabilities. In this repository it only *suggests*. The verifier, conformance tests and the owner decide.
## Hard limits
- Only `tools/eval/`. Never call Jev from `src/`, the verifier, the interpreter, `build.zig`, CI gates or conformance verdicts. Aji is deterministic, and an external model is not.
- Only failed runs of the `dev` and `validation` sets. Never send a `test`-set run, a held-out task or anything from the private benchmark repository (protocol §29, spec 14 §12). `jev.check_sendable` enforces this; do not bypass it.
- No language change follows from a classification alone. Protocol §38 requires repeated failures across tasks and agents; `triage` enforces this through the minimums in `tools/eval/triage.json`.
- Nothing during a frozen experiment. Pass `--plan` to `triage`. Record observations with `ajieval journal` and act only after the last cell has run.
- Never tune the language to the M or C corpus or to one benchmark task.
## Workflow
1. For each failed dev/validation run: `python3 -m ajieval classify RUN --suggest`. This needs `TYPESAFE_API_KEY`; never print or record it.
2. A human confirms or overrides the suggestion with `python3 -m ajieval classify RUN CATEGORY --cause CAUSE [--caught-by ...]`.
3. Once enough runs have both a human label and a suggestion, run `python3 -m ajieval calibrate runs/`. Propose `"calibrated": true` and the thresholds in `triage.json` to the owner only when agreement among auto-accepted suggestions is high. Do not flip it yourself.
4. Run `python3 -m ajieval triage runs/ [--plan PLAN]`. For each proposal, act according to its route:
- `diagnostics`: patch the message in `src/diag.zig` and `docs/reference/error-codes.md`, add a test, open a PR.
- `agent_bundle` / `documentation`: clarify `docs/agent/`, the Quick Reference or the reference without changing meaning. Check the bundle growth (`tools/agent_bundle_tokens.py`).
- `language`: add an entry to `docs/design/open-questions.md` with the evidence (runs, tasks, agents, codes). Only the owner turns it into an RFC.
- `harness`: fix `tools/eval/`.
- `task_ambiguity`: run the task acceptance review (protocol §8).
- `model_capability`: nothing.
## Session feedback on instructions and skills
A personal SessionEnd hook (`.Codex/settings.local.json`, never the shared settings) runs `python3 -m ajieval sessions hook` from `tools/eval`. In the background it pairs each human prompt with what the assistant did just before, redacts credential-like strings, truncates both, and asks Jev two questions: whether the prompt was a correction, and which rule in `sessions.RULES` the corrected behaviour broke. Answers stay in `~/.cache/aji-sessions/events.jsonl`. Without a TypeSafe key the hook does nothing.
`python3 -m ajieval sessions report` proposes clarifying a rule only when corrections pointing to it recur across sessions (thresholds in `triage.json`, `sessions`). Act on a proposal by sharpening the rule where it lives (`AGENTS.md`, this skill, or memory) and only after the owner agrees. The report never edits anything. Corrections no rule explains are listed as `unattributed`; recurring ones suggest a missing rule.
## Changing the questions
The option descriptions in `tools/eval/ajieval/jev.py` are the classifier's input. A change there changes `questions_hash`, and suggestions made under different hashes must not be mixed in `calibrate`. Keep the descriptions atomic and literal: Jev reads instructions at face value and handles multi-hop reasoning poorly.
+39
View File
@@ -0,0 +1,39 @@
---
name: aji-jev
description: Use when classifying failed Aji evaluation runs, deciding whether a spec, diagnostic, agent-bundle or documentation improvement is warranted, or when TypeSafe/Jev comes up in this repository. Covers `ajieval classify --suggest`, `calibrate` and `triage`, and the hard limits on where Jev may be used.
---
# Jev in Aji: advisory triage only
Jev (TypeSafe) is a System One classifier. It answers typed questions (`choice`, `score`, `noul`) about a small state and returns calibrated probabilities. In this repository it only *suggests*. The verifier, conformance tests and the owner decide.
## Hard limits
- Only `tools/eval/`. Never call Jev from `src/`, the verifier, the interpreter, `build.zig`, CI gates or conformance verdicts. Aji is deterministic, and an external model is not.
- Only failed runs of the `dev` and `validation` sets. Never send a `test`-set run, a held-out task or anything from the private benchmark repository (protocol §29, spec 14 §12). `jev.check_sendable` enforces this; do not bypass it.
- No language change follows from a classification alone. Protocol §38 requires repeated failures across tasks and agents; `triage` enforces this through the minimums in `tools/eval/triage.json`.
- Nothing during a frozen experiment. Pass `--plan` to `triage`. Record observations with `ajieval journal` and act only after the last cell has run.
- Never tune the language to the M or C corpus or to one benchmark task.
## Workflow
1. For each failed dev/validation run: `python3 -m ajieval classify RUN --suggest`. This needs `TYPESAFE_API_KEY`; never print or record it.
2. A human confirms or overrides the suggestion with `python3 -m ajieval classify RUN CATEGORY --cause CAUSE [--caught-by ...]`.
3. Once enough runs have both a human label and a suggestion, run `python3 -m ajieval calibrate runs/`. Propose `"calibrated": true` and the thresholds in `triage.json` to the owner only when agreement among auto-accepted suggestions is high. Do not flip it yourself.
4. Run `python3 -m ajieval triage runs/ [--plan PLAN]`. For each proposal, act according to its route:
- `diagnostics`: patch the message in `src/diag.zig` and `docs/reference/error-codes.md`, add a test, open a PR.
- `agent_bundle` / `documentation`: clarify `docs/agent/`, the Quick Reference or the reference without changing meaning. Check the bundle growth (`tools/agent_bundle_tokens.py`).
- `language`: add an entry to `docs/design/open-questions.md` with the evidence (runs, tasks, agents, codes). Only the owner turns it into an RFC.
- `harness`: fix `tools/eval/`.
- `task_ambiguity`: run the task acceptance review (protocol §8).
- `model_capability`: nothing.
## Session feedback on instructions and skills
A personal SessionEnd hook (`.claude/settings.local.json`, never the shared settings) runs `python3 -m ajieval sessions hook` from `tools/eval`. In the background it pairs each human prompt with what the assistant did just before, redacts credential-like strings, truncates both, and asks Jev two questions: whether the prompt was a correction, and which rule in `sessions.RULES` the corrected behaviour broke. Answers stay in `~/.cache/aji-sessions/events.jsonl`. Without a TypeSafe key the hook does nothing.
`python3 -m ajieval sessions report` proposes clarifying a rule only when corrections pointing to it recur across sessions (thresholds in `triage.json`, `sessions`). Act on a proposal by sharpening the rule where it lives (`AGENTS.md`, this skill, or memory) and only after the owner agrees. The report never edits anything. Corrections no rule explains are listed as `unattributed`; recurring ones suggest a missing rule.
## Changing the questions
The option descriptions in `tools/eval/ajieval/jev.py` are the classifier's input. A change there changes `questions_hash`, and suggestions made under different hashes must not be mixed in `calibrate`. Keep the descriptions atomic and literal: Jev reads instructions at face value and handles multi-hop reasoning poorly.
+15
View File
@@ -0,0 +1,15 @@
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "cd \"$CLAUDE_PROJECT_DIR/tools/eval\" && python3 -m ajieval sessions hook",
"timeout": 10
}
]
}
]
}
}
+27 -2
View File
@@ -1,8 +1,9 @@
name: ci name: ci
# Automatic runs are disabled to spare the runner; start manually from the UI.
# To re-enable, restore `push:` and `pull_request:` below.
on: on:
push: workflow_dispatch:
pull_request:
jobs: jobs:
build: build:
@@ -22,6 +23,30 @@ jobs:
- run: zig build && python3 tests/hosted/smoke.py - run: zig build && python3 tests/hosted/smoke.py
- run: python3 tests/hosted/source_modules.py - run: python3 tests/hosted/source_modules.py
- run: python3 tests/hosted/source_generics.py - run: python3 tests/hosted/source_generics.py
- run: python3 tests/hosted/source_borrow_returns.py
- run: python3 tests/hosted/source_format.py
- run: python3 tests/hosted/source_diagnostic_reasons.py
- run: python3 tests/hosted/source_atomic_access.py
- run: python3 tests/hosted/related_locations.py
- run: python3 tests/hosted/source_lifetimes.py
- run: python3 tests/hosted/source_array_arguments.py
- run: python3 tests/hosted/source_type_positions.py
- run: python3 tests/hosted/source_own_array_content.py
- run: python3 tests/hosted/source_array_literals.py
- run: python3 tests/hosted/source_inferred_content.py
- run: python3 tests/hosted/source_nonvalue_operands.py
- run: python3 tests/hosted/source_store_modes.py
- run: python3 tests/hosted/source_nominal_queries.py
- run: python3 tests/hosted/source_grammar.py
- run: python3 tests/hosted/source_expression_depth.py
- run: python3 tests/hosted/source_effect_names.py
- run: python3 tests/hosted/source_repair_advice.py
- run: python3 tests/hosted/source_independent_errors.py
- run: python3 tests/hosted/source_cfg_provenance.py
- run: python3 tests/hosted/source_loop_exit.py
- run: python3 tools/source_reject_twins.py
- run: python3 tests/hosted/source_reject_twins.py
- run: python3 tests/hosted/examples.py --stress 200
- run: python3 tests/hosted/source_static_functions.py - run: python3 tests/hosted/source_static_functions.py
- run: python3 tests/hosted/source_linear.py - run: python3 tests/hosted/source_linear.py
- run: python3 tests/hosted/source_buffers.py - run: python3 tests/hosted/source_buffers.py
+26
View File
@@ -18,6 +18,32 @@ zig build run -- run f.air # verify and execute @main (deterministic profile)
python3 tests/hosted/smoke.py # hosted profile against the real OS python3 tests/hosted/smoke.py # hosted profile against the real OS
python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts python3 tests/hosted/source_modules.py # explicit package CLI and file-loading contracts
python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance python3 tests/hosted/source_generics.py # explicit generics, constraints and provenance
python3 tests/hosted/source_borrow_returns.py # explicit origins, retained views, packages and profiles
python3 tests/hosted/source_format.py # formatter CLI, comments, idempotence and public-corpus AIR fidelity
python3 tests/hosted/source_diagnostic_reasons.py # stable E7006 categories and CLI/package provenance
python3 tests/hosted/source_atomic_access.py # factual E4202 types, source/package provenance and early failure
python3 tests/hosted/related_locations.py # factual conflict/spawn positions, source mapping and package provenance
python3 tests/hosted/source_lifetimes.py # AIR rejection twins and exact lifetime/join diagnostic positions
python3 tests/hosted/source_array_arguments.py # array argument shape, cleanup, AIR and package parity
python3 tests/hosted/source_type_positions.py # structural type errors at annotations, templates and packages
python3 tests/hosted/source_own_array_content.py # Copy content, nominal/generic types and repeated allocations
python3 tests/hosted/source_array_literals.py # inferred elements, repetitions, explicit moves and packages
python3 tests/hosted/source_inferred_content.py # constructor content, transfers, recovery and package provenance
python3 tests/hosted/source_nonvalue_operands.py # never operands, divergent receivers, traps and package provenance
python3 tests/hosted/source_store_modes.py # exclusive places, source positions, array modes and package provenance
python3 tests/hosted/source_nominal_queries.py # deep shared types, deterministic limits and package cache indices
python3 tests/hosted/source_grammar.py # syntax boundaries, canonical enum lists and formatter/AIR fidelity
python3 tests/hosted/source_expression_depth.py # deep unary chains, exact AIR/fuel and rejection positions
python3 tests/hosted/source_liveness_depth.py # deep SSA liveness, join decisions, formatting and exact fuel
python3 tests/hosted/source_loop_exit.py # CFG exits, naming collisions, diagnostic priority and packages
python3 tests/hosted/source_effect_names.py # effect-name errors, signature priority and package provenance
python3 tests/hosted/source_repair_advice.py # contextual syntax/cast/array-call advice and CLI/package parity
python3 tests/hosted/source_independent_errors.py # bounded source error collection without cascades or partial AIR
python3 tests/hosted/source_cfg_provenance.py # resource handoff, loan origins and source/package/AIR diagnostics
python3 tests/hosted/shield_relations.py # shield ordering, handoff, relation reuse, cancellation and exact diagnostics
python3 tools/source_reject_twins.py # audited same-code pairs and exhaustive, explicitly incomplete AIR inventory
python3 tests/hosted/source_reject_twins.py # false-pair, mapping and inventory regression probes
python3 tests/hosted/examples.py --stress 200 # all examples/packages, wire bytes, partial I/O and source/AIR schedules
python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers python3 tests/hosted/source_static_functions.py # explicit operations, effects, nominal policy identity and workers
python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors python3 tests/hosted/source_linear.py # whole-value owners, canonical AIR and CLI errors
python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts python3 tests/hosted/source_buffers.py # initialized storage, owning vectors and CLI contracts
+21
View File
@@ -0,0 +1,21 @@
The MIT License (Expat)
Copyright (c) 2026 Aji contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1 -1
View File
@@ -125,4 +125,4 @@ Do not start by writing a native code generator. The interpreter and verifier de
## License ## License
No license has been selected yet. Add one before public distribution. Aji is released under the [MIT License](LICENSE).
+51 -2
View File
@@ -58,6 +58,8 @@ RFC 0011 crossed the 10 % warning line (its own estimate said "below 10 %"): fou
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. 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.
**Historical layout and approximate counts (Phase 4, before std).** The following table is not the current bundle inventory or size. Later per-RFC measurements below record subsequent growth; use `tools/agent_bundle_tokens.py --source` on the generated bundle for current per-file and group counts.
| Path | Contents | cl100k tokens | | Path | Contents | cl100k tokens |
|---|---|---:| |---|---|---:|
| `QUICK.md` | the Quick Reference, then a table of which file to open for what | ~5.0k (Phase 4: +0.6k for §7 graphs) | | `QUICK.md` | the Quick Reference, then a table of which file to open for what | ~5.0k (Phase 4: +0.6k for §7 graphs) |
@@ -72,7 +74,7 @@ The `.aji` condition does not get the AIR bundle as its documentation. It gets a
| `diagnostics/errors.md` | spec 15 §10, stable codes, repair loop, error-code registry | ~1.9k | | `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 | | `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). At that historical point, without `air/` it came to about 26.8k tokens. The current 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 ```sh
zig build agent-reference # also writes zig-out/agent/source/ and source-report.json zig build agent-reference # also writes zig-out/agent/source/ and source-report.json
@@ -83,7 +85,7 @@ The groups `quick_reference`, `source_docs` and `air_docs` come from the `doc_gr
## Quick Reference (`.aji`) ## Quick Reference (`.aji`)
[`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. [`quick-reference.md`](quick-reference.md) is the front door of the Source Reference Bundle (`QUICK.md`). The [plan](../plan/README.md) targets 5–8k tokens; the earlier 4–6k target and approximately 4.4k measurement are historical. It covers most programs and is kept consistent with spec 15. Current measurements are recorded below; the target is not a hard CI cap.
**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. **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.
@@ -131,3 +133,50 @@ RFC 0033 bounded I/O (cl100k, relative to BinaryHeap): Quick Reference 8,284 →
RFC 0034 owning buffered files (cl100k, relative to bounded I/O): Quick Reference 8,350 → 8,445 (+1.1%), other source docs 58,473 → 61,223 (+4.7%), full source excluding AIR 66,823 → 69,668 (+4.3%). library/std.md is 24,364 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe concrete operations keep fixed allocation, file transfer, prefetch and first-error/partial-write cleanup visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +105.0%, justified by these contracts without an empirical MCC claim. Full representation/API details stay on demand; front-door consolidation remains separate work. RFC 0034 owning buffered files (cl100k, relative to bounded I/O): Quick Reference 8,350 → 8,445 (+1.1%), other source docs 58,473 → 61,223 (+4.7%), full source excluding AIR 66,823 → 69,668 (+4.3%). library/std.md is 24,364 tokens; AIR remains 179,282 bytes / 51 sections. Ten safe concrete operations keep fixed allocation, file transfer, prefetch and first-error/partial-write cleanup visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +105.0%, justified by these contracts without an empirical MCC claim. Full representation/API details stay on demand; front-door consolidation remains separate work.
RFC 0035 caller-buffer paths (cl100k, relative to buffered files): Quick Reference 8,445 → 8,518 (+0.9%), other source docs 61,223 → 63,296 (+3.4%), full source excluding AIR 69,668 → 71,814 (+3.1%). library/std.md is 26,437 tokens; AIR remains 179,282 bytes / 51 sections. Six pure operations return raw Copy ranges or write a measured canonical prefix, keeping lifetime, byte syntax, capacity failure and authority visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +111.3%, justified by these contracts without an empirical MCC claim. API details stay on demand; front-door consolidation remains separate work. RFC 0035 caller-buffer paths (cl100k, relative to buffered files): Quick Reference 8,445 → 8,518 (+0.9%), other source docs 61,223 → 63,296 (+3.4%), full source excluding AIR 69,668 → 71,814 (+3.1%). library/std.md is 26,437 tokens; AIR remains 179,282 bytes / 51 sections. Six pure operations return raw Copy ranges or write a measured canonical prefix, keeping lifetime, byte syntax, capacity failure and authority visible. No new syntax, diagnostic or verifier/runtime state; cumulative source growth is +111.3%, justified by these contracts without an empirical MCC claim. API details stay on demand; front-door consolidation remains separate work.
RFC 0036 (Proposed), explicit source borrow returns (cl100k, relative to paths): Quick Reference 8,518 → 8,642 (+1.46%), other source docs 63,296 → 64,160 (+1.37%), full source excluding AIR 71,814 → 72,802 (+1.38%). language/ownership.md is 1,834 tokens; AIR remains 179,282 bytes / 51 sections. Existing `from`, ref/mut bindings and named returns reuse verifier/runtime primitives; frontend ancestry selects transferred lexical ends. No new keyword, AIR feature, verifier state or diagnostic. Cumulative full-source growth is +114.24%, justified in the proposed RFC without an empirical MCC claim. This measurement records the implementation for review, not owner adoption.
2026-10-07 review documentation follow-up: the historical layout is now labeled, Q-016 states the implemented reserved status, and Quick Reference explicitly excludes floating point. The last sentence adds 46 cl100k tokens: Quick Reference 8,642 → 8,688 (+0.53%), other source docs stay 64,160, full source 72,802 → 72,848 (+0.06%). o200k groups are 8,723 / 64,359 / 73,082; Qwen2.5 8,954 / 65,733 / 74,687. AIR stays 46,300 cl100k tokens / 179,282 bytes; library/std.md stays 26,454 cl100k tokens. The clarification reduces status ambiguity without adding language semantics. RFCs 0037/0038 are Proposed and outside the bundles; their normative integration growth is not measured yet.
RFC 0036 review fixes clarify reserved task borrow returns and known array bounds in unused generic signatures. These rules add 54 cl100k tokens: other source docs 64,160 → 64,214, full source 72,848 → 72,902 (+0.07%); Quick Reference stays 8,688. o200k groups are 8,723 / 64,413 / 73,136; Qwen2.5 8,954 / 65,794 / 74,748. language/ownership.md is 1,873 cl100k tokens; AIR and library/std.md stay unchanged. The additions make source rejection predictable without adding a semantic feature.
P6-8 source formatter (cl100k): Quick Reference 8,688 → 8,728 (+40), other source docs 64,214 → 64,677 (+463), full source 72,902 → 73,405 (+0.69%). language/tooling.md is 3,051 tokens. o200k groups are 8,763 / 64,876 / 73,639; Qwen2.5 8,994 / 66,259 / 75,253. AIR stays 179,282 bytes / 46,300 cl100k tokens, and library/std.md stays unchanged. One command with check/write modes reduces whitespace repair and diff noise while preserving tokens, comments and canonical AIR; it adds no language concept, feature, verifier/runtime state or diagnostic code. No empirical MCC benefit is claimed.
Q-040 block boundaries (DD-016, cl100k): Quick Reference 8,728 → 8,769 (+41), other source docs 64,677 → 65,012 (+335), full source 73,405 → 73,781 (+0.51%). o200k groups are 8,805 / 65,212 / 74,017; Qwen2.5 9,037 / 66,603 / 75,640. AIR and library/std.md are unchanged. One syntactic boundary rule and an explicit-discard guard replace an ambiguity; there is no new syntax form, diagnostic code or verifier/runtime state. No empirical MCC benefit is claimed.
DD-017 stable E7006 reasons (cl100k): Quick Reference 8,769 → 8,807 (+38), other source docs 65,012 → 65,799 (+787), full source 73,781 → 74,606 (+1.12%). o200k groups are 8,843 / 66,001 / 74,844; Qwen2.5 9,077 / 67,402 / 76,479. AIR grows 46,300 → 46,937 (+637, +1.38%), 179,282 → 182,254 bytes, because the shared diagnostic registry includes the 28 source categories. library/std.md is unchanged. One structured discriminator replaces prose classification; there is no new code, programming syntax, verifier/runtime state or repair application. Historical reasons remain unknown. No empirical MCC benefit is claimed.
RFC 0037 related positions (cl100k): Quick Reference 8,807 → 8,859 (+52), other source docs 65,799 → 66,195 (+396), full source 74,606 → 75,054 (+0.60%). o200k groups are 8,895 / 66,397 / 75,292; Qwen2.5 9,135 / 67,810 / 76,945. AIR grows 46,937 → 47,328 (+391, +0.83%), 182,254 → 184,060 bytes; library/std.md is unchanged. Two factual roles locate an existing selected conflict or spawn; there is no new programming syntax, diagnostic code, semantic verifier state or runtime rule. One constant-sized origin is carried on each existing task loan. Necessary schema/source-map rules enter the bundles; RFC rationale does not. No empirical MCC benefit is claimed.
DD-019 unique diagnostic fields (cl100k): Quick Reference stays 8,859; other source docs 66,195 → 66,312 (+117), full source 75,054 → 75,171 (+0.16%). o200k groups are 8,895 / 66,517 / 75,412; Qwen2.5 9,135 / 67,933 / 77,068. AIR grows 47,328 → 47,445 (+117, +0.25%), 184,060 → 184,628 bytes; library/std.md is unchanged. Explicit payload names preserve the stable envelope and both guard/borrow identities. No language concept, syntax, code, verifier/runtime state or repair application is added; clients that previously read a capability payload as `kind` use `capability_kind`. No empirical MCC benefit is claimed.
Q-041 source scope names (DD-020, cl100k): Quick Reference 8,859 → 8,889 (+30), other source docs 66,312 → 66,484 (+172), full source 75,171 → 75,373 (+0.27%). o200k groups are 8,925 / 66,690 / 75,615; Qwen2.5 9,167 / 68,115 / 77,282. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. One existing lexical block identifier is explicitly excluded from ordinary value expressions, removing ineffective transfers and misleading repair hints. There is no new syntax, diagnostic code/reason, verifier/runtime state or feature. Former source aliases now reject; ordinary shadowing and AIR scope flow remain available. No empirical MCC benefit is claimed.
Q-023 whole-array arguments (DD-021, cl100k): Quick Reference 8,889 → 8,948 (+59), other source docs 66,484 → 66,669 (+185), full source 75,373 → 75,617 (+0.32%). o200k groups are 8,984 / 66,873 / 75,857; Qwen2.5 9,226 / 68,303 / 77,529. AIR stays 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. One rule follows an explicit ordinary-call signature so existing array-borrow parameters are callable; exact modes, lengths, lexical cleanup, named retained origins and task loans remain checked. No new syntax, diagnostic, feature or verifier/runtime state. Existing primitives suffice; no empirical MCC benefit is claimed.
Q-042 structural type positions (cl100k): Quick Reference stays 8,948; other source docs 66,669 → 66,761 (+92), full source 75,617 → 75,709 (+0.12%). o200k groups are 8,984 / 66,965 / 75,949; Qwen2.5 9,226 / 68,398 / 77,624. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing type-position predicates now reject invalid source annotations before AIR, including known unused generic headers, with structured E7005 fields at the constructor. No new concept, syntax, code, feature or verifier/runtime state is added. Earlier source diagnostic codes/fields may change; graph properties retain verifier diagnostics. No empirical MCC benefit is claimed.
Q-043 dynamic owning-array content (cl100k): Quick Reference stays 8,948; other source docs 66,761 → 66,827 (+66), full source 75,709 → 75,775 (+0.09%). o200k groups are 8,984 / 67,031 / 76,015; Qwen2.5 9,226 / 68,466 / 77,692. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing Copy-content rules now reject annotations and repeated allocation values with structured E7005 before AIR, including known unused generic/static contracts and nominal contents. Unknown parameters defer to substitution; iref remains phantom. No new concept, syntax, code, feature or verifier/runtime state is added. Earlier invalid-source diagnostics and priority may change; graph-root properties retain verifier diagnostics. No empirical MCC benefit is claimed.
Q-045 inferred array literals (cl100k): Quick Reference stays 8,948; other source docs 66,827 → 66,906 (+79), full source 75,775 → 75,854 (+0.10%). o200k groups are 8,984 / 67,110 / 76,094; Qwen2.5 9,226 / 68,550 / 77,776. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing member-position and Copy-repetition rules now reject invalid inferred elements before AIR, at the offending value. Lists retain explicit linear transfers; repeated borrows retain E7006 invalid_literal. No new concept, syntax, code, reason, feature or verifier/runtime state is added. Invalid-source diagnostic codes/priority may change; accepted canonical AIR is preserved. No empirical MCC benefit is claimed.
Q-046 inferred constructor content (cl100k): Quick Reference stays 8,948; other source docs 66,906 → 67,074 (+168), full source 75,854 → 76,022 (+0.22%). o200k groups are 8,984 / 67,279 / 76,263; Qwen2.5 9,226 / 68,724 / 77,950. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing value/Copy/borrow restrictions now reject at constructor arguments, including generic templates, before malformed AIR or null-block failure. Complete linear packing and recovery remain valid; graph/endpoint feature diagnostics keep their existing precedence. No new concept, syntax, code/reason, feature or verifier/runtime state is added. Accepted canonical AIR is preserved; invalid-source diagnostics may change. No empirical MCC benefit is claimed.
Q-047 non-value operands (cl100k): Quick Reference stays 8,948; other source docs 67,074 → 67,258 (+184), full source 76,022 → 76,206 (+0.24%). o200k groups are 8,984 / 67,461 / 76,445; Qwen2.5 9,226 / 68,912 / 78,138. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Typed operation inputs reject never before subsequent emission; divergent returns/branches/statements and variable receivers retain their control flow, and frame receivers skip writes. Store values remain required. Invalid-source diagnostic order may change; accepted canonical AIR is preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added. No empirical MCC benefit is claimed.
Q-048 source access modes (cl100k): Quick Reference stays 8,948; other source docs 67,258 → 67,343 (+85), full source 76,206 → 76,291 (+0.11%). o200k groups are 8,984 / 67,546 / 76,530; Qwen2.5 9,226 / 69,001 / 78,227. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Shared places reject at source stores and explicit mut bindings/arguments before array shape conversion; valid canonical AIR is preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added. No empirical MCC benefit is claimed.
DD-022 grammar surface (cl100k): Quick Reference stays 8,948; other source docs 67,343 → 68,219 (+876), full source 76,291 → 77,167 (+1.15%). o200k groups are 8,984 / 68,422 / 77,406; Qwen2.5 9,226 / 69,887 / 79,113. AIR remains 184,628 bytes / 47,445 cl100k tokens; library/std.md is unchanged. Existing syntax and ordered parsing choices replace incomplete grammar descriptions. Empty qualified enum payload lists now reject E7001; accepted public-source canonical AIR is preserved. No new programming concept, feature, diagnostic code or verifier/runtime state is added. The grammar stays a reference read on demand; no empirical MCC benefit is claimed.
Q-051 source effect names (DD-023, cl100k): Quick Reference 8,948 → 8,955 (+7); other source docs 68,219 → 68,323 (+104), full source 77,167 → 77,278 (+0.14%). o200k groups are 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227. The AIR copy in the source bundle grows 47,445 → 47,458 (+13); canonical AIR bundle bytes grow 184,628 → 184,678, through the shared E7002 registry description; library/std.md is unchanged. Unknown effects use existing E7002 with structured `name`/`effect`, replacing erroneous source E7900 or E0006. Accepted canonical AIR and authority/effect semantics are preserved. No new concept, syntax, code/reason, feature or verifier/runtime state is added; no empirical MCC benefit is claimed.
Q-052 CFG resource provenance (DD-024): Quick Reference and other/full source docs remain 8,955 / 68,323 / 77,278 cl100k (o200k 8,991 / 68,526 / 77,517; Qwen2.5 9,233 / 69,994 / 79,227); std is unchanged. Canonical AIR grows 184,678 → 185,220 bytes and 47,385 → 47,476 cl100k (+91), 47,540 → 47,631 o200k (+91), 48,917 → 49,009 Qwen2.5 (+92). The separately wrapped source-bundle AIR copy grows 47,458 → 47,549 cl100k. The added sentences clarify preservation of existing task/scope, guard and shield obligations through block arguments. No new agent concept, syntax, feature or diagnostic is introduced. Sparse implementation relations replace incomplete SSA metadata; verifier acceptance now enforces existing safety rules. No empirical MCC benefit is claimed.
P6-7 factual source E4202 fields (cl100k): Quick Reference stays 8,955; other source docs 68,323 → 68,353 (+30), full source 77,278 → 77,308 (+0.04%). o200k groups are 8,991 / 68,556 / 77,547; Qwen2.5 9,233 / 70,024 / 79,257. Only language/concurrency.md grows; AIR and library/std.md are unchanged. Concrete `found` and `use` fields distinguish ordinary atomic reads without message parsing. No new syntax, code, feature or verifier/runtime state is introduced; no empirical MCC benefit is claimed.
Spec 15 scope corrections (cl100k): Quick Reference stays 8,955 tokens despite the E1002 → E7005 correction; other source docs 68,353 → 68,403 (+50), full source 77,308 → 77,358 (+0.06%). o200k full source grows 77,547 → 77,594 (+47); Qwen2.5 79,257 → 79,315 (+58). AIR and std are unchanged. Existing source diagnostics, unpacking, escapes, buffers and borrow returns replace obsolete baseline descriptions; no semantic or implementation change.
Pointer-sized cast guidance (2026-10-09): Quick Reference grows 9,255 → 9,276 cl100k (+21); other source docs 69,817 → 69,863 (+46), full source 79,072 → 79,139 (+67, +0.085%). o200k grows by the same +21/+46/+67 (full 79,373); Qwen2.5 by +21/+47/+68 (full 81,127). AIR grows 188,993 → 189,078 bytes and +22 tokens for each tokenizer (48,398 cl100k / 48,551 o200k / 49,956 Qwen2.5). The existing target-independent ban on usize/isize widening is explained in the registered numeric-cast hint and source cast table. No new concept, syntax, feature, diagnostic code/kind or verifier/runtime state is introduced. Pointer identity casts now reject with source E7005/advice before AIR E1002; the accepted set is unchanged. No empirical reduction in repair rounds is claimed.
Parameter/array-call advice (2026-10-09): Quick Reference grows 9,276 → 9,360 cl100k (+84); other source docs 69,863 → 70,167 (+304), full source 79,139 → 79,527 (+388, +0.49%). o200k grows +84/+303/+387 (full 79,760); Qwen2.5 +84/+308/+392 (full 81,519). AIR grows 189,078 → 190,503 bytes, +304/+303/+308 tokens respectively (48,702 cl100k / 48,854 o200k / 50,264 Qwen2.5). Two registered advice kinds distinguish parameter ownership choices and explicit array-to-slice argument borrows; applicability and fixed prefix units account for the growth. No new syntax, semantic concept, code, feature or verifier/runtime state is added; existing envelopes/rejection priority and accepted lowerings remain unchanged. No empirical repair-round benefit is claimed.
+36 -5
View File
@@ -1,9 +1,25 @@
# Aji Quick Reference (`.aji` 0.1) # Aji Quick Reference (`.aji` 0.1)
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. 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. `aji fmt file.aji` prints formatted source; `--check` checks formatting, `--write` replaces the file. Formatting preserves tokens and comments; it does not verify or repair code. Diagnostics are JSON lines; read the complete list and repair independent errors together. Frontend collection is capped at 32 and stops at uncertain boundaries.
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. 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.
**If you know Rust:** use these Aji spellings. Rejected familiar syntax may carry a `repair_candidates` hint; cast alternatives require your choice.
| Familiar spelling | Aji |
|---|---|
| `!condition` | `not condition` (boolean negation) |
| a narrowing `x as T` | `x as! T` checks/traps; `x as% T` wraps |
| `let mut x = value` / `var x = value` | `var x: T = value;` (type required) |
| immutable `let x = value` | `let x = value;` (type may be inferred) |
| `fn f(mut x: T)` | `fn f(x: T)` with a local `var`, or `fn f(x: mut<T>)` for an exclusive borrow; choose the ownership contract |
| mutable/shared slice type | `slice_mut<T>` / `slice<T>` |
| `s[start..]` | `s[start..end]` (explicit upper bound) |
| `f(&x)` / `f(&mut x)` | `f(ref x)` / `f(mut x)` |
| `let r = &x` / `let r = &mut x` | `ref r = x;` / `mut r = x;` |
| `[zero; N]` | `var storage: [T; N] = zero;` (zeroable T) |
| `-> ()` / implicit effects | `-> void effects [...]` |
## 1. Skeleton ## 1. Skeleton
```aji ```aji
@@ -23,7 +39,7 @@ effects [io.read, io.write]
- `main`'s parameters are capabilities, granted by name: `aji run --grant input=io.read --grant out=io.write --stdin 'hi' main.aji`. - `main`'s parameters are capabilities, granted by name: `aji run --grant input=io.read --grant out=io.write --stdin 'hi' main.aji`.
- Every function lists its effects after the signature. A missing effect is `E3101`, whose `suggested_effects` field is the full list to write. - Every function lists its effects after the signature. A missing effect is `E3101`, whose `suggested_effects` field is the full list to write.
- Statements end with `;`; `if`/`while`/`for`/`loop`/`match`/`select`/`scope`/`shield`/`lock` blocks do not. - Statements end with `;`; block statements do not require one. A bare `if`, `match` or `{…}` at statement/tail start ends at its final `}`. Parenthesize it to continue with an operator. Before another statement it must yield `void` or diverge; use `;` to explicitly discard a value (`E7006` otherwise). Initializers, returns and arguments use ordinary expression parsing.
## 2. Types ## 2. Types
@@ -41,6 +57,8 @@ effects [io.read, io.write]
| `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>` | concurrency (§8) | | `task<T>`, `sender<T>`, `receiver<T>`, `mutex<T>` | concurrency (§8) |
| `io_error`, `alloc_error`, `cap_error` | built-in error enums | | `io_error`, `alloc_error`, `cap_error` | built-in error enums |
`f32`/`f64` are reserved in AIR (`E0006`, `reserved_type`) and unavailable in `.aji` 0.1 (`E7002`); floating-point semantics remain Q-016.
**Linear** values (resources, `own`, `region`, `task`, endpoints, `mutex`) are consumed exactly once. Everything else that is a plain value is copyable. **Linear** values (resources, `own`, `region`, `task`, endpoints, `mutex`) are consumed exactly once. Everything else that is a plain value is copyable.
## 3. Statements and expressions ## 3. Statements and expressions
@@ -69,7 +87,7 @@ return x + y + w; // also: `trap;`
| `+% -% *%` | wrapping | | `+% -% *%` | wrapping |
| `& \| ^ << >>` | bitwise; shift ≥ width traps `T0005` | | `& \| ^ << >>` | bitwise; shift ≥ width traps `T0005` |
| `== != < <= > >=`, `and or not` | comparisons, booleans | | `== != < <= > >=`, `and or not` | comparisons, booleans |
| `x as T` | lossless widening only (else `E1002`) | | `x as T` | lossless fixed-width widening only; `usize`/`isize` use `as!` or `as%` (else `E7005`) |
| `x as! T` | checked conversion, traps `T0006` | | `x as! T` | checked conversion, traps `T0006` |
| `x as% T` | wrapping conversion | | `x as% T` | wrapping conversion |
| `42`, `42u8`, `0xff`, `1_000` | literals; type from context or suffix (else `E7007`) | | `42`, `42u8`, `0xff`, `1_000` | literals; type from context or suffix (else `E7007`) |
@@ -100,12 +118,21 @@ ref q = p; // shared borrow of a struct; q.a reads a field
Rules (checked by the verifier): Rules (checked by the verifier):
- **A borrow lives until the end of the block where it was bound** (`ref r = …;` / `mut r = …;`). A borrow written as an argument (`f(mut buf)`) lives for that call. To end one early, put it in an inner `{ … }` block. - **A borrow lives until the end of the block where it was bound** (`ref r = …;` / `mut r = …;`). A borrow written as an argument (`f(mut buf)`) lives for that call. To end one early, put it in an inner `{ … }` block.
- A whole-array argument `f(ref a)` / `f(mut a)` preserves the array for a `ref<[T; N]>` / `mut<[T; N]>` parameter; otherwise it becomes a slice. Length and mode must match. Bound array borrows remain slices.
- An array value is not a slice argument: use `f(ref a)` for `slice<T>` or `f(mut a)` for `slice_mut<T>`; the place and loan must verify.
- **Exclusive XOR shared.** While a `mut` borrow of a place is live, no other borrow of the same place, and no direct use of it, is allowed (`E2101`). Disjoint fields and `split_at` halves are independent. - **Exclusive XOR shared.** While a `mut` borrow of a place is live, no other borrow of the same place, and no direct use of it, is allowed (`E2101`). Disjoint fields and `split_at` halves are independent.
- A borrow cannot outlive what it borrows from (`E2102`). A function returns a borrow only with `-> ref<T> from param`. - A borrow cannot outlive what it borrows from (`E2102`). A function returns a borrow only with explicit `from param`. Bind returned views with `ref`/`mut`; the `from` argument must be a named borrow. Return the bound name without `move`; a local-frame view cannot escape (`E2108`).
- **Moves are explicit:** a named linear value is consumed only as `move x` (otherwise `E7003`). A fresh temporary needs no `move`: `consume(make())`. Copyable values are passed plainly; `move` on them is `E7006`. - **Moves are explicit:** a named linear value is consumed only as `move x` (otherwise `E7003`). A fresh temporary needs no `move`: `consume(make())`. Copyable values are passed plainly; `move` on them is `E7006`.
- Use after move is `E2001`, use after close/free/take `E3001`, a second consumption `E2002`, and a linear value never consumed `E3002`. Every path must consume it, including early `return`s. - Use after move is `E2001`, use after close/free/take `E3001`, a second consumption `E2002`, and a linear value never consumed `E3002`. Every path must consume it, including early `return`s.
- Index proofs: inside `if i < s.len { … }` the access `s[i]` needs no runtime check. - Index proofs: inside `if i < s.len { … }` the access `s[i]` needs no runtime check.
Returned views (details in `/docs/language/ownership.md`):
```aji
fn first(s: slice<u64>) -> ref<u64> from s effects [] { ref item = s[0]; return item; }
fn main() -> u64 effects [] { let data = [42u64, 7u64]; ref s = data; ref item = first(s); return *item; }
```
## 5. Failure: every outcome is a `match` arm ## 5. Failure: every outcome is a `match` arm
```aji ```aji
@@ -212,6 +239,7 @@ scope s { // every task spawned in s must
``` ```
- **Spawning:** - **Spawning:**
- a scope name is only the first operand of `task.spawn`; no aliases, `move` or ordinary value use (`E7006`);
- effect `task.spawn`; - effect `task.spawn`;
- a value moved into a task must be `Send`, and data shared by `ref` must be `Share` (`E4001`, `E4002`); - a value moved into a task must be `Send`, and data shared by `ref` must be `Share` (`E4001`, `E4002`);
- two live tasks may not hold overlapping `mut` loans (`E4101`); - two live tasks may not hold overlapping `mut` loans (`E4101`);
@@ -298,7 +326,7 @@ scope s { // every task spawned in s must
| Code | Meaning | Usual repair | | Code | Meaning | Usual repair |
|---|---|---| |---|---|---|
| E7001 | syntax | check `;`, braces, `=>` in `match` | | E7001 | syntax | check `;`, braces, `=>` in `match` |
| E7002 | unknown name | spelling; declare the variable or function | | E7002 | unknown name | spelling; declare missing bindings; for `effect`, use a registered atom |
| E7003 | linear value consumed without `move` | write `move x` (or borrow it with `ref`/`mut` if it must stay) | | E7003 | linear value consumed without `move` | write `move x` (or borrow it with `ref`/`mut` if it must stay) |
| E7004 | `match` not exhaustive | add the arms listed in `missing` (integers: add `_`) | | E7004 | `match` not exhaustive | add the arms listed in `missing` (integers: add `_`) |
| E7005, E1001 | type mismatch | convert with `as`, `as!`, `as%`; check borrow vs value | | E7005, E1001 | type mismatch | convert with `as`, `as!`, `as%`; check borrow vs value |
@@ -308,6 +336,7 @@ scope s { // every task spawned in s must
| E2001, E3001, E2002 | used after move / after consume / twice | restructure so each linear value is consumed once on every path | | E2001, E3001, E2002 | used after move / after consume / twice | restructure so each linear value is consumed once on every path |
| E3002 | linear value leaked | consume it (close, free, take, join, send) on every path, including `return` | | E3002 | linear value leaked | consume it (close, free, take, join, send) on every path, including `return` |
| E3101 | effect not declared | copy `suggested_effects` into `effects [...]` | | E3101 | effect not declared | copy `suggested_effects` into `effects [...]` |
| E7006 | invalid source construct | inspect stable `reason`; `move_copy` means an explicit move of a Copy value, `move_borrow` a move of a borrow |
| E3201 | wrong capability kind | pass the right `cap<K>` | | E3201 | wrong capability kind | pass the right `cap<K>` |
| E4001, E4002 | not Send / not Share | move owned data into tasks; share only `Share` data by `ref` | | E4001, E4002 | not Send / not Share | move owned data into tasks; share only `Share` data by `ref` |
| E4101 | data race with a task | lend disjoint parts (`split_at`, fields) or join first | | E4101 | data race with a task | lend disjoint parts (`split_at`, fields) or join first |
@@ -319,6 +348,8 @@ scope s { // every task spawned in s must
| T0010 | `iref` of another graph | use a handle with the graph it came from | | T0010 | `iref` of another graph | use a handle with the graph it came from |
| T0001–T0009 | runtime trap | see `kind` and `source_location` | | T0001–T0009 | runtime trap | see `kind` and `source_location` |
E2101/E2104 `related_locations` identifies the selected conflicting borrow; E4302 identifies its task's spawn. Use the source position when present; an unmapped record retains AIR coordinates and the SSA identity. These are facts, not repair instructions.
## 10. Standard library ## 10. Standard library
Import a bundled module after the module header; call its functions by their full path. `std.bytes` and `std.math` are safe source, declare `effects []` and allocate no heap. No grants are needed. Read `/docs/library/std.md` for the API. Import a bundled module after the module header; call its functions by their full path. `std.bytes` and `std.math` are safe source, declare `effects []` and allocate no heap. No grants are needed. Read `/docs/library/std.md` for the API.
+1
View File
@@ -48,6 +48,7 @@ docs/reference/type-properties.md
docs/spec/01-language-overview.md :: ## 6. Trap docs/spec/01-language-overview.md :: ## 6. Trap
> language/ownership.md > language/ownership.md
docs/spec/15-source-language.md :: ## 19. Source borrow returns
docs/spec/15-source-language.md :: ## 9. Frame storage, borrow scopes and features 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 :: ## 3. Safe-reference aliasing rule
docs/spec/03-memory-model.md :: ## 4. Borrow lifetime docs/spec/03-memory-model.md :: ## 4. Borrow lifetime
+241
View File
@@ -0,0 +1,241 @@
# AIR anonymous type-depth audit
Non-normative evidence for Q-059, initially at ba99ad6. This audit introduces no syntax-nesting limit, code, feature or acceptance rule. The sections below record successive failures and repairs; their remaining-work statements are historical. The [closing inventory](type-traversal-inventory.md) gives the final compiler type-traversal scope and bounds. Runtime validation remains separately tracked by Q-060.
## Reproducer and observations
Generate a parameter type with depth d using `"array<" * d + "u8" + ",1>" * d`:
```air
module type.depth
air 0
lang 0.1
features [arrays, ownership]
fn @f(%x: TYPE) -> void
effects []
entry:
ret
```
Replace TYPE with the generated type and call `aji check FILE.air`. Each array has length one; accounted size is one byte. No runtime execution, model experiment or held-out input is involved. Tests used the ordinary 8-MiB native stack; only core-dump capture was disabled for the child. No wall-clock timeout ended a probe.
| Depth | Input bytes | Before parser repair | After parser repair |
|---|---:|---|---|
| 64 | 683 | accepted, exit 0 | not rerun |
| 256 | 2,411 | accepted, exit 0 | not rerun |
| 1,024 | 9,323 | accepted, exit 0 | accepted, exit 0 |
| 4,096 | 36,971 | aborted, exit -6 | accepted, exit 0 |
| 16,384 | 147,563 | not run | aborted, exit -6 |
The old 4,096-depth probe emitted no diagnostic JSON and a Zig segmentation-fault traceback before SIGABRT. It contains 3,529 parseType and 3,528 parseCompoundType frames. The new 16,384-depth failure instead contains 5,000 sizeQuery and 5,000 sizeValue frames in verifier/budget.zig. These repeated native frames and stack-dependent depth are evidence of native stack exhaustion, rather than a specified E5101 rejection. No core was captured; diagnosis uses Zig's symbolized stderr traceback. The observation confirms two recursive failure sites, not bounded behavior of every downstream traversal.
## Parser repair and validation
Compound syntax is a unary chain. The parser now stores pending constructors and their inner spans in an arena-backed list, then closes/builds them from the innermost outward. File modes and capability kinds remain leaves. Feature checks still precede child parsing; member gates still precede the closing delimiter. The same constructor names, array-length checks, unknown-name behavior and error positions remain. Memory grows with the explicit input depth; no program heap allocation, ABI or language semantics changes.
Unit tests parse and inspect 32,768 array levels without recursive equality/formatting in the test. Separate 8,192-depth probes retain a single E0004 at the unknown leaf and a single E0001 at the missing outer delimiter. All unit tests, Zig format checks and 1,765/1,765 conformance cases pass. An old/new comparison over all 364 public conformance AIR files preserves exit status, stdout diagnostics and stderr exactly. A further 232 constructor/feature/error probes cover all nineteen unary/array constructors, reserved/unknown leaves, invalid file/capability names and invalid array lengths. These constrain parser compatibility; they are not proof of all input compatibility or a complete Q-059 fix.
The subsequent budget failure is verified and must be repaired without silently limiting previously permitted syntax. Iterative size evaluation, inner-type budget visiting, property/validity/equality traversals and diagnostic/canonical formatting require separate inspection. Q-059 stays open; resolving parser recursion alone does not resolve verifier processing.
## Size-query repair
The next increment replaces the verifier's recursive size evaluation with explicit continuations for array/atomic/mutex wrappers, struct sums and enum payload sums/maxima. Only nominal member edges advance the original cycle-depth guard. Null overflow short-circuits remaining fields/variants and is cached at every completed ancestor, retaining the existing finite result for invalid nominal cycles. Inner-type budget visiting is iterative too.
The immutable size cache now also keys anonymous array/atomic/mutex nodes by constructor, storage identity and nominal depth. Different atomic/mutex constructors sharing one content pointer remain distinct. Every query reuses its pending stack; read-only runtime queries allocate nothing. Verification still rebuilds caller-supplied caches, including anonymous entries. Raw identities do not enter AIR, reports, diagnostics or canonical text; replacing type storage invalidates the cache.
The allocation-free fallback folds anonymous chains using a saturated affine map, retaining zero-sized leaves even when its multiplicative coefficient exceeds u64. Invalid zero array lengths cannot mask an overflowing inner segment. Nominal fallback traversal remains recursive; the memoized verifier query handles deep nominal chains explicitly. This distinction is not a claim of bounded native stack for arbitrary uncached host-side queries.
Unit cases cover 32,768 anonymous levels, 32,768 nominal declarations, zero/overflow behavior, null-result reuse, shared-content constructor identities and rebuilding a forged anonymous cache. Two AIR/source pairs additionally preserve acceptance of sixty-four huge arrays over an empty record and E5101 for the same chain over u64. All four new fixtures pass GC-before-each-step checking; the rejection adds a verified same-code twin. The existing full 1,765-case conformance snapshot and sixteen focused nested-size/heap-quota cases pass, and all 364 pre-existing AIR checks retain exact old/new outputs. The full snapshot plus four focused fixtures cover all 1,769 current conformance cases; test-extended also passes. These tests confirm the metric and cache behavior, not the whole Q-059 pipeline.
At depth 4,096 the complete check still accepts. At depth 16,384 it now reaches type validity and aborts with 8,711 wellFormed frames in verifier/types.zig, rather than sizeQuery/sizeValue. The size failure is removed; validity/property/equality/formatting and uncached nominal traversal remain open. No syntax-depth limit, semantic feature, public code or bundle text is added.
## Type-validity and finite-layout repair
Type-position validation and generic-argument array-length checking now walk anonymous chains iteratively. The order of per-node checks, the transition to each inner position, and the graph-owner stop remain unchanged: graph content is checked for IslandSafe and is not rechecked as an ordinary member. Property predicates called by those checks are a separate traversal obligation.
Finite-layout checking now uses suspended DFS frames for nominal declarations, retaining field order, enum variant/payload order, empty variants and the original grey/black cycle behavior. An active declaration continues its remaining siblings after a back edge marks it black. Anonymous layout edges are iterative too. Arrays always follow their element; the original ownership/borrow wrapper set follows its content only with linear_aggregates. Graph owners and atomic cells retain their original layout boundary. No new accepted/rejected type position or cycle rule is introduced.
Unit cases cover 32,768 anonymous levels, a 32,768-declaration acyclic nominal chain, a deep anonymous self-cycle, the wrapper feature gate, graph validation's single E2111 and diagnostic order through siblings after back edges. Unit/format checks and all 1,769 conformance cases pass. All 366 public conformance AIR checks retain exact old/new exit status, stdout and stderr. An additional 48 generated mixed struct/enum cyclic graphs retain exact old/new outputs, including cycle selection and order.
The complete 4,096-depth check still accepts. At 16,384 it passes wellFormed and then aborts in Module.isLinearType: the symbolized traceback contains 10,001 isLinearType frames, no JSON diagnostics and exit -6. The probe stops there; 32,768 is not claimed to pass the complete pipeline. This confirms the next property-query failure, while equality, formatting and uncached nominal traversals also remain open. Q-059 is not resolved. No syntax-depth limit, semantic feature, public diagnostic code or bundle text is added.
## Anonymous property-query repair
Whole-value linearity, Zeroable, Copy, Local, IslandSafe and endpoint/forbidden-content queries now follow their original anonymous edges iteratively. Send/Share uses an explicit query mode: Send follows ref/slice by querying Share, and Share follows mutex by querying Send. The unchanged terminal classifications and nominal-cache leaves decide acceptance. No borrow, transfer, aliasing, concurrency or runtime rule changes; predicates remain allocation-free read-only queries.
Nominal-property preparation now discovers dependencies through anonymous chains iteratively, still including phantom edges. Its monotone worklist, declaration/field order and fixed-point values are unchanged. Height and source-witness distance fold anonymous edges using their existing saturation at 65 and 34. These are property summaries, not new syntax limits; saturated chains can stop without changing the summary. Uncached nominal fallback calls remain recursive. The existing depth-64 guarded bounded predicate and depth-32 witness remain separate bounded traversals.
Unit tests cover 32,768 anonymous arrays ending in plain data, task-local state or a channel endpoint, both direct and nominal cached queries. A 32,768-handle phantom chain retains dependency/height behavior, and 65,536 alternating ref/mutex edges retain Send/Share mode changes at a non-Share region leaf. Boundary tests retain height and witness-distance saturation. Existing cyclic fixed-point, shared-diamond and mixed cached/uncached tests pass with the new loops. All unit/format checks, test-extended and all 1,769 conformance cases pass; all 366 public AIR files retain exact old/new exit status, stdout and stderr.
The original complete check now accepts depths 4,096, 16,384 and 32,768 on the ordinary 8-MiB stack, with no diagnostic output. A separate 16,384-depth return-equality check accepts, and an invalid atomic content type at the same depth returns E1001 with the complete found type rather than aborting. These observations do not prove arbitrary-depth equality/formatting or uncached nominal traversal. Q-059 remains open; no semantic feature, public diagnostic code, bundle growth or new acceptance limit is introduced.
Further probes confirm the remaining sites rather than merely inferring them from source: return equality accepts depth 32,768 but aborts at 65,536 with 10,001 Type.eql frames; invalid atomic content aborts at depth 32,768 with 9,999 printType frames. Both failing checks exit -6 without diagnostic JSON. Core capture is disabled only for the child; no timeout ends a probe. Equality and diagnostic/canonical type printing now have independently verified native-stack failures.
## Type equality and printing repair
Type.eql now compares anonymous chains iteratively without allocation. Tags still differ before descent; every array length is checked before its element, and named types compare declaration indices without expanding the nominal graph. All constructor and leaf identities are unchanged.
Type printing now records anonymous suffixes in an explicit stack, then emits them from the innermost outward. Array suffixes retain their original lengths and canonical comma/space spelling; other wrappers close with >. Named declarations remain names. The internal Zig print/printType API receives a compiler allocator explicitly, with updated verifier/serializer callers; allocation and writer errors propagate. Stack storage is proportional to input nesting, deallocated after the print attempt, and adds no heap allocation to an Aji program. AIR text, diagnostic fields/codes and JSON serialization rules do not change.
Unit tests compare separate 65,536-level chains with equal types, unequal deep leaves and unequal middle array lengths; they retain each unary constructor identity. A 65,536-level varied-length type prints exactly and passes parse/print/parse/print canonical equality. Wrapper spellings, suffix-allocation failure and buffered writer failure are checked independently. Unit/format checks, test-extended and all 1,769 conformance cases pass, and all 366 public AIR checks retain exact old/new exit status, stdout and stderr.
Both verified crashing CLI inputs now finish: return equality at depth 65,536 accepts with no output, and invalid atomic content at depth 32,768 returns exactly one E1001 at the original primary position with the complete canonical found type. These are direct process outcomes on the ordinary native stack, not just isolated helper tests. Uncached nominal fallback and other type-query call paths still require audit; Q-059 remains open. No new syntax-depth limit, semantic feature, public diagnostic code or bundle text is introduced.
## Audit-report traversal
Call-path inspection finds a further anonymous traversal in report.write's capability-kind collector. The verified 65,536-depth parameter module accepts checking but `aji report` aborts with 10,000 go frames (plus one inner frame), no JSON and exit -6. The collector now iterates inner types, preserving its nominal-name stop, scan sites, deduplication and sorted output. The complete report probe now returns an audit JSON document, and a checked deep capability parameter unit test retains sorted deduplication across declarations, parameters, return and block parameters. Unit/format checks and all 1,769 conformance cases pass; all 366 public AIR report commands preserve exact old/new exit/stdout/stderr.
The CLI retains verifyModule's size/property caches in check.Report.module; frontend constraints use properties.prepare before structural queries. Uncached nominal fallback remains present in the low-level APIs and needs its own audit. No blanket native-stack claim is made for all query paths. A separate accepted runtime zero-materialization probe exposes [Q-060](runtime-value-depth-audit.md); compiler type repairs do not resolve runtime value traversal.
## Cache-free nominal accounted-size queries
At c906441, a direct accountedSize query over a constructed chain of 32,768 single-field nominal records ending in u8 aborts with exit -6 on the ordinary 8-MiB stack. Its symbolized stderr contains 5,001 accountedSize and 5,000 uncachedBaseSize frames before the traceback limit. This is an executed low-level size-query failure, not a claim that the full verifier accepted that constructed module. A separate parsed programme with 1,024 or 4,096 uniquely named nested records passes the public verify wrapper, retains neither cache in the caller's module, then allocates/frees its one-byte contents through interp.run under fuel 8. Both old runs return normally after six instructions. No wall-clock timeout ends a probe; only child core capture is disabled.
The public size query now accepts a compiler allocator and propagates OutOfMemory separately from null arithmetic overflow. Cached entries and anonymous/scalar queries remain allocation-free. An uncached nominal leaf uses SizeMemo's explicit continuations in a temporary host arena, released before returning. Partial immutable module caches may supply child entries, including cached null; neither type storage nor caller cache is mutated. The nominal cycle guard, checked field sums, enum payload maxima/tag accounting, unary affine folding and early overflow behavior are unchanged. The recursive arithmetic derivation is retained only as a shallow independent test oracle.
All runtime size-query callers propagate metadata allocation errors before charging authority or publishing new payloads. The existing accounted-size invariant (spec 08 §7.1), verifier acceptance/priority, heap/region/graph/buffer/channel charges and release rules remain unchanged. This adds no Aji allocation, effect, fuel charge, scheduling point, code, trap, feature, semantic flag or depth limit. The internal Zig accountedSize API gains an allocator/error result; AIR/source syntax and CLI records are unchanged. The existing nominal_queries/cycle AIR/source rejection pair still expects E1003, and the valid nested_allocation_quota pair retains its precise allocation and release behavior.
Unit tests compare 7,168 shallow mixed struct/enum/wrapper queries, including invalid cycles, zero lengths and overflow, against the independent arithmetic derivation. A 32,768-declaration query now returns one byte. Every underlying metadata allocation is failed in turn, checking propagated OutOfMemory and complete temporary cleanup; cached success/overflow and partial-cache reads are checked separately. A verified enum/record/array programme runs 108 times across cached/cache-free modules, quota boundaries, fuel 0–8 and ordinary/per-instruction collection; all 54 paired records and instruction counts agree. Runtime metadata OOM remains a host error, not a budget_exceeded edge.
The repaired process-level 32,768-declaration query returns one byte, and both parsed cache-free library programmes retain their six-instruction result. All units, format checks, test-extended and all 1,791 current conformance cases pass; all 370 public conformance AIR check commands retain exact old/new exit status, stdout and stderr. Uncached nominal property predicates and their public call paths remain separate Q-059 work. No fresh Claude review was available.
## Cache-free nominal property queries
At 897f538, each of nine direct queries over 32,768 nested nominal records ending in u8 aborts with exit -6 and recursive property frames on the ordinary 8-MiB stack: linearity, Zeroable, Copy, Local, Send, Share, IslandSafe, endpoint and forbidden content. These constructed resolved graphs test the query API, not acceptance by the complete verifier. Only child core capture is disabled; no timeout terminates a probe. All nine repaired probes return their expected booleans.
Public property queries now take a host allocator and propagate metadata OutOfMemory. An iterative classifier retains the original anonymous edges, Send/Share transitions and terminal rules. Cached facts and anonymous terminal paths allocate nothing. A cache-free nominal query runs the existing monotone property worklist in a temporary arena and releases it before returning; it neither mutates the caller's module nor installs a cache. Zeroable rejects an enum without preparing its payload graph. Explicit prepared queries serve internal stages whose preceding type verification supplies immutable caches and value types. Public generic-argument validation uses fallible queries where that precondition does not hold. The private derivedType helper already receives the prepared module; its fallible calls therefore read cached facts without allocating.
The preserved invariant is that ownership/transfer/aliasing decisions use the same structural facts, independently of whether the caller retained verifier caches (spec 02/03/04). Property preparation retains its fixed points, universal/existential aggregation, declaration dependencies, phantom edges and saturated summaries. Invalid recursive layouts still reject E1003. Valid `source/generics/constraints_positive.aji` and the `nominal_queries/cycle` AIR/source rejection pair remain conformance examples; raw and prepared `own_array<Plain>` arguments accept, while `own_array<Owner>` arguments retain the same E1001 envelope. Verifier rules, runtime ownership, authority, fuel and deterministic scheduling are unchanged. There is no new Aji allocation, code, trap, feature, flag, syntax limit or bundle text. Only the internal Zig allocator/error API changes.
Tests compare both raw and prepared queries against 9,216 independent shallow pre-repair derivations (18,432 comparisons). Twenty-seven deep queries cover plain, task-local and endpoint leaves with pending sibling fields. Every temporary allocation is failed in turn for all nine properties, checking OutOfMemory and complete cleanup; prepared/terminal reads succeed with an allocator that rejects its first request. Generic-argument metadata failure produces no semantic diagnostic. Units, format checks and test-extended pass. The full property-engine conformance snapshot passes all 1,791 cases; old/new CLI checks are byte-identical for all 370 AIR and 1,421 source files, as are all 506 accepted source lowerings. Final full conformance after the generic-argument call-site correction also passes all 1,791 cases, with exact corpus coverage.
Q-059 remains open for the closing public-call-path audit and source AST traversal inspection. The earlier full per-instruction collection suite is still running; no incomplete suite or unavailable Claude review is counted as a pass. Phase 6 and contract decisions remain open.
A subsequent read-only Claude review, relayed by the owner, examined the property diff against 897f538, including frontend/lower.zig. No defects were reported in the nine classifications, fixed-point preparation, cache preconditions, allocator/error lifetime or test construction. Nothing was built or run, and the expanded suite was not observed; this is code-review evidence only, not independent test confirmation or review of later source-parser work. The resultType/derivedType wording above is corrected, and query's API comment now directs repeated callers to prepare once rather than rebuilding the entire module for each nominal query.
## Source type-syntax parser
At 3563560, an 82,013-byte monomorphic source file containing 16,384 nested length-one arrays aborts in `typeExpr` with 8,704 symbolized frames and exit -6. Depths 63, 64 and 4,096 accept. Spec 15 §15's depth-64 generic traversal guard is not a universal parser limit: specialization returns an unchanged module when there are no generic declarations or uses. Applying that guard to every parsed annotation would change existing acceptance. Only child core capture is disabled during probes; no timeout terminates them.
The source type parser now suspends array suffixes and argument lists in explicit frames, including nested static function arguments. Array lengths, argument order, wrapper classification, qualified names, `cap`/`file` paths, wrapper-arity errors and split `>>` positions retain their original behavior. Static function references remain argument syntax; no ordinary type synonym is added. Frame storage is released, AST argument/element storage retains the caller's arena lifetime, and host allocation errors propagate without exposing a partial AST. Spec/reference, verifier and runtime rules, diagnostics and bundles are unchanged; there is no new nesting limit, feature or semantic flag.
Unit tests inspect 32,768 mixed array/wrapper/applied-type levels with sibling arguments, 16,384 nested static function argument pairs and split-closer spans. Deep malformed input retains its leaf and wrapper-name failure positions. Failing each underlying parser arena allocation checks OutOfMemory and cleanup. All units, format checks and all 1,791 conformance cases pass, with exact corpus coverage. Hosted grammar and repair-advice suites pass 288 and 299 checks. Formatter integration passes 6,072 checks over 1,467 public files (1,412 parsed, 55 syntax errors and 782 identical AIR outputs). All 1,421 old/new source checks and 506 accepted lowerings are byte-identical; 156 additional constructor/argument/error probes retain exact outputs.
The formerly failing array input now formats successfully, producing 82,019 bytes; a second formatting pass is byte-identical. Full checking reaches a separate confirmed failure in `generics.usesGenerics` (20,002 symbolized frames, exit -6), without `typeExpr` frames. A second deep input, invalid `mut slice<…>`, previously aborts while speculative repair-advice parsing recurses; it now returns one E7001 at the original primary position with the exact `slice_mut_type` candidate. Passing parsing/formatting or this diagnostic does not establish complete checking for arbitrary source depth. Q-059 remains open for source AST traversal and closing call-path work. No fresh Claude review was available.
## Source generic-use detection
The preceding 16,384-array source reproduces the `usesGenerics` failure again at cef944d (10,001 frames before the traceback limit, exit -6). The query now visits immutable AST storage through explicit work entries. Typed callbacks enqueue pointers to original struct fields, active union payloads, optional contents and slice/pointer children; no pointer to a copied temporary payload escapes. Reversed enqueue order retains the original depth-first field/element order. String bytes and scalar fields remain leaves. Temporary work storage is released on completion, early positive detection or allocation error.
The original generic-use markers are unchanged: applied/static-function types, explicit expression specialization, enum/struct expressions with type arguments and constructor patterns with type arguments. Generic declarations still take their preceding specialization path; monomorphic input is not assigned a new depth limit. OutOfMemory propagates as a host error rather than false or a source diagnostic. Syntax, nominal identity, effects, verifier acceptance, ownership/runtime/fuel rules and bundles are unchanged. The private host query gains an allocator/error result; no AIR feature, public diagnostic or semantic flag is introduced.
Unit tests compare 387 shallow type/expression/pattern/block/module queries against the independent pre-repair derivation, including empty arguments and optional fields. Positive and negative queries traverse 32,768 type, expression and nested-block levels. Every work-allocation request is failed in turn for both outcomes, checking error propagation and cleanup. All units and format checks pass; generic and static-function CLI integration passes 32 and 25 checks. All 1,791 conformance cases pass with exact corpus coverage. All 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr.
The complete 4,096-array check still accepts before and after. The 16,384-array check now reaches a separate confirmed native-stack failure in lowering's resolveType (10,883 frames, exit -6), with no usesGenerics frames or diagnostic JSON. No timeout terminates these probes; only child core capture is disabled. This is progress through the pipeline, not full deep-source acceptance. Q-059's source lowering/remaining traversals and Phase 6 gates remain open. The earlier full per-step collection suite is still in progress. Claude's preceding property review does not cover this change.
## Source annotation resolution
The 16,384-array source again aborts before this increment at 24a3876: the fresh traceback contains 5,440 resolveType frames, exit -6 and no diagnostic JSON. Lowering now records array/wrapper continuations, resolves the leaf and constructs the source Ty chain from inside outward. Array-length and known-wrapper checks remain before child resolution; array value-content and AtomicScalar checks remain after it, with the original spans, messages and fields. Nominal names still stop at their declaration index. The pending list is deinitialized on success, rejection or allocation error; its caller-arena buffers remain until arena destruction. Metadata and resulting type allocation failures propagate as host OutOfMemory. No source/AIR constructor, semantic limit, diagnostic code, runtime/fuel/effect/ownership rule or bundle is changed.
Tests compare 1,736 shallow leaf/array/wrapper combinations against the independent pre-repair derivation, including unknown names/constructors, array boundary lengths and competing error priority. A 32,768-level mixed annotation is constructed and inspected iteratively; unknown and nonvalue leaves retain their original diagnostics. Every allocator request is failed in turn, with arena cleanup checked. Type-position and Copy-content CLI integration pass 74 and 119 checks. All units and format checks pass. All 1,791 conformance cases pass with exact corpus coverage; all 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr.
Complete checking still accepts the 4,096-array input. At 16,384 it now passes resolveType and aborts in type_properties.firstInvalid (10,001 symbolized frames, exit -6 and no diagnostic JSON). Only child core capture is disabled; no timeout ends a probe. Recursive diagnostic type text and other source property/query paths remain audit candidates. This is not arbitrary-depth source acceptance: Q-059, Q-060's closing validation and Phase 6 gates remain open. Claude's previous nominal-property review covers neither this increment nor the generic-use repair.
## Source anonymous property scans
At b23f3e6, the ordinary 16,384-array source aborts in type_properties.firstInvalid (10,001 frames). A second source wraps the same array annotation in own_array; it aborts in linear (7,060 frames). Both exit -6 without diagnostic JSON. The repair makes firstInvalid follow array/wrapper syntax with constant traversal state, preserving outer-before-inner own_array checks and the island/frozen/arc stop. Its known-linearity helper peels only anonymous array chains; named declaration lookup, parameter binding/shadowing, memo generations, cyclic paths and fixed-point retries retain their original algorithm. No new allocation or error conversion is introduced by either loop.
Tests compare 2,160 shallow cases against the independent pre-repair anonymous traversal, including nominal/generic content, cycles with a positive witness, unknown parameters, parameter shadowing, nested own_array and graph stops; the nominal declaration algorithm is shared, not an independent nominal oracle. Deep array/mixed-wrapper queries cover 32,768 levels, positive/negative content and original failure spans, while an allocator failing at its first request verifies zero work allocations on these anonymous paths. Existing diamond/cycle tests, all units and format checks pass. Copy-content/generic CLI integration passes 119/32 checks; all 1,421 public source checks and 506 accepted lowerings retain exact old/new exit/stdout/stderr. All 1,791 conformance cases pass with exact corpus coverage.
Both previously aborting complete 16,384-level checks now accept without output, as does the 4,096-array input. Non-Copy content behind the deep own_array returns exactly one E7005 at 2:19, with constraint Copy and type_constructor own_array. Core capture alone is disabled and no timeout ends a probe. These process outcomes establish repairs for these inputs, not arbitrary-depth source acceptance. A separate 8,192-declaration source probe confirms remaining native recursion through named source types: before this repair, 3,326 linear and 3,325 declaration frames; afterward, 3,306 and 3,305, both exit -6 without diagnostic JSON. Source Ty equality/text/AIR conversion and other closing call paths also remain to audit. Q-059 and Phase 6 gates remain open; Q-060's full per-step validation remains separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule or acceptance limit changes. No fresh Claude review is claimed.
## Source nominal property continuations
The independently reproduced 8,192-declaration linear/declaration failure is repaired by an explicit query/argument/member continuation machine. Static arguments finish in their parent environment/path before cache and cycle checks. Struct fields and enum payloads retain source order and positive short-circuiting. Cycle state remains the declaration name plus known-linear parameter flags; indexed path entries survive work-list growth. Negative entries retain the generation captured before argument evaluation, while positive completions invalidate provisional negatives in the original order. Memo keys remain in caller-arena storage across retries; temporary frame/path buffers are released on success, early result or OOM. Metadata allocation errors propagate, never become false or a diagnostic. Anonymous terminal paths still allocate no work storage.
The old recursive nominal declaration algorithm is now copied into the shallow oracle as well, removing the shared-nominal limitation of the preceding tests. Tests compare 4,613 roots over 128 generated six-declaration graphs and targeted nested-argument/parameter states, each queried three times with retained caches: results, lookup counts, complete entry order/keys/values/generations and final generation all agree. The existing 2,160 shallow syntax comparisons now use this independent nominal derivation too. Three 16,384-declaration mixed struct/enum queries cover negative content, positive leaves and a deep cyclic back-edge with a later positive witness. Six argument/cycle/result shapes fail every underlying arena allocation request in turn, checking OOM and full arena cleanup. Units/format checks, nominal/Copy-content/static-function CLI integration (110/119/25) and all 1,791 conformance cases pass with exact corpus coverage; all 1,421 source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr.
The complete formerly failing Copy chain accepts with no output. Replacing its final field with own<u8> returns exactly one E7005 at 8194:19, with constraint Copy and type_constructor own_array. No timeout ends these probes; only child core capture is disabled. A separate 65,536-array invalid-atomic source now confirms source typeText native-stack exhaustion (10,001 frames, exit -6, no JSON), before any diagnostic is emitted. Source Ty equality/text/AIR conversion and closing query paths keep Q-059 open; Q-060 validation and Phase 6/contract gates remain separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule, generic traversal guard or accepted-depth limit changes. No fresh Claude review is claimed.
## Source type text repair
The 65,536-array invalid-atomic source's confirmed typeText abort is repaired by an iterative prefix/leaf/suffix writer. One growing byte buffer replaces recursively copied ancestor strings; parent lists are deinitialized, while their buffers and failed output buffers retain caller-arena lifetime. Canonical spelling, array decimal lengths/spaces, source-versus-AIR nominal names and the resources feature side effect are preserved. The internal typeText/tyText/diagnosticTyText APIs now propagate host OutOfMemory at every caller, replacing the old array/borrow/cap fallback strings. Failed metadata allocation must not fabricate a found type or generated AIR; ordinary diagnostics, syntax, effects, ownership/runtime/fuel and acceptance rules are unchanged.
Independent shallow tests compare 3,696 canonical/diagnostic outputs and feature states against the old printer, covering every wrapper/leaf, nominal display-name fallbacks and zero/max-u64 array lengths. A 65,536-level mixed chain has independently assembled exact text in both modes. Allocation failures cover direct printing, diagnostics and local AIR emission, with arena cleanup and no fabricated diagnostic/partial instruction; constant leaves retain the allocation-free path. Units and format checks pass. Repair-advice/nonvalue/static-function CLI integration passes 299/635/25 checks; all 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. All 1,791 conformance cases pass with exact corpus coverage.
The formerly aborting invalid-atomic check now returns exactly one E7005 at 2:9 without stderr; its complete found type is byte-identical to the independent 655,362-byte expectation. A separate correct 65,536-array parameter check accepts without output. A struct field containing 16,384 arrays then confirms remaining native recursion in source-to-AIR type conversion: 4,425 airType frames, exit -6, no JSON. Only child core capture is disabled, and no timeout ends a probe. Source-to-AIR repair, Ty equality and closing query paths keep Q-059 open; Q-060 validation and Phase 6 gates remain separate. No syntax/feature/code/bundle growth, runtime/effect/ownership rule, generic guard or accepted-depth limit is introduced. No fresh Claude review is claimed.
## Source-to-AIR type conversion
The confirmed 16,384-array struct-member airType failure is repaired by an iterative output-target cursor. Array/wrapper nodes are allocated in the original outer-to-inner order; each target is the local root or stable newly owned output storage, never source Ty storage. Only the completed root is returned. A failed allocation propagates host OutOfMemory without publishing a partial type/module; already allocated nodes remain in the caller's arena as before. There is no work buffer, new metadata allocation or API change. Leaf indices, wrappers, array lengths, feature/ownership effects and all source/verifier rules remain unchanged.
Independent shallow comparison covers 2,352 leaf/array/wrapper shapes, every registered capability and internal wrapper, plus allocation-free leaves. A 65,536-level mixed conversion is inspected and freed iteratively; exactly one output allocation per constructor proves no additional work allocation or borrowed source node. Per-node request lengths/alignments, OOM points, byte/allocation counts and cleanup match the old recursive derivation on a 64-level mixed type. Arena backing growth is deliberately not an equivalence oracle: in-place resize availability can differ between two arenas. Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact corpus coverage and old/new checks/lowerings (1,421/506) pass.
Complete checks of structs with 16,384 and 65,536 array levels now accept without output. A separate 65,536-level source return-equality input confirms the next native failure in Ty.eql (10,001 frames, exit -6, no JSON). Core capture alone is disabled; no timeout ends a probe. Source equality and closing query paths keep Q-059 open; Q-060 validation and Phase 6 gates remain separate. No normative/bundle/feature/code, runtime/effect/ownership or accepted-depth limit changes. No fresh Claude review is claimed.
## Source type equality
The confirmed Ty.eql failure is repaired with two type cursors and no allocation or mutation. Tag checks still precede descent, each array length is checked before its element, integer/capability names compare string contents, and nominal types compare declaration indices without expanding their graph. All wrapper and leaf identities are unchanged. An independent shallow copy of the old comparator covers every pair of leaf/array/wrapper shapes, including equal names in different storage and zero/max-u64 lengths. Separate 65,536-level mixed trees test equality in both directions and differences at the leaf, interior array length, interior wrapper and outer tag.
Units/format checks and all 1,791 conformance cases pass with exact corpus coverage; all 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. Complete return-equality checks now accept at 16,384 and 65,536 array levels without output. Changing the deep return leaf to u16 yields exactly one E7005 at 2:655407, with independently verified full found/expected types (655,362/655,363 bytes) and no stderr. A separate deep Copy-array move probe yields E7006/move_copy at 65,536 levels with its complete type; no native failure is observed in that query path. Only child core capture is disabled; no timeout ends a probe. Closing source-query inventory and Q-060 validation remain open, as do the independent Phase 6 gates. No normative/bundle/feature/code, runtime/effect/ownership or accepted-depth limit changes; no fresh Claude review is claimed.
## Remaining source linear queries
Call-path inspection finds native recursion in Lowerer.isLinear's array descent and needsLinearType's signature feature scan. The latter's existing guard depends on module cardinality (types.len + 32), so it is not a constant stack bound. Both now use explicit cursors without allocation. Whole-value linearity still follows arrays only and stops at a prepared nominal-cache entry or the original terminal classification. Feature discovery retains its exact guard, named-leaf handling, qualifying wrapper set and content-query-before-depth-increment order. This is an inspection-driven robustness change: the preceding 65,536-level Copy-move CLI probe did not reproduce a native failure in either query.
An independent shallow copy of both old queries covers all leaves/wrappers, array lengths, mixed shapes and initial depths around the guard. Deep helper tests traverse 65,536 arrays ending in Copy/linear nominal leaves and 65,536 ref edges under a complete property snapshot of 65,536 declarations. The feature scan retains true at initial depth 32 and false at 33, pinning its inclusive boundary. This constructed snapshot tests the helper stage, not complete CLI acceptance of that module. Units/format checks, source linear/nominal CLI integration (49/110) and all 1,791 conformance cases pass with exact corpus coverage. All 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr.
The closing inventory separately confirms source SSA zero generation as a remaining failure: at 16,384 array levels above a Plain record, a var initialized with zero aborts with 10,001 Lowerer.zeroValue frames, exit -6 and no JSON (82,026 input bytes). The existing SSA lowering rejects record leaves with E7006/zero_not_zeroable; AIR's broader zeroability and the unresolved source policy Q-056 are separate. Only child core capture is disabled; no timeout ends the probe. Source zero emission and the remaining specialization/call-path inventory keep Q-059 open; Q-060 validation and Phase 6 gates remain separate. No normative/bundle/feature/code, ownership/runtime/effect or accepted-depth limit changes; no fresh Claude review is claimed.
## Source SSA zero emission
The confirmed Lowerer.zeroValue failure is repaired by counting the array chain, classifying its leaf, then emitting through a single arena-owned table of immutable parent pointers. Unsupported leaves retain the implemented E7006/zero_not_zeroable before any traversal allocation or instruction emission; this does not resolve Q-056 or adopt broader source zeroability. Allowed leaves remain integers and bool. The original constant precedes array.splat instructions from inner to outer, retaining lengths, source type storage, names, spans, feature state and constant-group markers. The table adds only compiler metadata; its OOM propagates the existing host error. Completed private instruction prefixes may survive a later emission OOM as before, but the public lower wrapper returns that error rather than publishing partial AIR. Runtime/verifier rules, allocation authority, copies and fuel events are unchanged.
Independent shallow comparison with the old derivation covers all leaves/wrappers and array lengths including zero/max-u64, reserved SSA-name collisions and exact error objects. A 1,024-level supported helper emits independently assembled exact instructions, preserving the original outer type pointer. A 65,536-level unsupported helper rejects without allocating even with a failing allocator; emitted prefixes and arena cleanup are checked across allocation failures on a supported chain. Units/format checks, independent-error integration (234 checks), reason integration (229 checks over 113 public E7006 fixtures), and all 1,791 conformance cases pass with exact corpus coverage. All 1,421 public source checks and 506 accepted lowerings preserve exact old/new exit/stdout/stderr. Twelve generated source programs preserve byte-identical lowering and 46 old/new run records across zero/final fuel boundaries; their nested u8/bool values are independently checked through depth 512.
Complete checking of the previously failing 16,384-level source, and a 65,536-level counterpart, now returns exactly one E7006/zero_not_zeroable at 3:32 without stderr. Only child core capture is disabled; no timeout ends a probe. The supported deep-helper result is not a claim of complete CLI acceptance of its varying-length type. Specialization/call-path inventory keeps Q-059 open; Q-056 policy, Q-060 closing validation and Phase 6 gates remain separate. No normative/bundle/feature/code, ownership/runtime/effect or accepted-depth limit changes; no fresh Claude review is claimed.
## Composed specialization identity
At f5e2af1, a recursive generic call adding 31 or 63 arrays around T aborts before the fixed active-expansion guard: the 272/432-byte sources produce no JSON and exit -6, with 1,851/2,340 identity frames and 61/39 instantiate frames. Adding one array instead reaches the existing depth-64 E7006; a single 64-array argument reaches the existing structural-traversal E7006. The guarded ty query can return an already composed environment argument, so it does not bound the subsequent recursive identity writer. These are executed failures, not a proposed wider source depth limit. Only child core capture is disabled; no timeout ends probes.
The identity writer now emits prefixes through a type cursor and stores suffix lengths/spans in explicit arena-owned frames. Its leaf checkpoint and each inner-to-outer closing checkpoint retain the original >16,384-byte test and exact offending span. Named defining-module identities, generated-type/function keys, capability/file spelling and punctuation are unchanged. It does not add a prefix checkpoint or alter expansion/structural/key/count limits, reuse, sorting or SHA-based AIR names. Host OOM propagates before a complete key/module is published; private prefix bytes retain their existing partial-output behavior, and caller-arena lifetime owns the metadata.
Independent shallow comparisons cover scalar/nominal/generated names, capabilities, file modes, static functions, all wrappers, array lengths and prefixes around the exact byte boundary, including complete error objects and intermediate bytes. Writer-only deep fixtures produce an independently assembled 4,095-array key (16,382 bytes), reject the next array at its outer closing span (16,386 bytes), and reject a 32,768-array prefix at the original leaf checkpoint. These helper fixtures are not full source acceptance claims. Failed allocations check propagated OOM, prefix bytes and arena cleanup. Units/format checks and generic/static-function CLI integration (42/25 checks) pass; both new conformance regressions pin code E7006, and hosted checks pin implementation_limit/name/call-site provenance and identical check/lower/report/run/explore diagnostics.
Both previously failing growth sources now reach one E7006/implementation_limit at 2:35 without stderr; the one-array and single-64-array results retain their prior behavior. All 1,421 pre-existing public source checks and 506 accepted lowerings retain exact old/new exit/stdout/stderr. The full 1,791-case snapshot plus the two added focused regressions cover all 1,793 current conformance files exactly, with every case passing. Closing call-path inventory keeps Q-059 open; Q-056, Q-060 validation and Phase 6 gates remain separate. No normative/bundle/feature/code, runtime/effect/ownership or accepted-depth limit changes; no fresh Claude review is claimed.
## Best-effort field type lookup and closing inventory
The closing inspection finds native recursion in `typeOfNoFail`, called by
`peekType`/use inference. At d98ddbc, a shallow `r.x.len` expression over a
record's nested-array field accepts depth 4,096, but aborts at 16,384 and
65,536 with 10,001 typeOfNoFail frames, exit -6 and no diagnostic JSON.
Source arrays use `[T; N]`; the failing inputs are 65,662/262,270 bytes.
Only child core capture is disabled; no timeout ends a probe.
The query now validates the chain and resolves its leaf before allocating,
then constructs output with a fresh-node cursor. Its restricted name/array
classification and length rules are unchanged. OOM-to-null was retained at this historical checkpoint; the [Q-061 host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) supersedes that error policy and renames the helper `queryAnnotation`.
Invalid/unknown leaves allocate nothing. Nodes are allocated outer-to-inner
instead of inner-to-outer; request counts, sizes and alignments match the old
query, and a partial private type is never returned. The caller arena owns
partial storage on failure. No verifier, runtime, ownership or syntax rule changes.
Independent shallow comparisons cover all recognized leaves, unsupported
constructors and valid/invalid nested lengths. A 65,536-node output is inspected
and freed iteratively; invalid deep leaves/lengths allocate nothing. Every one
of 64 node-allocation failures retains null, no diagnostic and complete cleanup.
Units/format checks and all 1,793 conformance files pass with exact coverage;
all 1,423 public source checks and 506 accepted lowerings retain byte-identical
old/new exit/stdout/stderr. Nominal CLI integration passes 130 checks, including
deep formatting/lowering, source/AIR checks, report parity and scalar execution.
The complete formerly aborting checks now accept without output. These tests
do not materialize a deeply nested runtime value.
The [production inventory](type-traversal-inventory.md) closes Q-059's compiler
type-traversal scope: loops/continuations cover unbounded type descent, and
remaining recursive type predicates retain their pre-existing fixed guards.
Expression/statement depth is a separate scope. Q-056 policy, Q-060's unfinished
full per-step GC validation and Phase 6 exit gates remain open. No accepted-depth
limit, normative/bundle/feature/code growth or fresh Claude review is claimed.
@@ -0,0 +1,124 @@
# Contract accounting, diagnostics and status candidate
Non-normative research for [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), following the [invariant-boundary candidate](contract-invariant-boundaries.md). All new constructs, limits and codes here are proposals, not registry allocations. Full P6-6 remains open.
## Evidence and budget rule
At `9a3e135`, the verifier runs limits before CFG, SSA and types, stopping at the first failing stage (spec 08 §14; `src/verifier.zig`). Frame storage counts `local.alloc`; SSA values have the separate maximum-value bound. Nine current-language probes confirm:
- an exactly 1,048,576-byte local accepts and returns 0; one extra byte rejects E5101;
- that local plus a 1,048,576-byte SSA array still accepts and returns 0;
- limits beat malformed CFG (E5101); CFG beats forward SSA use (E5002); forward SSA use beats type mismatch (two E5001s);
- type mismatch beats unsafe-boundary failure (two E1001s); unsafe beats initialization (E6001); initialization beats a live-borrow leak (E1010).
Runs use fuel 10,000. These are baseline constraints, not tests of implemented contracts.
Four complete pre/post assume/document opcode probes each reject E0004 alone. An existing source `assume(false)` in an unsafe function accepts verification and traps T0009 when run with fuel 10,000. These five further baselines constrain compatibility and unsafe enforcement; they do not implement the proposed modes.
Proposed activation storage, using spec 08's checked, platform-independent accounted sizes:
```text
L = sum of all local.alloc content sizes in the function
S = old helper's declared Data return size, or zero
E(clause) = sum of Copy-value places for each explicit ref binding
E(old) = the same sum for old's input bindings
E(checked.make) = size(R) for Copy R; zero for linear R
E(checked.modify) = 0
activation = L + S + max(0, E for executable clause/old/make sites)
```
Each explicit Copy ref binding creates its own temporary place, even when two bindings name the same parameter. Borrow/owner/linear-root observations use in-place views and contribute zero; they MUST NOT copy or transfer ownership. Documented clauses create no runtime places. Their virtual access checks still apply. Locals and S persist for the activation; clauses execute sequentially and their places end before the next evaluation. Helper/callback activations have their own bounds and ordinary call-depth rules.
For make, a Copy representation needs the instruction-internal whole-value place; a linear representation is observed through its existing SSA cell before transfer into the checked value. The latter contributes no new place and cannot be copied, moved during validation or exposed before success. The explicit R operand supplies size/root shape before SSA; both cases retain the ordinary maximum-value bound.
Pending callback/return values remain ordinary SSA values, bounded by `max_value_size` and traced by GC. They are not a new frame term. A Copy `ref result` place is counted once in E; an update result retained during validation is not materialized merely because it is pending. The candidate maximum activation size is 1,048,576 bytes, using E5101's existing `limit: "local frame bytes"`, `max` and `found` fields; overflow is `found: "overflow"`. Functions without the new sites retain their current accounting.
All descriptors MUST be available before SSA inference: clause bindings name original parameters, the snapshot or result; parameter/result types come from the enclosing header, snapshot type from its helper header, and make explicitly names `checked<R,@p>`. Callback result types come from callback signatures. Budget calculation never dereferences an absent parameter or assumes predicate validity. Malformed bindings wait for their later stage; size and Copy/root-shape queries must be total on recursive/invalid types, with cycle detection and memoization, without invoking full type verification. Existing size accounting supplies the size-query precedent; the current recursive linearity query is not a safe pre-types substitute. An arbitrary body SSA binding is forbidden. Accounted size of checked<R,p> is size(R); predicate identity contributes no runtime member.
For this budget query, seed the existing intrinsically linear kinds and propagate linearity backwards through array elements, nominal struct/enum members and checked<R,@p>'s representation R to a least fixed point. Predicate identity contributes no edge. An invalid member cycle with no reachable linear leaf is non-linear (Copy for accounting); one reaching an owner or another linear leaf is linear. Direct borrow/root bindings remain in-place. This matches ordinary linearity on valid types and supplies a deterministic value on cycles, without accepting them. Use the corrected nominal-edge size-depth convention ([Q-058](open-questions.md#q-058--finite-anonymous-types-truncated-by-the-size-cycle-guard)); anonymous checked representation edges preserve that depth. Keep invalid-graph queries bounded rather than replacing a whole cyclic type's size with zero. Required candidate vectors include both kinds of cycle next to the frame limit: budget excess still reports E5101 first; otherwise the invalid cycle reaches the ordinary type rejection. These vectors are not among the fourteen executed baselines.
Two sequential clauses each materializing 600,000 bytes fit when L=S=0. One clause materializing both needs 1,200,000 and rejects. Snapshot 600,000 plus locals 500,000 rejects even with no temporary place. This rule does not infer lifetime reuse between arbitrary locals.
## Bound the virtual boundary work
Post bindings are checked at every return, so instruction count alone does not adequately bound the product. Count syntactically, including unreachable blocks, before SSA:
```text
W = sum_pre/old(1 + binding_count)
+ ret_count * sum_post(1 + binding_count)
+ 2 * make_count
+ sum_modify(4 + extra_argument_count)
```
The proposed limit is 1,048,576 virtual binding positions per function: four times the ordinary instruction limit, independent of any benchmark. The extra position covers each virtual invocation; modify covers its callback's first argument, extra arguments and predicate invocation. Count documented clauses because their virtual legality checks still run. Excess/overflow rejects E5101 with `limit: "contract binding positions"` and the existing fields. Actual argument lists retain the 64-argument limit, including modify's generated first argument. P/S closure computation and diagnostic witnesses need independent memoized bounds; this formula is not a bound on every verifier algorithm.
## Four statuses, three enforcement modes
Default `contract.pre/post` and checked make/modify evaluate their predicates at every specified boundary. Source `requires`/`ensures` retain this default. Propose explicit variants `contract.pre.assume/post.assume` and `contract.pre.document/post.document`, with contextual source `requires/ensures assume` and `requires/ensures document` groups.
| Mode | Proof treatment | Spec 13 status | Execution |
|---|---|---|---|
| runtime, all boundaries proved by the closed rule below | proven | PROVEN_STATICALLY | predicate still executes |
| runtime, no complete proof | none | CHECKED_AT_RUNTIME | predicate executes |
| explicit assume | not attempted | ASSUMED_UNSAFE | interpreter evaluates; false is T0009; native unsafe treatment follows assume |
| explicit document | not attempted | UNPROVEN | declaration recorded; predicate is not executed |
Assumed variants require the existing unsafe effect/trusted boundary and appear in the unsafe report; ordinary P/helper typing, availability and lifetime checks remain mandatory. They need a separately gated extension depending on contracts and unsafe, so ordinary contracts need not declare unsafe support solely to be understood. False unsafe assumptions retain the existing unsafe-precondition semantics, rather than becoming a safe guarantee.
Documented variants also retain P membership and the same virtual observation/access checks at entry and every normal return. They grant no fact to a caller or the body. Switching a clause to document removes its guarantee and must remain visible in the report/Quick Reference. A documented post may bind an old snapshot only when an executable runtime/assumed post also uses that snapshot; a snapshot used solely by documents rejects as unused. Checked types have no document/assume construction mode in this candidate: persistent value claims remain enforced.
Every executed prefix operation still costs one fuel step, including document declarations and post installation. Documented clauses invoke no helper at entry or return; executable clauses use ordinary helper instruction and frame accounting. Recording metadata introduces no extra dispatch step. This extends the prefix accounting candidate without making classification change execution.
No successful run, absence of a trap, check count or empty effect set establishes proof. Profiles may reject statuses but MUST NOT alter enforcement or proof classification. Static classification adds no skipped helper instruction or fuel/scheduler change. Even PROVEN_STATICALLY does not promise termination or freedom from other traps. Counts describe declaration/operation sites, separately from the number of covered returns, never invocation frequencies.
## Closed initial proof classification
This is deliberately a restricted classifier, not a restriction on executable contracts. Unsupported predicates remain CHECKED_AT_RUNTIME. It never imports a caller fact into a callee's global pre status and never assumes an unchecked declaration.
An eligible predicate has one block, no calls, and only typed constants, copy, Data struct construction/projection, integer/bool comparisons, bool and/or/xor, and shared binding-derived field views with load/end, ending in ret bool. The same form with a Data return can describe old's snapshot fields. Arithmetic, casts, indexing, graph/buffer/enum operations, calls and multiple blocks are unsupported initially. Normalization uses an immutable DAG, not expanded copies of paths/aggregate trees.
Terms are typed constants, immutable Data parameter identities/projections, stable shared parameter field projections, snapshot terms from an eligible old helper, and the current return operand's Data origin. Resolve return origins through constants, copy, struct.make and struct.get; every other Data SSA definition is an opaque identity at this boundary. A snapshot cannot capture body SSA, so a loop's repeated definition is not conflated with an entry observation. Borrow-return origins remain unsupported. Mutable-root entry/current observations have distinct identities, even when the body happens not to write; no interprocedural write-summary proof is inferred.
Shared field terms are stable because ref cannot become mut, overlapping mutable call arguments and root consumption are forbidden, and task loans exclude writers. Field views in this normal form do not traverse interior-mutable interfaces. P/S alone are not substituted for this exact normal-form condition; future pure observations outside the form stay unsupported.
Decision rules are closed: compare typed constants with their declared signedness; identical typed terms give true for eq/le/ge and false for ne/lt/gt; otherwise an atom is unknown. Bool combinations use three-valued logic (`true or unknown` is true, `false and unknown` is false; xor with unknown is unknown). A runtime clause is proven only if its formula is definitely true at every prescribed boundary. Pre parameters are universally unconstrained; a post must hold at every syntactic ret, including unreachable ones, and zero ret sites give no vacuous proof. A make site may substitute a constant/parameter-derived representation; modify remains runtime initially.
Examples: a Data identity function whose every return is x can prove `result == old(x)` when old merely captures x. A second return of y prevents that classification. A constant Range representation or `{lo:x, hi:x}` can prove lo <= hi through shared field inspection. A pre over unrelated lo/hi remains runtime. `x + 0 == x`, hashing and mutation-based restoration remain runtime even when mathematically true.
The [proof/report candidate](contract-proof-and-report.md) refines the work bound with exact opcode/node charges, binding-substitution positions, checked u64 counters and ordered fallback reasons. Pre has one boundary and no body-origin work; adding unrelated body instructions cannot make a pre proof exceed its budget. Post/make charge each required origin definition once per record, including shared definitions across return sites. The proposed bound is 1,048,576 per record. Excess, overflow or unsupported forms yield proof none without rejecting or weakening runtime enforcement; logical costs are independent of cache hits. The concrete candidate and its vectors await adoption and implementation rather than an implementation-dependent prover choice.
## Diagnostics and report
Map the new rules into existing stages: limits first; prefix order/entry predecessors in CFG; snapshot-use restrictions and binding identities in SSA; signatures/Data followed by P/S membership at the end of types; callback effects in effects; assumed boundaries in unsafe; ordinary initialization checks unchanged; virtual access/loans/return availability in borrows; existing bounds last. Observation places are materialized from complete parameter/result/snapshot values and introduce no independent initialization failure. Parse/name and feature errors precede verification. Invalid signature errors precede purity classification. Runtime clauses retain ordinary E2001/E3001/E2101 and lifetime codes instead of a generic contract error.
Candidate new codes are E8001 `contract.invalid_binding` (snapshot escape/unused/document-only snapshot with stable reason), E8002 `contract.predicate_not_pure`, E8003 `contract.predicate_not_stable`, and T0011/T0012/T0013 for false runtime pre/post/invariant. None is allocated here; adopting E8xxx also requires a new family entry in spec 10 and the error registry. Existing signature/type errors use E1001, structural errors E5002, limits E5101 and missing unsafe boundary E6001. Source-decided errors follow spec 15 §10's E7xxx policy; semantic new codes retain source provenance. A purity witness must contain real helper/type/op facts, with bounded length and explicit truncation, not invented locations.
### Collection at returns
For a contracted ret, retain the body state before return transfer. Run the ordinary return check on isolated working state, keeping its existing diagnostics and early-return/leak behavior. Track failure of the returned operand's availability, transfer access or declared borrow origin separately from resource/borrow leaks; do not infer that flag by parsing a diagnostic message. If return legality failed, suppress virtual post access checks at this ret: the invalid returned boundary is not a usable clause observation. Keep every ordinary diagnostic that today's return check would emit, and continue other independently valid returns.
Otherwise check every installed post in prefix order against the original pre-transfer body state, using isolated temporary view/state bookkeeping for each. Isolation includes borrow/loan state, transfer summaries and emitted verifier events; commit ordinary return facts/events only once, and discard synthetic temporary-view events after each virtual check. A failed clause cannot leave synthetic live borrows or suppress a later clause or the ordinary leak records. Type/P rules ensure these helpers cannot permanently mutate caller state, so successful sequential predicates have the same available roots. This is static legality collection, not runtime execution of later predicates after a trap. Runtime still stops at the first failing predicate. Finally merge ordinary and virtual facts using the existing AIR (line,col,code) order; source mapping retains existing one-per-code/source-location selection. Contract-free returns use today's path unchanged.
A virtual post-access error's primary span is its binding token, not ret; code-specific function/block/inst fields identify the installing post instruction. They are not additions to the common diagnostic envelope. Function and block are AIR names without sigils, as in ordinary borrow diagnostic payloads; inst is the zero-based instruction index. Map that binding independently to the source root occurrence in its clause. Preserve existing factual payload and conflict/spawn origins; result payloads name the actual ret operand, not a synthetic result ValueId. Add proposed code-specific fields `contract_binding` (zero-based argument index) and `contract_return` (the evaluated return position). The latter's field order is `function,block,inst`, followed by file/line/col only when exactly mapped, then mandatory air_line/air_col. Its block is a name, not an index; names/inst identify the actual ret and source coordinates map independently. This is a separate factual position object: today's related_locations roles require a value identity and cannot represent ret without inventing one. No role is silently added to that closed schema.
For AIR-only input, contract_return still includes air_line/air_col and omits file/line/col because no source lowering map exists; the primary envelope continues to identify the input AIR file. This deliberately differs from today's AIR-only related_locations serialization and must not be normalized by inventing a source map.
All returns are checked. Buffer only the new virtual facts and append them in increasing return block index, then instruction index, retaining clause/binding order within each return. The existing stable (line,col,code) sort therefore retains that return order within a tied virtual primary/code, before source duplicate selection; the current comparator itself supplies no return key. Internal block indices establish this order, while JSON records contain block names. Ordinary facts and contract-free ordering stay unchanged. Source may retain one representative failure for a binding across several returns or repeated mapped specializations under its existing code/location rule. This output selection does not suppress checking another clause or return. Distinct source clause bindings have distinct primary positions and survive independently. Future collection tests must cover two clauses failing with the same code at one ret, one clause failing at several returns, and duplicate imported/template maps, with the exact retained return context. No contract diagnostic fields are implemented by this candidate.
Current baselines at `8df6cac`: a wrong-origin borrow return with an unrelated live owner emits only E2102, while a valid-origin or scalar return retaining that owner emits E3002. Returning an already taken owner emits E2002. Returning an owner with a live child view emits both E2101 and E2105: the current return check kills the root after reporting its transfer conflict, then reports the view leak. Do not replace this with an invented first-error-only return contract. Future vectors must pair an otherwise valid ret's unavailable post root with an unrelated leak, proving both survive; a return-legality failure must preserve the baseline list and suppress dependent post errors. These are proposed collection rules, not an implemented post checker.
### Purity/stability witnesses
Complete ordinary type validation first. Compute P and then S membership once over the direct-call graph, including unreachable instruction/call sites. For each locally inadmissible function select its first seed in this fixed order: declared effects, trusted metadata, header/block-parameter types in declaration order, then instruction type operands/results before opcode in textual block/instruction order. Each seed names its real function/type/op position. Required predicate roots outside P report E8002; if any such root fails, stop the types stage before required S-root checks. Ordinary functions outside P do not reject unless a contract requires them. After all required P roots pass, S uses published stable classifications and required roots outside S report E8003. No source annotation or proof result substitutes for either closure.
Use a reverse-edge multi-source BFS to give each excluded function its minimum number of call edges to a local seed. Resolve ties after distances are known: select the first textual call site leading to distance minus one. A distance-zero function keeps its first local seed even if it also calls another invalid helper. Recursive components with no local failure remain admitted; a component reaching a seed is excluded. The selected witness edges strictly decrease distance, so a witness never loops. Propagate the terminal fact and bounded path summaries in increasing distance order. BFS/local scans cost O(F+C); retaining the first/last 16 edges per excluded function adds at most 32F position copies, not a fresh graph traversal per clause.
Candidate E8002/E8003 fields are `predicate,reason,witness`. Predicate is the referenced AIR name without @; reason is the terminal seed category, independently of prose. Witness field order is `call_count,prefix,suffix,omitted_calls,terminal`. For at most 32 calls, prefix contains every call and suffix is empty. For a longer path, prefix is its first 16 and suffix its last 16; omitted_calls is call_count minus 32 and represents the gap between them. Terminal is always retained. This bounds witness positions, not the size of arbitrary input names/type strings. A malformed/unreachable callee has already failed ordinary validation and is not an invented seed.
Each call record is `function,block,inst,callee,source`, in that order, with exact zero-based AIR instruction identity and source `{file,line,col}` or null. Terminal is `function,block,inst,reason,type,operation,source`; header seeds have null block/inst, unused fact fields are null, and reason is effects/trusted/type/operation. Operation is the actual canonical opcode, not a suggested repair. Source positions use the exact lowering map; missing maps stay null. The primary diagnostic belongs to the clause/checked-type use that requires the predicate. Witness positions identify the callee chain and terminal fact independently, preserving real imported/template locations. This is a candidate typed field extension; no code/field registry is allocated here.
The [diagnostic vectors](contract-diagnostic-vectors.json) retain the five executed return baselines and proposed graph cases for recursion, shortest-path/tie selection and a 40-edge witness with eight omitted calls. Graph/vector checks validate the candidate algorithm and metadata, not a new compiler diagnostic. Required vertical tests additionally cover several clauses sharing a seed, unreachable calls, duplicate source mappings, invalid types preceding purity, constant-true predicates with forbidden unused operations, and leak/access collection at several returns.
Emit the proposed additive `contracts` section only for modules declaring the relevant feature; contract-free canonical report bytes stay unchanged. Each row identifies function/block/instruction, helper, kind, scope (`boundary` or persistent `value`), status, proof and enforcement, plus covered return sites and positions. A pre row belongs to the callee declaration, not a selected caller. A type guarantee and a relation over listed functions require distinct scopes. Include per-status site totals; totals are not sums over executions or returned branches. Snapshot metadata is not itself a truth obligation. Rejected modules still produce diagnostics and no audit document.
Required tests include max/sum activation cases, invalid descriptors before SSA, argument/work limits, all four modes, mixed executable/documented snapshot use, unsafe/trap/fuel behavior, multi-return and trap-only coverage, proof-budget fallback, old/current mutation counterexamples, callback/GC pending values, exact rejection ordering and identical contract-free report bytes. Predicate/trap rows must survive generic/package/source mapping. The linked research supplies a concrete function/value report grammar and classifier; module-claim representation, owner adoption, RFC 0040 observations, diagnostic collection and full vertical implementation remain gates. This file changes no normative bundle.
+81
View File
@@ -0,0 +1,81 @@
# Contract AIR bindings candidate
Non-normative completion of the binding grammar in [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), following [source elaboration](contract-source-and-module-state.md) and [accounting/diagnostics](contract-accounting-and-status.md). This document allocates no feature, instruction or diagnostic and authorizes no implementation. Compatibility, trap/dispatch schemas, owner adoption and full vertical delivery remain gates.
## Text and identity
Reuse AIR format 0's tokens, comments, significant instruction newlines, global/local namespaces and list conventions (air-text.ebnf). Proposed additions are:
```ebnf
contract_pre = ( "contract.pre" | "contract.pre.assume" | "contract.pre.document" )
global bindings ;
contract_old = local "=" "contract.old" global bindings ;
contract_post = ( "contract.post" | "contract.post.assume" | "contract.post.document" )
global bindings ;
bindings = "(" [ binding { "," binding } ] ")" ;
binding = [ "ref" ] ( local | "result" ) ;
checked_type = "checked" "<" type "," global ">" ;
checked_op = "checked.make" checked_type "," local
| ( "checked.view" | "checked.take" ) local
| "checked.modify" local "," global "(" [ local_list ] ")" ;
```
The generic instruction production still governs checked operation result bindings: make/view/take bind exactly one result; modify follows ordinary call rules (one for a value return, none for void, optional for never). A never callback cannot publish an update or produce an observable result; an optional never-typed SSA binding does not change this. Old binds exactly one snapshot, while pre/post bind none. There is no old.assume/document or optional old result. Lists have no trailing comma, matching ordinary AIR call lists. Empty bindings are valid for parameter-free helpers. There are no type annotations, constants, projections, nested calls, mut/move modifiers or inline expressions in a binding. Compute those inside the helper. Source spelling remains type.checked and explicit static function application; this grammar does not reserve a source module named checked.
Checked operands and modify extras remain ordinary body SSA operands, not restricted clause roots. Make's explicit checked type determines R/p without operand inference; its operand has exactly R. View accepts ref/mut<checked<R,p>> and produces a shared dependent ref<R>; take accepts the whole checked value and produces R. Modify's first operand is mut<checked<R,p>>, and its callback signature starts with mut<R>, followed by exactly the extra argument types. The implicit first argument counts toward the 64-argument bound, leaving at most 63 extras. Callback return/effects/loan rules remain those of the invariant candidate; no runtime function value or optional inline callback is added.
The word result is a contextual placeholder only in these binding lists. `%result` is always an ordinary SSA identity and may name a header parameter; `@result` is an ordinary global. Names such as `%ref` remain locals. Parsing does not infer a placeholder from an SSA spelling or reverse a generated name. Contract operations occupy the uninterrupted entry prefix pre*, at most one old, then post*; entry has no predecessors. Interleaved modes retain textual order within each class. Ordinary instructions, including constants, start the body and end the prefix. These are CFG rules, not a new function header or lexer keyword policy.
A resolved binding is `(root,form,span)`, where root is a header parameter ordinal, this function's single snapshot identity, or result, and form is value or shared. Span identifies the binding token (`ref` when present) separately from the installing operation. The parser retains ordinary ValueIds for local name resolution; verifier preparation converts legal roots to the typed descriptor without inventing a body SSA type. Bindings are descriptors, not immediate ordinary SSA reads: the SSA stage classifies their root/context before applying ordinary instruction-use dominance checks. Thus a pre naming the later snapshot reports snapshot_not_post, rather than pretending it reads that snapshot early. Ordinary body uses retain their existing SSA rules. All binding fields needed for pre-SSA budgets come from the header or old-helper signature. A malformed/unknown root is not dereferenced for size calculations.
Local resolution is ordinary function-wide AIR resolution, including forward definitions. A known body/block-parameter identity is not silently reinterpreted as a header parameter. Function lookup accepts forward global declarations; helpers need not appear before their uses. Repeated bindings are legal and preserve their order and count. Handwritten AIR is not deduplicated; repeated Copy ref bindings materialize separate places, while repeated in-place shared roots create ordinary overlapping shared children. Source capture deduplication remains a frontend rule, with each selected binding counted once. Canonical serialization preserves the binding list and inserts `ref ` only for shared form; it cannot erase a duplicate or replace result with a ret-specific SSA name.
## Observation type and lifetime
A binding's produced type must exactly equal the corresponding helper parameter. Arity must match and retain the ordinary 64-argument bound. There is no numeric conversion, array-to-slice coercion, dereference or owner/checked representation fallback based on the expected helper type. Post result type is the enclosing declared return type, independent of which valid SSA operand a particular ret uses. The checked predicate signature is exactly ref<R> -> bool; clause/old root adaptation is a different operation from make/modify's whole-R observation.
| Root type T | Value form | Shared form |
|---|---|---|
| Data T, including snapshot Data | T, ordinary Copy observation | ref<T>, through a complete temporary Copy place |
| complete Copy non-Data T, e.g. cap<K> | rejected | ref<T>, temporary Copy place; predicate rules still forbid extracting non-Data content |
| ref<U> or mut<U> | rejected | ref<U>, shared child/reborrow |
| slice<U> or slice_mut<U> | rejected | slice<U>, shared child/reborrow |
| own<U> | rejected | ref<U>, ordinary owner-content view |
| own_array<U> | rejected | slice<U>, ordinary owner-array view |
| addressable linear aggregate/resource/graph/buffer root | rejected | ordinary borrow.ref result type, dependent view without ownership transfer |
| checked<R,p> | value only when R is Data | ref<checked<R,p>>; Copy uses a temporary place, linear uses a direct dependent SSA-root view; never implicitly ref<R> |
Apply the ordinary type validity and root-position rules before accepting a row. Storage/function-bound/void/never values do not become complete Copy places merely because a shallow Copy query returns true. Shared observation of a borrowed checked value uses the borrow row, preserving checked content. Predicate P entry signatures contain no mutable parameters; S additionally applies to persistent checked predicates. The table does not admit new operations to P/S or widen ordinary body addressability. On Data checked values, shared materialization preserves the existing claim without reevaluating the predicate.
Linear checked roots require an explicit checked case in ordinary borrow.ref typing and runtime root access, analogous to linear named/array roots; a frame local cannot substitute because it requires Copy content. Before CFG/SSA, the accounting candidate charges every Copy ref occurrence to E(clause/old), including duplicates and shared snapshots/results, using header/helper descriptors and its total size/Copy queries. The activation bound is L + S + max E; each materialized complete value also retains the ordinary maximum-value bound. For example, 64 ref bindings of array<u8,16385> with L=S=0 require 1,048,640 bytes and reject E5101, whereas 64 bindings of array<u8,16384> exactly fit. Sequential clauses use max, not sum; views within one evaluation coexist. Documented bindings create no runtime places and contribute no E, while their argument/W limits and virtual access checks remain.
Pre/old bindings may name only original header parameters. Post bindings may additionally name the earlier snapshot and result. A bare borrow or linear root cannot bind by value; shared roots require explicit ref. Result in pre/old is rejected even if no evaluation would occur. A void function has no result binding; a never function cannot install any post, including document. No contract fact revives a consumed root or bypasses a frozen parent.
Pre evaluates in entry state; old evaluates after all executable pre helpers and before the body. Post installation creates no view/place/read. Every normal ret re-resolves its bindings against the final pre-transfer state, including result's actual operand and the current loan ancestry. All arguments of one helper are prepared in list order and coexist for that evaluation. Their temporary views/places and descendants end before the next predicate or normal result transfer. Helpers may not return their views through bool/Data. Post observation through an exclusive result may be valid while a simultaneous observation through its frozen input parent rejects; selecting a different form does not bypass ordinary access checks. Preserve the isolated return/post collection rule in the accounting candidate.
The snapshot is a named contract-only Data value, not a general body definition. Its only legal uses are post bindings, including shared form. It cannot be passed into old/pre, copied/projected in the body, used in an ordinary helper call/branch or returned. At least one executable post (runtime or assume) must use it. A documented post may reuse that snapshot but cannot be its only consumer. Projections occur inside post helpers after receiving the Data record; direct prefix field projection is not a binding. No snapshot is created for a function with no executable old expressions.
## Stages and factual errors
Ordinary parsing/name resolution retains E0001 for malformed syntax, E0004 for unknown globals/opcodes and E5001 for undefined/duplicate SSA values. Known new operations require their registered feature before verification (E0006 if missing); assumed variants require their separate extension. No registry spelling/status is allocated here. Unknown-opcode research probes do not establish full format-0 compatibility, particularly when an unknown snapshot also has a dependent body use (Q-055).
Limits use total queries/descriptors and retain E5101; CFG checks prefix order and entry predecessors with E5002. SSA then checks root identity/context and snapshot escape/use. Proposed E8001 has stable reason values:
| Reason | Fact |
|---|---|
| invalid_root | a resolved binding names a body definition or block parameter rather than an allowed root |
| result_not_post | result is used by pre/old |
| snapshot_not_post | a snapshot binding is used by pre/old |
| snapshot_escape | an ordinary body instruction uses the snapshot |
| snapshot_unused | no post binding uses the snapshot |
| snapshot_document_only | post uses exist, all in document mode |
Invalid root/context facts belong to each binding use; escape belongs to the body use. Unused/document-only belongs to the old declaration, and is classified only after that snapshot's root/context/escape checks pass, preventing a secondary unused diagnosis for the same misuse. Any correctly resolved snapshot binding in a post counts as a use, even if another binding in that post is invalid. An old operation referencing its own snapshot is snapshot_not_post and suppresses its dependent unused check. Ordinary SSA duplicate/undefined checks remain earlier evidence; descriptor operands do not undergo ordinary dominance checks and cannot add a competing E5001 for an invalid root/context. Prefix structural failure stops before SSA, and malformed root metadata cannot cause an earlier budget crash. This table defines proposal reasons, not allocated public codes.
Candidate E8001 code-specific fields are `function,block,inst,reason,binding,root`, in that order; none is a new common-envelope field. Function/block are the enclosing AIR names without sigils and inst is the zero-based primary instruction index. Binding is the zero-based argument index for a binding misuse, null for a body escape or old-declaration failure; root is `%name` for the actual resolved local or `result` for the placeholder. A body escape identifies the actual body instruction; unused/document-only identifies old; invalid bindings identify their prefix instruction. No synthetic ValueId or invented name is serialized. Types/access errors retain their existing payload rather than adding this schema.
Types checks Data/value admissibility, shared adaptation, exact arity/signatures, Data old result and bool pre/post result with E1001. It also rejects result on void and every post on never. Complete ordinary type validation precedes P/S and their proposed E8002/E8003 witnesses. Effects and unsafe follow existing stage order. At the evaluation boundary, use existing initialization, availability, borrow-conflict and lifetime diagnostics; a post's invalid result transfer preserves the ordinary return diagnostic list and suppresses dependent post checks. An alias-conflict message is not relabeled as invalid_binding. Runtime false/helper traps and their exact invocation metadata remain a separate gate.
The [binding vectors](contract-binding-vectors.json) retain 18 current-language probes at `5ed0d86`: eleven ordinary-view/call cases verify owner/owner-array adaptation, mut/slice_mut reborrows, simultaneous shared children, frozen-parent rejection, exclusive-result observation, scalar/authority Copy non-addressability, and both never-call binding forms. Seven complete prefix spellings reject E0004 alone without falsely declaring a future feature. These constrain the design; they do not test implemented contract bindings or settle Q-055.
Future vertical fixtures must cover every grammar form/mode, empty/64/65 lists, duplicate binding storage, scalar Copy places versus owner unwrapping, result/%result, snapshot shared uses/escapes, unrelated prefix/SSA/type errors and return legality. Current-language probes and candidate vectors are evidence for these requirements, not implemented-contract conformance.
+344
View File
@@ -0,0 +1,344 @@
{
"purpose": "Non-normative current-language probes; no contract binding semantics implemented.",
"compiler": "5ed0d86",
"cases": [
{
"case": "owner_unwrap",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: own<u64>) -> u64",
"effects []",
"entry:",
" %r = borrow.ref %v",
" %x = load %r",
" borrow.end %r",
" %taken = own.take %v",
" ret %taken"
]
},
{
"case": "owner_array_unwrap",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: own_array<u64>) -> own_array<u64>",
"effects []",
"entry:",
" %r = borrow.ref %v",
" %n = slice.len %r",
" borrow.end %r",
" ret %v"
]
},
{
"case": "mutable_scalar_reborrow",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: mut<u64>) -> u64",
"effects []",
"entry:",
" %r = borrow.ref %v",
" %x = load %r",
" borrow.end %r",
" ret %x"
]
},
{
"case": "mutable_slice_reborrow",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: slice_mut<u64>) -> usize",
"effects []",
"entry:",
" %r = borrow.ref %v",
" %n = slice.len %r",
" borrow.end %r",
" ret %n"
]
},
{
"case": "repeated_shared_owner_children",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: own<u64>) -> own<u64>",
"effects []",
"entry:",
" %a = borrow.ref %v",
" %b = borrow.ref %v",
" %ok = call @same(%a, %b)",
" borrow.end %b",
" borrow.end %a",
" ret %v",
"fn @same(%a: ref<u64>, %b: ref<u64>) -> bool",
"effects []",
"entry:",
" %yes = const.bool true",
" ret %yes"
]
},
{
"case": "frozen_parent_observation",
"codes": ["E2101"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: mut<u64>) -> void",
"effects []",
"entry:",
" %exclusive = borrow.mut %v",
" %wrong = borrow.ref %v",
" borrow.end %wrong",
" borrow.end %exclusive",
" ret"
]
},
{
"case": "exclusive_result_shared_observation",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: mut<u64>) -> mut<u64> from %v",
"effects []",
"entry:",
" %exclusive = borrow.mut %v",
" %view = borrow.ref %exclusive",
" %x = load %view",
" borrow.end %view",
" ret %exclusive"
]
},
{
"case": "copy_scalar_not_addressable",
"codes": ["E1001"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: u64) -> u64",
"effects []",
"entry:",
" %r = borrow.ref %v",
" ret %v"
]
},
{
"case": "copy_authority_not_addressable",
"codes": ["E1001"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%v: cap<mem.alloc>) -> u64",
"effects []",
"entry:",
" %r = borrow.ref %v",
" %x = const.u64 0",
" ret %x"
]
},
{
"case": "never_call_with_binding",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f() -> never",
"effects []",
"entry:",
" %n = call @die()",
" trap",
"fn @die() -> never",
"effects []",
"entry:",
" trap"
]
},
{
"case": "never_call_without_binding",
"codes": [],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f() -> never",
"effects []",
"entry:",
" call @die()",
" trap",
"fn @die() -> never",
"effects []",
"entry:",
" trap"
]
},
{
"case": "unknown_contract.pre",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" contract.pre @yes()",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
},
{
"case": "unknown_contract.pre.assume",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" contract.pre.assume @yes()",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
},
{
"case": "unknown_contract.pre.document",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" contract.pre.document @yes()",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
},
{
"case": "unknown_contract.old",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" %old = contract.old @yes()",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
},
{
"case": "unknown_contract.post",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" contract.post @yes(ref result)",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
},
{
"case": "unknown_contract.post.assume",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" contract.post.assume @yes(result)",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
},
{
"case": "unknown_contract.post.document",
"codes": ["E0004"],
"source": [
"module contract.bindings",
"air 0",
"lang 0.1",
"features [arrays, capabilities, effects, heap, linear_aggregates, ownership, resources]",
"fn @f(%result: u64) -> u64",
"effects []",
"entry:",
" contract.post.document @yes(%result)",
" ret %result",
"fn @yes() -> bool",
"effects []",
"entry:",
" %t = const.bool true",
" ret %t"
]
}
]
}
@@ -0,0 +1,409 @@
{
"purpose": "Executed current-language rejection baselines, not implemented-contract conformance or proof of format-0 compatibility. File labels removed; all other emitted diagnostic fields retained.",
"compiler": "c633f23",
"command": "aji check FILE.air",
"cases": [
{
"case": "pre_unknown",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" contract.pre @p(%x)",
" ret %x",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 8,
"col": 2,
"name": "contract.pre",
"message": "unknown opcode"
}
]
},
{
"case": "old_post_unknown",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" %old = contract.old @snapshot(%x)",
" contract.post @post(%old, result)",
" ret %x",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b",
"fn @snapshot(%v: u64) -> u64",
"effects []",
"entry:",
" ret %v",
"fn @post(%before: u64, %after: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 8,
"col": 9,
"name": "contract.old",
"message": "unknown opcode"
},
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 9,
"col": 2,
"name": "contract.post",
"message": "unknown opcode"
}
]
},
{
"case": "old_body_escape",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" %old = contract.old @snapshot(%x)",
" %v = add.checked.u64 %old, %x",
" ret %v",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b",
"fn @snapshot(%v: u64) -> u64",
"effects []",
"entry:",
" ret %v"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 8,
"col": 9,
"name": "contract.old",
"message": "unknown opcode"
},
{
"code": "E5001",
"kind": "air.invalid_ssa",
"severity": "error",
"line": 9,
"col": 23,
"function": "f",
"value": "%old",
"message": "value used but never defined"
}
]
},
{
"case": "pre_unrelated_undefined",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" contract.pre @p(%x)",
" %v = add.checked.u64 %missing, %x",
" ret %v",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 8,
"col": 2,
"name": "contract.pre",
"message": "unknown opcode"
},
{
"code": "E5001",
"kind": "air.invalid_ssa",
"severity": "error",
"line": 9,
"col": 23,
"function": "f",
"value": "%missing",
"message": "value used but never defined"
}
]
},
{
"case": "old_body_and_unrelated_undefined",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" %old = contract.old @snapshot(%x)",
" %v = add.checked.u64 %old, %missing",
" ret %v",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b",
"fn @snapshot(%v: u64) -> u64",
"effects []",
"entry:",
" ret %v"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 8,
"col": 9,
"name": "contract.old",
"message": "unknown opcode"
},
{
"code": "E5001",
"kind": "air.invalid_ssa",
"severity": "error",
"line": 9,
"col": 23,
"function": "f",
"value": "%old",
"message": "value used but never defined"
},
{
"code": "E5001",
"kind": "air.invalid_ssa",
"severity": "error",
"line": 9,
"col": 29,
"function": "f",
"value": "%missing",
"message": "value used but never defined"
}
]
},
{
"case": "checked_make_used",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects, ownership]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" %s = checked.make checked<u64,@p>, %x",
" %r = checked.take %s",
" ret %r",
"fn @p(%v: ref<u64>) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 8,
"col": 7,
"name": "checked.make",
"message": "unknown opcode"
},
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 9,
"col": 7,
"name": "checked.take",
"message": "unknown opcode"
},
{
"code": "E5001",
"kind": "air.invalid_ssa",
"severity": "error",
"line": 10,
"col": 6,
"function": "f",
"value": "%r",
"message": "value used but never defined"
}
]
},
{
"case": "checked_type_signature",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects, ownership]",
"fn @f(%x: checked<u64,@p>) -> checked<u64,@p>",
"effects []",
"entry:",
" ret %x",
"fn @p(%v: ref<u64>) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0004",
"kind": "parse.unknown_name",
"severity": "error",
"line": 5,
"col": 11,
"name": "checked",
"message": "unknown type"
}
]
},
{
"case": "contract_header",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"requires @p(%x)",
"entry:",
" ret %x",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0001",
"kind": "parse.unexpected_token",
"severity": "error",
"line": 7,
"col": 10,
"expected": "`:`",
"found": "p",
"message": "expected `:`"
}
]
},
{
"case": "ordinary_undefined",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" %v = add.checked.u64 %missing, %x",
" ret %v",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E5001",
"kind": "air.invalid_ssa",
"severity": "error",
"line": 8,
"col": 23,
"function": "f",
"value": "%missing",
"message": "value used but never defined"
}
]
},
{
"case": "unknown_feature",
"source": [
"module contract.compatibility",
"air 0",
"lang 0.1",
"features [contracts, effects]",
"fn @f(%x: u64) -> u64",
"effects []",
"entry:",
" contract.pre @p(%x)",
" ret %x",
"fn @p(%v: u64) -> bool",
"effects []",
"entry:",
" %b = const.bool true",
" ret %b"
],
"exit": 1,
"diagnostics": [
{
"code": "E0006",
"kind": "module.unsupported_feature",
"severity": "error",
"line": 4,
"col": 1,
"reason": "unknown_feature",
"feature": "contracts",
"message": "feature cannot be used"
}
]
}
]
}
@@ -0,0 +1,273 @@
{
"purpose": "Non-normative diagnostics research: return baselines are current CLI results; graph/witness cases describe an unimplemented contract closure.",
"compiler": "8df6cac",
"return_baselines": [
{
"case": "wrong_origin_with_leak",
"codes": ["E2102"],
"source": [
"module contract.return_baseline",
"air 0",
"lang 0.1",
"features [capabilities, effects, heap, ownership, resources]",
"fn @f(%a: ref<u64>, %b: ref<u64>, %owner: own<u64>) -> ref<u64> from %a",
"effects []",
"entry:",
" %view = borrow.ref %b",
" ret %view"
]
},
{
"case": "valid_origin_with_leak",
"codes": ["E3002"],
"source": [
"module contract.return_baseline",
"air 0",
"lang 0.1",
"features [capabilities, effects, heap, ownership, resources]",
"fn @f(%a: ref<u64>, %owner: own<u64>) -> ref<u64> from %a",
"effects []",
"entry:",
" %view = borrow.ref %a",
" ret %view"
]
},
{
"case": "scalar_return_with_leak",
"codes": ["E3002"],
"source": [
"module contract.return_baseline",
"air 0",
"lang 0.1",
"features [capabilities, effects, heap, ownership, resources]",
"fn @f(%owner: own<u64>) -> u64",
"effects []",
"entry:",
" %zero = const.u64 0",
" ret %zero"
]
},
{
"case": "consumed_return",
"codes": ["E2002"],
"source": [
"module contract.return_baseline",
"air 0",
"lang 0.1",
"features [capabilities, effects, heap, ownership, resources]",
"fn @f(%owner: own<u64>) -> own<u64>",
"effects []",
"entry:",
" %plain = own.take %owner",
" ret %owner"
]
},
{
"case": "owner_return_with_live_view",
"codes": ["E2101", "E2105"],
"source": [
"module contract.return_baseline",
"air 0",
"lang 0.1",
"features [capabilities, effects, heap, ownership, resources]",
"fn @f(%owner: own<u64>) -> own<u64>",
"effects []",
"entry:",
" %view = borrow.ref %owner",
" ret %owner"
]
}
],
"graph_cases": [
{
"case": "recursive_admitted",
"entry": "a",
"calls": {
"a": ["b"],
"b": ["a"]
},
"seeds": {},
"expected": {"admitted": true}
},
{
"case": "recursive_reaches_seed",
"entry": "root",
"calls": {
"root": ["a"],
"a": ["b"],
"b": ["a", "bad"],
"bad": []
},
"seeds": {"bad": "operation"},
"expected": {
"admitted": false,
"witness": {
"call_count": 3,
"prefix": [
{"function": "root", "block": "entry", "inst": 0, "callee": "a", "source": null},
{"function": "a", "block": "entry", "inst": 0, "callee": "b", "source": null},
{"function": "b", "block": "entry", "inst": 1, "callee": "bad", "source": null}
],
"suffix": [],
"omitted_calls": 0,
"terminal": {"function": "bad", "block": "entry", "inst": 0, "reason": "operation", "type": null, "operation": "task.cancelled", "source": null}
}
}
},
{
"case": "shortest_before_textual",
"entry": "root",
"calls": {
"root": ["long", "bad"],
"long": ["bad"],
"bad": []
},
"seeds": {"bad": "operation"},
"expected": {
"admitted": false,
"witness": {
"call_count": 1,
"prefix": [
{"function": "root", "block": "entry", "inst": 1, "callee": "bad", "source": null}
],
"suffix": [],
"omitted_calls": 0,
"terminal": {"function": "bad", "block": "entry", "inst": 0, "reason": "operation", "type": null, "operation": "task.cancelled", "source": null}
}
}
},
{
"case": "textual_tie",
"entry": "root",
"calls": {
"root": ["z", "a"],
"z": [],
"a": []
},
"seeds": {"z": "operation", "a": "type"},
"expected": {
"admitted": false,
"witness": {
"call_count": 1,
"prefix": [
{"function": "root", "block": "entry", "inst": 0, "callee": "z", "source": null}
],
"suffix": [],
"omitted_calls": 0,
"terminal": {"function": "z", "block": "entry", "inst": 0, "reason": "operation", "type": null, "operation": "task.cancelled", "source": null}
}
}
},
{
"case": "local_seed_before_calls",
"entry": "root",
"calls": {
"root": ["bad"],
"bad": []
},
"seeds": {"root": "effects", "bad": "operation"},
"expected": {
"admitted": false,
"witness": {
"call_count": 0,
"prefix": [],
"suffix": [],
"omitted_calls": 0,
"terminal": {"function": "root", "block": null, "inst": null, "reason": "effects", "type": null, "operation": null, "source": null}
}
}
},
{
"case": "long_path",
"entry": "f0",
"calls": {
"f0": ["f1"],
"f1": ["f2"],
"f2": ["f3"],
"f3": ["f4"],
"f4": ["f5"],
"f5": ["f6"],
"f6": ["f7"],
"f7": ["f8"],
"f8": ["f9"],
"f9": ["f10"],
"f10": ["f11"],
"f11": ["f12"],
"f12": ["f13"],
"f13": ["f14"],
"f14": ["f15"],
"f15": ["f16"],
"f16": ["f17"],
"f17": ["f18"],
"f18": ["f19"],
"f19": ["f20"],
"f20": ["f21"],
"f21": ["f22"],
"f22": ["f23"],
"f23": ["f24"],
"f24": ["f25"],
"f25": ["f26"],
"f26": ["f27"],
"f27": ["f28"],
"f28": ["f29"],
"f29": ["f30"],
"f30": ["f31"],
"f31": ["f32"],
"f32": ["f33"],
"f33": ["f34"],
"f34": ["f35"],
"f35": ["f36"],
"f36": ["f37"],
"f37": ["f38"],
"f38": ["f39"],
"f39": ["f40"],
"f40": []
},
"seeds": {"f40": "operation"},
"expected": {
"admitted": false,
"witness": {
"call_count": 40,
"prefix": [
{"function": "f0", "block": "entry", "inst": 0, "callee": "f1", "source": null},
{"function": "f1", "block": "entry", "inst": 0, "callee": "f2", "source": null},
{"function": "f2", "block": "entry", "inst": 0, "callee": "f3", "source": null},
{"function": "f3", "block": "entry", "inst": 0, "callee": "f4", "source": null},
{"function": "f4", "block": "entry", "inst": 0, "callee": "f5", "source": null},
{"function": "f5", "block": "entry", "inst": 0, "callee": "f6", "source": null},
{"function": "f6", "block": "entry", "inst": 0, "callee": "f7", "source": null},
{"function": "f7", "block": "entry", "inst": 0, "callee": "f8", "source": null},
{"function": "f8", "block": "entry", "inst": 0, "callee": "f9", "source": null},
{"function": "f9", "block": "entry", "inst": 0, "callee": "f10", "source": null},
{"function": "f10", "block": "entry", "inst": 0, "callee": "f11", "source": null},
{"function": "f11", "block": "entry", "inst": 0, "callee": "f12", "source": null},
{"function": "f12", "block": "entry", "inst": 0, "callee": "f13", "source": null},
{"function": "f13", "block": "entry", "inst": 0, "callee": "f14", "source": null},
{"function": "f14", "block": "entry", "inst": 0, "callee": "f15", "source": null},
{"function": "f15", "block": "entry", "inst": 0, "callee": "f16", "source": null}
],
"suffix": [
{"function": "f24", "block": "entry", "inst": 0, "callee": "f25", "source": null},
{"function": "f25", "block": "entry", "inst": 0, "callee": "f26", "source": null},
{"function": "f26", "block": "entry", "inst": 0, "callee": "f27", "source": null},
{"function": "f27", "block": "entry", "inst": 0, "callee": "f28", "source": null},
{"function": "f28", "block": "entry", "inst": 0, "callee": "f29", "source": null},
{"function": "f29", "block": "entry", "inst": 0, "callee": "f30", "source": null},
{"function": "f30", "block": "entry", "inst": 0, "callee": "f31", "source": null},
{"function": "f31", "block": "entry", "inst": 0, "callee": "f32", "source": null},
{"function": "f32", "block": "entry", "inst": 0, "callee": "f33", "source": null},
{"function": "f33", "block": "entry", "inst": 0, "callee": "f34", "source": null},
{"function": "f34", "block": "entry", "inst": 0, "callee": "f35", "source": null},
{"function": "f35", "block": "entry", "inst": 0, "callee": "f36", "source": null},
{"function": "f36", "block": "entry", "inst": 0, "callee": "f37", "source": null},
{"function": "f37", "block": "entry", "inst": 0, "callee": "f38", "source": null},
{"function": "f38", "block": "entry", "inst": 0, "callee": "f39", "source": null},
{"function": "f39", "block": "entry", "inst": 0, "callee": "f40", "source": null}
],
"omitted_calls": 8,
"terminal": {"function": "f40", "block": "entry", "inst": 0, "reason": "operation", "type": null, "operation": "task.cancelled", "source": null}
}
}
}
]
}
@@ -0,0 +1,73 @@
# Contract invariant boundaries: candidate and counterexamples
Non-normative research for [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), 2026-10-09. No feature, type, opcode, code or source spelling below is adopted. The full P6-6 gate remains open, including module scope, statuses and proof rules.
## Verified constraints
Probes with the existing compiler at `d041c07` contain no invariant declarations. They expose coverage requirements, not compiler defects. Runs use fuel 10,000.
| Probe | Result | Consequence |
|---|---|---|
| `Range {lo:0, hi:5}`; call `change(mut r.lo)` where `change(part: mut<u64>)` stores 10 | returns 1 for `lo > hi` | the callee's canonical AIR contains only `store %part, %value`; its signature/provenance does not identify the enclosing Range |
| ordinary `ValidRange {rep: Rep}` built by a checking library function; subsequently set `v.rep.lo = 10` | returns 1 for `lo > hi` | public fields bypass a constructor convention; spec 15 §14.2 permits imported construction and field access |
| two Counter roots; check `a.n <= b.n`, then change only a | returns 1 for failed relation | individual type claims or checks on a selected function set cannot imply a persistent relation between independent roots |
| AIR `type @Range = invariant @Rep @ordered` | E0001 | this declaration extension is outside spec 07 §8.7's E0004/E0006 exception |
| AIR parameter `checked<@Rep>` | E0004 alone, unknown type | a new type constructor has a different compatibility path |
The earlier RFC probes also demonstrate invalid Copy publication and shared-reader overflow during a repaired exclusive update. End-of-borrow checks alone miss both. A complete eager alternative must find every affected invariant ancestor after projected writes, including scalar callees, graph nodes and buffer storage in other cells. Current interpreter places carry a cell/path, not enclosing invariant instances. It would require additional provenance and predicate access rules, including how to read a whole root while an exclusive child freezes it.
## Leading type candidate: checked representation plus explicit update
Investigate `checked<R, @predicate>` in AIR, source `type.checked<R, fn predicate>` under the [module/source refinement](contract-source-and-module-state.md). The reserved type prefix avoids hijacking user modules/types named checked. Identity is structural over representation and resolved function identity. The predicate takes exactly `ref<R>`, returns bool, and has no captures or implicit roots. Source uses existing explicit function resolution/specialization rules; the refinement proposes a narrow checked-type binding, not a general alias facility. A generic representation is checked after concrete substitution.
The claim is: every exposed checked value/shared content view satisfies its predicate. An explicit update temporarily exposes ordinary R under exclusive access; R carries no such claim. Whole checked values retain R's Copy/linear, size and structural concurrency classifications, subject to a complete property audit. Copies and transfers need no additional check. The representation is initialized as a complete value, and checked types have no zero constructor even when R is zeroable.
| Candidate operation | Type/transfer | Validation boundary |
|---|---|---|
| `checked.make checked<R, @p>, %r` | R → checked<R,@p>; move linear R, copy Copy R | observe the complete candidate through a temporary shared view; run p before exposing the result; false traps |
| `checked.view %c` | ref/mut<checked<R,@p>> → ref<R>, dependent owned shared child | no new check; ordinary lifetime/loan rules preserve the established claim |
| `checked.take %c` | checked<R,@p> → R; consume linear capsule, copy Copy content | output is ordinary R with no invariant claim; live views block consuming the root |
| `checked.modify %m, @f(args)` | mut<checked<R,@p>>; direct callback f receives a temporary lent mut<R> first, then ordinary typed arguments | suspend capsule access, call f, end its temporary mutation view, run p on the resulting R, then expose f's result |
`make` needs an explicit new instruction-internal place for a complete Copy R candidate. Linear R is observed in its existing SSA cell, with no copy, move during validation or new frame local; only success transfers it into the capsule. Its predicate receives a dependent `ref<R>` preserving R itself rather than unwrapping an owner root. The view and every child end before exposure of the result and cannot escape through bool. This adds no general AIR/source addressability for Copy SSA or partially initialized/linear frame locals. The [accounting candidate](contract-accounting-and-status.md) charges size(R) only for the Copy place and retains pending results as SSA; use bounded activation storage, no program heap allocation. Existing `borrow.ref` on a Copy scalar or Copy struct SSA root rejects E1001; both baseline cases were independently verified. Their attempted `borrow.end` adds a dependent second E1001 because the invalid result has placeholder type void.
These are proposed operation contracts, not syntax sugar for optional assertions. Ordinary operations cannot project mutable R from a checked value. Interior changes through shared atomic/mutex/endpoint/arc interfaces do not affect the claim because their mutable observations are outside S below. Whole-value store/exchange replaces it with another checked value. Existing `local.alloc`, owners, regions, arrays, buffers, graph storage, channels and mutexes must transport the complete new type under their existing content restrictions; no field write can manufacture it from R. Nested checked values remain checked when an enclosing representation is extracted. A Copy `take` leaves the capsule and its claim intact, while its plain R copy carries no claim.
**Explicit update is necessary.** A linear representation with `buffer<T>` held behind a borrow cannot be consumed and rebuilt directly. Replacing its capsule would otherwise need another complete buffer and allocation authority even for an in-capacity update. `checked.modify` must permit this update without allocating a replacement. Limiting the candidate to Copy reconstruction would omit required linear-state behavior.
The callback can perform ordinary multi-field updates and use disjoint fields in structured tasks. Its complete effects and authority requirements propagate to the caller; ordinary critical-section/no-wait checks apply. It may return an ordinary borrow-free result, including an owned value removed through a complete initialized exchange. Void and never keep ordinary call/control rules: void binds no result, and a never callback cannot complete normally or publish an update. A borrow result or loan surviving the callback would escape unvalidated storage and must reject. It cannot re-enter the frozen capsule through another argument; ordinary overlapping-argument checks apply. No general borrow joins, holes or implicit cleanup are introduced.
Successful callback completion is not yet successful update completion. Predicate false, callback/predicate traps or fuel exhaustion publish no checked result. Failure traps with no rollback of state or external effects. Pending borrow-free results, including linear ones, must be retained and traced until validation finishes. Candidate fuel accounting is one unit for the make/modify operation, then ordinary helper instructions, with no synthetic callback-to-predicate instruction. Callback and predicate use normal call frames, sequentially; the callback frame ends before the predicate starts. Exact dispatch, temporary-view and trap rules still require RFC integration and tests. Checking after a callback must use a legal shared view after its exclusive loan has ended, not privileged access through a frozen ancestor.
The [runtime/context candidate](contract-runtime-and-context.md) now supplies concrete continuation, last-fuel, publication, depth/quantum, GC-root and failure-location rules for this sequence. Its executed evidence is ordinary calls/returns/traps, not checked updates. New callback/predicate transitions, pending linear results and context mapping still require normative adoption and vertical implementation/tests.
Candidate source surface is an explicit API under type.checked: a shared `ref raw = type.checked.view(parent)` binding, `type.checked.make::<R, fn p>`/`type.checked.take`, and `type.checked.modify::<fn update>(parent, args...)` on a named exclusive binding. Callback specialization uses existing static function identity, not a runtime function value. The module/source refinement gives grammar and clause-root rules; diagnostics and any later scoped block form still need integration. A block form must specify captures and effects before adoption.
## Stability is stronger than purity
The predicate closure P in RFC 0039 excludes atomic, mutex, channel, authority and ambient observations. Caller-visible observations currently either require exclusive access to change or are deeply immutable; opaque iref identity retains no external graph root. This is a soundness premise for persistent checked claims. A read-only predicate over interior-mutable data could become false after construction without any capsule update.
Define a candidate stable-observation closure S within P. All its caller-state observations must remain stable while the checked shared content is exposed. It uses the same direct-call closure and fresh-scratch proof; it does not imply totality. Initially the existing allowed observations satisfy this restriction. Future features must separately justify stable membership for their new operations; admitting a new operation to P alone is insufficient. Freeze each published classification rather than silently extending old invariants. Predicate construction/modification of checked values is excluded to avoid implicit validation dispatch; shared `checked.view` and Copy extraction of Data content are candidates for P/S. Data may admit checked<R,p> when R is Data, subject to publication rules. Compute membership with memoized opcode/type scans and direct-call edge elimination, O(F+C) per closure after local scans. Predicate membership is checked after ordinary SSA/type validation, before accepting the new type; exact diagnostic ordering remains a delivery rule.
Interior-mutable members need not be banned when the predicate ignores their mutable interior. A mutex containing ordinary data, an atomic field or a shared arc handle can still be held by R under ordinary rules. Their read/synchronization/count-changing operations stay outside S. Other allocations reached through unique owner/buffer/island roots inside R remain protected by the checked borrow ancestry; immutable frozen/arc content is stable. Audit this reasoning for every new observable primitive, rather than equating `effects []` with stability.
## Module claims require explicit roots and scope
AIR has one linked module, and source modules contain types/functions without globals or visibility. A module-state identity, hidden singleton or private-field policy cannot be inferred from spec 13's example.
Two claims need distinct representations and audit scopes:
- A persistent state-root invariant uses one caller-owned checked<State,p>. A State struct can own several correlated roots. Shared views are valid everywhere, including across modules; updates use the explicit primitive. Independent subroots can be lent to joined tasks during an update, but moving a root out relinquishes the joint state claim unless a complete valid replacement remains.
- A boundary relation over separately owned roots is a predicate mapped to the explicit input/result bindings of listed functions. It holds only at covered entry/normal-exit boundaries, through RFC 0039 pre/post obligations. Unlisted code or public field access can break it between calls. Reports must identify boundary scope and covered functions, never present it as an all-values invariant.
Choosing which source declaration spec 13 means by a module invariant, its root mapping and coverage rules remains part of the full gate. The state-root candidate supports explicit module state without adding globals; the boundary candidate does not provide hidden-state encapsulation. Neither closes that decision by changing the P6-6 requirement.
## Compatibility, cost and remaining delivery
The isolated type probe is not a complete AIR0 audit. Both Claude and the root independently checked full `checked<@Rep,@p>` spellings in seven positions: field, payload, parameter, return, borrowed parameter, block parameter and local allocation. Each aborts with E0004 alone. An opcode-first module with `checked.make`, `checked.take` and a normal use of the latter's result reports E0004, E0004, E5001. Together with the five initial probes and the two Copy-SSA borrow probes, all fifteen baseline cases were verified. These dependent errors retain the RFC 0039/0040 compatibility question (Q-055). No E0001 policy exception or format version is adopted here.
This candidate adds a type form, four semantic operations, stable-closure classification and pending update dispatch. It avoids hidden per-write checks and runtime ancestor hooks. That cost must be compared against complete eager/epoch models, not only their simplest examples. The feature must depend on the published predicate rules; nested linear observations additionally need RFC 0040. Definition-only paths must not weaken verifier budgets or initialization.
Delivery still needs registered features; exact grammar/type/function identity; closure and boundary diagnostics; false-invariant trap/status/report schemas; legal update/result/loan transfer rules; deterministic interpreter/native semantics; source lowering/formatter/generic/package coverage; and AIR/source positive/reject, GC and schedule tests. Mandatory cases include projected-callee bypass, invalid Copy escape, shared readers, borrowed linear in-place updates without new allocation, nested predicates, buffer/graph storage, mutex critical sections, callback results/traps/fuel, early exits and correlated roots. Measure normative/source/Quick Reference growth before acceptance; this research file is outside their manifests.
Claude's read-only review identified the missing linear update in the extraction-only design and distinguished state-root from boundary claims. The proposal remains a candidate; no static proof, unsafe construction mode or completed P6-6 implementation is claimed.
+181
View File
@@ -0,0 +1,181 @@
{
"purpose": "Non-normative naming vectors: current-language baselines are executed; proposed contract descriptors are not implemented compiler output.",
"compiler": "8df6cac",
"baseline_cli_checks": 10,
"current_language": [
{
"case": "generic_collision_and_positions",
"key": "fn:contract.names.id<u64>",
"generated_name": "__aji_g_44149b3201451c67d8b3f9c9666ff1821b489ed944cfef2fe6f2e8153d62726d_2",
"value": 42,
"source": [
"module contract.names",
"fn id<T: Copy>(x: T) -> T effects [] { return x; }",
"fn __aji_g_44149b3201451c67d8b3f9c9666ff1821b489ed944cfef2fe6f2e8153d62726d() -> u64 effects [] { return 0u64; }",
"fn __aji_g_44149b3201451c67d8b3f9c9666ff1821b489ed944cfef2fe6f2e8153d62726d_1() -> u64 effects [] { return 0u64; }",
"fn main() -> u64 effects [] { return id::<u64>(42u64); }"
]
},
{
"case": "static_identity_reuse_and_file_label",
"key": "fn:contract.names.apply<u64,fn contract.names.keep>",
"generated_name": "__aji_g_097a92c7dfcc67ab0d19bd87c3a3a83c38d883f8defb6350b50030f524b11c22",
"calls": 2,
"value": 42,
"source": [
"module contract.names",
"fn keep(x: u64) -> u64 effects [] { return x; }",
"fn apply<T, F: fn(T) -> T effects []>(x: T) -> T effects [] { return F(move x); }",
"fn main() -> u64 effects [] {",
" let one = apply::<u64, fn keep>(20u64);",
" let two = apply::<u64, fn keep>(22u64);",
" return one + two;",
"}"
]
},
{
"case": "module_flatten_collision_order_and_path",
"allocated": [
"__aji_app_a_b_c_2",
"__aji_app_a_b_c_3"
],
"value": 42,
"entry": [
"module app.entry",
"import app.a;",
"import app.a_b;",
"fn __aji_app_a_b_c() -> u64 effects [] { return 0u64; }",
"fn __aji_app_a_b_c_1() -> u64 effects [] { return 0u64; }",
"fn main() -> u64 effects [] { return app.a.b_c() + app.a_b.c(); }"
],
"modules": {
"app.a": [
"module app.a",
"fn b_c() -> u64 effects [] { return 20u64; }"
],
"app.a_b": [
"module app.a_b",
"fn c() -> u64 effects [] { return 22u64; }"
]
}
}
],
"proposed": [
{
"kind": "pre",
"owner": "fn:app.work.bump",
"ordinal": 0,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n0\n0\n0\n",
"digest": "1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338",
"occupied": [],
"allocated": "__aji_contract_1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338"
},
{
"kind": "pre",
"owner": "fn:app.work.bump",
"ordinal": 1,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n1\n0\n0\n",
"digest": "4020cdfe37495ff036b0ac25e49f38b515b84384b41e63832f59aebe4cd2d1eb",
"occupied": [],
"allocated": "__aji_contract_4020cdfe37495ff036b0ac25e49f38b515b84384b41e63832f59aebe4cd2d1eb"
},
{
"kind": "post",
"owner": "fn:app.work.bump",
"ordinal": 0,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\npost\n16:fn:app.work.bump\n0\n0\n0\n",
"digest": "cf71b816e97c5befd170bcae4de1150754d805ad0875a96a6f0c76d26932237a",
"occupied": [],
"allocated": "__aji_contract_cf71b816e97c5befd170bcae4de1150754d805ad0875a96a6f0c76d26932237a"
},
{
"kind": "old",
"owner": "fn:app.work.bump",
"ordinal": 0,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\nold\n16:fn:app.work.bump\n0\n0\n0\n",
"digest": "a0fcd7d0ec09f4bca91e7feac53ad2fba281e9d5928baf83acf8ccb972063ca3",
"occupied": [],
"allocated": "__aji_contract_a0fcd7d0ec09f4bca91e7feac53ad2fba281e9d5928baf83acf8ccb972063ca3"
},
{
"kind": "snapshot",
"owner": "fn:app.work.bump",
"ordinal": 0,
"level": 0,
"group": 1,
"encoding": "aji.contract/1\nsnapshot\n16:fn:app.work.bump\n0\n0\n1\n",
"digest": "af4bb0b4bc123bf822bc3eaf6c99ac985391dda522d190273e963371547abc4a",
"occupied": [],
"allocated": "__aji_contract_af4bb0b4bc123bf822bc3eaf6c99ac985391dda522d190273e963371547abc4a"
},
{
"kind": "witness",
"owner": "invariant:app.state.State<u64>",
"ordinal": 0,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\nwitness\n30:invariant:app.state.State<u64>\n0\n0\n0\n",
"digest": "70f85479ae7feb61ae4e622908c19addb48d69ad46fbb2b86d82bd8e669b2094",
"occupied": [],
"allocated": "__aji_contract_70f85479ae7feb61ae4e622908c19addb48d69ad46fbb2b86d82bd8e669b2094"
},
{
"kind": "pre",
"owner": "fn:app.work.bump",
"ordinal": 0,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n0\n0\n0\n",
"digest": "1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338",
"occupied": [
"__aji_contract_1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338",
"__aji_contract_1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338_1"
],
"allocated": "__aji_contract_1359541cfa11c597fd0b86cac844724f07d4a07f6ce3b36116eacc8c39669338_2"
},
{
"kind": "pre",
"owner": "fn:app.work.bump",
"ordinal": 2,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n2\n0\n0\n",
"digest": "c9f6aaa9419c3218c57598f9a73556160d402558e308c578bce6bd4af5bc293f",
"occupied": [],
"allocated": "__aji_contract_c9f6aaa9419c3218c57598f9a73556160d402558e308c578bce6bd4af5bc293f"
},
{
"kind": "pre",
"owner": "fn:app.work.bump",
"ordinal": 10,
"level": 0,
"group": 0,
"encoding": "aji.contract/1\npre\n16:fn:app.work.bump\n10\n0\n0\n",
"digest": "e6f22da69e00ebc6fef2fa201fce7f02e8ec4eeaff4bf57875ba70fac0fbfb5c",
"occupied": [],
"allocated": "__aji_contract_e6f22da69e00ebc6fef2fa201fce7f02e8ec4eeaff4bf57875ba70fac0fbfb5c"
}
],
"ordering_cases": [
{
"kind": "pre",
"owner": "fn:app.work.bump",
"input_ordinals": [
2,
10
],
"sorted_ordinals": [
10,
2
]
}
]
}
+107
View File
@@ -0,0 +1,107 @@
# Contract proof classification and report grammar candidate
Non-normative continuation of [RFC 0039](../rfcs/0039-verifier-visible-contracts.md) and the [accounting/status candidate](contract-accounting-and-status.md), at `a4181f2`. These are proposed closed rules, not implemented verification or an accepted schema. All executable P predicates remain available; this classifier only distinguishes two runtime statuses. Module-claim metadata, source clause elaboration, diagnostic collection, adoption and vertical delivery remain part of full P6-6.
## Eligible helper and terms
Classification runs only after ordinary verification, P/S membership and virtual binding checks succeed. An eligible helper has exactly one block, ends in a value `ret`, and contains only the following well-typed operations. Its result is bool for a predicate or Data for old. All instructions, including unused definitions, must qualify.
| Operation | Operand positions, including one instruction position | Logical node positions |
|---|---:|---:|
| `const.I`, `const.bool` | 1 | 1 |
| `copy` | 2 | 0 |
| Data `struct.make` with n fields | 1+n | 1 |
| Data `struct.get` | 2 | 1 |
| shared binding-derived `borrow.field` | 2 | 1 |
| `load` of Data from such a view or its root | 2 | 1 |
| `borrow.end` of an owned child view | 2 | 0 |
| `eq/ne.I`, `eq/ne.bool`, `lt/le/gt/ge.I` | 3 | 1 |
| `and/or/xor.bool` | 3 | 1 |
| value `ret` | 2 | 0 |
I is an existing AIR integer type, including isize/usize. Constants are compared by their exact accepted mathematical values; classification assumes no target pointer width. No bool ordering, integer bitwise operations, array operations, calls, assertions, casts, arithmetic, checked extraction, owner/enum views or branch instructions qualify. The predicate may execute any of those permitted by P; it then remains runtime-classified. A helper's signature cannot contain mutable parameters under the boundary rules. A view is eligible only when its root is a helper's bound shared parameter and every edge is an ordinary struct-field projection. Loading a whole linear/authority value does not become eligible.
Terms form a typed immutable DAG: constants; original Data parameter identities; opaque current Data SSA identities; field projections; Data records in declared field order; scalar comparisons; bool combinations. Copy aliases its input. Projection of a constructed record selects that field; projection of a parameter/opaque record appends the nominal field identity. Other records stay structural, with no expansion of arrays or repeated subtrees. Constant identity includes its type and exact mathematical value; field identity includes its resolved nominal declaration and ordinal. Paths are parent-linked nodes, not copied strings.
Bindings substitute in parameter order. By-value Data and explicit ref of Copy Data use the same value terms. Shared observations of original Data parameters likewise use their immutable terms. A shared root originally typed `ref<T>` is identified by its enclosing parameter ordinal and field path, independent of entry/return epoch. An original exclusive/owned root instead includes its observation boundary: entry for old/pre, the particular ret for post. The helper's temporary ref type does not make an exclusive/owned enclosing root stable. Slice operations and borrow-result observations are unsupported initially. Different parameter identities are never equated because a particular caller aliases them.
Old is normalized once at entry, with its own bindings. Its result is substituted for a snapshot binding; it never contains a body SSA identity. Result/Copy make origins follow only const, copy, Data struct.make/get and original Data parameters. Every other Data value, including a block parameter or load, is an opaque identity containing function/value identity and this boundary. Traversal stops there; loops do not turn it into an entry term. Linear make representations are unsupported for proof initially, while their runtime construction remains fully supported. Modify is always runtime-classified.
Terms of bool type evaluate to true, false or unknown. A constant supplies its value. A comparison evaluates typed constants exactly; identical scalar terms give true for eq/le/ge and false for ne/lt/gt. Otherwise it is unknown. A definitely true/false bool operand can be folded to its typed constant before eq/ne; two identical bool formula terms can still be equal when their truth is unknown. AND/OR use strong three-valued logic, XOR with unknown is unknown. No arithmetic identities, path facts, precondition facts, caller facts, commutative operand sorting or SMT are imported. A raw symbolic bool is unknown. Truth is proved only when the returned formula is definitely true.
Runtime pre has one universal entry boundary. Post must be true at every syntactic ret, including unreachable blocks, and has no proof when there are zero ret sites. Make has one construction boundary. A constant false formula is reported as not proven; mandatory execution still handles its trap. Classification never rejects a module, eliminates a check, changes fuel or promises termination.
Once published, this classification, its limits and reasons are frozen as part of the contracts feature's semantics (spec 07 §8.7 and the feature registry's published-feature immutability rule). Toolchain prover strength, cache strategy and optimizations cannot classify more or fewer rows as proven. Changing these rules needs a separately specified compatibility path through an RFC; adding a feature does not itself authorize changing existing format-0 constructs or report bytes.
## Exact logical work and fallback
For each runtime record independently, let H be the sum of the table's operand-position charges for its predicate and N the sum of logical node positions. These counts are before folding/interning, including unused definitions. Let n be the predicate binding count and B the prescribed boundary count. For a post using old, O is old helper's operand-position sum plus its binding count plus its logical node count; otherwise O=0. Let D be the operand-position cost of the union of origin-DAG-reachable result/make definitions, counted once per function/value identity for this record across every prescribed boundary, including CFG-unreachable blocks. Post has result-origin work exactly when a binding names result, even if that helper parameter is unused; otherwise D=0.
Origin constants, copy and struct.make/get use the same position charges as the table. A terminal original Data parameter, block parameter or other opaque Data definition costs one; its operands are not traversed. Pre has D=0. Type/function/field metadata, result identifiers, literal digits, source positions and cache hits add no position. Shared origin definitions are charged once, whether or not an implementation had cached them earlier.
```text
C = H + O + D + B * (n + N)
limit = 1,048,576 positions per record
```
Compute with checked unsigned 64-bit counters; overflow or C>limit gives no proof. C=limit is within budget. Under current structural limits C cannot overflow u64; that fallback is defensive, not a reachable current-module test. Helpers/origin DAGs may be cached but the logical charge is independent of cache state. This bounds classification positions, not elapsed time or every module analysis. Structural type/property scans retain their independent memoized bounds. Unrelated body instructions do not affect a pre's cost.
Choose exactly one reason in this order, without sampling a run:
1. Assume/document: `not_attempted`, with no cost or classifier invocation.
2. Modify: `update`, with no cost.
3. Post with zero returns: `no_normal_return`, with no cost.
4. Noneligible predicate: `unsupported_predicate`, with no cost.
5. Used noneligible old helper: `unsupported_old`, with no cost.
6. Unsupported binding/linear make: `unsupported_binding`, with no cost.
7. Overflow or over-budget C: `budget`, with cost `"overflow"` or the integer C.
8. Every boundary definitely true: `closed_scalar`, proof proven, cost C.
9. Otherwise: `not_established`, proof none, cost C.
Eligibility checks do not follow arbitrary helper calls or execute predicates. Unsupported forms and budget fallback preserve acceptance and runtime enforcement. The report's reason is an explanation of the closed classifier, not a repair proposal or a frequency estimate. These exact charges refine the earlier accounting candidate's open node/operand conventions.
Initially unsupported bindings are observations of a borrowed/slice result, or a linear make representation. Other verified bindings supply Data terms or shared view anchors, including unused slice/authority-containing anchors; an unsupported operation on an anchor already makes the helper noneligible. Runtime reasons other than closed_scalar have proof none. Only explicit assume/document has proof not_attempted.
## Report rows and canonical form
For modules declaring the proposed contracts feature, append a `contracts` object after existing `unsafe`. The proposed checked-type and assumption extensions depend on it, so their full declared dependency closure also triggers this section. Otherwise emit exactly today's report bytes. Its fixed field order is `rows`, `totals`, then `types` under the [checked inventory refinement](contract-source-and-module-state.md#declared-claims-in-the-report). Feature-declared modules with no truth sites emit an empty rows array and four zero totals; types is empty when no checked identity occurs. Every new object has the field order specified below or in that refinement; no optional omissions, unknown keys, whitespace or floating-point numbers. Use the existing canonical-record string escaping.
Rows iterate functions, blocks and instructions in textual module order, one per pre/post or make/modify operation. Old/view/take are not truth rows. Snapshot helper execution remains in the call graph. This gives stable declaration-site counts independent of callers, number of returns or invocations.
Row field order:
```text
site, kind, scope, predicate, callback, bindings, status, proof, enforcement, boundaries
```
`kind` is `pre`, `post`, `make` or `modify`. Scope is `boundary` for pre/post and `value` for make/modify: the latter establishes a persistent checked claim, rather than a relation that holds only at a function boundary. Predicate is the resolved AIR function name, without @. Callback is the resolved modify callback name, otherwise null. Checked identity still includes R and the resolved predicate; a later metadata integration must represent it without a source-only claim.
Site and boundary-position object field order is `function`, `block`, `inst`, `source`. Function/block are AIR names without prefixes; inst is the existing zero-based instruction index. Input-text AIR line/col is omitted so comments/formatting do not affect semantic rows. Source is `{file,line,col}` from the supplied lowering map, or null, with one-based line/col. Use the mapping for that exact instruction; never guess a variable name or an enclosing block. No filesystem lookup, path rewriting or source hashing is performed by report generation. Borrowing truth or positions from a caller is forbidden.
The source field requires an explicit adoption-time clarification to spec 10 §6.1: semantic report data depends only on verified AIR, while locations may use supplied frontend provenance. Currently the CLI passes only the module to report.write; implementing this field needs that provenance context. It changes no contract-free report. An AIR-only input has source null even if its AIR file happens to have a .aji-looking name. Equal verified AIR with different supplied source maps has equal semantic rows: replacing every source value with null gives identical bytes, while the original reports may differ. A generated helper's location is never substituted for the source clause/operation.
Bindings are in helper parameter order, each `{kind,name,view}`. Kind is `parameter`, `snapshot`, `result` or `representation`; name is the actual AIR value name without % for parameter/snapshot/representation, null for result. View is `value` or `ref`. Pre/post retain their explicit bindings; make/modify have one implicit ref representation binding. Make names its R operand, modify names its capsule-borrow operand. A post's return operand is identified by the corresponding boundary position, not an invented entry result SSA name.
Proof field order is `result`, `reason`, `cost`, `limit`; result is `proven`, `none` or `not_attempted`, reason is from the ordered list above, cost is null/integer/`"overflow"`, limit is always 1048576. Enforcement is `runtime`, `assumed_unsafe` or `documented`. Status is the corresponding uppercase spec 13 name; only runtime+proven yields PROVEN_STATICALLY. Assumed/documented use not_attempted regardless of formula truth.
Boundaries are positions in textual order: the pre/make/modify site itself, or all ret positions for post. A zero-ret post has an empty list. Documented clauses retain their syntactic coverage even though no helper executes. Totals field order is PROVEN_STATICALLY, CHECKED_AT_RUNTIME, ASSUMED_UNSAFE, UNPROVEN; each counts rows of that status exactly once. A snapshot is not a fifth status or a truth guarantee.
The [module/source candidate](contract-source-and-module-state.md) proposes rooted state declarations and a type inventory after rows/totals so unused declared invariants are visible. Its exact inventory schema and universal-root classification still need integration; the component vector here specifies site rows/totals only. Persistent checked state and pre/post relations have distinct scopes, but site rows cannot replace declarations, root mappings or coverage. Full P6-6 cannot close until the chosen module model and its report representation are integrated.
## Call/effect/check accounting
At each executable pre/old/post site, add its helper to calls in instruction order, deduplicating with ordinary call sites. Executable includes runtime and assume, independently of backend elision. A post contributes one call edge at its declaration position, not one per ret; the edge denotes possible invocation, not execution order. Documented clauses add no executable edge. Make adds its predicate; modify adds callback then predicate. Adoption must extend spec 10's calls definition to named invocations of these gated operations, explicitly excluding document; contract-free meanings/bytes stay unchanged. The callback's declared/used effects propagate as for an ordinary call, including trusted-boundary discharge. P helpers have no declared effects but their ordinary call edges remain visible.
Helper instructions contribute runtime_checks/proven_checks only in their own function rows. Do not copy their asserts, bounds checks or counts into each caller/return. Existing checks fields retain their instruction meanings; contract predicate tests appear in contracts rows rather than new assertion counts. A PROVEN contract still executes and does not increment proven_checks.bounds. Assume variants contribute a direct unsafe operation at their prefix site and unsafe used effect, independent of whether the helper is true. Document adds neither. Rejected modules produce diagnostics and no audit object.
Required implementation vectors cover exact and one-over proof budgets, cache-independent costs, shared DAGs and many returns, unsupported unused instructions, typed signed/bool comparisons, mutated old/current roots, opaque loop origins, source maps and missing maps, explicit modes, empty feature sections, site totals versus coverage, snapshot-only call edges, callbacks/trusted effects, and unchanged contract-free bytes. The candidate allocates no code/feature and enters no normative/source bundle.
## Research evidence
Five current-language probes at `a4181f2` confirm byte-identical reports after AIR comments/whitespace changes, source versus its lowered AIR, and before/after an unsafe T0009 trap. A fourth verifies a shared Pair predicate using i8 limits -128/127, field views/load/end, copy/struct.make/get and bool eq/and/or/xor; it returns true, with the expected ordinary call edge. A fifth verifies the ordinary AIR helper/8,191-return structure used below, without any contract operation. Runs use fuel 10,000. These constrain compatibility and eligible operation shapes; no contract opcode or report section is implemented.
[Fifteen scalar/cost vectors](contract-proof-vectors.json) pin the proposed arithmetic and truth rules. Symbols denote distinct u64 observations unless explicitly typed otherwise; repeat multiplies boundary count without duplicating the stored formula. The formula representation is research data, not an AIR encoding. Independent concrete evaluation checked 328,965 assignments from 0..255 and all 27 three-valued Boolean combinations/completions. Every classified-true formula held over the sampled assignments; each not_established example had a concrete counterexample. This finite check does not prove the full classifier or the verifier implementation sound.
The exact-limit vector is attainable within ordinary structural bounds: a 63-parameter helper has 64 bool constants, a one-field Data struct.make, 30 copies and one ret (H=128, N=65). One post covers 8,191 syntactic returns, binds original parameters and has D=O=0, so C=1,048,576. Replacing one unused binding with result from an original parameter gives D=1 and budget fallback at 1,048,577, without changing truth or acceptance. These are proposed classifier vectors, not an executed new-contract test. Old-identity vectors use a two-position identity old helper plus one binding, O=3; Range field predicates have H=17, N=5.
The [report component vector](contract-report-vector.json) pins field order and all four statuses, including a two-return post, a modify callback and a constant Range make. It has six rows and seven covered boundaries, with totals counting six sites. It is a proposed contracts component, formatted for inspection, not output captured from today's CLI. Its conceptual function f has pre sites 0..2, old at 3 and post at 4; left/right return different Data parameters, yielding the cost-16 vector above. Function g's modify row is runtime/update over StateRep with an unsupported classifier predicate. Function h constructs Rep {lo:0,hi:5} in raw and makes its checked value at instruction 3. The inventory lists StateRep first through g's signature, Rep second at h's make, and an unused always-true u64 witness last; ordinary declarations and earlier signatures contain no checked type. Universal within stays runtime/not_established even though h's make is proven. No module-state declaration or source provenance is implied.
+21
View File
@@ -0,0 +1,21 @@
{
"purpose": "non-normative scalar truth and logical-cost vectors; not implemented contract conformance",
"limit": 1048576,
"vectors": [
{"case":"literal_true","H":3,"O":0,"D":0,"B":1,"n":0,"N":1,"boundaries":[true],"cost":4,"reason":"closed_scalar"},
{"case":"universal_identity","H":5,"O":0,"D":0,"B":1,"n":1,"N":1,"boundaries":[["eq","x","x"]],"cost":7,"reason":"closed_scalar"},
{"case":"unrelated_parameters","H":5,"O":0,"D":0,"B":1,"n":2,"N":1,"boundaries":[["eq","x","y"]],"cost":8,"reason":"not_established"},
{"case":"old_identity_return","H":5,"O":3,"D":1,"B":1,"n":2,"N":1,"boundaries":[["eq","x","x"]],"cost":12,"reason":"closed_scalar"},
{"case":"two_returns_same_origin","H":5,"O":3,"D":1,"B":2,"n":2,"N":1,"boundaries":[["eq","x","x"],["eq","x","x"]],"cost":15,"reason":"closed_scalar"},
{"case":"second_return_other_origin","H":5,"O":3,"D":2,"B":2,"n":2,"N":1,"boundaries":[["eq","x","x"],["eq","y","x"]],"cost":16,"reason":"not_established"},
{"case":"constant_range_make","H":17,"O":0,"D":5,"B":1,"n":1,"N":5,"boundaries":[["le",0,5]],"cost":28,"reason":"closed_scalar"},
{"case":"equal_endpoints_make","H":17,"O":0,"D":4,"B":1,"n":1,"N":5,"boundaries":[["le","x","x"]],"cost":27,"reason":"closed_scalar"},
{"case":"exclusive_old_current","H":11,"O":11,"D":0,"B":1,"n":2,"N":3,"boundaries":[["eq","entry.m.n","ret.m.n"]],"cost":27,"reason":"not_established"},
{"case":"stable_shared_old_current","H":11,"O":11,"D":0,"B":1,"n":2,"N":3,"boundaries":[["eq","shared.r.n","shared.r.n"]],"cost":27,"reason":"closed_scalar"},
{"case":"signed_constants","integer_type":"i8","H":7,"O":0,"D":0,"B":1,"n":0,"N":3,"boundaries":[["lt",-128,127]],"cost":10,"reason":"closed_scalar"},
{"case":"identical_unknown_bool_formulas","H":8,"O":0,"D":0,"B":1,"n":2,"N":2,"boundaries":[["eq",["le","x","y"],["le","x","y"]]],"cost":12,"reason":"closed_scalar"},
{"case":"true_or_unknown","H":9,"O":0,"D":0,"B":1,"n":2,"N":3,"boundaries":[["or",true,["lt","x","y"]]],"cost":14,"reason":"closed_scalar"},
{"case":"exact_work_limit","H":128,"O":0,"D":0,"B":8191,"n":63,"N":65,"boundaries":[true],"repeat":8191,"cost":1048576,"reason":"closed_scalar"},
{"case":"one_over_work_limit","H":128,"O":0,"D":1,"B":8191,"n":63,"N":65,"boundaries":[true],"repeat":8191,"cost":1048577,"reason":"budget"}
]
}
@@ -0,0 +1,67 @@
{
"purpose": "Non-normative current-language baselines for the checked-type candidate; no checked feature is implemented.",
"compiler": "4cda448",
"header": [
"module contract.properties",
"air 0",
"lang 0.1",
"features [arc, arrays, atomics, cancellation, capabilities, channels, effects, error_values, heap, islands, linear_aggregates, linear_buffers, ownership, regions, resources, sync, tasks, unsafe]"
],
"cases": [
{
"case": "region_identity", "command": "check", "exit": 0, "codes": [],
"body": ["fn @w(%value: region) -> region", "effects []", "entry:", " ret %value"]
},
{
"case": "sender_identity", "command": "check", "exit": 0, "codes": [],
"body": ["fn @w(%value: sender<u64>) -> sender<u64>", "effects []", "entry:", " ret %value"]
},
{
"case": "wrapped_channel_endpoint", "command": "check", "exit": 1, "codes": ["E0006"],
"body": [
"type @Box = struct { endpoint: sender<u64> }",
"fn @f(%heap: cap<mem.alloc>) -> void", "effects [mem.alloc]", "entry:",
" %n = const.usize 1",
" channel.make @Box, %n, %heap, ok -> @made, err -> @oom",
"made(%tx: sender<@Box>, %rx: receiver<@Box>):", " trap",
"oom(%e: alloc_error):", " trap"
]
},
{
"case": "wrapped_mutex_endpoint", "command": "check", "exit": 1, "codes": ["E0006"],
"body": [
"type @Box = struct { endpoint: sender<u64> }",
"fn @f(%value: @Box) -> void", "effects []", "entry:", " %m = mutex.make %value", " trap"
]
},
{
"case": "copy_cap_zero", "command": "check", "exit": 1, "codes": ["E1001"],
"body": ["fn @f() -> void", "effects []", "entry:", " %cell = local.alloc cap<mem.alloc>", " local.zero %cell", " ret"]
},
{
"case": "nominal_atomic", "command": "check", "exit": 1, "codes": ["E1001", "E1001"],
"body": ["type @Box = struct { value: u64 }", "fn @w(%value: atomic<@Box>) -> atomic<@Box>", "effects []", "entry:", " ret %value"]
},
{
"case": "checked_identity", "command": "check", "exit": 1, "codes": ["E0004"],
"body": [
"fn @w(%value: checked<u64,@always>) -> checked<u64,@always>", "effects []", "entry:", " ret %value",
"fn @always(%value: ref<u64>) -> bool", "effects []", "entry:", " %yes = const.bool true", " ret %yes"
]
},
{
"case": "range_predicate", "command": "run", "fuel": 10000, "exit": 0, "status": "returned", "value": true,
"body": [
"type @Rep = struct { lo: u64, hi: u64 }",
"fn @within(%r: ref<@Rep>) -> bool", "effects []", "entry:",
" %lo = borrow.field @Rep.lo, %r", " %hi = borrow.field @Rep.hi, %r",
" %a = load %lo", " %b = load %hi", " borrow.end %lo", " borrow.end %hi",
" %ok = le.u64 %a, %b", " ret %ok",
"fn @main() -> bool", "effects []", "entry:",
" %a = const.u64 0", " %b = const.u64 5", " %v = struct.make @Rep(%a, %b)",
" %cell = local.alloc @Rep", " local.store %cell, %v", " %r = borrow.ref %cell",
" %ok = call @within(%r)", " borrow.end %r", " ret %ok"
]
}
]
}
+75
View File
@@ -0,0 +1,75 @@
{
"rows": [
{
"site": {"function":"f","block":"entry","inst":0,"source":null},
"kind": "pre", "scope": "boundary", "predicate": "always_true", "callback": null,
"bindings": [], "status": "PROVEN_STATICALLY",
"proof": {"result":"proven","reason":"closed_scalar","cost":4,"limit":1048576},
"enforcement": "runtime",
"boundaries": [{"function":"f","block":"entry","inst":0,"source":null}]
},
{
"site": {"function":"f","block":"entry","inst":1,"source":null},
"kind": "pre", "scope": "boundary", "predicate": "positive", "callback": null,
"bindings": [{"kind":"parameter","name":"x","view":"value"}],
"status": "ASSUMED_UNSAFE",
"proof": {"result":"not_attempted","reason":"not_attempted","cost":null,"limit":1048576},
"enforcement": "assumed_unsafe",
"boundaries": [{"function":"f","block":"entry","inst":1,"source":null}]
},
{
"site": {"function":"f","block":"entry","inst":2,"source":null},
"kind": "pre", "scope": "boundary", "predicate": "positive", "callback": null,
"bindings": [{"kind":"parameter","name":"y","view":"value"}],
"status": "UNPROVEN",
"proof": {"result":"not_attempted","reason":"not_attempted","cost":null,"limit":1048576},
"enforcement": "documented",
"boundaries": [{"function":"f","block":"entry","inst":2,"source":null}]
},
{
"site": {"function":"f","block":"entry","inst":4,"source":null},
"kind": "post", "scope": "boundary", "predicate": "same", "callback": null,
"bindings": [{"kind":"snapshot","name":"old","view":"value"},{"kind":"result","name":null,"view":"value"}],
"status": "CHECKED_AT_RUNTIME",
"proof": {"result":"none","reason":"not_established","cost":16,"limit":1048576},
"enforcement": "runtime",
"boundaries": [{"function":"f","block":"left","inst":0,"source":null},{"function":"f","block":"right","inst":0,"source":null}]
},
{
"site": {"function":"g","block":"entry","inst":2,"source":null},
"kind": "modify", "scope": "value", "predicate": "valid_state", "callback": "update_state",
"bindings": [{"kind":"representation","name":"state","view":"ref"}],
"status": "CHECKED_AT_RUNTIME",
"proof": {"result":"none","reason":"update","cost":null,"limit":1048576},
"enforcement": "runtime",
"boundaries": [{"function":"g","block":"entry","inst":2,"source":null}]
},
{
"site": {"function":"h","block":"entry","inst":3,"source":null},
"kind": "make", "scope": "value", "predicate": "within", "callback": null,
"bindings": [{"kind":"representation","name":"raw","view":"ref"}],
"status": "PROVEN_STATICALLY",
"proof": {"result":"proven","reason":"closed_scalar","cost":28,"limit":1048576},
"enforcement": "runtime",
"boundaries": [{"function":"h","block":"entry","inst":3,"source":null}]
}
],
"totals": {"PROVEN_STATICALLY":2,"CHECKED_AT_RUNTIME":2,"ASSUMED_UNSAFE":1,"UNPROVEN":1},
"types": [
{
"type": "checked<@StateRep, @valid_state>", "predicate": "valid_state", "status": "CHECKED_AT_RUNTIME",
"proof": {"result":"none","reason":"unsupported_predicate","cost":null,"limit":1048576},
"enforcement": "construction_update", "declarations": []
},
{
"type": "checked<@Rep, @within>", "predicate": "within", "status": "CHECKED_AT_RUNTIME",
"proof": {"result":"none","reason":"not_established","cost":23,"limit":1048576},
"enforcement": "construction_update", "declarations": []
},
{
"type": "checked<u64, @always>", "predicate": "always", "status": "PROVEN_STATICALLY",
"proof": {"result":"proven","reason":"closed_scalar","cost":5,"limit":1048576},
"enforcement": "construction_update", "declarations": []
}
]
}
@@ -0,0 +1,66 @@
# Contract runtime dispatch and context candidate
Non-normative continuation of [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), [AIR bindings](contract-air-bindings.md) and [invariant boundaries](contract-invariant-boundaries.md). This completes a candidate runtime rule, not an implementation or a feature/code allocation. Format-0 compatibility, source reasons, owner adoption and vertical delivery remain gates.
## Continuations and publication
A frame retains an explicit continuation describing the invocation it is awaiting: ordinary call, pre, old, post index with pending return, make validation, modify callback or modify validation. Record the installing instruction, evaluated boundary and helper identity as module indices; never infer this from its opcode after an ordinary result assignment. Parent frames remain active until their pending operation/return completes. Returning from a helper goes through the saved continuation rather than the current ordinary `caller result; inst += 1` path. Continuations are per task and frame, with at most one pending operation in each frame; nested callbacks/calls use the ordinary frame stack, not an unbounded side stack.
| Initiating instruction | State until helper completion | Successful completion |
|---|---|---|
| pre, runtime/assume | invocation views/places, bool helper | inspect bool, end temporary observations, advance prefix once |
| old | invocation views/places, Data helper | end observations, save one snapshot, advance prefix once |
| post, any mode | install ordered metadata, no evaluation | advance prefix once |
| ret with executable posts | retain frame, exact ret and pending value; select first executable post | finish normal return only after every executable post succeeds |
| checked.make | retain unexposed complete R and whole-R observation | end observation, form checked value and bind result once |
| checked.modify | retain capsule root, suspend its access; invoke callback through temporary mut<R> | retain callback result, end mutation loan, invoke p through shared whole-R observation; bind callback result only after p succeeds |
Pre.document is a paid metadata operation with no helper. Post.document installs metadata but is skipped by return-time dispatch. Proven runtime clauses still execute. Old executes once after all pre groups; documented old notation only reuses the existing snapshot. A callback returning never never reaches validation/publication. Void callbacks carry a pending void value. Normal cleanup is the explicit AIR that preceded ret, not hidden work in these continuations.
A helper ret is charged as an ordinary instruction; the same step inspects its bool/Data result and performs its continuation. A false bool stops immediately, before scheduling or beginning another instruction. A true final post completes the original ret: end temporary observations, remove the contracted frame, transfer the pending value to the caller's saved continuation, or mark the task done and expose its result. Task.join cannot observe a pending value. Main completes only at this point. Cascaded completion uses an iterative dispatcher: every transition consumes a completed helper, advances a finite clause list or completes a frame; it cannot reexecute a paid ret or spin through a cyclic continuation.
A callback's successful return is not a successful modify. The callback frame ends before the validation frame is pushed, so they do not count simultaneously. Its borrow-free result, including a linear owner, is retained but unavailable to the caller until validation succeeds. No callback mutation or external effect is rolled back on failure. Trap, fuel/task limit and blocked outcomes grant no completed checked/postcondition claim. A failure ends the whole program under format-0 policy, including failure in a child task; no destructor, unwind, rollback, join or cleanup callback is invented.
## Fuel, depth and scheduling
Every textual instruction pays one fuel and quantum unit when it begins, including all document prefix operations, post installation, ret, make and modify. Helper/callback instructions pay separately. Pushing a helper, processing its returned value, advancing to the next predicate and completing a pending return add no synthetic instruction/unit. Before pushing any helper/callback apply the ordinary 1,024-active-frame bound; a contracted parent still counts. The dispatcher performs that check explicitly, not only through the ordinary call opcode path.
Normalize the completed instruction's continuation before the current loop's quantum check: inspect bool, retain/publish values, end temporary loans and push the next helper when required. There is no fuel check inside this normalization. False on the last fuel unit is a trap. If the original ret or callback ret spent the last unit, a needed next predicate frame is ready, but execution stops before its first instruction with limit_exceeded. If the final predicate ret spent the last unit and succeeds, return/update completion still happens; fuel is checked only when another instruction would begin. A depth violation discovered while pushing after a paid instruction is T0007 even when no fuel remains, as with ordinary call.
After normalization apply the usual quantum rule to the still-runnable task, except that completing a task/returning main follows today's scheduling/termination path. Switching may occur after the initial ret, between predicate instructions or between callback and validation. No validation region is an atomic section; all saved values/loans must survive switching. Contract execution can change interleavings and schedule.choices; equivalence with a contract-free instruction stream is not claimed. Modes also differ in their executed instructions.
P/S operations have no newly visible synchronization/atomic/ambient operation, so prefix/install/validation dispatch adds no exploration choice or scheduler draw of its own. The existing visible operations in an unrestricted callback keep their ordinary exploration, weak-memory and cancellation behavior. Callback waiting retains its continuation and existing fuel_paid handling; resume does not repay the waiting instruction or restart callback/validation. Cancellation of the current task does not skip a predicate/post: only existing explicit cancellation operations observe it. The pending claim is never published because a scheduler selected another task.
## Execution memory and observations
GC roots include all ordinary frame values plus each frame's pending return/candidate/callback value, persistent snapshot and active observation places. Copy them with the same Copier/memoization as ordinary cells, arrays, graphs and owners, preserving aliasing, backing-frame identity, paths and race shadows. Indices into immutable module data require no execution-heap tracing. Retained runtime context must remain valid after the execution heap is released. No Value/place pointer may live solely in a Zig local across a collection, scheduling point or hosted wait.
Linear make and whole linear checked observations use an SSA-backed cell rather than a copied local. Copy observations get distinct complete temporary cells, each covered by the activation formula L+S+max E; temporary helper descendant views cannot escape. Checked representation access needs an explicit runtime representation edge/accessor, not a fake user field 0. Ordinary owner-content adaptation and whole-R validation are distinct. Collection traverses checked representation values without invoking predicates or changing fuel, authority charges, task clocks, schedules or graph identities. An old iref copies only its opaque identity/slot and does not retain a destroyed graph.
After each successful helper end its evaluation views/places; after final success bind/transfer the value once. Scratch, snapshots and pending slots are unreachable after their activation completes, except ordinary escaping ancestor storage allowed by existing borrow-return rules. GC every step must produce byte-identical records, including all context positions, to ordinary collection. Retention is bounded by active frames/verified value and activation budgets, not the number of completed calls/updates. This is a requirement for new continuations, not evidence that today's GC already visits them.
## False conditions and additive context
Candidate false codes/kinds are T0011 trap.contract_precondition, T0012 trap.contract_postcondition and T0013 trap.type_invariant. A false assumed pre/post retains T0009 trap.unsafe_precondition. The primary function/block/inst for these dispatch-generated failures is the installing pre/post or make/modify instruction; existing source_location therefore maps to the clause/checked operation. The helper ret that yielded false is retained as the context's at position. Old returns Data and has no false code. A helper/callback's own trap retains its existing code and actual innermost instruction, including arithmetic/assert/unsafe/depth traps; do not relabel it as a false condition. An implicit frame-push depth failure has the evaluated boundary as its primary instruction and at null because no helper instruction began. No trap code is allocated here.
Propose one optional `contract` object on trapped, limit_exceeded, blocked and race_detected records when the failing/current execution unit is inside an active contract evaluation. Race context identifies the same actual detected access and does not turn a verifier defect into a contract-false trap. Omit it on successful return, not_instantiated and ordinary failures outside evaluation. Existing fields/values and the relative order of existing fields remain unchanged. Object field order is:
```text
kind, mode, phase, helper, task, site, boundary, at
```
Kind is pre/post/old/make/modify. Mode is runtime for old/make/modify and ordinary pre/post, assume for assumed pre/post; document starts no active evaluation. Phase is predicate, snapshot (old) or callback (modify). Helper is the directly selected phase function name without @, not an invented source variable. Task is the actual zero-based task identity. Site is the installing prefix/checked operation. Boundary is the evaluated ret for post, otherwise the initiating operation. At is the actual failing/completing instruction; for fuel it is the next instruction prevented from beginning; for task limits/blocked/races it is the actual spawn/wait/access instruction. An implicit push-depth failure has at null. This does not claim that a fuel-stopped instruction executed.
Each non-null position is `function,block,inst`, optional file/line/col when exactly source-mapped, then mandatory air_line/air_col. Function/block are AIR names without sigils; inst is zero-based. Map every position independently using its real lowering span, including imported/template/standard-library helpers. AIR-only positions omit source coordinates. No map is inferred from a helper name; missing exact context maps stay omitted. Primary source_location retains existing behavior. A failure inside a helper's ordinary descendant call retains the innermost trap as primary/at but still identifies the directly selected evaluation helper in contract.helper.
Use the nearest active evaluation continuation in the same task. Nested callback contracts replace the reported context with their own innermost boundary; there is no unbounded dumped stack or ambiguous outer-root selection. Child tasks do not inherit the creator's active evaluation: their own contracts identify their own boundaries; an ordinary child trap carries no fabricated parent context. For global fuel, use the task selected to begin the prevented instruction. For blocked, use the existing oldest-waiter selection, including that waiter's task and continuation; unrelated pending validations are not reported as its cause.
Build/enrich typed context before JSON serialization. writeOutcome emits contract after the base outcome fields and before captured stdout/stderr/files/schedule; the CLI appends primary source_location last as today. Lowered-source position mapping must enrich each context position before serialization, rather than append a second contract object or patch nested JSON text. Position/context values reference immutable module data or result-arena-owned storage, not released execution memory. Hosted result files use the same schema and enforcement; hosted program streams remain owned by the program.
Explore keeps today's identity rule: distinct outcomes are the exact bytes produced by writeOutcome, sorted by those bytes. Include the complete AIR-only contract object in that key, task included; do not strip/normalize metadata during deduplication. Schedule-dependent task IDs or different boundaries may therefore produce distinct records for the same trap code, even when the program-visible failure is similar. This is an explicit consequence of factual outcome identity. Explore does not enrich source positions or append primary source_location today; its new context also stays AIR-only for .aji input. Normal run/hosted result mapping remains as specified above. Required tests pin enumeration/dedup/order and bounded max-runs behavior without conflating metadata-distinct records with different returned program values.
## Evidence and delivery
The [runtime vectors](contract-runtime-vectors.json) record six current-language groups at `2db752d` (16 CLI runs, quantum 1): ordinary return/fuel cuts, assertion at the last unit, depth at 1023/1024 steps, a linear owner across a returned call, exact source mapping of a helper trap, and a child assertion under five schedule seeds. Nine ordinary fixture variants pass normal-versus-GC-every-step comparison (13 schedule cases, 26 interpreter runs, race detection enabled). These executed programs contain no contracts. Six separately marked hypothetical context components pin field/position order, false versus existing trap identity, a depth-null at, callback fuel and an assumed child post. The components are schema vectors, not executed new-contract output. These show constraints on the proposed dispatcher/serializer, not successful new-contract execution.
Required vertical coverage includes pre/old/post/install/document fuel, false at the final unit, cuts before/within/between helpers, helper-depth boundaries, several returns/posts, void/never callbacks, nested callback contracts, blocked/cancelled callbacks, unexposed linear callback results, distinct Copy places, graph/owner/checked pending roots under GC every step, joined workers and quantum/weak-memory exploration. Preserve contract-free bytes. New false codes, exact typed context and continuation state must land in spec/reference, verifier/interpreter, source/formatter/Quick Reference and AIR/source conformance together; these research rules alone do not complete P6-6.
+379
View File
@@ -0,0 +1,379 @@
{
"purpose": "Non-normative runtime research: baseline groups are executed current-language programs; context components are unimplemented schema vectors, not compiler output.",
"compiler": "2db752d",
"cli_runs": 16,
"baseline_groups": [
{
"case": "ordinary_call_return",
"suffix": "air",
"source": [
"module contract.runtime",
"air 0",
"lang 0.1",
"features [effects]",
"fn @main() -> u64",
"effects []",
"entry:",
" %v = call @leaf()",
" ret %v",
"fn @leaf() -> u64",
"effects []",
"entry:",
" %v = const.u64 42",
" ret %v"
],
"runs": [
{
"fuel": 0,
"quantum": 1,
"exit_code": 5,
"record": {"status": "limit_exceeded", "kind": "fuel", "limit": 0, "steps": 0}
},
{
"fuel": 1,
"quantum": 1,
"exit_code": 5,
"record": {"status": "limit_exceeded", "kind": "fuel", "limit": 1, "steps": 1}
},
{
"fuel": 2,
"quantum": 1,
"exit_code": 5,
"record": {"status": "limit_exceeded", "kind": "fuel", "limit": 2, "steps": 2}
},
{
"fuel": 3,
"quantum": 1,
"exit_code": 5,
"record": {"status": "limit_exceeded", "kind": "fuel", "limit": 3, "steps": 3}
},
{
"fuel": 4,
"quantum": 1,
"exit_code": 0,
"record": {"status": "returned", "value": 42}
}
]
},
{
"case": "helper_trap_last_fuel",
"suffix": "air",
"source": [
"module contract.runtime",
"air 0",
"lang 0.1",
"features [effects]",
"fn @main() -> void",
"effects []",
"entry:",
" call @fail()",
" ret",
"fn @fail() -> void",
"effects []",
"entry:",
" %v = const.bool false",
" assert %v",
" ret"
],
"runs": [
{
"fuel": 2,
"quantum": 1,
"exit_code": 5,
"record": {"status": "limit_exceeded", "kind": "fuel", "limit": 2, "steps": 2}
},
{
"fuel": 3,
"quantum": 1,
"exit_code": 4,
"record": {"status": "trapped", "code": "T0002", "kind": "trap.assert", "function": "fail", "block": "entry", "inst": 1}
}
]
},
{
"case": "call_depth_before_next_fuel",
"suffix": "air",
"source": [
"module contract.runtime",
"air 0",
"lang 0.1",
"features [effects]",
"fn @main() -> void",
"effects []",
"entry:",
" call @rec()",
" ret",
"fn @rec() -> void",
"effects []",
"entry:",
" call @rec()",
" ret"
],
"runs": [
{
"fuel": 1023,
"quantum": 1,
"exit_code": 5,
"record": {"status": "limit_exceeded", "kind": "fuel", "limit": 1023, "steps": 1023}
},
{
"fuel": 1024,
"quantum": 1,
"exit_code": 4,
"record": {"status": "trapped", "code": "T0007", "kind": "trap.call_depth", "function": "rec", "block": "entry", "inst": 0}
}
]
},
{
"case": "linear_owner_across_return",
"suffix": "aji",
"source": [
"module contract.runtime",
"fn pass(o: own<u64>) -> own<u64> effects [] { return move o; }",
"fn main(heap: cap<mem.alloc>) -> u64 effects [mem.alloc] {",
" let owner = own.new(42u64, heap) or trap;",
" let after = pass(move owner);",
" return own.take(move after);",
"}"
],
"grants": ["heap=mem.alloc:4096"],
"runs": [
{
"fuel": 10000,
"quantum": 1,
"exit_code": 0,
"record": {
"status": "returned",
"value": 42,
"stdout": "",
"stderr": "",
"files": {}
}
}
]
},
{
"case": "mapped_helper_trap",
"suffix": "aji",
"source": ["module contract.runtime", "fn fail() -> void effects [] {", " assert(false);", "}", "fn main() -> void effects [] { fail(); }"],
"runs": [
{
"fuel": 10000,
"quantum": 1,
"exit_code": 4,
"record": {
"status": "trapped",
"code": "T0002",
"kind": "trap.assert",
"function": "fail",
"block": "entry",
"inst": 1,
"source_location": {"file": ".zig-cache/contract-gate/runtime/mapped_helper_trap.aji", "line": 3, "col": 5}
}
}
]
},
{
"case": "child_task_global_trap",
"suffix": "air",
"source": [
"module contract.runtime",
"air 0",
"lang 0.1",
"features [effects, ownership, tasks]",
"fn @main() -> void",
"effects [task.spawn, task.wait]",
"entry:",
" %s = task.scope.begin",
" %t = task.spawn %s, @worker()",
" task.join %t",
" task.scope.end %s",
" ret",
"fn @worker() -> void",
"effects []",
"entry:",
" %v = const.bool false",
" assert %v",
" ret"
],
"runs": [
{
"fuel": 10000,
"quantum": 1,
"schedule_seed": 0,
"exit_code": 4,
"record": {
"status": "trapped",
"code": "T0002",
"kind": "trap.assert",
"function": "worker",
"block": "entry",
"inst": 1,
"schedule": {"seed": 0, "quantum": 1, "choices": 1}
}
},
{
"fuel": 10000,
"quantum": 1,
"schedule_seed": 1,
"exit_code": 4,
"record": {
"status": "trapped",
"code": "T0002",
"kind": "trap.assert",
"function": "worker",
"block": "entry",
"inst": 1,
"schedule": {"seed": 1, "quantum": 1, "choices": 2}
}
},
{
"fuel": 10000,
"quantum": 1,
"schedule_seed": 2,
"exit_code": 4,
"record": {
"status": "trapped",
"code": "T0002",
"kind": "trap.assert",
"function": "worker",
"block": "entry",
"inst": 1,
"schedule": {"seed": 2, "quantum": 1, "choices": 2}
}
},
{
"fuel": 10000,
"quantum": 1,
"schedule_seed": 3,
"exit_code": 4,
"record": {
"status": "trapped",
"code": "T0002",
"kind": "trap.assert",
"function": "worker",
"block": "entry",
"inst": 1,
"schedule": {"seed": 3, "quantum": 1, "choices": 1}
}
},
{
"fuel": 10000,
"quantum": 1,
"schedule_seed": 4,
"exit_code": 4,
"record": {
"status": "trapped",
"code": "T0002",
"kind": "trap.assert",
"function": "worker",
"block": "entry",
"inst": 1,
"schedule": {"seed": 4, "quantum": 1, "choices": 2}
}
}
]
}
],
"gc_baseline": {
"fixtures": 9,
"schedule_cases": 13,
"interpreter_runs": 26,
"quantum": 1,
"child_schedule_seeds": 5,
"normal_vs_collect_every_step": "byte_identical",
"detect_races": true,
"source_headers": "// metadata for .aji; ; metadata for AIR"
},
"context_components": [
{
"case": "false_pre",
"expected_code": "T0011",
"primary": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"contract": {
"kind": "pre",
"mode": "runtime",
"phase": "predicate",
"helper": "p",
"task": 0,
"site": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"boundary": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"at": {"function": "p", "block": "entry", "inst": 1, "air_line": 21, "air_col": 2}
}
},
{
"case": "false_post",
"expected_code": "T0012",
"primary": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"contract": {
"kind": "post",
"mode": "runtime",
"phase": "predicate",
"helper": "p",
"task": 0,
"site": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"boundary": {"function": "f", "block": "exit", "inst": 2, "air_line": 15, "air_col": 2},
"at": {"function": "p", "block": "entry", "inst": 1, "air_line": 21, "air_col": 2}
}
},
{
"case": "implicit_post_depth",
"expected_code": "T0007",
"primary": {"function": "f", "block": "exit", "inst": 2, "air_line": 15, "air_col": 2},
"contract": {
"kind": "post",
"mode": "runtime",
"phase": "predicate",
"helper": "p",
"task": 0,
"site": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"boundary": {"function": "f", "block": "exit", "inst": 2, "air_line": 15, "air_col": 2},
"at": null
}
},
{
"case": "predicate_arithmetic_trap",
"expected_code": "T0003",
"primary": {"function": "descendant", "block": "entry", "inst": 2, "air_line": 27, "air_col": 2},
"contract": {
"kind": "post",
"mode": "runtime",
"phase": "predicate",
"helper": "p",
"task": 0,
"site": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"boundary": {"function": "f", "block": "exit", "inst": 2, "air_line": 15, "air_col": 2},
"at": {"function": "descendant", "block": "entry", "inst": 2, "air_line": 27, "air_col": 2}
}
},
{
"case": "callback_fuel_cut",
"expected_status": "limit_exceeded",
"contract": {
"kind": "modify",
"mode": "runtime",
"phase": "callback",
"helper": "update",
"task": 0,
"site": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"boundary": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"at": {"function": "update", "block": "loop", "inst": 3, "air_line": 34, "air_col": 2}
}
},
{
"case": "assumed_post_false_in_child",
"expected_code": "T0009",
"primary": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"contract": {
"kind": "post",
"mode": "assume",
"phase": "predicate",
"helper": "p",
"task": 3,
"site": {"function": "f", "block": "entry", "inst": 0, "air_line": 8, "air_col": 2},
"boundary": {"function": "f", "block": "exit", "inst": 2, "air_line": 15, "air_col": 2},
"at": {"function": "p", "block": "entry", "inst": 1, "air_line": 21, "air_col": 2}
}
}
]
}
@@ -0,0 +1,188 @@
# Contract source elaboration and rooted module-state candidate
Non-normative continuation of [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), [checked representations](contract-invariant-boundaries.md) and [proof/report rules](contract-proof-and-report.md), initially at `8260d35`, with the property/inventory refinement verified against `4cda448`. This proposal adds no implemented syntax, feature or normative rule. It preserves full P6-6, including type/module claims and all four statuses. Hidden globals, visibility, diagnostics/dispatch integration, adoption and vertical delivery are not established here.
## Module invariant and identity
Propose that a module may name its explicitly rooted persistent state with a narrow declaration:
```aji
module account
struct Rep { balance: u64, limit: u64 }
fn within(r: ref<Rep>) -> bool effects [] { return r.balance <= r.limit; }
invariant State = type.checked<Rep, fn within>;
```
`invariant` is contextual only at item start. State is a type binding for exactly the structural checked<R,p> identity; it is not an ordinary struct with a public rep field. Its defining module owns the declaration, while callers own each value. All exposed State values/shared content views satisfy p, even in unlisted functions/importers, because creation and updates use checked.make/modify and ordinary operations cannot manufacture it or mutate representation observations admitted by p. Interior-mutable interfaces may still change ignored members, as required by S. Extraction returns ordinary R with no claim. Neither a singleton nor an invocation of a module constructor is implied.
Correlated owners belong in one representation State: its borrow ancestry protects the joint relation while views are shared. A relation over independently owned roots instead remains a pre/post boundary claim; it can fail between calls. This is not a module-wide persistent guarantee. No new named boundary-group metadata is proposed: listing functions cannot establish that all mutators are listed when fields are public. Ordinary prefix coverage is still checked independently by the AIR verifier.
Choosing rooted state as spec 13's module-invariant model is an owner decision. If hidden module-global state is required, this candidate does not provide it and a separate state/encapsulation abstraction is needed. The module requirement is not silently replaced with function contracts.
Two invariant names with the same resolved R and p denote the same type. Distinct nominal representations remain distinct. This is a narrow checked-type binding, not a general alias facility. Direct type.checked<Rep, fn within> type expressions remain available. A generic declaration uses existing type/static-function parameters, for example `invariant State<T: Copy> = type.checked<Rep<T>, fn within::<T>>;`. Predicates specialize explicitly and must have exactly ref<R> -> bool, no captures, and S membership after substitution. A binding's constraints restrict its use; direct checked types still follow their own R/p validity rules, not an unrelated alias's constraints.
Resolve these bindings before equality, property tests and specialization-key construction. The canonical type key spells `checked<canonical-R,fn canonical-function-identity>`; an alias spelling does not create a different container specialization. Existing type/function keys are unchanged. Imports retain direct-import lookup; no module name is inferred from AIR mangling. Alias-resolution cycles fail with a stable E7006 reason; expansion depth, specialization count and key bytes use the existing 64/4096/16384 compiler bounds. Nominal representation references stop alias expansion; ordinary recursive-layout validation remains independent.
Every concrete declaration must reach AIR type verification even when no value is constructed. Candidate lowering emits a generated identity witness `fn @w(%value: checked<R,@p>) -> checked<R,@p> effects [] { ret %value }`. It is never implicitly invoked, holds no global state and validates the type/predicate through its signature. Linear values transfer on its ordinary ret. Its declaration appears in canonical AIR and the report's ordinary functions list, with no calls or check rows. Generic witnesses are emitted for concrete specializations; known template restrictions still check before substitution. The representation/type-position rules below require parameter/return admissibility, so this witness does not impose an additional position restriction on an otherwise valid checked type.
## Source grammar and explicit operations
Proposed additions to the existing grammar: new clause/declaration introducers are contextual; type/fn reuse existing reserved keywords.
```ebnf
checked_type = "type" "." "checked" "<" type "," "fn" name_path [ application ] ">" ;
invariant_decl = "invariant" ident [ type_params ] "=" checked_type ";" ;
checked_op = "type" "." "checked" "." ( "make" | "view" | "take" | "modify" )
[ application ] call_args ;
contract_mode = "assume" | "document" ;
contract_block = "{" expr ";" { expr ";" } "}" ;
requires_group = "requires" [ contract_mode ] contract_block ;
ensures_group = "ensures" [ contract_mode ] contract_block ;
fn_tail = "effects" "[" [ path { "," path } [ "," ] ] "]"
{ requires_group } { ensures_group } block ;
```
Groups are nonempty, use bool expressions with terminators, and appear after effects. Requires groups precede all ensures groups; relative source order within each class is preserved. No trailing expression substitutes for the semicolon and no clause occurs in the body. Requires/ensures/assume/document remain identifiers outside this header position; old/result remain ordinary names outside ensures. This deliberately replaces spec 13's illustrative clause placement, not today's implemented grammar.
Use existing explicit static-function argument syntax for checked operations:
```aji
let s: State = type.checked.make::<Rep, fn within>(Rep { balance: 0u64, limit: 10u64 });
ref whole = s;
ref raw = type.checked.view(whole);
// A later exclusive scope, after both shared views end:
type.checked.modify::<fn update>(state_borrow, amount);
let plain = type.checked.take(value); // use move value when it is linear
```
Make has two static arguments, representation and predicate. Modify has one explicit static function selection; its first runtime operand is a named exclusive checked borrow, followed by callback extras. View uses a named shared/exclusive checked borrow and returns a shared child; take uses an ordinary whole checked value with the existing move discipline. View/take have no static arguments. The `::` application form is chosen because selecting a static function uses the existing generic-argument syntax; channel.make/buffer.new's type-only dot-step syntax is unchanged. Built-in operations are not selectable function arguments. No runtime function value or special `fn` expression argument is introduced. Whole-value literals initialize R, not State: `State { ... }`, zero State and direct mutable content projections reject. Construction validation is visible in type.checked.make rather than hidden in a struct literal.
The reserved type keyword anchors these new forms. Ordinary modules/functions/types named checked, including user generic `checked<R, fn f>` and self-qualified `checked.make`, retain ordinary lookup. Using checked.* as the built-in namespace would hijack accepted programs; no such reservation or context-sensitive fallback is proposed. Exact source spelling uses type.checked, while AIR operations/type constructors retain checked.* / checked<...>. Grammar integration adds checked_type to types, checked_op to expression primaries, and the view form to borrow-binding calls; it does not admit type names or other checked operations as borrow results.
## Clause roots, result and snapshots
A clause is checked in a separate lexical environment containing original header parameters and directly accessible functions/types; it cannot capture a body local or a reassigned/shadowing body binding. Data parameters may be read by value. Borrow parameters expose a temporary read-only view (mut becomes ref; slice_mut becomes slice), not their writable mode. Owned/authority-containing non-Data values require an explicit shared root observation, such as `valid(ref owner)` or a nested expression block with `ref r = owner;`; they cannot be passed/loaded by value. Ordinary owner unwrap and whole-array/slice argument rules remain explicit. There is no new implicit owner dereference.
Expression blocks may use fresh Data scratch and ordinary P helper calls, including loops. Inline clause/old expressions cannot return from the surrounding function or the generated collector: reject return statements with a stable contract-context reason; break/continue target only loops inside the expression. Named predicate/Data helpers retain ordinary returns. Writing through a header root, synchronization, authority, ambient observations or ownership transfer remains forbidden. The helper is independently checked by AIR P membership; a source purity annotation is not evidence. Capture keys are (original parameter ordinal, value/shared-root form), with projections/adapters inside the helper. Repeated equal keys share an argument; value precedes shared-root form for each ordinal. Old's helper uses the same deduplicated union of captures across all executable old expressions. Post appends its one snapshot-record argument when used, then result observations (value before ref) when used. More than 64 helper arguments, including these, reports the mapped E5101 parameter/argument bounds; do not split a clause silently. This fixes AIR n/E/W independently of syntax repetition. Complete materialization and helper-frame budgets still apply; new observational root shapes require a separate addressability/loan audit rather than assuming that ordinary body SSA becomes addressable.
Inside ensures, unqualified result is the actual return observation, not a body variable or an entry capture. A header parameter or clause-local binder named result conflicts when ensures is present; reject with a stable source reason at the conflicting binder. Ordinary body bindings named result and functions without ensures keep their existing meaning. Void has no result; never has no postcondition. `old(expr)` is recognized as snapshot notation only as the unqualified one-argument call in ensures. If old is also visible there as a local function, parameter or clause binder, the unqualified call rejects with a source name-conflict reason; self-qualified/import-qualified old functions remain ordinary calls. Outside ensures, old calls use ordinary name resolution, not snapshot semantics. Result inside old, nested old and non-Data old results reject. Old's free value roots must be original header parameters; clause locals declared outside expr are unavailable at entry and reject. Local scratch binders declared inside expr remain allowed.
Every runtime/assumed old occurrence is evaluated once, in lexical clause/expression order, after all preconditions and before the body. Even an occurrence in a short-circuited post branch is captured eagerly. It may trap or exhaust fuel before the body; old is not observationally free. Distinct executable occurrences remain distinct slots, even with identical text; no optimizer deduplication changes fuel. All slots lower to one bounded Data record and one contract.old helper. Since ordinary struct.make has a 64-operand bound as well as the 256-member bound, package slots by greedy left-full chunking: zero-based group i holds slots 64*i through min(64*i+63, last). Only the final group may be short; always wrap it in a record, even when it has one slot. Recursively apply this same rule to child records until one root remains. Evaluate all expressions first, then construct each record level left to right, bottom up. A count at most 64 uses one direct record. Fields use their zero-based positions within each record; projection paths follow this fixed tree. Snapshot-record name keys extend the function/specialization key with zero-based level (leaves are 0) and group index. No padding, partial initialization or program heap allocation is introduced; existing type/value/frame/function/instruction bounds still apply.
A documented old(expr) must refer to an equal executable capture already present in this function; choose the first matching executable occurrence. Equality is structural over the typed expression tree, ignoring spans/comments/parentheses, retaining internal local binder spellings and resolved parameter/function/type identities. It is alpha-sensitive: changing an internal scratch binder's name does not match. It is not algebraic equivalence or hash equality. A document cannot add snapshot work of its own. No matching executable capture rejects with a stable source reason; deleting the last executable use must not silently retain a snapshot for documentation alone. This refines the AIR rule allowing documented binding of an existing executable snapshot.
Post helpers receive the snapshot record and result only when needed, alongside original roots. Snapshot field projection happens inside the helper. Original body SSA never enters the prefix binding list. Parameter-free predicates remain possible on main. Generic/static/package calls, recursive calls and spawned workers use the callee's same prefix; returns, implicit tails and ordinary cleanup lead to the same enforced post boundary. Source loan/cleanup machinery must retain required original roots without extending loans past ret or resurrecting consumed values; exact integration tests remain mandatory.
## Generated names and source provenance
First discover all ordinary declarations/specializations needed by bodies and clauses, resolving alias arguments before their existing specialization keys. Allocate their AIR names by today's linking/monomorphization rules, then reserve those names in both declaration categories. Contract artifacts cannot change an ordinary symbol's collision suffix. They are a separate final generation pass; visiting a clause before another body cannot allocate its public/helper names early.
An artifact has the full tuple `(kind,owner,ordinal,level,group)`. Kind is pre, post, old, witness or snapshot. Owner is the existing canonical `fn:` specialization key, or `fn:` plus the full defining-module/function path for a monomorphic function. A witness uses `invariant:` plus the defining-module/declaration path and its ordered canonical arguments when specialized. Its owner retains the declaration identity even if another alias denotes the same checked type. Physical source paths, file labels, spans, diagnostic order and predicate results contribute no key bytes. Owner keys have the existing 16,384-byte compiler-input bound, including these new monomorphic descriptors. The ordinal/level/group are unsigned u32 values in canonical decimal.
Pre/post ordinal counts every clause expression in its class in lexical order across groups, including assume/document. Mode is metadata, not a helper-name component. There is one old collector per function; old and witness use zero ordinal/level/group. Snapshot uses ordinal 0 and the packing algorithm's zero-based level/group. Pre/post use level/group 0. Distinct executable old occurrences retain their separate slots inside the one collector; documents do not add slots. Helpers for documented clauses are still emitted for independent typing/P validation, though they have no executable call edge.
Encode a tuple as these UTF-8 bytes, with LF at every indicated line end:
```text
aji.contract/1\n
KIND\n
OWNER_BYTE_LENGTH:OWNER\n
ORDINAL\n
LEVEL\n
GROUP\n
```
The owner length is canonical decimal and counts bytes. The length prefix makes components unambiguous; full tuples/bytes, not digests, determine identity and reuse. The descriptor adds bounded fixed overhead to its bounded owner; it does not tighten the existing ordinary specialization-key limit. The AIR base is `__aji_contract_` plus lowercase SHA-256 of these bytes. Sort artifacts lexicographically by complete encoding bytes, then allocate the smallest unused positive `_1`, `_2`, ... suffix when the base is occupied. Decimal fields compare as text: ordinal 10 sorts before 2, and owner length 100: before 16:. This is artifact emission order, not clause evaluation order, which remains lexical. Reserve each allocation immediately; handle a digest collision identically to an original-name collision. No user identifier prefix is reserved.
Emit ordinary types followed by snapshot types in artifact order, then ordinary functions followed by helper/witness functions in artifact order; each category retains today's original/generic ordering. Ordinary specialization counters retain their meaning, including specialized invariant declarations; helpers/snapshot records are not additional generic instantiations. All emitted types/functions/instructions/arguments count toward the ordinary AIR limits, including documented helpers and unused witnesses. No new unbounded generation exemption or private runtime storage is introduced. A contract-free input creates no descriptors and keeps today's canonical bytes.
Use the defining declaration/clause map rather than reversing a mangled name. The witness header/ret map to its invariant declaration. A pre/post prefix site maps to its bool expression; the old prefix/collector header map to the first executable old occurrence. Predicate/collector instructions preserve each original expression/subexpression span. Snapshot struct declarations and packing/projection operations map to the first old slot they represent. Explicit checked operations map to the source operation; implicit/tail returns retain today's return/tail span. Helper call/parameter adaptation maps to the source argument/root that caused it, not the surrounding generated name. A deduplicated capture binding maps to the first lexical occurrence of that root/form in its clause; old's capture union uses the first such occurrence across its executable old expressions. A post's snapshot argument maps to its first old occurrence, including a documented reuse; result forms map to their first corresponding result occurrence. Repeated generic specializations retain template spans; supplied static/type argument errors retain application spans. In a clause helper, its header/parameter facts map to that clause expression; a named external helper retains its own header and body spans.
The lowering output carries a separate typed declaration map `(canonical source declaration name, witness function identity, declaration span)` for inventory provenance. It is not parsed from comments or consumed as semantic evidence; verified signature/body/type identity still controls the inventory record. Runtime dispatch retains both the installing site and evaluated boundary, so a post failure reports its clause plus the actual ret separately. Missing exact mappings use the existing primary fallback; related positions omit source coordinates instead of borrowing another mapping. Complete dispatch/trap schema and AIR0 compatibility remain separate gates.
[Naming vectors](contract-naming-vectors.json) retain three current-language source groups at `8df6cac` (ten CLI checks): a generic base plus _1 collision allocates _2, two calls with the same static-function key reuse one specialization, and flattened module-name collisions allocate _2/_3 in canonical module order. Runs return 42 with fuel 10,000. Tested comment/position changes, path changes and import/mapping permutations preserve AIR bytes. Nine proposed artifact descriptors separately pin encoding, digest and collision allocation; hashlib and sha256sum agree. The follow-up ordinal 2/10 pair pins text-byte ordering. They are design vectors, not implemented contract-helper output.
## Representation, properties and positions
Candidate R validity requires ordinary well-formedness, a complete value, and admissibility as a function parameter and return. Borrow/storage/function-bound content is forbidden along the same content edges as aggregate-member checking, including inside owners, buffers and nested checked types. This combines the shallow `types.complete` test with recursive member validity; `complete` alone is insufficient. Void/never, local, ref/mut/slices, task/scope/shield and guard cannot be wrapped to bypass their ordinary position or transfer rules. An iref is an opaque content leaf; its referent still needs ordinary type validity. Ownership cycles through R retain E1003 and existing stage order. R is not restricted to Copy or Data: borrowed linear-state updates are a required use case.
The checked feature itself need not depend on linear_aggregates solely because R is a linear complete value. R's own features remain required, and placing a linear checked value in a field/payload/array or individual own content retains the ordinary linear_aggregates gate. This is a proposed dependency choice, not an allocated feature. All checks repeat after generic substitution; a template is rejected early only for a restriction invalid under every substitution.
| Property/query on checked<R,p> | Candidate rule |
|---|---|
| Copy / linear | exactly R's Copy / linear classification |
| Send / Share / Local | exactly R's corresponding structural property |
| IslandSafe / ArcSafe / Freeze | exactly R's corresponding property; the latter two still equal IslandSafe in format 0 |
| Data | exactly when R is Data; predicate identity is not a value/member |
| Zeroable | false, including constant-true predicates and zeroable R |
| Accounted size | size(R), with no predicate-handle charge |
| Forbidden content / endpoints / capability kinds | traverse R using each existing query's own edge rules |
| Type height / bounded syntax | one checked constructor edge followed by R; predicate identity contributes no edge |
| Ownership/layout cycle traversal | enter R; an iref edge remains non-owning |
Zeroability cannot depend on evaluating p at compile time: zero/local.zero/region zero-fill cannot manufacture a checked claim. Accounted size is not ABI layout. Anonymous checked edges preserve Q-058's nominal-edge size depth, while the separate type-height query counts the constructor. Size/property scans must stay total before type validation, including invalid cycles; use the accounting candidate's fixed-point linearity rather than module-free `Type.isLinear` for representation-dependent answers.
Keep `Type.inner()`'s storage/borrow/element meaning unchanged. Introduce a dedicated representation accessor and explicit checked cases in equality, canonical type keys, property caches/dependency edges, feature/position checks, finite-layout validation, size, source forbidden witnesses, capability inventory and runtime value traversal. A query that currently has an `else` default needs the same audit as an exhaustive switch. Do not make an ordinary borrow or integer operation accept checked content through a generic inner accessor.
| Position/operation | Candidate restriction |
|---|---|
| SSA, parameter, return, block parameter | complete checked value; ordinary linear consumption/edge rules |
| Struct/enum/fixed array, individual own | existing linear-member/content feature gate; no new partial moves |
| Frame local, region content, repeated own_array content | Copy checked values only; zero initialization remains forbidden |
| Buffer | existing complete-member rules and explicit drain obligations |
| Channel element / mutex content | Send and existing recursive endpoint/forbidden-content checks through R; channel_transfer is not bypassed |
| Island/frozen/arc content | existing graph-content property, inherited from R |
| Borrow/slice of checked | ordinary ancestry/alias/loan rules; shared representation access only through checked.view |
| Task argument/result | existing Send/Share and transfer rules |
| Main parameter | checked is not a capability and cannot receive a grant |
| AtomicScalar, arithmetic/casts, field/tag projection | checked remains a distinct type; extract/view R explicitly, then apply ordinary rules |
A whole checked Copy value may be loaded/stored; a linear one uses complete exchange/transfer. Ordinary struct literals, struct.get/unpack, enum.take and borrow.field cannot expose the capsule's R directly. `checked.take` relinquishes only this outer claim, preserving nested checked claims. These restrictions apply in AIR as well as source. Pure/stable closures may view checked roots and take Copy Data content; make/modify remain excluded, and the initial proof normal form still excludes checked extraction.
No ABI layout or foreign transparency is granted by size(R). Current FFI declarations are illustrative/unsupported; this refinement claims no FFI implementation. A future FFI feature must prevent foreign construction/writes from publishing checked values without validation. An ordinary foreign adapter should transport R and validate through make on re-entry; any unsafe promise needs its own explicit obligation and compatibility rules. Casts or serialization cannot confer checked identity.
Propose that canonical run-result rendering recursively renders R, without a checked tag, predicate identity or re-evaluation. Nested struct fields, enum payloads and arrays follow their existing order; opaque values retain their existing rendering. This is output serialization, not an Aji value conversion or validation bypass. Copies/transfers/GC visit the representation exactly as needed for its ordinary values and resource identities; predicate identity remains compile-time metadata with no allocation, refcount or destructor.
## Declared claims in the report
Make/modify rows alone omit a library invariant whose type has no construction site. Append `types` after `rows,totals` in the proposed contracts object; emit an empty array when no checked identity occurs. Contract-free report bytes remain unchanged. Enumerate distinct checked identities in first structural occurrence order: type declarations and members/payloads, then functions in textual order (parameters, return, each block's parameters and instruction type operands). Each walk is preorder, visiting checked identity before R, and follows ordinary type-parameter edges even for phantom iref targets. Visit each nominal declaration once globally and each checked identity once for inventory output; predicate identity is not a traversal edge. Ordinary resolved graph references are required, not string parsing or expansion of shared paths. This is an inventory walk, not the ownership-cycle query. The identity witness ensures concrete unused source declarations are represented. Its ordinary return is not an extra invariant-check row.
Type-record field order is `type,predicate,status,proof,enforcement,declarations`. Type spells `checked<R, @p>` with one space after the comma and ordinary recursive AIR spelling for R; predicate is the resolved function name without @. Proof uses the existing `result,reason,cost,limit` object. Enforcement is always `construction_update`: ordinary copies/transfers do not rerun p. Type invariants have no assume/document mode. Records contribute neither rows nor row totals, and have no separate totals.
Classify p over one universally unconstrained shared R observation (B=1, n=1, D=O=0). The universal root term is keyed by resolved checked identity and root parameter ordinal 0; ordinary field paths append resolved nominal declaration/field ordinals. It represents all raw R values, not only those already satisfying p or seen at make sites. Scalar/Data loads retain the existing eligibility rules, including alongside linear fields. A literal-true ref<R> predicate has H=3,N=1,C=5 and is proven. The Range predicate in the baseline vectors has H=17,N=5,C=23; distinct lo/hi terms leave it not_established. A constant {0,5} make can independently be proven at C=28. Unsupported helpers/bindings and budgets use the same closed fallback order. Proof never eliminates runtime evaluation or promises termination.
Declarations contain supplied source provenance only: ordered objects `name,witness,source`, where name is the canonical source declaration/specialization name, witness is the AIR function name without @, and source is the existing `{file,line,col}` or null. A frontend may supply these records only for its concrete identity witnesses. Before attaching one, require a verified witness with exactly one parameter of this checked type, the same return type, effects [], no trusted/prefix metadata, and one block containing only ret of that parameter. Omit mismatched records; never infer names/modules from mangled symbols. Order by witness function order, then supplied declaration order, deduplicating identical records. AIR-only input has declarations []; missing maps do not suppress a checked identity or alter proof/status. These names/positions make no independent semantic claim. Clearing declarations and other source fields must recover identical semantic reports for identical verified AIR.
The [report vector](contract-report-vector.json) now includes a constant Range make and three inventory identities, one with no construction site. The unused identity still has its universal proof; the modify identity uses an unsupported predicate and remains runtime. This component is proposed research data, not today's CLI output.
Valid target: a module exports State holding two correlated counters; unrelated imported code can share it, exchange it, or update it through a callback, and the persistent relation survives every successful update. An in-place update of a borrowed linear buffer representation needs no replacement allocation. Rejected targets: public field writes into State; callback returning a borrow from R; overlapping update arguments; predicate with mutable atomic observations; zero construction; an invariant declaration with wrong predicate signature even when unused. A boundary relation over separate mutable roots remains valid only at its explicit pre/post boundaries.
## Compatibility and delivery
No new AIR header/type-declaration kind is used. Identity witnesses use ordinary function declarations; checked type operands and operations retain the unknown-constructor/opcode E0004 path, subject to Q-055's dependent-error audit. The evidence below pins complete current spellings without claiming full format-0 compatibility. Source item/header, reserved expression and reserved type positions have the separately recorded E7001/E7002 transitions; existing ordinary identifiers/namespaces are preserved. Wrong static selections/argument types and invalid type positions follow existing E7002/E7005 rules; new source-context conflicts need stable E7006 reasons, not message parsing.
Costs: one narrow named declaration, clause groups, contextual result/old, four explicit checked operations, capture/snapshot elaboration, identity witnesses and type-level audit records. No module-global instance, hidden checking constructor, general alias system, new runtime function values or boundary-group verifier state is introduced. Compare this against inline checked types and nominal checked-struct syntax before adoption. Measure final Quick Reference/source/AIR growth; this research is outside the bundles. Remaining gates include exact mangling/source-map integration, source/semantic diagnostic order, traps and pending dispatch, RFC 0040, Q-055 compatibility, owner model selection and full source/AIR/package/generic/GC/schedule validation. Property/position/rendering and inventory rules above are candidate resolutions, not an accepted feature or completed implementation.
## Verified source compatibility constraints
Nineteen current-language probes at `8260d35` contain no implemented contracts. All source fixtures include main, so unknown-name cases do not accidentally measure a missing entry point. Executions use fuel 10,000.
| Cases | Current result |
|---|---|
| Ordinary functions/parameters named old, result, requires, ensures, invariant, assume, document and checked | accepts; returns 6 |
| Existing explicit static-function application | accepts; returns 6 |
| Invariant declaration / clause header | E7001 |
| Unresolved unprefixed checked type / make / modify | E7002, naming checked / checked.make / checked.modify |
| User module checked calling make/view/take/modify by self-qualified name | accepts; returns 10 |
| User generic struct checked<R, fn p> | accepts |
| Reserved type.checked type position | E7002, naming type.checked |
| Reserved type.checked.make / modify expressions | E7001 |
| A module or type binding named type | E7001 |
| Ordinary Copy / linear AIR identity witnesses | accepts |
| Complete checked AIR identity witness | E0004 alone |
| Flat AIR struct.make with 65 fields/operands | E5101: arguments per call, found 65, max 64 |
| Same 65 values packed into 64/1 leaf records and a two-field root | accepts; returns last value 64 |
The reserved-prefix choice is justified by inability to bind its first component, not by assuming every type position is a syntax rejection. The proposed type form changes an E7002 rejection to acceptance; the expression/item/header forms change E7001 rejections. Existing module checked and generic checked types must keep their meaning. Witness acceptance on ordinary R does not prove all checked type/property positions valid. Claude independently read the recorded results and reviewed name/capture/snapshot rules; no language feature or owner policy is adopted.
At `4cda448`, all twelve previously recorded property probes retain their exit status/code lists: scalar, linear-record, capability, atomic, mutex and buffer identity accept; guard/task/shield transfers reject E0006, borrowed member and linear own_array content reject E1001, and graph resource content rejects E2111. Eight additional [reproducible property vectors](contract-property-vectors.json) verify region/endpoint identity, recursive endpoint gates in channel/mutex, nonzeroable Copy capability, rejected nominal AtomicScalar, E0004 for a complete checked witness, and the ordinary Range predicate returning true with fuel 10,000. Concatenate header/body lines, then run the listed command (run uses the listed fuel). They validate current-language constraints, not the proposed checked feature, universal proofs or inventory output. The property rules incorporate Claude's earlier read-only audit; this refinement has not received a fresh Claude review because the live Herdr channel is unavailable.
@@ -0,0 +1,61 @@
# Contract source errors and AIR compatibility audit
Non-normative completion of the source rejection map for [RFC 0039](../rfcs/0039-verifier-visible-contracts.md), following [source elaboration](contract-source-and-module-state.md), [AIR bindings](contract-air-bindings.md) and [runtime context](contract-runtime-and-context.md). No reason, code, feature or language rule is allocated here. This candidate does not authorize implementation or resolve Q-055.
## Source rejection map
Keep spec 15 §10's frontend/verifier division. Syntax and source-resolvable type/name errors stop before AIR; independently verified access, ownership, purity, stability and status obligations retain their AIR codes and independently mapped positions. A source type mismatch must not become E1001 from a generated helper. New E7006 reasons below are proposed additions to the existing stable registry; existing reasons keep their meaning. No message parsing or parallel `contract_reason` vocabulary is needed.
| Source fact | Candidate code / reason | Primary position |
|---|---|---|
| Malformed/empty clause group, missing terminator, misplaced group or unsupported mode spelling | E7001 with ordinary expected/found | offending token |
| Unknown value/function/type, including a body local absent from the clause environment | E7002 | unresolved name |
| Header parameter or clause binder named result when ensures exists | E7006 / contract_result_conflict | conflicting binder |
| Snapshot-shaped unqualified old call also resolves to a visible function/parameter/binder | E7006 / contract_old_conflict | call target old |
| Inline return in a clause or old expression | E7006 / contract_return | return keyword |
| Nested old inside executable/documented old expression | E7006 / contract_old_nested | inner old call target |
| result referenced inside old expression | E7006 / contract_old_result | result occurrence |
| old expression refers to a known enclosing clause-local binder rather than an original header root or its own scratch local | E7006 / contract_old_capture | captured name |
| Documented old has no structurally equal executable capture | E7006 / contract_document_old | documented old call target |
| Checked alias-resolution cycle | E7006 / invariant_cycle | reference that closes the active resolution chain |
| Non-bool clause; non-Data old value; result on void; any ensures group on never | E7005 with expected/found | clause expression; old argument; result occurrence; ensures keyword, respectively |
| Wrong checked predicate/callback signature or static argument kind | E7005 with existing static-signature fields where applicable | supplied fn/type argument |
| Wrong runtime operand type/mode, including mutable projection through a checked representation | E7005 with expected/found | operand/place |
| State { ... } attempts to construct a checked alias as a struct | E7005 | literal's type name |
| zero State or zero of a containing non-zeroable type | E7006 / zero_not_zeroable | zero expression |
| break/continue outside a loop within the inline expression | E7006 / loop_control_outside_loop | control keyword |
| Existing explicit transfer, borrow-binding, duplicate declaration or static-function restriction | existing source code/reason | existing position |
| Source alias/specialization depth, instance count or key-byte bound | E7006 / implementation_limit | existing expansion/application position |
| Generated helper exceeds AIR argument, frame, value or virtual-boundary bounds | E5101, mapped through generation provenance | offending root/clause/declaration mapping |
There are eight proposed reason additions, all for newly introduced constructs. Ordinary unknown names remain E7002 even inside old. The special capture reason requires a resolved enclosing clause-local identity; it must not be guessed from spelling. Unqualified old recognition remains exactly the source candidate's one-argument ensures form. Qualified old calls, old outside ensures and body bindings named result retain ordinary rules.
Check conflicts before binding the special result/old forms; classify nested old and result within old before checking snapshot value type or document matching. Type-check a documented expression before searching for an equal executable capture. A matching capture is still eager work, not proof that its expression terminates. Alias-cycle detection uses the active resolved alias identities; an ordinary nominal representation reference stops alias expansion, while finite-layout validation remains a separate obligation.
Existing global/signature phase stops, first body error per source declaration, generic-template skipping, limit 32 and code/location dedup remain in force. These rules do not make malformed or type-invalid clauses reach the AIR verifier to collect extra purity errors. Once typed lowering succeeds, P membership precedes S membership, and ordinary access errors remain factual access errors. Generated headers, deduplicated roots, snapshot projections and actual source helper instructions use the already specified provenance map; no generated-name parsing or fabricated source binder is introduced.
The table is a delivery checklist, not compiler output. Vertical tests must pair every new rejection with a valid neighbor: ordinary body result; qualified old; inner scratch rather than outer capture; own loop rather than outer break; Data old rather than non-Data; executable/documented matching versus mismatch; nominal recursion versus alias cycles. Existing E7006 reasons and contract-free CLI records must remain unchanged.
## Executed format-0 rejection baselines
[Ten current-language vectors](contract-compatibility-vectors.json) at c633f23 retain complete source and emitted diagnostic fields except the physical file label. All are `aji check` calls, exit 1; no runtime/model experiment is involved. Relevant helper declarations are included so their absence does not explain a future rejection. The old parser has not been executed.
| Case | Current codes | Audit obligation |
|---|---|---|
| Unknown pre; unknown checked signature | E0004 each | named opcode/type exception candidate |
| Unknown old/post | E0004, E0004 | independently classify both registered names |
| Old snapshot used in ordinary body | E0004, E5001(%old) | still invalid under the proposal; a transition to snapshot_escape changes the code list |
| Pre plus unrelated undefined operand | E0004, E5001(%missing) | recognizing pre cannot erase the independent SSA defect |
| Old body escape plus unrelated undefined operand | E0004, E5001(%old), E5001(%missing) | identical codes conceal different causes; retain value identities and positions |
| Checked make/take, returned take result | E0004, E0004, E5001(%r) | ordinary use of a newly defined result is not the forbidden snapshot escape |
| New requires header | E0001 | outside the named-opcode/type exception |
| Ordinary undefined operand | E5001 | no extension-related cause |
| Unknown contracts feature | E0006 / unknown_feature | current header stop, not evidence for future construct validation |
The checked make/take example is intended to become valid with the proposed feature and pure predicate; the old body escape is intended to remain invalid. Neither result is implemented or claimed by these baselines. Comparing only acceptance, the first code or aggregate code frequencies misses the rejection-compatibility question.
Spec 07 §8.7 requires preservation of accepted behavior/canonical form and rejected codes, with an exception for names formerly rejected E0004/E0006. It does not explicitly decide whether the exception includes dependent undefined-result diagnostics in a mixed list. A possible **owner policy**, not adopted here, would restrict that exception to the newly recognized construct and facts causally dependent on it, preserving unrelated invalid operands. It would need an explicit normative rule and a complete parser/stage audit, not a blanket waiver whenever E0004 occurs. Alternatively, an RFC can introduce AIR1 while retaining AIR0 unchanged. Header E0001 is a distinct issue; these opcode probes cannot legitimize it.
## Remaining adoption and delivery gates
The source rejection map and runtime schemas are now concrete candidates. Owner decisions remain: rooted caller-owned state versus another module-invariant abstraction; Q-055's version/compatibility policy; and adoption of the RFC 0039/0040 representations. They are not resolved by continued probe collection. Once chosen, integrate complete normative/reference rules, register features/codes/reasons, and deliver verifier/interpreter/frontend/formatter/report/Quick Reference changes with positive and negative AIR/source fixtures, GC and schedule coverage, contract-free compatibility checks and measured bundle growth. Full P6-6 still includes module/type claims and all four statuses. RFC 0039 remains Draft.
@@ -0,0 +1,486 @@
# Control-depth performance audit (Q-063)
## Scope and reproduction (2026-10-14)
Q-063 has several independent causes. Repeated liveness queries dominate the
mutable-match case, textual incoming-edge searches dominate loop lowering,
and shield relations dominate verification. This profiling change does not
optimize production code or close Q-063.
The measured binary is a fresh Debug `zig build` at
`17cbe3eb4ea9cf7ec2d811613ebb1b9e3affb976`, Zig 0.17.0, SHA-256
`527dbce1cdd80d48ed3e5c14c6c6a814aa016e2421fb5e7ffa5260545e5b8216`.
Generated fixtures and raw evidence are in
`/tmp/aji-q063-profile-20261014-jeo0_cfr/`: `provenance.json`,
`timings.jsonl`, `summary.json`, generated `.aji`/`.air`, and five
`*.profile.json`/`*.gdb.log` pairs. These local artifacts are not versioned.
The harness is retained as [`tools/profile_control_depth.py`](../../tools/profile_control_depth.py):
```sh
zig build
python3 tools/profile_control_depth.py --depths 32 64 128 256 512 --repeats 3
```
The default maximum depth is 256 to keep reproduction practical. It generates
scope/shield nesting, `while false`, loops with a reachable `break` at every
level, and integer matches with one nested arm and one empty default arm.
The `*_live` variants assign `x = x + 1u64` at the leaf and return `x` after
the outer construct. Other variants have one immutable leaf binding and return
zero. These are generated public-language probes, unrelated to evaluation tasks.
Each fixture is lowered, its AIR checked, and its source checked, with three
repetitions per command: 315 commands, all exit 0 with empty diagnostics.
Repeated lowerings are byte-identical. The retained harness additionally passes
a 42-command smoke run at depths 2 and 4, one repetition, all seven shapes.
No runtime execution, fuel consumption or scheduler behavior is measured.
No wall-clock timeout terminates a command. Timings include process startup,
allocator cleanup, and command-specific I/O; the AIR check includes AIR parsing.
They are medians on one machine, not portable limits or exact complexity proofs.
## Stage timings
Seconds, shown as **128 / 256 / 512 levels**:
| Shape | Source lowering | AIR parsing + verification | Full source check |
|---|---|---|---|
| scope | 0.039 / 0.060 / 0.091 | 0.029 / 0.029 / 0.031 | 0.046 / 0.062 / 0.098 |
| shield | 0.041 / 0.069 / 0.092 | 0.093 / 0.363 / 1.991 | 0.109 / 0.412 / 2.034 |
| while | 0.086 / 0.208 / 0.628 | 0.036 / 0.064 / 0.164 | 0.104 / 0.248 / 0.749 |
| loop | 0.039 / 0.062 / 0.141 | 0.027 / 0.044 / 0.079 | 0.045 / 0.080 / 0.190 |
| match | 0.060 / 0.099 / 0.178 | 0.044 / 0.062 / 0.161 | 0.072 / 0.135 / 0.321 |
| while_live | 0.130 / 0.373 / 1.235 | 0.041 / 0.072 / 0.177 | 0.147 / 0.413 / 1.398 |
| match_live | 0.558 / 3.973 / 31.827 | 0.035 / 0.068 / 0.171 | 0.587 / 4.083 / 31.819 |
The mutable-match lowering grows by about 7.1× and 8.0× for successive depth
doublings, consistent with cubic work in this fixture. The no-mutation control
is much cheaper. Shield lowering stays close to scope lowering while checking
the generated AIR reproduces almost the whole source-check cost.
## Sampled stacks and source inspection
GDB launches each target as its child, interrupts at roughly 20 ms intervals,
records up to 41 frames and resumes until normal exit. All five targets and
their debuggers exit normally. These are inclusive stack-presence counts,
not additive CPU percentages; debugger overhead and the small samples limit
precision. Profiling is separate from the timing matrix.
| Target | Samples | Observed path |
|---|---|---|
| match_live, 256, lower | 195 | `liveAfter` in 186; `liveness.Workspace.query` in 188 |
| while, 512, lower | 30 | `finishDriveLoop` → `reaches` in 23 |
| while_live, 512, lower | 60 | `reaches` in 27; liveness query in 22 |
| loop, 512, lower | 6 | `reaches` in 3; too few for a precise proportion |
| shield, 512, check | 101 | `borrow.checkFunction` in 96; `provenance.State.kill` in 49 |
**Mutable matches:** `prepareDriveValueMatch` calls `carriedLive`, which calls
`liveAfter` for assigned mutable bindings. `liveAfter` walks enclosing rest
frames and searches their containing statement/expression with a fresh `After`
cursor. Nested matches therefore revisit ancestor subtrees at many levels.
The stacks and mutation control support this as the principal cause of the
measured cubic behavior. A cache keyed only by variable name would be invalid:
construct position, rest-frame context, rebinding/kills and loop reads matter.
**Loops:** `finishDriveLoop` calls `reaches` for every exit block. This helper
does not traverse a reachability graph: it searches the text of all emitted
instructions for a reference to the target block name. Repeating this for
nested exits produces quadratic worst-case scanning independently of liveness.
The stacks show it dominates the measured no-mutation while lowering. Mutable
while lowering additionally spends substantial time on liveness queries.
**Shields:** `borrow.step` records an `.inner` relation for each new shield
against every live outer shield: n(n−1)/2 facts at maximum depth. Both event
replay and the checking walk apply those relations. `provenance.State.kill`
scans the whole fact list when a shield ends. For simple nested shields, a
full pop sequence scans lists whose lengths sum to (n³−n)/6 per complete
application of that sequence (22,369,536 fact visits at n=512). This is a
source-derived count, not an instrumented measurement. Relation insertion,
hash-table growth, access checks and replay add cost. A lowerer liveness cache
cannot remove this verifier cost.
## Follow-up order
1. Replace repeated textual incoming-reference searches for loop exits with
explicit incoming-edge metadata. This is the smallest isolated candidate;
preserve the helper's actual reference-existence behavior, including
references from blocks whose execution is unreachable.
2. Design context-correct reuse or indexing for liveness searches, starting
with mutable-match ancestor rescans. Preserve pruned SSA sets, first-use
kills, rebinding barriers, diagnostics, host-OOM propagation and publication.
3. Separately optimize shield relation representation or removal. This changes
verifier implementation and needs review of exact shield-order joins,
resource handoff, E3002/E4305 priority and deterministic behavior.
Each optimization needs independent positive/negative coverage and exact
old/new lowering, diagnostics and observable-runtime comparisons appropriate
to its scope. The present work changes only a profiling tool and documentation:
no verifier/runtime rule, language feature, accepted-depth limit, diagnostic,
instruction, agent bundle or benchmark claim changes. Residual AIR verification
growth for while/match is visible but not assigned a specific cause by these
profiles. Q-063 remains open for implementation decisions and those remaining
measurements; Q-060's composite closure and the B1 gate on P7/P8 are independent.
## First optimization: loop-exit reference index (2026-10-14)
`Lowerer.reaches` now looks up a function-local index instead of scanning all
previously emitted instructions. `emit` indexes references to generated
`after_N` exit names. Keys borrow the instruction text's arena lifetime; the
index resets for each function. It reserves both index and instruction
capacity before publishing either, so metadata OOM cannot leave a phantom
reference or an emitted instruction absent from the index. Queries allocate
nothing. Metadata grows with distinct referenced exit names; arena storage is
released with the caller's arena, not immediately at the function reset.
Inspection and frozen-CLI probes found that the old predicate also counted
calls to functions with colliding names, including references emitted before
the exit block existed, and used only the first substring match per
instruction. These are preserved exactly and logged as
[Q-064](open-questions.md#q-064--loop-exit-reference-search-confuses-function-and-block-names).
Consequently this increment indexes the old reference predicate rather than
changing it to actual CFG-edge reachability. References from unreachable
blocks still count. The frozen control oracle retains the independent old
full scan; it does not share the new query.
Paired Debug measurements use the frozen and changed binaries on CPU 0 with
inherited process affinity, alternating before/after order, two warmups per
binary/shape, and seven measured repetitions per version. All source and AIR
bytes match. Medians for `lower`, at 512 levels:
| Shape | Before | After | Before / after |
|---|---|---|---|
| scope (control) | 0.0927 s | 0.0952 s | 0.97× |
| while | 0.6291 s | 0.1956 s | 3.22× |
| loop | 0.2169 s | 0.1174 s | 1.85× |
| while_live | 1.2246 s | 0.6800 s | 1.80× |
The control is 2.7% slower in this batch; the index has emission overhead and
these finite timings do not establish a statistical bound on that overhead.
Earlier unpinned batches had substantial control timing variation, so they are
not used for the quoted speedups. This removes the repeated full-function
search, not liveness rescans or AIR verification costs, and does not establish
linear whole-pipeline complexity.
Validation:
- `zig build test` exits 0 with the production change and the first two new
index tests; the final additional function-isolation/public-OOM cases and
both index tests pass in a focused `zig test --test-filter 'loop exit'`
run (8/8 including import-discovery tests). The emission test injects every
allocation failure before publication. Public lowering tests inject each
recovering and persistent allocation failure and check full arena release.
- All 1,799 current conformance files pass, terminal exit 0, with exact unique
coverage, no missing/extra/duplicate or nonpassing records.
- All 1,429 public source conformance files plus four function-name collision
probes retain exact `check` and `lower` exit/stdout/stderr: 2,866 comparisons.
- Six finite loop/shield examples, in source and AIR, retain exact run records
and exits at fourteen fuel values: 168 old/new pairs. Valid nested loops
with `break` still return normally; a divergent loop followed by a statement
still rejects E7006, subject to the explicitly preserved Q-064 collision.
- Zig format and diff whitespace checks pass. No new verifier rule needs a
conformance pair: this increment changes metadata, not source/AIR semantics.
Evidence is in `/tmp/aji-q063-reaches/`: `aji-before`,
`conformance.audit.json`, `parity.audit.json`, `runtime-parity.json`,
`clean-before/`, `clean-after/`, `pinned-timings.jsonl` and `pinned-audit.json`.
The old binary hash is recorded above; the measured new Debug binary is
`46a1c15b25e84729ce03d24e04aeead05c4835ddb2355c64dd64f14d248e067a`.
No wall-clock timeout ends a run. No ownership/borrow/resource invariant,
runtime operation, fuel/scheduling rule, diagnostic, feature, normative text,
agent bundle or accepted-depth limit changes. Q-063 remains open for liveness
and shield improvements; Q-064 is a separate correctness follow-up.
## Second optimization: negative After-query reuse (2026-10-14)
`liveAfter` now keeps one stack-local memo while walking outwards through Rest
frames. It reuses a completed **negative subtree After query**, not the answer
to whole-variable liveness. The key includes the immutable control payload's
AST identity/kind and positional span, variable name and construct position.
Supported expression roots are if, match and block; other forms retain the
original traversal. There is no name-only or function-wide result cache.
The proof carried by an entry is narrow: the query entered with `seen=false`,
found the construct and returned no later read. An enclosing unseen traversal
of exactly that subtree can set `seen=true` and resume its existing work stack.
Sibling-arm exclusion and loop-back continuations therefore retain their old
state transitions. A query entered with `seen=true`, an absent construct,
a positive result, another AST node/name/position or a failed query cannot
supply this proof. Statement wrappers seed an expression entry only when their
position checks agree. The existing position-only span policy, including
cross-file position comparisons, is unchanged.
First-use kills, pattern rebinding, enclosing-rest order, loop reads and
assignment queries still run in their original order. The memo resets for each
`liveAfter` invocation, allocates nothing and retains one entry regardless of
source depth. Successful reuse may avoid scratch allocations; every actual
scratch OOM still propagates and clears pending work before any memo publication.
The governing pruned-SSA rule in spec 15 section 4, diagnostics, accepted source,
canonical AIR and interpreter/fuel rules are confirmed unchanged.
### Measurements
Seconds for mutable-match lowering; medians of three measured runs.
| Depth | Before | After | Before / after |
|---|---:|---:|---:|
| 128 | 0.560870 | 0.093792 | 5.98× |
| 256 | 3.991630 | 0.220675 | 18.09× |
| 512 | 30.981500 | 0.635286 | 48.77× |
Other shapes at depth 512:
| Shape | Before | After |
|---|---:|---:|
| scope | 0.093227 | 0.091937 |
| shield | 0.094780 | 0.094081 |
| while | 0.180449 | 0.179080 |
| loop | 0.074227 | 0.074617 |
| match | 0.182518 | 0.183027 |
| while_live | 0.674470 | 0.675189 |
The six depth-512 controls change by at most 1.4% in this batch. The series
contains 126 measured lowerings, 42 warmups and 42 final source/AIR acceptance
checks. These controls do not establish a universal overhead bound.
The paired Debug series compares the frozen first-optimization executable
against this increment on CPU 0: depths 128/256/512, all seven original public
probe shapes, one warmup per case/version and three measured repetitions.
Version order alternates and case order rotates. All generated sources match
the preceding audit's fixtures; every lowering has identical AIR. No builds or
correctness suites run alongside the timed series. The reports retain wall/CPU
and wait4 peak RSS (the latter can include the launcher's pre-exec memory).
These are lowering measurements on one machine, not a portable complexity or
whole-compiler latency bound. Source/AIR acceptance is checked separately.
Repeated ancestor descent is avoided on the audited nested-match path, but
assignment/read queries, positive After queries, unsupported root shapes and
AIR verification still have their prior costs. Q-063 therefore remains open;
shield relations and Q-064 are independent follow-ups.
### Validation and evidence
- Full unit suite: **341/341**, terminal exit 0. Four new tests cover exact
memo keys, already-seen state, statement/expression position mismatch,
pre/post-boundary scratch OOM, frozen Rest-frame comparisons with kills,
competing siblings and loop reads, and 4,096 enclosing control frames with
bounded query scratch. Existing recovering/persistent OOM and frozen
liveness/CFG/error-order tests pass. The focused selection is 9/9 including
five import-discovery tests.
- All **1,799** conformance cases pass with exact unique inventory, no missing,
extra, duplicate or nonpassing records.
- All **1,429** public source conformance inputs and ten new finite positive/
negative probes retain exact old/new `check`/`lower` exits, stdout and stderr:
**2,878 comparisons**. Four Q-064 collisions add eight exact comparisons.
- Eight positive new probes, in source and AIR at fifteen fuel values, retain
**240** exact run-record/exit pairs. They include nested mutation, straight-line
kills, competing-arm reads, loop backedges, continue, shadowing, returns and
independent variables. The negative probes preserve assignment/type errors.
- The existing hosted liveness-depth suite passes **418** CLI checks through
depth 65,536, including formatting, source/AIR, exact fuel and hosted records.
That run used a separately retained production-identical build before a
test-only setup correction; final unit/parity/timing artifacts use the
corrected test source. Both native hashes are retained in the provenance.
- Zig formatting and patch whitespace checks pass. No new verifier rule,
language feature, diagnostic, semantic flag or normative limit is introduced.
Evidence is under `/tmp/aji-q063-review-20261014-se2oa131/liveness/`:
`baseline.json`, `source.json`, `unit-final.log`, `focused.log`,
`conformance-audit.json`, `parity-audit.json`, `runtime-parity.json`,
`collision-parity.json`, `hosted-liveness.log` and `performance/` with sources,
old/new AIR, provenance, warmups, timings, summary and acceptance checks.
Reproduce generated probes with `tools/profile_control_depth.py`; freeze each
Debug binary, pin the launcher to one CPU, and rotate versions on identical
inputs. The exact paired driver is retained as
`/tmp/aji-q063-liveness-performance.py`. No wall-clock timeout ends a command.
## Correctness follow-up: explicit CFG incoming edges (Q-064, 2026-10-14)
The compatibility index in the first optimization deliberately retained the
old textual predicate. Q-064 is now corrected independently: each frontend
block records whether an emitted terminator targets it, using block indices
supplied by the lowering construct. `term` requires an explicit successor
slice; `select` passes its existing outcome records without allocating a new
index. `ret` and `trap` have no successors. The loop-completion query reads the
exit block's bit in constant time. Instruction emission no longer searches
text or allocates a loop-exit hash table.
The bit starts false with each new block and is published only after the
instruction append succeeds. There is no fallible step between publishing a
terminator and recording its edges. Targets exist before emission; no names,
source operands, calls or textual prefixes take part in the query. Edges from
syntactically emitted but disconnected blocks still count, and constant
conditions are not folded. This preserves the prior conservative CFG policy
apart from the naming defects; it does not add reachability analysis.
Two corrected cases demonstrate why the separate correctness change is
needed:
- A helper call `after_2()` inside `loop { after_2(); return 0u64; }` previously
supplied a phantom incoming edge to the loop exit. A following statement now
rejects E7006 `unreachable`, as spec 15 §10 requires. Trap, continue, nested
loops and function-state reset have corresponding rejection fixtures.
- A boolean parameter `after_2` (or the prefix `after_20`) previously masked the
genuine `@after_2` exit later in a conditional branch instruction. A reachable
statement after `while after_2 { return 1u64; }` now accepts. Both boolean
outcomes execute correctly; real break edges remain valid even when the
same helper name occurs.
Validation uses Zig 0.17.0, Debug, with a frozen pre-fix executable containing
both Q-063 optimizations. The complete public corpus, without held-out or
untracked evaluation material, gives:
| Check | Result |
|---|---|
| Unit suite, including emission OOM and recovering/persistent lowering OOM | 342 passed |
| Conformance, including nine new source fixtures | 1,808 passed |
| Pre-existing public sources: exact check/lower exit, stdout and stderr | 2,858 pairs on 1,429 files, no differences |
| New fixture check/lower comparisons | 18 pairs; 14 intentional corrections, four exact |
| Existing finite source/AIR runtime and fuel comparisons | 240 exact pairs |
| Targeted collision/diagnostic/format/package CLI suite | 182 passed |
| Existing diagnostic-reason suite | 236 passed |
| Existing independent-error suite | 234 passed |
| Existing CFG-provenance suite | 146 passed |
| Hosted smoke, including local TCP sockets | passed |
| Zig formatting | passed |
The incoming-edge unit oracle independently parses emitted AIR and obtains
successors from AIR operations for ten programs covering loops, joins, short
circuiting, integer/enum/builtin matches, fallible outcomes, lock, select and
linear aggregate unpacking. It compares every function's block bits with
those parsed successors. The old textual predicate remains frozen in the
control compatibility oracle; the two collisions are tested as deliberate
old/new differences rather than silently changing that oracle.
The targeted CLI suite checks E7006 reason and exact source position,
diagnostic ordering before and after divergence, independent function errors,
canonical formatting, package provenance, both loop-condition outcomes and
source/AIR fuel equality. Five erroneous acceptances now reject; two erroneous
rejections now accept. Other public acceptance, diagnostics, canonical AIR and
finite runtime/fuel behavior are unchanged. AIR format 0 and its verifier and
interpreter semantics are unchanged. No portable performance bound is claimed
for this correctness slice; Q-063's remaining liveness and shield work remains
open.
Reproduction and qualification artifacts are retained in
`/tmp/aji-q064-20261014-x_a6b4gb/`: `baseline.json`, frozen binaries,
`reproduction.json`, `parity.jsonl`, `collision-changes.json`,
`runtime-parity.jsonl`, `parity-audit.json`, `unit-final.log`,
`conformance.jsonl`, CLI-suite logs and `qualification.json` with source and
executable hashes. The reproducible targeted test is
`python3 tests/hosted/source_loop_exit.py`.
## Third optimization: indexed resource relations (2026-10-14)
`provenance.State` now keeps an insertion-ordered active list, endpoint
adjacency lists and lists by relation kind. A fact retains its complete
identity: kind, both value IDs and the loan's spawn span. Duplicate insertion
keeps the original position. `kill(v)` unlinks only facts whose first or second
endpoint is `v`, including self-edges exactly once. It neither compacts nor
scans unrelated facts. The killed endpoint bucket remains pinned until its
chains are empty; Zig 0.17's hash-map removal tombstones other buckets without
relocating them. Removed node slots are recycled, so one state's node storage
tracks its live-fact high-water mark rather than historical insertions.
`borrow.step` checks E4305 through the ended shield's second-endpoint list,
retaining the old live-subject filter and first-conflict choice. Generic access
checks visit only loan facts; borrow-end guard checks visit only guards, and
scope-end checks visit only that scope's target list. These restricted lists
preserve the corresponding full-list order. Whole-state clone, union and
simultaneous edge/handle renaming still traverse surviving insertion order.
Exact shield joins compare the same `.inner` set and choose the same first
mismatching resource. No fact is inferred or discarded by the new indexes.
The internal relation-kind tag is explicitly `u32`. This leaves the fact's
five scalar words without padding and selects Zig's standard byte-hash path
instead of recursive field hashing in Debug. Fact equality, printed names and
AIR are unchanged. Membership insertion is rolled back if subsequent host
growth fails; endpoint, kind and order links are published only after growth
succeeds. Clone/rename replacement is published only after the replacement is
complete. Removal and iteration allocate nothing. The checker still returns
actual host allocation failures as `error.OutOfMemory`.
### Paired timing and memory
Zig 0.17.0, Debug, CPU 0; one warmup and three measured repetitions per binary
and case, alternating version order. Both frozen executables receive the same
bytes. Twenty lowering preflights produce exact identical AIR. Timings cover
shield depths 128/256/512/1024 through AIR checking and full source checking,
plus six source controls at 512: 28 warmups and 84 measured commands. All
commands accept cleanly. Each child's CPU time and peak RSS come from `wait4`.
These are finite measurements, not portable latency or whole-compiler bounds.
| Shield depth | AIR check seconds, before → after | Source check seconds, before → after | Source speedup | Source RSS MiB, before → after |
|---|---|---|---|---|
| 128 | 0.0903 → 0.0934 | 0.1277 → 0.1092 | 1.17× | 20.4 → 20.4 |
| 256 | 0.3623 → 0.3166 | 0.3948 → 0.3499 | 1.13× | 24.0 → 44.9 |
| 512 | 1.9534 → 1.1833 | 1.9848 → 1.2405 | 1.60× | 56.4 → 120.9 |
| 1024 | 14.8610 → 7.6246 | 12.1542 → 5.0732 | 2.40× | 166.8 → 400.9 |
The endpoint/kind indexes trade memory for reduced scanning. The larger RSS
is material; small-case RSS can include the runner's inherited process floor.
The implementation still creates n(n−1)/2 shield-order facts. A complete
innermost-first pop now removes each such fact once per state application,
rather than visiting lists totaling (n³−n)/6 entries; hash-table work has
expected constant cost per lookup/removal. Creation, cloning, live-value
checks and other verifier passes remain. Reducing the quadratic fact count or
index footprint is separate work, so Q-063 stays open.
Source-check controls at 512 (seconds):
| Shape | Before | After | Change |
|---|---:|---:|---:|
| scope | 0.097691 | 0.098552 | +0.9% |
| while | 0.305123 | 0.308303 | +1.0% |
| loop | 0.128656 | 0.134261 | +4.4% |
| match | 0.317832 | 0.324534 | +2.1% |
| while_live | 0.825396 | 0.828236 | +0.3% |
| match_live | 0.770816 | 0.782526 | +1.5% |
### Correctness and concurrency invariants
This is an implementation optimization of existing spec 04 §34/§37.3,
spec 06 §6 and spec 08 §11. The AGENTS.md memory/concurrency checklist is:
| Contract | Preserved behavior and evidence |
|---|---|
| Invariant | Identical fact membership and survivor order; loans retain task, borrower and spawn origin; both endpoints are killed |
| Verifier | Innermost shield ending (E4305), exact incoming shield order (E3002), loan/scope/guard transfer and existing error recovery |
| Runtime | Interpreter, shield depth, pending cancellation and scheduler rules are unchanged |
| Valid example | `shield_index_handoff.air`, `shield_index_reuse.air`, and source `layer8/shield_index_reuse.aji` |
| Rejected example | `shield_index_first_conflict.air` and `shield_index_join_priority.air` |
| Diagnostic impact | Same codes, order, conflict/resource names, source/AIR positions and loan-related locations |
| Determinism | Exact old/new records and exits at finite fuel, quantum and scheduler choices, plus scheduled conformance runs |
| Compatibility | All public source/AIR comparisons below are exact; AIR format 0 and source rules are unchanged |
Validation on the final source and executable:
- **348 unit tests**, including the frozen compact-list oracle over 2,304
mixed operations with duplicates, self-edges, deletion/reinsertion, clones,
self/ordinary merges and simultaneous renaming. Both indexes and kind/order
links are checked against that independent oracle. Storage reuse and
allocation-failure probes cover empty and grown indexes, atomic publication,
deduplicating rename and complete arena release.
- **1,813 conformance cases** pass with unique complete inventory, including
five new cases. The three new run cases use 32 scheduler seeds each; existing
cancellation/resource tests retain their own scheduled runs.
- **3,252 exact old/new comparisons** on 1,813 public files: check all 1,439
source and 374 AIR files, and lower every source file. Exit, stdout and
stderr match byte for byte, including rejections.
- **378 exact runtime/fuel/schedule pairs** on nine source/AIR inputs, including
pending cancellation under a shield, resource handoff, returned loans,
repeated cancelled join and task-loop propagation. Two quanta, three
scheduler seeds and seven fuel values are compared; final-fuel results are
checked against the fixture's expected value.
- Targeted shield CLI suite: **291 checks**; existing CFG-provenance suite:
**146 checks**; related-location suite: **409 checks** with 220 context
records. These cover first E4305 conflict after node reuse, E3002/E4305
priority at a join, source formatting/AIR fidelity and hosted execution.
Hosted smoke, including local TCP sockets, and Zig formatting pass.
The frozen baseline contains both earlier Q-063 optimizations and Q-064. Raw
qualification is in `/tmp/aji-q063-shield-20261014-y7i34hqh/`:
`baseline.json`, frozen executables, `unit-final.log`,
`conformance-final.jsonl`, `parity.jsonl`, `runtime-parity.jsonl`,
`performance-final/` and `qualification.json` with source/binary hashes. The
first endpoint-only experiment and intermediate sources remain separately
labelled; they are not the final qualification. The reproducible targeted suite
is `python3 tests/hosted/shield_relations.py`.
+68
View File
@@ -87,3 +87,71 @@ Reason: format 0 is frozen; features make it an extensible protocol without an o
AIR format 0 defines `max_value_size` = 1 048 576 bytes. Every materializable type in a module has an accounted size (spec 08 §7.1, a platform-independent metric, not a layout) of at most this value; violation, including overflow while computing a size, is `E5101`, checked during module validation. `max_local_frame` (1 MiB per function) is a separate guarantee. Neither depends on host memory. AIR format 0 defines `max_value_size` = 1 048 576 bytes. Every materializable type in a module has an accounted size (spec 08 §7.1, a platform-independent metric, not a layout) of at most this value; violation, including overflow while computing a size, is `E5101`, checked during module validation. `max_local_frame` (1 MiB per function) is a separate guarantee. Neither depends on host memory.
Reason: a verified IR needs its own deterministic validity limits instead of inheriting host behavior; and large data should live in storage reached through borrows, not travel as SSA values. Total allocation is bounded separately in Phase 2, as fuel bounds execution. Reason: a verified IR needs its own deterministic validity limits instead of inheriting host behavior; and large data should live in storage reached through borrows, not travel as SSA values. Total allocation is bounded separately in Phase 2, as fuel bounds execution.
## DD-016 — Explicit block statement boundaries
Spec 15 §4 and the grammar resolve Q-040 syntactically: leading bare `if`, `match` and `{…}` finish before outer expression operations in statement/tail position. A final construct remains a tail; `;` explicitly discards its value; without either, a value-producing block statement is E7006. Parentheses opt into continuation, while explicit expression contexts retain full expression parsing.
Reason: `if true { *p = 2u64; } *p = 3u64;` must denote two statements regardless of spacing. Greedy expression parsing consumed multiplication instead. Merely splitting would silently change `{2i64} -3i64` from −1 to −3; rejecting the undiscarded value avoids that change. Neither line-sensitive syntax nor assignment lookahead is needed. This is a small grammar decision, not a new AIR facility.
Compatibility: formerly accepted bare continuations in statement/tail position require parentheses around the initial construct. Formerly accepted value-producing bare block statements require explicit `;`, including mixed branches such as `if c { return 1u64; } else { 2u64 }` before another statement. Existing tails, explicit discards and initializer/return/argument/condition/expression-arm continuations retain their meanings. Ownership, lexical borrow ends, verifier transfers and deterministic runtime rules are unchanged. A borrow bound inside a preceding block remains inaccessible afterwards (E7002); aliasing and task rules still come from the existing verifier. No new diagnostic code, source syntax form, feature or verifier/runtime state is added. One frontend statement marker enforces the value guard and gives the formatter an explicit boundary; it never changes tokens or inserts separators. No empirical Model Capability Compression benefit is claimed; source documentation growth is measured in docs/agent/README.md.
## DD-017 — Stable E7006 reasons before repair-frequency analysis
Spec 15 §10 requires a registered reason on each E7006. Frontend rejection sites select an enum category explicitly; `move_copy` excludes borrowed and non-materializable operands. ajieval groups observed codes/reasons per run and reports unknown historical reasons separately, without reading message prose. Existing code counts remain compatible; missing logs are unavailable evidence. Counts describe observed command outputs, not the true frequency of all errors.
Reason: a shared code cannot establish whether Copy moves occur often enough to justify RFC 0038. Structured categories also let an agent choose the appropriate rule without classifying prose. This small diagnostic schema extension uses a decision record and a P6-7 plan increment; no new rejection, code, source/AIR syntax, verifier/runtime state or repair application is introduced. Existing locations, payloads, interpreter records, resource/borrow invariants and frozen evaluation inputs remain intact. Enum/registry and CLI/report tests cover serialization, generic/package propagation and historical uncertainty. Bundle growth is recorded in docs/agent/README.md. RFC 0038 remains Proposed with its existing recommendation to defer pending frequency and application-usability data.
## DD-018 — Factual related positions without choosing a repair
RFC 0037's implementation/spec integration is prepared under P6-7; formal RFC status remains Proposed for owner adoption. Spec 10 §2 and spec 15 §10 define one typed related record for each identified E2101/E2104 conflict and E4302 task. Definition lookup retains the selected conflict; loan metadata retains the creating spawn even when a cancelled join replaces its SSA handle. Source mapping is independent, and an absent mapping exposes AIR coordinates without a guessed source position. Primary selection, fields and duplicate suppression are unchanged. There is no enclosing-block inference, conflict enumeration or edit.
The invariant is unchanged acceptance, ownership/loan verification and deterministic interpreter behavior; provenance never participates in liveness or transfer decisions. AIR format 0, syntax, effects/capabilities and diagnostic codes are unchanged. Positive/rejected source/AIR fixtures, repeated cancelled joins, CLI/package mapping and typed serialization tests check the contract. Bundle growth is measured in docs/agent/README.md. This improves factual repair context; no measured repair-cost or MCC claim is made, and RFC 0038 stays deferred pending evidence.
## DD-019 — Unique diagnostic fields preserve the machine envelope
Compatibility review found legacy payload collisions: unsupported AIR narrowing and unknown source capability kinds each emitted a second `kind`, and unlock with a live guard borrow emitted `borrow` twice. Ordinary JSON consumers lost the stable machine kind or one identity. Spec 10 §2 requires unique names and reserves envelope fields. Capability payloads use `capability_kind`; unlock reports the selected `borrow` and its `guard` separately, retaining the borrow seen by former last-key-wins readers. Clients must read the capability payload by its new name; stable diagnostic kinds are restored rather than redefined.
These are diagnostic corrections, not new source/AIR or ownership/concurrency rules. Existing rejection codes, positions, conflict selection, guard/loan state and deterministic execution remain unchanged; valid capabilities and guard programs remain accepted. Pipeline/CLI tests reproduce the three cases, the verifier unit helper checks payload uniqueness across its existing rejection tests, and conformance validates every final mapped diagnostic's fields and serialized JSON. The invariant is an unambiguous machine diagnostic without hidden loss of context. Budget growth is recorded in docs/agent/README.md; no repair candidate or measured MCC benefit is introduced.
## DD-020 — Source scope names are lexical identifiers
Spec 15 §7 resolves Q-041: the name introduced by `scope s` is only the named first operand of `task.spawn`, not an ordinary source value. Lowering rejects plain/moved aliases and value expressions before suggesting a transfer. Ordinary lexical shadowing remains legal; block completion retains its original SSA identity independently of source lookup. This removes an apparent ownership transfer that formerly neither consumed nor changed completion of the handle.
The invariant is one retained completion obligation per source scope, with every child joined and every loan released before completion. Existing AIR verification, including E4301/E4302 and function-local scope flow (spec 04 §33), remains authoritative and unchanged. No runtime rule, instruction, feature, syntax, verifier state or interpreter behavior changes. Shield handles and lock guards already have no source value names; task values remain ordinary linear values.
Valid: `scope s { let t = task.spawn(s, work); let s = 0u64; let n = task.join(move t); }`. Rejected: `scope s { let alias = move s; }` (E7006, existing reason `invalid_expression`, fields `name`/`type: scope`); plain aliases, yields, returns, aggregates and ordinary arguments are rejected likewise. Borrowing keeps `invalid_place`, assigning the immutable identifier keeps `invalid_assignment`, and a moved/non-scope spawn operand keeps E7005. The existing structured reason plus type identifies the category without reading prose; no additional reason is needed.
Compatibility: formerly accepted scope aliases, spawning through an alias or the apparently moved original, standalone scope names and block/scope tails now reject. Accepted shadowing, nested scope lookup, cleanup at fall-through/return/break/continue, and all AIR format-0 programs retain their meanings. Public source conformance covers accepted/rejected forms, specialized bodies and live children; CLI tests cover exact reasons/locations, packages and deterministic/hosted execution. Scheduler stress and per-instruction collection check cleanup. Source documentation growth is measured in docs/agent/README.md. The change improves explicitness and repairability without an empirical MCC claim; it does not finish P6-2.
## DD-021 — Whole-array arguments follow explicit parameter types
Q-023 is resolved in spec 15 §5: a temporary `ref`/`mut` argument preserves its array referent when the known parameter is an array borrow, including explicitly specialized calls. This is the existing small inference from one declared signature, with no overload search. It makes an already expressible parameter callable without hand-written AIR. Array bindings and slice parameters retain their slice behavior; bare byte strings retain their shorthand. Consequently, array-borrow origins and task loans require forwarding an existing array-borrow parameter; a local whole-array binding is still a slice.
Invariant: temporary children and ancestors remain live through the call, then end child first; no view escapes a temporary origin. Existing AIR type, aliasing, initialization, bounds, origin and task-loan verification remains authoritative. Runtime and deterministic interpreter rules are unchanged. Valid: `fn first(a: ref<[u64; 2]>) -> u64 effects [] { return a[0]; }` called with `first(ref data)` for a two-element array. A different length or explicit mode rejects E7005; overlapping exclusive/shared arguments reject E2101. Returning a view from an inline origin and lending an inline argument to a task retain E7006.
Compatibility: formerly rejected array-borrow calls become available; accepted source retains canonical AIR. No new syntax, AIR instruction/feature, diagnostic, verifier/runtime state, allocation or cleanup semantics. The frontend selects array versus slice using the parameter, then emits existing borrow/reborrow and end instructions. Source/AIR conformance and CLI checks cover projections, modes, specialization, packages and temporary cleanup. Source budget growth is recorded in docs/agent/README.md; AIR is unchanged. This improves explicitness and completes source access to an existing primitive without a measured MCC claim.
## DD-022 — Document ordered source parsing and canonical enum payload lists
P6-1/P6-2 synchronizes the grammar with implemented syntax: graph/atomic wrappers, binary literals, signed integer patterns, parenthesized places, declared borrow-return calls and existing list/arm punctuation. Contextual words and the ordered choices for statements, body-opening braces and typed built-ins are explicit. The grammar is not claimed to be LL(k). Existing grouping and optional list delimiters introduce no operation; formatter token preservation remains mandatory.
Q-050 corrects empty parentheses on qualified enum variants, contrary to spec 15 §5–§6. Construction and pattern parsing reject E7001 at the opening parenthesis without symbol lookup, including generic, qualified and built-in variants. Payload-bearing variants with empty lists change from E7005 to E7001; non-empty arity/type checks remain. Bare variants, ordinary zero-argument calls and empty outcome bindings retain their meanings. No AIR, verifier, runtime, ownership/concurrency, feature or code changes; accepted public-source canonical AIR is preserved. Source grammar/CLI tests cover both sides and formatting. Bundle growth is recorded in docs/agent/README.md. Future grammar features still require their RFCs; P6-1 remains open. Q-051 separately records unknown ordinary-function effects.
## DD-023 — Unknown source effects are name errors
Q-051 validates ordinary effect names before body lowering using the existing closed registry. Templates/static contracts use the same E7002 with `name` and `effect`; legacy E0006 without a feature reason was incorrect. Function/template positions remain declaration starts, static contracts use their parameter start. Ordinary parameter/return/from checks retain priority; existing template/header ordering remains. Unknown effects cannot generate malformed AIR or E7900. AIR E0004 and its registry contract are unchanged.
Only invalid-source codes/priority/fields change. Registered effects, explicit authority, effect coverage, duplicate-list set semantics and static-contract uniqueness remain unchanged; no code, reason, syntax, AIR feature, verifier/runtime or ownership/concurrency state is added. Positive/rejected source tests and CLI/package tests cover headers, unused declarations, priority, missing-effect/capability diagnostics, formatting and source/AIR execution. Budget growth is measured in docs/agent/README.md. This completes this diagnostic correction, not P6-2 or an empirical MCC claim.
## DD-024 — Resource obligations survive SSA handoff
Q-052 corrects the verifier's loss of task loans/scopes, guard parents and shield order at block parameters. The preserved invariants are no ending or conflicting access to a loan before its task is joined, no live child at scope completion, no ending a mutex borrow while its guard lives, and properly nested shields. Spec 04 clarifies the already permitted function-local transfer; no AIR feature or new semantic restriction is introduced.
The verifier records static definition/consumption events, solves sparse relations over the CFG to a fixed point, then checks instructions in the existing diagnostic order. Edge transfer renames both positions simultaneously: a scope association follows the scope even if its task is not passed. This preserves correlated permutations of scopes and tasks; independent origin sets would reject valid code. Task/loan/guard alternatives join by union, while the existing shield-stack equality rule is checked separately. Definition sites retain diagnostic spawn positions. The collecting walk excludes relational error recovery; extra facts about subsequently rejected/dead resources are filtered by final liveness. Functions without these resource types retain one walk.
Valid: forward a task and its scope, join the renamed task, then end the renamed scope; end renamed shields inner first; unlock a renamed guard before ending its mutex borrow. Rejected: end the lent borrow or store through its exclusive loan before joining the forwarded task; end a forwarded scope with a live child; end the guard's parent borrow; end the outer forwarded shield first. Source/AIR conformance fixtures cover these cases, cancelled joins, joins with different loan origins, loops and correlated scope/task permutations.
Diagnostic impact: the existing E4302/E4101/E4301/E2102/E4305/E3002 rules now apply after handoff. A transferred live child reports E4301 in preference to E3002. E4302 identifies the current handle and the original spawn. Incompatible shield stacks report E3002 with a shield identity; a subsequent wrong end can also report E4305. New codes, reasons and repairs are unnecessary.
Runtime and deterministic interpreter behavior are unchanged: transfer already moves the same resource, and a cancelled join already returns the same task. Compatibility changes only for violations formerly accepted, or reported with a generic leak after provenance was lost; valid lowering remains unchanged. Counted rotation tests bound fixed-point visits, scheduler/collection tests cover execution, and CLI tests cover exact source/package/generic positions and canonical AIR. Bundle growth is recorded in docs/agent/README.md. This strengthens verification without claiming an empirical MCC improvement or completing P6-7.
+459 -1
View File
@@ -28,10 +28,13 @@ Status values: `open`, `resolved`.
| Q-020 | resolved | P2 | Size bound for SSA array values | | Q-020 | resolved | P2 | Size bound for SSA array values |
| Q-024 | resolved | P5 | Memory-model clarifications found by the independent oracle | | Q-024 | resolved | P5 | Memory-model clarifications found by the independent oracle |
| Q-025 | resolved | STD-5 | Array construction from complete element values | | Q-025 | resolved | STD-5 | Array construction from complete element values |
| Q-034 | open | P6-11 adoption | Source borrow-return calls (implementation prepared; RFC 0036 Proposed) |
| Q-035 | resolved | STD-5 | Whole-value linear aggregates | | Q-035 | resolved | STD-5 | Whole-value linear aggregates |
| Q-036 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain | | Q-036 | resolved | STD-6a | Dynamic initialized linear buffer storage and drain |
| Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors | | Q-038 | resolved | STD-6d.2 | Pure construction of built-in errors |
| Q-039 | resolved | STD-6d | Explicit static function parameters | | Q-039 | resolved | STD-6d | Explicit static function parameters |
| Q-041 | resolved | P6-2 task block forms | Source scope-handle value bindings |
| Q-062 | open | P6-2 | Parenthesized block constructs without a statement terminator |
## Q-001 — Text AIR grammar ## Q-001 — Text AIR grammar
@@ -135,7 +138,9 @@ The SB litmus test requires the interpreter not to forbid `r1=0, r2=0` under rel
## Q-016 — Floating-point determinism ## Q-016 — Floating-point determinism
`f32`/`f64` exist (spec 02 §1) with no rules on NaN payloads, fused operations, rounding mode or denormals. Deterministic replay requires these to be fixed. `f32`/`f64` are listed in spec 02 §1 but reserved by spec 07 §8.4: AIR rejects their use with `E0006`, reason `reserved_type`, and `.aji` 0.1 exposes no floating-point types. They do not create a determinism gap in currently accepted programs. This question remains open for future activation: NaN payloads, fused operations, rounding mode and denormals need explicit rules before floating point can participate in deterministic replay.
Source naming also needs an activation decision: `.aji` currently accepts nominal declarations such as `struct f64 { value: u8 }`; their uses lower to `@f64`, not the reserved AIR primitive `f64`. An undeclared `f64` is an ordinary E7002 unknown name. Future primitive activation needs an explicit source-name and backward-compatibility policy for these existing nominal programs.
## Q-017 — Replay file format ## Q-017 — Replay file format
@@ -177,6 +182,8 @@ A byte string lowers to one `local.zero`, then a borrow, index, store and end pe
In `.aji` a borrow of a whole array written as an argument (`f(ref a)`, `a: [u64; 4]`) is always lowered as a slice (`slice<u64>`), so a function declared with a parameter `ref<[u64; 4]>` cannot be called with `ref a` (`E7005`). Spec 15 §5 says that binding a borrow of a whole array (`ref r = a;`) gives a slice. It does not say what an argument borrow gives, so the frontend's choice is not specified. Options: the argument borrow follows the parameter type (array borrow for `ref<[T; N]>`, slice for `slice<T>`), which is a small amount of inference from a known signature; or keep slices only and state it in spec 15. Found while writing the interpreter memory test; not urgent. In `.aji` a borrow of a whole array written as an argument (`f(ref a)`, `a: [u64; 4]`) is always lowered as a slice (`slice<u64>`), so a function declared with a parameter `ref<[u64; 4]>` cannot be called with `ref a` (`E7005`). Spec 15 §5 says that binding a borrow of a whole array (`ref r = a;`) gives a slice. It does not say what an argument borrow gives, so the frontend's choice is not specified. Options: the argument borrow follows the parameter type (array borrow for `ref<[T; N]>`, slice for `slice<T>`), which is a small amount of inference from a known signature; or keep slices only and state it in spec 15. Found while writing the interpreter memory test; not urgent.
**Resolved (DD-021, spec 15 §5):** an explicit temporary borrow preserves an array when the known ordinary-call parameter is an array borrow. Exact type/length/mode checks remain; slices, bindings, byte-string shorthand, retained origins and task loans keep their existing rules.
## Q-024 — Memory-model clarifications found by the independent oracle ## Q-024 — Memory-model clarifications found by the independent oracle
The independent author of `tools/litmus/enumerate.py` (P5-1a) worked from spec 04 §20 only. It reported five points the text leaves implicit. For each, the author chose the RC11 reading, and all 20 corpus tests agree with the stated sets under it. Proposed clarifying text for spec 04 §20, for owner approval: The independent author of `tools/litmus/enumerate.py` (P5-1a) worked from spec 04 §20 only. It reported five points the text leaves implicit. For each, the author chose the RC11 reading, and all 20 corpus tests agree with the stated sets under it. Proposed clarifying text for spec 04 §20, for owner approval:
@@ -260,6 +267,8 @@ The source plan names monomorphized generics but does not define application syn
During STD-4 validation, existing `from` declarations still return the frontend's unimplemented outcome and borrow bindings accept places rather than borrow-returning calls. Generics preserve the syntax/metadata and this existing limitation; they do not add an implicit lifetime or a new binding spelling. A separate source/lifetime increment must specify and implement the binding/temporary-end rules vertically before public libraries return retained borrowed views. During STD-4 validation, existing `from` declarations still return the frontend's unimplemented outcome and borrow bindings accept places rather than borrow-returning calls. Generics preserve the syntax/metadata and this existing limitation; they do not add an implicit lifetime or a new binding spelling. A separate source/lifetime increment must specify and implement the binding/temporary-end rules vertically before public libraries return retained borrowed views.
**Implementation prepared (P6-11, RFC 0036 Proposed):** spec 15 §19 and the frontend define exact-mode ref/mut call bindings, a named borrowed `from` argument, named returns and transfer of owned ancestors. The existing AIR verifier enforces provenance/lifetime; no runtime rule or AIR construct changes. Source/AIR twins, generic/package/profile checks, task loans and per-step collection cover the increment. Owner adoption of RFC 0036 remains separate.
## Q-035 — Whole-value linear aggregates ## Q-035 — Whole-value linear aggregates
**Resolved on the STD-5 branch (RFC 0023 Implemented):** spec 03 §25 and source spec 15 §16 specify complete construction/exhaustive consumption, fixed arrays, explicit exchange and ownership-preserving allocation failure. No partial-move/field initialization state or destructor is introduced. Among heap/frame/region storage forms, only individual own<T> may hold linear content; frame locals, repeated heap arrays and bulk regions retain Copy-only content. Dynamic linear buffers need a separately specified extension in the collection phase. **Resolved on the STD-5 branch (RFC 0023 Implemented):** spec 03 §25 and source spec 15 §16 specify complete construction/exhaustive consumption, fixed arrays, explicit exchange and ownership-preserving allocation failure. No partial-move/field initialization state or destructor is introduced. Among heap/frame/region storage forms, only individual own<T> may hold linear content; frame locals, repeated heap arrays and bulk regions retain Copy-only content. Dynamic linear buffers need a separately specified extension in the collection phase.
@@ -288,3 +297,452 @@ STD-6d.2 needs to return allocation-size validation failure without allocating.
General collections and algorithms need explicit typed hash/equality/order operations, while current generics carry only types. General collections and algorithms need explicit typed hash/equality/order operations, while current generics carry only types.
**Resolved contract (RFC 0029 Implemented):** spec 15 §18 permits explicitly selected source functions as static parameters with exact typed/effect contracts. Selection is part of nominal specialization identity and lowers to existing named AIR calls/workers. No function pointers, capture environment, inferred effects or runtime dispatch are introduced. Q-037 is resolved by the implemented and verified generic map/set contracts (RFCs 0030/0031). **Resolved contract (RFC 0029 Implemented):** spec 15 §18 permits explicitly selected source functions as static parameters with exact typed/effect contracts. Selection is part of nominal specialization identity and lowers to existing named AIR calls/workers. No function pointers, capture environment, inferred effects or runtime dispatch are introduced. Q-037 is resolved by the implemented and verified generic map/set contracts (RFCs 0030/0031).
## Q-040 — Block statements followed by unary-leading expressions
P6-8 review found an existing parser ambiguity: `if true { *p = 2u64; } *p = *p + 1u64;` is consumed as an expression continued by multiplication and then rejects E7006 at the assignment. The same failure is reproduced after a standalone block or `match`; `while` dispatches separately and is not affected. Source whitespace is insignificant; spec 15 §4 and the grammar admit both block statements and expressions beginning with block/control-flow forms. The intended disambiguation must be specified before changing which previously parsed expressions are accepted. Decide how a standalone block statement ends before a dereference/other unary-leading statement while preserving block-valued expressions in explicit expression contexts. Add positive/rejected parser and lowering cases for the chosen rule. The formatter preserves the current tokens/AST and MUST NOT insert semicolons or infer the intended statement boundary. This question is separate from P6-8.
**Resolved (DD-016, spec 15 §4):** leading bare `if`, `match` and `{…}` in statement/tail position stop before outer expression operations. The next `}` selects a tail, `;` an explicit discard, otherwise a block statement must yield `void` or diverge (E7006). Parentheses permit continuation; nested expression contexts retain ordinary parsing. The value guard prevents silent reinterpretation of former expressions such as `{2i64} -3i64`. Parser, lowering, formatter and source conformance cover the boundary and compatibility rules. This resolves one P6-1/P6-2 ambiguity, not the complete grammar tasks.
## Q-041 — Source scope-handle value bindings
Independent E7006 review found that `module scope_move fn main()->u64 effects [] { scope sc { let alias = move sc; } 42u64 }` checks and returns 42 with fuel 10,000. Its AIR contains only `task.scope.begin` and `task.scope.end` on the same SSA value; the unused alias introduces no instruction. This observation alone establishes no memory/concurrency safety defect. Spec 15 §3 excludes `scope` from source type spellings, §7 ties scope completion to the block, and spec 04 §33 permits function-local scope flow while preserving linear completion. They do not explicitly say which ordinary source value-binding forms may name that internal handle or how an explicit transfer interacts with the block's retained completion obligation.
Clarify whether `let`/`move` aliases and rebinding of a scope name are permitted, how their availability relates to the originating block, and which existing diagnostic applies to rejected forms. Keep AIR scope identity, live-child/loan checks, deterministic completion and the no-escape invariant intact; add source acceptance/rejection tests for the chosen contract before changing lowering. This is separate from DD-017's reason field and RFC 0038's proposed repairs; neither adopts a new scope rule.
**Resolved (DD-020, spec 15 §7):** a source scope name is a lexical identifier usable only as the named first operand of `task.spawn`. Ordinary `s`/`move s` value uses reject E7006 `invalid_expression`, with `name` and `type: scope`; borrowing remains E7006 `invalid_place`. Ordinary shadowing remains legal and never replaces the originating block's saved completion identity. Source/AIR tests retain existing live-child and loan rules, deterministic completion and function-local AIR scope flow. Previously accepted aliases and scope-valued expressions now reject; no new syntax, reason, code or verifier/runtime state is added. This resolves one P6-2 question, not the phase.
## Q-042 — Source type-position validation before AIR verification
Read-only P6-2 review reproduced `module nested fn f(p: ref<ref<u64>>) -> void effects [] {} fn main() -> void effects [] {}` on the preceding compiler. It reaches the verifier and reports E1001 (`position: borrowed`, `found: ref<u64>`) at the source function. Spec 15 §10 requires errors fully decided by source types to be reported as E7xxx, and the AIR type-position rule already rejects this referent. This is an existing frontend validation gap, independent of dereferenced argument parsing; no new borrow semantics is proposed.
**Resolved for structural positions (spec 15 §10):** frontend annotation checks use the verifier's pure type-position predicates. Parameters, returns, fields, payloads, nested constructors, local annotations and known unused generic/static-contract headers reject E7005 at the invalid constructor with `position` and `type_constructor`; unknown parameter restrictions are checked after substitution. Graph-content properties retain E2111. Existing AIR acceptance, diagnostics and runtime rules are unchanged. Invalid source types formerly rejected by E1001 or a feature diagnostic now reject earlier; known invalid unused generic headers and annotations previously skipped by lowering also reject. Generic argument diagnostics may have more precise coordinates and different fields. Property checks beyond structural positions are separate (Q-043); this does not establish complete source type-check coverage.
## Q-043 — Copy content validation for source dynamic owning arrays
Read-only review after Q-042 reproduced `module nested fn unused(p: own_array<own<u64>>) -> void effects [] { trap; } fn main() -> void effects [] {}`. It reaches the AIR verifier with E1001, `dynamic heap arrays require Copy content`. Spec 03 §25 requires Copy content for `own_array<T>`, and spec 15 §10 requires fully source-type-decided errors to be E7xxx. This is a content-property check, not a structural type position. Graph-content properties and Send/Share checks retain their separately specified verifier diagnostics.
**Resolved (spec 15 §10):** annotation and repeated-allocation checks report E7005 at the non-Copy content/value, with `constraint: Copy` and `type_constructor: own_array`. The shared AST property query follows nominal fields and enum payloads in their declaring namespace, honors user types before built-in names, and keeps `iref` content phantom. Unused generic/static headers reject when linear content is already known; unknown parameter properties wait for substitution. Recursive generic paths are distinguished by the known-linear parameter vector, so parameter rotations cannot hide a known linear leaf. Pure by-value cycles retain E1003; a proven Copy-content violation may reject before a simultaneous layout error. Graph-root content checks retain E2111. AIR acceptance, codes, type identity, allocation/cleanup and interpreter behavior are unchanged; invalid source programs now stop earlier instead of producing invalid AIR. No new syntax, code, feature or verifier/runtime state is introduced.
## Q-044 — Nominal linearity query cost before layout rejection
Q-043 review identified a separate existing cost in `Lowerer.linearAt`: repeated fields and by-value cycles revisit nominal declarations until its depth bound, with no shared-result cache. `checkRequirements` asks this query before `checkFiniteLayouts` rejects E1003. The bound guarantees finite recursion but does not bound the number of branching revisits. Q-043's new annotation query has counted tests for shared acyclic/cyclic branches; the old classification query is unchanged. The precise cost and scope of other nominal property queries remain unverified.
Audit the existing classification/layout ordering and shared-query cost with counted tests, preserving structural ownership classes, graph/iref boundaries, source E1003 provenance, accepted-source canonical AIR and frozen AIR behavior. Avoid wall-clock timeout tests. This is an implementation audit, not a new recursion or memory rule.
**Resolved:** lowering reads structural linearity from a resolved nominal-property table after finite-layout checks. AIR verification rebuilds the same table before type checking, with a monotone dependency worklist for the existing predicates, depth-64 guard and source depth-32 witness pruning. The earlier budget stage memoizes sizes by nominal index and depth, preserving cutoff, overflow and E5101 precedence exactly. Checked modules retain immutable caches for subsequent queries. Counted diamond/cycle tests and differential small-graph tests cover all predicates, witness order, depth boundaries, sizes and caller-supplied cache rejection. Source/AIR diagnostics, ownership classes, valid canonical AIR and runtime semantics are unchanged; standalone uncached helpers remain available for small test oracles.
## Q-045 — Source array literals with second-class elements
Q-043 review reproduced `fn unused(p: ref<u64>) -> void effects [] { let a = [p, p]; }`: the source array literal reaches AIR type checking with E1001 because borrows cannot be stored as array elements. Q-042 validates annotations; an inferred literal has none. Q-043 now rejects that array as a repeated `own.array` value, but constructing it without that operation remains a separate source validation gap.
**Resolved (spec 15 §5/§10):** each inferred list/repeat element is checked before array construction. Borrows retain E7006 `invalid_literal`; forbidden member constructors (including void/never/task) report E7005 with `position` and `type_constructor`. Repeated elements use the verifier's exact Copy predicate and report E7005 with `constraint: Copy` and `type_constructor: array`. Lists preserve explicit linear moves, E7003 for missing moves and verifier E2002 for duplicates. Element validity precedes expected-type agreement with or without an annotation; an invalid annotation itself still rejects first. Thus some earlier mismatches/ownership-wrapper errors are replaced by a diagnostic at the first invalid element. The Q-043 `own.array` check remains a second line of defense. AIR acceptance, verifier/runtime rules and valid-source canonical output are unchanged. Wrapper construction from inferred values is separate (Q-046).
## Q-046 — Inferred content types in ownership and graph constructors
Q-045 review reproduced `fn unused(heap: cap<mem.alloc>, p: ref<u64>) -> void effects [mem.alloc] { let a = own.new(p, heap) or trap; trap; }`: the inferred `own<ref<u64>>` reaches AIR E1001 in member position. Existing source annotations reject this under Q-042, but the constructor infers its content type from a value. Review identified analogous call paths in `own.pack`, `mutex.make` and graph allocation; those additional cases remain unverified.
Audit each constructor against its own existing content/position/property rules and diagnostic precedence before changing it. In particular, distinguish Copy-only construction, explicit linear transfer and graph-content E2111. Add source positives/rejections and stable E7xxx at fully source-decided errors, preserving provenance, effects/capabilities, outcomes and frozen AIR behavior. Do not apply one broad Copy restriction to every wrapper.
**Resolved (spec 15 §10):** inferred void/never content rejects E7005 before constructors form results or outcomes; never operands formerly reached a null-block panic, and void operands could produce malformed AIR/E7900. `own.new`, `region.new` and `region.array` use the verifier's exact Copy predicate on the completed nominal type snapshot, reporting `constraint: Copy` and `operation` at the value. `own.pack` rejects root borrows with `position: member` and `type_constructor`; complete linear values and allocation-failure recovery remain valid. Existing explicit-move checks run first. `own.array` retains its earlier Copy diagnostic, including void/never. Mutex element rules, graph properties and reserved transfers otherwise stay in the verifier: `own.pack(task)` retains E0006 task_transfer, and mutex endpoints retain E0006 channel_transfer. Copy-only constructors reject task content independently of that gate. Existing `island.alloc` precedence reports E1001 for root borrows through `iref<T>` positioning; root owners report E1001 without `linear_aggregates`, but E2111 when an owning aggregate declaration enables that feature in the module. Nominal values with owning members report E2111. This distinction depends on the feature header, not lexical block nesting, and remains with the verifier. No AIR acceptance, ownership/effect/capability rule, outcome, allocation/cleanup or deterministic interpreter behavior changes. Invalid source stops earlier; accepted canonical AIR is unchanged. This closes the audited constructor paths, not all source type-check completeness.
## Q-047 — Non-value operands outside inferred constructors
Q-046 review identified other uses of `never` that reach lowering with no current block. Independently reproduced: `module test.never_operand fn stop() -> never effects [] { trap; } fn main() -> u64 effects [] { return 1u64 + stop(); }` aborts while `Lowerer.binary` calls `def`/`emit` after `stop()` terminated the block. Review also reproduced ordinary call arguments and struct fields; their exact scope remains unverified. Q-046 guards constructor content only.
Audit non-value operands in ordinary calls, operators and aggregates against spec 15 before emission. Distinguish value-requiring positions from valid void statements and never-returning control flow. Add source rejection/acceptance and CLI tests, preserving evaluation order, explicit transfers, diagnostics and canonical AIR for valid source. A source program MUST NOT cause a lowering panic; do not infer a new divergence/coercion rule from implementation behavior.
**Resolved (spec 15 §10):** typed operation inputs reject never with E7005 at the operand (`expected`, `found: never`) before subsequent inputs/emission, while ordinary void mismatches retain their diagnostics. Calls, operators, fields/payloads, conditions, ranges/indices, sizes, atomics, channels and place-store values use this rule. `select` checks a divergent send value before endpoint borrows. Return/tail/statement/branch divergence and existing SSA variable receivers remain valid; divergent assignment by name or `var` initialization in frame storage now performs no store. Binding/annotation checks still precede those receivers. Place writes through `*`, fields or indices require a value; rejecting never before target evaluation prevents formerly invalid targets from being accepted. Unknown target types use `expected: a stored value`, so earlier E7002 can become E7005 at the RHS. `let` retains its existing no-value error. Emission into a terminated block returns E7006 unreachable rather than aborting; a state-machine unit test preserves the terminated block and diagnostic span. AIR acceptance, ownership/lifetime rules, effect/capability contracts, normal-path execution and accepted-source canonical AIR are unchanged. Programs that previously aborted now reject or, for valid variable receivers, diverge normally. Q-048 records a separate store-mode gap.
## Q-048 — Source place-store access modes
Q-047 review independently reproduced `fn update(p: ref<u64>) -> void effects [] { *p = 1u64; }`: it reaches AIR E1001 (`expected: mut<T>`, `found: ref<u64>`) instead of frontend E7xxx, although the mode is determined by source types (spec 15 §10). Review also observed accepted writes to fields of a `let` aggregate. An immutable binding does not necessarily imply immutable owned content; whether that behavior disagrees with the specification remains unverified and MUST NOT be guessed from the binding's `mutable` flag.
Audit existing place modes and referents against spec 15 §4/§5 and AIR borrow/store rules. Reject fully type-decided incompatibilities at the source, preserving ownership, aliasing/lifetime diagnostics, evaluation order and canonical AIR for valid source. Determine the binding/content distinction from governing text before proposing any semantic restriction.
**Resolved (spec 15 §10):** stores require `mut<T>`; explicit `mut` bindings and arguments require an exclusive place before array-to-slice conversion. Shared places reject E7005 with expected/found borrow types at the place or argument. This also prevents accepted `mut` bindings from silently retaining shared field/index/range modes, or requesting an exclusive slice from a shared array. Dereferenced slices are not scalar store places. Whole-array stores retain E7006; RHS evaluation, valid canonical AIR, ownership/projection/alias/lifetime rules and runtime semantics remain unchanged. Q-049 separates the unresolved Copy-let storage policy.
## Q-049 — Immutable Copy bindings and mutable frame content
Read-only Q-048 review reproduced accepted `let p = Pair { a: 0u64 }; p.a = 42u64; return p.a;`, and exclusive borrows of Copy-let frame storage. Spec 15 §4 calls `let` an immutable binding; assignment by name already rejects. Whether this should also prohibit content writes through fields/indices/borrows is unresolved. Owned content through `let` intentionally remains mutable and is used by public std examples. Do not infer a new restriction from `Binding.mutable`: distinguish Copy frame storage from owners, regions, resources and borrow bindings, and settle the normative policy before changing accepted source. This question is independent of Q-048's existing shared/exclusive borrow modes.
## Q-050 — Empty parentheses on qualified enum variants
The parser accepted `E::Empty()` and the corresponding match pattern, although spec 15 §5 requires a bare payload-free variant. Public tests/examples/std contain no such forms. Outcome binding lists such as `closed()` are separate delimiters used by std and remain legal.
**Resolved (DD-022, spec 15 §5–§6):** qualified variant construction and patterns reject empty payload lists with E7001 at `(`, without symbol lookup. This includes payload-bearing variants formerly rejected with E7005; non-empty lists retain their existing arity/type checks. Ordinary calls, grouping and outcome bindings are unaffected. No AIR or runtime rule changes.
## Q-051 — Unknown effects in ordinary source signatures
An ordinary function declaring `effects [bogus.effect]` reaches AIR and reports E7900 with `air_code: E0004`; templates/static contracts reject the same known-invalid effect directly with E0006. Effect membership is determined entirely from source and the registry. A P6-2 task should align ordinary signature validation with the existing template contract, preserving effect/capability semantics and checking diagnostic priority/positions. No implementation is included in DD-022.
**Resolved (DD-023, spec 15 §9):** ordinary signatures validate the existing effect registry before body lowering; templates/static contracts replace the incorrect E0006 with E7002. Fields `name` and `effect` identify the atom without prose; locations retain declaration/parameter starts. Signature/type/from and template/header priority, accepted AIR, effect/capability semantics and AIR E0004 are preserved. Invalid-source diagnostics can change; no new code or reason.
## Q-052 — Resource provenance through CFG parameters
P6-7 rejection-twin work reproduced accepted source that returns the cancelled handle from an inner block, ends its lent borrow at that block's exit, then joins the renamed handle. Ordinary AIR `br` has the same defect: loans and creating scopes remain attached to the moved SSA value. Review also reproduced lost guard parents and shield order. These violate existing spec 04 §33–§34, §37.3 and §40; they are verifier bugs, not missing transfer semantics.
**Resolved (DD-024):** resource relations follow simultaneous edge renaming, with a finite worklist covering later predecessors and backedges. Loans retain the creating spawn; tasks retain scope associations even when only the scope is passed. Guard parents and ordered shield relations survive handoff. Task/guard facts merge by union; shield stacks retain their existing exact join requirement. Existing codes E4302/E4101/E4301/E2102/E4305/E3002 apply. Valid correlated scope/task permutations and joins remain accepted. Runtime, source lowering and AIR format-0 meanings are unchanged; previously accepted violations now reject.
## Q-053 — P6-7's literal same-code exit criterion and the source boundary
P6-7 originally required every conformance rejection to have a source twin with the same code; that criterion is now tracked in P6-14 (2026-10-13 decision below). Spec 15 §10 instead requires fully source-decided type errors to use E7xxx, and malformed generated AIR/SSA/CFG to report E7900 as compiler defects. Spec 15 §1/§9 also makes SSA, CFG, local placement, lexical borrow ends and feature headers generated mechanics. Examples: AIR lossy widening is E1002 but source is E7005; missing borrow-return `from` is E2102 in AIR but E7006 in source (§19); explicit branch arity, unsupported AIR versions and duplicate feature headers have no source operation. Uninitialized locals and deliberately invalid proven-index fact forms likewise have no implemented source spelling.
The exhaustive inventory in `tools/source_reject_twins.py` keeps these rows visible: same-code pairs, audited source-error analogues, AIR-only cases and pending audits. Only verified same-code pairs satisfy the current criterion; the other categories are not exclusions or completion evidence. The owner needs to decide how the final phase review should account for mandatory E7xxx translation and generated-only AIR defects, without weakening existing AIR tests, exposing raw mechanics in source, or changing diagnostics solely to satisfy coverage. Until then the original criterion and P6-7's doing status remain unchanged; unreviewed and authorable twins can still be completed.
2026-10-08 completed public audit: all 199 AIR rejection files are reviewed. The executable check verifies 91 same-code cases and 45 prescribed E7xxx source analogues; 63 cases have an audited source-boundary reason. No rows remain pending. Full conformance passes 1,713/1,713, but `--require-complete` still exits 1 because it requires every row to be same-code.
Proposed criterion, for owner decision: retain every AIR rejection test; for each source-authorable rule/context, require a compiled source twin with the same code or its spec-prescribed E7xxx translation, stable facts and independent positions. Generated-only contexts require an explicit governing source-policy audit. Every newly discovered public AIR rejection remains pending until audited. This proposal changes no language rule and does not count a matching code alone as a twin. It is not adopted; the literal gate and doing status remain unchanged.
2026-10-09: after the Q-058 size correction, all 205 public AIR rejection files are classified: 96 verified same-code pairs, 45 E7xxx analogues, 63 AIR-only cases and one `source_early` analogue. The last category retains an authorable cyclic-array declaration whose AIR budget rejects E5101 while source finite-layout validation rejects E1003 before lowering. Both codes, facts, declaration positions and reviewed artifact fingerprints are checked; it contributes no same-code coverage. The final criterion must also account explicitly for such earlier verifier-code rejections, rather than label their authorable shape AIR-only or change diagnostics for coverage. No policy is adopted; `--require-complete` still exits 1.
2026-10-13: the owner confirmed moving the literal same-code criterion out of Phase 6 into P6-14; P6-7 is done for diagnostic source mapping. This supersedes the earlier statements that P6-7 remains doing. The alternative criterion above is still not adopted, and Q-053 remains open for that decision. The current inventory has 206 classified rows: 97 verified same-code pairs, 45 E7xxx analogues, one source-early analogue and 63 AIR-only cases. Deferral does not count the latter 109 rows as same-code completion.
## Q-054 — Executable contract obligations and invariant boundaries
P6-6 requires contracts and their four audit statuses, but spec 13 §1/spec 08 §8 do not define predicate purity, snapshot/result lifetime, boundary coverage or a proof calculus. AIR has no contract table. Current probes at `94414da` show identical audit reports for mandatory/bypassable assertions, effects-empty mutation and ambient task.cancelled observation, and E3001 after consuming an observed owner. New contract headers also need an AIR0 rejected-code audit: an unfeatured header currently reports E0001, outside §8.7's E0004/E0006 exceptions; Q-055 records the conflict with §8.1.
[RFC 0039](../rfcs/0039-verifier-visible-contracts.md) is a Draft spec gate covering requires/ensures and preserving the unresolved type/module invariant work. Decide complete rules before implementation; function-boundary checks alone do not establish value invariants, and source 0.1 has no module-state/visibility declaration surface. No semantic policy, feature or code is introduced by this entry.
2026-10-09: the candidate function representation now uses a leading `contract.pre/old/post` prefix; all three isolated spellings currently reject E0004, avoiding Q-055's header-specific E0001 conflict. The used-result probe additionally reports E5001; complete rejection-code compatibility remains to be audited. Deferred post bindings require ordinary access checks at every return. Verified Range probes distinguish a repaired exclusive update from an invalid Copy escape and shared-reader overflow; exclusive-borrow end alone cannot establish publication coverage. Type/module invariant representation and predicate purity remain unresolved; no implementation is authorized.
[Invariant-boundary research](contract-invariant-boundaries.md) compares eager/epoch coverage with a checked representation and explicit in-place callback update. The latter avoids requiring replacement allocation for borrowed linear state, but still needs stable-observation rules, pending-result semantics and exact type/source representation. Current probes confirm a scalar helper mutating an enclosing Range, public fields bypassing a library wrapper and independent-root relation drift (each returns 1), plus E0001 for a new type declaration versus E0004 for an unknown type constructor. Persistent state-root claims and function-boundary relations must have distinct scope; module roots/declarations and full P6-6 proof/status rules remain open.
[Accounting/status research](contract-accounting-and-status.md) proposes pre-SSA activation and virtual-binding bounds, a restricted proof classifier that preserves predicate execution, and explicit unsafe-assumed/documented modes. Nine current-language probes confirm frame/value separation and verifier-stage priority; four proposed mode opcodes reject E0004 alone, while existing unsafe `assume(false)` accepts and traps T0009. These fourteen cases constrain the candidate, not demonstrate contract implementation. Exact proof costs, diagnostic collection, report schema, source/module metadata and adoption remain open.
[Proof/report refinement](contract-proof-and-report.md) supplies a closed opcode normal form, cache-independent position charges and fallback precedence, plus canonical function/value rows and explicit source annotation/call-edge rules. Five current-language baselines verify report equivalence, eligible helper operations and the limit-vector structure; fifteen research vectors check cost/truth with a finite independent oracle. These do not implement contracts or close module metadata, source elaboration, diagnostic collection, owner adoption or vertical delivery.
[Module/source research](contract-source-and-module-state.md) proposes a narrow checked-state binding with a generated type-validation witness, explicit reserved-prefix operations, clause capture/snapshot rules and type-level audit inventory. Nineteen complete current-language baselines confirm existing checked namespaces/types and ordinary contract-word identifiers, static function selection, keyword binding rejection, identity-witness behavior and bounded snapshot-record packing. Claude independently reviewed the recorded evidence; checks concern compatibility constraints, not implemented invariants. Rooted module state versus hidden state remains an owner choice; property/ABI, schema, source lowering and diagnostic/dispatch gates remain open.
The [property/inventory refinement](contract-source-and-module-state.md#representation-properties-and-positions) provides candidate inherited-property, complete-position, zeroability, recursive transfer-gate and ABI/rendering rules. Its exact inventory separates universal raw-representation proof from site proof and source provenance. Twelve prior probes match `4cda448`; eight additional reproducible current-language vectors constrain identity/content rules and predicate shape. The updated report component's totals, ordering and proof costs are independently checked. These refine the Draft, not the normative language. Source-map/mangling, diagnostic/dispatch, Q-055 compatibility, owner model selection and vertical delivery remain open; no contract implementation is claimed.
The next candidate fixes contract artifact name encoding/order and typed declaration maps, with three naming groups (ten CLI checks) and seven hash/collision vectors. Global P-before-S subpasses, bounded shortest-call witnesses and isolated return/post collection now have concrete rules; five current-language return probes preserve existing leak/early-return code lists and six graph vectors validate proposed witness selection. These remain unimplemented research constraints. Complete binding/diagnostic/trap schemas, compatibility, model adoption and vertical delivery remain open.
The [AIR binding grammar](contract-air-bindings.md) now proposes exact prefix/checked spellings, root descriptors, observation adaptation and E8001 reason/field shapes. Eighteen ordinary view/call/unknown-opcode probes confirm existing constraints, including optional never-call result bindings and the difference between an owner root and a complete Copy place. Candidate grammar is not adopted spec; source reasons, trap/dispatch schemas, compatibility, model adoption and vertical delivery remain gates.
The [runtime/context candidate](contract-runtime-and-context.md) gives concrete continuation/publication, fuel/depth/quantum, pending GC-root and additive trap/environment context rules, including AIR-only byte-identity exploration. Sixteen ordinary CLI runs and nine normal/GC-every-step fixture variants constrain current behavior; hypothetical context components are not new compiler output. Claude independently checked the mechanics, replayed the CLI records and reviewed the refined schema. Source reasons, compatibility/model adoption and full vertical runtime tests remain open; no implemented contract claim is made.
## Q-055 — Feature-gated AIR headers and frozen rejection codes
2026-10-09: [ten executed rejection vectors](contract-source-errors-and-compatibility.md#executed-format-0-rejection-baselines) distinguish snapshot body escape, ordinary checked-result use and independent missing operands, retaining complete diagnostic identities/positions. The same E5001 code can represent either a dependent or unrelated defect. The candidate lists a narrowly causal policy and AIR1 as owner alternatives; neither is adopted, and the historical parser is still unexecuted. Complete feature/parser compatibility remains open.
Spec 07 §8.7 permits changes to earlier E0004/E0006 rejections, not E0001. Source inspection of the parser before commit `0086549` shows that an unfeatured `trusted "..."` header was parsed as a block label and failed while expecting `:`; current spec 13 §6.3 and the parser require E0006 `feature_not_declared`. RFC 0009 calls the header additive, although this diagnostic transition is outside the literal exception. The historical parser has not been executed in this audit.
Resolve this compatibility policy before using `trusted` as a precedent for new contract headers (Q-054). Preserving legacy E0001 parsing conflicts with §8.1's E0006 for an undeclared construct; replacing E0001 conflicts with §8.7. Instructions whose old rejection is E0004 or a new AIR version avoid this header conflict. Amending either rule is an owner decision, not implied by the implementation. No existing parser, diagnostic or stability rule changes here; other historical syntax extensions remain unaudited.
The opcode candidate needs a separate dependent-error audit: at `94414da`, `%old = contract.old @snapshot(%x)` followed by `add.checked.u64 %old, %x` reports both E0004 for the unknown opcode and E5001 for its undefined result. This body-use shape remains invalid under the candidate's contract-only snapshot rule; audit its rejection-code transition, not its acceptance. A snapshot used only by `contract.post` currently reports two E0004s without E5001. Establish how §8.7's named-opcode exception applies to combined rejections before claiming the entire extension compatible. An unrelated invalid SSA use must not be accepted merely because the same module also contains a new opcode.
## Q-056 — Source zeroability versus AIR zeroability
Spec 15 §4 calls `var x: T = zero` a lowering to `local.zero` for zeroable types, without naming a narrower source set. Spec 07a's `local.zero` includes structs whose fields are zeroable. At `94414da`, source `var range: Range = zero` with two u64 fields rejects E7006 `zero_not_zeroable`; AIR `local.alloc @Range` followed by `local.zero` accepts and runs. `src/frontend/lower.zig` restricts source zeroability to integers, bool and arrays of those types.
Decide whether source intentionally exposes that narrower set (and make spec 15 precise), or whether the missing structural lowering is an implementation gap. This entry changes neither layer. P6-6 invariant coverage must independently include the existing AIR construction path, regardless of the source decision.
## Q-057 — Shared observation of linear variants and nested owner content
Current `match *value` with `value: ref<Outcome>` and `Outcome = enum { ok(own<u64>), err(u64) }` rejects E1001 at the linear load, even when both arms only return bool. Spec 03 §25 forbids observational `enum.switch` on a linear enum; `enum.take` consumes it. There is no borrowed tag/payload projection. Similarly, `*p.payload` through `p: ref<Record>` with a field `payload: own<u64>` rejects E1001; AIR `borrow.ref` on `ref<own<u64>>` keeps that type, and its load cannot copy the owner. A direct `own<u64>` root can expose its contents through existing `borrow.ref`, so distinguish this nested/shared-owner case.
These are specified observation limits, not new verifier bugs. A shared linear struct's Copy field is readable (a count probe returns 7); a read-only contract could likewise need to inspect a linear result's success variant or owned nested data without consuming either. RFC 0039's purity candidate cannot supply missing observation semantics, and the full P6-6 gate remains open.
Decide the required source/AIR observation surface. Candidate directions include a shared-view variant operation yielding borrowed payloads and an explicit shared content view through `ref<own<T>>`; neither is adopted here. Any new primitive requires a registered feature, its full AIR contract, ordinary alias/loan/lifetime enforcement, deterministic behavior, format compatibility and vertical source/Quick Reference/conformance coverage. Do not enable consumption, hidden owner copies or unrestricted partial moves to make predicates expressible.
2026-10-09: [RFC 0040](../rfcs/0040-shared-enum-and-owner-views.md) Draft proposes selective `enum.view` edges and shared `own.view` for scalar and array owners, with explicit source `match ref place`. Single-ingress arm blocks create only the chosen edge's dependent views; no general borrow joins or variant proofs are assumed. A current-language probe confirms that a dormant 65-payload variant is legal, while its value match rejects E5101; selecting no payloads or one would avoid that limit in the candidate. Complete unknown `enum.view` spellings currently report E0004 alone, not E0006 for their borrowed parameters. Isolated `own.view` reports E0004; a used result adds E5001, retaining Q-055's dependent-error gate. This is not adoption, implementation or complete contract coverage.
## Q-058 — Finite anonymous types truncated by the size cycle guard
The checked-property audit independently reproduced three accepted modules at `03614c9` that violate spec 08 §7.1/§11.5: a 1,049,600-byte nested-array parameter, a 1,048,576-byte nested-array local plus one byte, and a 1-GiB nested-array parameter with an unrelated nominal declaration. The budget query counted anonymous wrapper edges toward a cutoff based on the number of nominal declarations, truncating finite content to zero. Claude independently identified the same defect. These are implementation failures against existing mandatory limits, not an unresolved size policy.
**Resolved:** only nominal struct-field/enum-payload edges advance the bounded cycle-query depth; array/atomic/mutex size edges preserve it. Finite valid types therefore follow the existing checked sum/product metric regardless of unrelated declarations. Memo keys and the published runtime cache use the same nominal-depth convention; invalid cycles still terminate within V × (V + 2) nominal states. No new feature, diagnostic code, configurable limit or semantic rule is introduced.
Compatibility impact is explicit: oversized values/frames formerly accepted now reject E5101; valid nested content previously undercharged can select allocation failure under a tight grant. A named 32-byte nested-array record is rejected by a 31-byte heap grant and accepted by a 32-byte grant. Invalid cyclic layouts with large array multiplicities can now exceed max_value_size in the budget stage and report E5101 before E1003; the cyclic-wrapper regression pins that transition with finite found = 4,294,967,297. Diagnostic collection and source-position ordering remain unchanged. AIR and source boundary/rejection cases, runtime quota cases and cached/uncached size tests cover the correction. This fix is separate from adopting or implementing RFC 0039.
## Q-059 — AIR type-syntax nesting and native recursion
**Resolved, 2026-10-10, for the compiler type-traversal scope in the [closing inventory](type-traversal-inventory.md).** The final inspection found another unguarded type walk: `typeOfNoFail`, reached by shallow `r.x.len` expressions with deep field annotations. At d98ddbc, 16,384/65,536 levels abort with 10,001 query frames and no diagnostic JSON; the iterative repair accepts both. All production paths in the inventory now use loops/continuations or their unchanged fixed-depth guards. Units, format checks, all 1,793 conformance files with exact coverage and deep source/AIR CLI integration pass. This adds no syntax-depth limit or semantic rule. Expression/statement recursion, fabricated cyclic host pointers and Q-060's runtime validation are outside this resolution. The following paragraphs retain the historical investigation states.
Source inspection during Q-058 finds recursive `parseType` in `src/air/parse.zig` without an explicit syntax-nesting bound. Size/property traversals also use native recursion over finite anonymous type syntax. **Unverified:** no parser stack-exhaustion reproducer has been run; syntactic finiteness alone does not establish a bound on native stack use.
2026-10-09 [executed audit](air-type-depth-audit.md): a 36,971-byte input with 4,096 length-one nested arrays aborts with a traceback containing thousands of parseType/parseCompoundType frames, rather than a diagnostic. The iterative parser repair accepts that input and unit-tests 32,768 levels, preserving old/new output on 364 public AIR files and constructor/error probes. A subsequent 16,384-depth check still aborts in verifier sizeQuery/sizeValue; that remaining failure is now verified. The original unverified note describes the state before these probes. No syntax-depth acceptance limit is introduced; Q-059 remains open for size, property, validity, equality and formatting traversal audits.
Audit parser and subsequent type traversals before claiming bounded processing for arbitrary AIR type syntax. Iterative traversal could preserve accepted syntax; imposing a new acceptance limit instead needs normative spec 08 resource rules and fixed diagnostic facts. Q-058 does not add such a limit or claim to resolve this separate issue.
The [size-query increment](air-type-depth-audit.md#size-query-repair) removes recursive verifier sizing and inner-budget visiting, preserves nominal-depth/overflow/zero semantics, and adds immutable anonymous-node cache entries. Unit queries handle 32,768 anonymous and nominal levels; AIR/source zero/overflow fixtures and exact old/new output comparisons constrain compatibility. A repeated 16,384-depth CLI probe now aborts in verifier wellFormed, confirming the next native-recursion failure. Uncached nominal fallback, validity, properties, equality and formatting are still open; Q-059 is not resolved and no new input acceptance limit is introduced.
The [type-validity increment](air-type-depth-audit.md#type-validity-and-finite-layout-repair) iterates anonymous position/length checks and finite-layout DFS, preserving graph stops, wrapper gates and ordered cycle diagnostics. Deep unit cases cover 32,768 anonymous and nominal levels. Complete checking at 16,384 now passes wellFormed and aborts in Module.isLinearType; property, equality, formatting and uncached nominal queries remain open. No new depth limit or normative rule is introduced.
The [anonymous property-query increment](air-type-depth-audit.md#anonymous-property-query-repair) removes recursive anonymous linearity/property/dependency walks, preserving Send/Share mode changes, nominal fixed points and the existing saturated height/witness summaries. Complete checking now accepts 32,768 nested arrays. Follow-up checks verify separate remaining failures: Type.eql at depth 65,536 and diagnostic printType at depth 32,768, both without diagnostic JSON. Equality/printing and uncached nominal fallback remain open; Q-059 is not resolved.
The [equality/printing increment](air-type-depth-audit.md#type-equality-and-printing-repair) removes anonymous recursion from Type.eql and diagnostic/canonical printing. The formerly failing 65,536-depth equality check now accepts; the 32,768-depth invalid-atomic check returns one E1001 with the complete found type. The serializer uses an explicit compiler allocator for its suffix stack, retaining AIR spelling and diagnostic fields. Uncached nominal fallback and remaining type-query call paths still need audit; Q-059 remains open.
The [audit-report increment](air-type-depth-audit.md#audit-report-traversal) fixes the capability-kind collector after a verified 65,536-depth module crashes `aji report`. The collector now iterates anonymous edges and retains report contents/order. Uncached nominal/query call paths remain open; Q-059 is not resolved.
The [cache-free nominal size increment](air-type-depth-audit.md#cache-free-nominal-accounted-size-queries) fixes an independently reproduced 32,768-declaration low-level query failure. Uncached queries use temporary explicit continuations, release their metadata and propagate host OutOfMemory separately from arithmetic overflow. Deep queries, 7,168 independent arithmetic comparisons, cached null/partial-cache reads and 54 cached/cache-free verified runtime outcome pairs constrain compatibility. Parsed depth-1,024/4,096 public verification/runtime programmes pass before and after; no old runtime failure at those depths is claimed. Uncached nominal property predicates and remaining public query call paths keep Q-059 open.
The [cache-free nominal property increment](air-type-depth-audit.md#cache-free-nominal-property-queries) repairs independently reproduced failures in all nine uncached structural queries at 32,768 declarations. Public allocator/error APIs reuse the existing iterative fixed-point preparation in temporary storage; cached reads and anonymous terminal paths allocate nothing. Independent shallow comparisons, deep leaf/sibling cases, failed-allocation cleanup and raw/prepared generic-argument accept/reject tests preserve structural rules and diagnostic facts. No acceptance limit or semantic feature is introduced. Closing public-call-path and frontend AST traversal audits keep Q-059 open.
The [source parser increment](air-type-depth-audit.md#source-type-syntax-parser) repairs a confirmed `typeExpr` failure at 16,384 source-array levels, preserving syntax, argument order, split-angle spans and existing shallow diagnostic envelopes. Deep speculative slice-advice parsing also returns its original E7001 instead of aborting. The same monomorphic file now formats but full checking reaches a confirmed recursive `usesGenerics` failure; that remaining source AST traversal keeps Q-059 open. The generic depth-64 guard is not silently extended to ordinary parsed annotations.
The [source generic-use increment](air-type-depth-audit.md#source-generic-use-detection) replaces the confirmed recursive AST scan with explicit borrowed work entries. Generic-use markers, field order and the specialization path are unchanged; independent shallow comparisons, deep positive/negative ASTs and failed-allocation cleanup cover the query. The repeated 16,384-array check now passes this stage and confirms the next native-stack failure in lower.resolveType. Source lowering/remaining traversals and the closing audit keep Q-059 open; no generic guard is imposed on monomorphic parsing.
The [source annotation resolution increment](air-type-depth-audit.md#source-annotation-resolution) replaces recursive source-to-Ty construction with explicit continuations while preserving pre/post checks and error positions. Deep isolated resolution succeeds; complete checking exposes the next confirmed failure in type_properties.firstInvalid. Source property traversal, diagnostic text and closing call-path checks remain open; no universal source depth limit is added.
The [source anonymous property increment](air-type-depth-audit.md#source-anonymous-property-scans) removes confirmed recursion from firstInvalid and the array-chain portion of known linearity. Both 16,384-array and own_array checks now accept, while non-Copy content retains E7005 at its original span. A separate 8,192-declaration probe confirms remaining linear/declaration native-stack exhaustion before and after this increment. Named-declaration repair and source Ty/query closing checks remain open; no acceptance limit or semantic rule changes.
The [source nominal property increment](air-type-depth-audit.md#source-nominal-property-continuations) repairs the confirmed linear/declaration failure with explicit argument/member continuations, retaining cache generations and known-parameter cycle states. An independent recursive nominal oracle checks ordered cache records; complete checking accepts the 8,192-Copy chain and rejects linear content with E7005. A separate 65,536-array invalid-atomic source confirms typeText native-stack exhaustion. Source Ty text/equality/AIR conversion and closing call-path work keep Q-059 open; no semantic limit or rule changes.
The [source type text increment](air-type-depth-audit.md#source-type-text-repair) repairs the confirmed diagnostic printing failure with iterative prefix/suffix output and exact canonical/source naming. Host OOM propagates instead of supplying fabricated type strings. The deep invalid atomic now returns E7005 with its complete found type, and a correct 65,536-array parameter accepts. A 16,384-array struct member independently confirms the remaining airType native-stack failure. Source-to-AIR repair, Ty equality and closing query audits still keep Q-059 open. No semantic limit or rule changes.
The [source-to-AIR conversion increment](air-type-depth-audit.md#source-to-air-type-conversion) repairs airType using a constant-state target cursor with the same constructor allocations and host-error behavior. Deep struct-member checks now accept; an independent return-equality probe confirms Ty.eql native-stack exhaustion at 65,536 array levels. Source equality and closing query work keep Q-059 open; no accepted-depth limit or semantic rule changes.
The [source equality increment](air-type-depth-audit.md#source-type-equality) repairs Ty.eql with allocation-free cursors preserving structural identity. Deep equal returns accept and unequal leaves yield one factual E7005 with complete types. A deep move-on-Copy query produces E7006/move_copy without a native failure. Closing source-query inventory keeps Q-059 open; Q-060 and Phase 6 gates remain separate. No semantic rule or accepted-depth limit changes.
The [remaining source linear-query increment](air-type-depth-audit.md#remaining-source-linear-queries) replaces array descent and signature feature scanning with allocation-free loops, preserving prepared nominal reads and the module-sized depth guard exactly. No preceding CLI failure in these queries is claimed. The closing inventory independently confirms Lowerer.zeroValue stack exhaustion on 16,384 arrays above a non-zeroable source record. Source zero emission and specialization/call-path inspection keep Q-059 open; this does not resolve Q-056 or change zeroability.
The [source SSA zero increment](air-type-depth-audit.md#source-ssa-zero-emission) repairs that native failure with explicit parent storage, preserving constant/splat ordering and the implemented leaf classification. Both 16,384/65,536-level checks now return the existing E7006/zero_not_zeroable, with no new traversal allocation for unsupported leaves. Exact emission/error comparisons, supported helper sequencing, OOM cleanup and old/new fuel-boundary runs constrain compatibility. Specialization/call-path inventory keeps Q-059 open; Q-056's source zeroability decision is not resolved here.
The [composed identity increment](air-type-depth-audit.md#composed-specialization-identity) repairs independently reproduced native failures during expanding generic substitution. Iterative key emission retains postorder byte-limit checks, spans, canonical identities and all existing specialization limits. Two tiny source regressions now reach E7006/implementation_limit instead of aborting; all 1,793 current conformance files are covered by the full prior snapshot plus the two additions. Closing call-path inventory keeps Q-059 open; helper-only deep identity tests are not broader source acceptance claims.
## Q-060 — Native recursion while materializing runtime values
**Closed (2026-10-14).** All five confirmed native-recursion paths are repaired, and the [full per-step validation result](runtime-value-depth-audit.md#full-per-step-validation-result-2026-10-14) covers all 1,793 conformance tests with collection before every step (composite of one stalled original run and 150 per-test processes on the same snapshot). The original single process has no terminal exit status yet; a later failure from it would reopen this entry. The historical paragraphs below describe superseded states.
The [executed runtime audit](runtime-value-depth-audit.md) confirms that a verified one-byte value with 32,768 length-one nested arrays aborts inside zeroValue under `aji run --fuel 8`, rather than producing a run record. The instruction has not exhausted fuel. Iterative runtime traversal must preserve initialization, value shape, allocator/root lifetimes, collection safety and instruction accounting; adding a depth trap/acceptance limit needs a normative decision. At that baseline, recursive copying, value sizing, collection and serialization were additional audit candidates with unverified failure paths; the increment below records subsequent executed failures. Compiler type repairs in Q-059 do not resolve Q-060.
The [zero-materialization increment](runtime-value-depth-audit.md#zero-materialization-repair) removes recursion from zeroValue while preserving payload shape/order, whole-local publication and instruction accounting. Deep unit tests cover 32,768 anonymous/nominal levels and pending siblings; the original run now returns normally. Follow-up probes independently verify native-stack failures in deepCopy/copyAll on local.load and Copier.value/items with collection before every instruction. Those are remaining Q-060 work, not a new acceptance limit; value sizing and output serialization remain audit candidates.
The [storage/value-copy increment](runtime-value-depth-audit.md#storagevalue-copy-repair) removes recursion from deepCopy/copyAll while retaining per-occurrence payload independence, aggregate identities, shallow handles and failure publication rules. The previous 32,768-level local.load run now returns normally. An added local.store forces ordinary-threshold collection and independently confirms the remaining Copier.value/items native-stack failure, without collect-every-step instrumentation. Sharing-preserving collection/result copying, accounted-value queries and output serialization remain open; no accepted-depth or trap limit is introduced.
The [sharing-preserving copy increment](runtime-value-depth-audit.md#sharing-preserving-copy-repair) removes recursive collector/result copying while retaining forwarded identities, backing storage, cycles, slice paths/ranges, buffer metadata, race shadows and mutex views. Deep verified runs now pass ordinary and per-instruction collection, with unchanged fuel boundaries and returned payload lifetimes. Follow-up CLI probes independently confirm valueBytes native-stack exhaustion on own.new and output failure at std.json.Stringify's fixed nesting stack. The latter is not yet evidence of writeValue native-stack overflow. Q-060 stays open for sizing and serialization; no normative depth limit, feature or trap is introduced.
The [runtime value-size increment](runtime-value-depth-audit.md#runtime-value-size-repair) iterates fixed-array first-element chains with constant state, preserving zero-sized leaves, checked overflow, nominal maximum payloads and the element-before-dynamic-count rule. The previously crashing 32,768-level own.new probe now returns normally with the original one-byte charge; zero authority takes the original failure edge. Deep verified fuel/collection tests, nested-quota AIR/source runs and an independent allocation-size oracle constrain compatibility. Q-060 remains open for output serialization; there is no new normative limit or trap, and Q-059's nominal-query audit remains separate.
The [runtime value JSON increment](runtime-value-depth-audit.md#runtime-value-json-repair) removes recursive value serialization and bypasses the outer stringify's fixed nesting table for internal payloads. Exact encoding/options, outer-container state, writer/allocation failure and deep returned-payload lifetimes are tested; the formerly failing CLI now emits a complete record in deterministic and hosted profiles. All five confirmed Q-060 failure paths have repairs, without a new limit or trap. Q-060 remains open for closing call-path checks, including the inspection-only cache-free public verification/runtime entry path and its connection to Q-059's uncached nominal queries; no verified failure on that path is claimed yet.
The [cache-free runtime increment](runtime-value-depth-audit.md#cache-free-runtime-size-query-path) removes the recursive accounted-size fallback available through public verification/runtime entry. All runtime size callers propagate temporary metadata OOM before authority charging, retaining quota, fuel and ownership behavior. The deep query-only failure is independently reproduced and repaired; verified library entry and cache equivalence are separately tested. Q-060 remains open for closing traversal checks and full per-step validation; no new normative limit, trap or diagnostic is introduced.
The [closing path/lifetime inspection](runtime-value-depth-audit.md#closing-runtime-paths-and-error-exit-cleanup) identifies and repairs a separate execution-arena leak on propagated host OOM. Failure tests across caller/result and execution/collection allocations verify complete release under ordinary/per-step collection; all 1,793 ordinary conformance cases and test-extended pass. The runtime traversal inventory is documented, with verified handle-shape preconditions for the remaining one-borrow selectors. Both full GC processes are now confirmed live by host-namespace inspection, correcting an earlier mistaken termination inference; an additional std run emits each completed record immediately. None has terminal full-pass evidence yet, so Q-060 remains open for full per-step validation.
The [2026-10-11 per-step observation](runtime-value-depth-audit.md#per-step-validation-observation-2026-10-11) finds the historical ReleaseSafe process absent with 1,789 distinct passing records but no available exit status. Current ReleaseSafe GC-mode filtered runs cover exactly the four absent current cases with exit 0; two are verifier rejections. Debug/full and source/std processes remain live. This focused supplement does not prove the full current-binary GC gate; Q-060 remains open.
## Q-061 — Source expression/statement nesting and native recursion
**Closed (2026-10-13) for the native-stack-abort defect**, using the
final probe battery and the preceding traversal repairs. The
[closing observation](source-expression-depth-audit.md#closing-observation-and-performance-limitation-2026-10-13)
records the tested constructions, timings and limits of that evidence. Deep
`loop` was probed later (2026-10-14, see Q-063): no native-stack failure.
Closure is not a proof of arbitrary-depth
acceptance or linear compilation time. Superlinear lowering is separately
tracked in Q-063; Q-060's full per-step GC validation is closed separately.
The paragraphs below record chronological checkpoints. Later repairs supersede
earlier failure/OOM findings; the [current inventory](source-expression-depth-audit.md#remaining-work)
lists the remaining paths.
Inspection during Q-059's closing inventory finds native recursion through source expression parsing (`binary`/`unary`), expression queries (`peekType`/`useIn`) and generic expression transformation (`expression`/`walk`). The fixed generic type/instantiation guards do not establish a bound on arbitrary expression or statement nesting. **Unverified:** no expression/statement stack-exhaustion probe has been run in this audit; this entry records inspection risk, not an observed failure or a new acceptance rule.
Follow-up [expression-depth probes](source-expression-depth-audit.md) now confirm native-stack aborts without JSON diagnostics: 1,024 `not` prefixes fail in lowering; 16,384/65,536 fail earlier in the unary parser. The parser's direct prefix recursion is replaced by explicit continuations with unchanged grammar, AST spans, syntax errors and OOM propagation. Deep parse/format/missing-operand checks pass, but the confirmed lowering failure and other expression/statement paths remain open. The preceding inspection-only statement describes the initial checkpoint, not the current evidence.
The [unary lowering/addressability increment](source-expression-depth-audit.md#unary-lowering-and-addressability-continuations) removes direct not/neg/deref/cast descent and the separately confirmed recursive storage-marking prepass. Typed scalar checks/lowerings pass through 65,536 nodes; direct malformed dereferences return their inner E7005. Instruction order, signed-boundary literals, storage policy, diagnostics and host OOM propagation are retained. Q-061 remains open: a separate 16,384-dereference operand beneath a cast still aborts in `peekType` without stdout JSON, confirming the next query path; other expression/statement and generic paths remain to be audited. No normative depth limit is inferred from these repairs or tests.
The [expression-query increment](source-expression-depth-audit.md#expression-type-query-continuations) repairs that cast/dereference failure and the recursive callee path callbacks. Query continuations retain existing classification and fallback order; host metadata OOM follows the best-effort unknown-result contract. Deep cast/dereference checks now return the expected inner E7005, and deep unknown callees return E7002. This does not close `useIn`, other expression/statement lowering, nested primary parsing or generic expression transformation; no whole-frontend bound or new acceptance rule is claimed.
A subsequent finite source probe, `let n = 1; return - … n;` in an i64 function, accepts 1,024 negations but aborts without stdout JSON at 16,384 in `useIn`, during expected-use inference for the unsuffixed binding. Its raw evidence is in the linked audit. Q-061 remains open for that confirmed path and the other unverified paths above.
The [expected-use increment](source-expression-depth-audit.md#expected-use-query-continuations) repairs that mutual expression/statement/block query path. It preserves lazy hint queries, search order, cast hint removal and the outer let rebinding barrier; deep inferred unary checks accept through 65,536 and missing hints retain E7007. No new inference or acceptance limit is introduced. Follow-up finite probes now confirm separate native failures at 1,024 levels in binary lowering, parenthesized parsing and generic expression transformation. Q-061 remains open for those observed paths and the remaining inventory.
The [binary operand increment](source-expression-depth-audit.md#binary-operand-lowering-continuations) shares explicit continuations with unary lowering, preserving type/error priority, instruction order and short-circuit CFG. Arithmetic checks/lowerings accept through 65,536 operations; deep boolean chains now reach the existing E5101 block limit without stack failure. No normative depth limit or operator rule changes. Current parenthesized and generic-unary checks still abort at 1,024 levels; Q-061's remaining inventory and independent Phase 6 gates stay open.
The [external review and host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) supersede the initial query OOM-to-unknown policy. A one-shot allocation failure reproduces false E7007 before repair. Expression/expected-use queries and their annotation, field, signature and place callbacks now propagate host OOM separately from optional unknown answers. Worklist buffers retain caller-arena lifetime; list deinit is not immediate physical release. The audit explicitly inventories non-scalar parsing/lowering, generic cloning/path callbacks and liveness/read/assignment scans. Build/units/format checks, all 1,793 ordinary conformance cases, 360 expression-depth and 234 independent-error CLI checks pass; frozen old/new public checks/lowerings remain exact (1,423/506). Recovering caller/callback and public-lowering allocation tests reject false diagnostics and partial publication. Q-061 remains open; this follow-up has no external review yet.
The [generic transformation increment](source-expression-depth-audit.md#generic-ast-transformation-continuations) replaces expression/statement/block cloning and its qualified-path callback with typed work entries. AST/error/instance order, spans, Copy-transfer and static-worker policy are preserved; existing type/instance guards remain. A separate baseline confirms generics.path also aborted on a 16,384-field unknown callee. Full generic scalar checks/lowerings now accept through 65,536; deep unknown callees return exact E7002. Independent shallow/deep/OOM and 497/42/25 CLI checks pass; frozen old/new public checks/lowerings remain exact (1,423/506). All 1,793 ordinary conformance cases pass with exact coverage. Follow-up probes confirm remaining parser failures at 1,024 parenthesized/mixed-call levels and 16,384 qualified-variant fields. Q-061 remains open, without a new limit or external review of this increment.
The [parser constructor-path increment](source-expression-depth-audit.md#parser-qualified-constructor-paths) repairs Parser.exprPath independently of generic/lowering paths. Frozen baseline probes confirm enum and struct constructor aborts at 16,384 fields; the repaired CLI returns exact E7002 through 65,536. Named-root classification, spelling, type arguments, spans, syntax errors and host OOM propagation are preserved, with one complete string allocation. Q-061 remains open for the confirmed parenthesized/mixed-call parser failures and the remaining lowering/liveness inventory; no new acceptance limit or external review is claimed.
The [shared expression parser increment](source-expression-depth-audit.md#shared-expression-parser-continuations) removes native re-entry through grouping, call arguments, arrays, index bounds and struct fields, sharing binary/cast/unary/postfix/primary continuations. Token/AST/spans, grammar/error priority and scoped advice remain unchanged; host OOM propagates without diagnostics or partial AST. Reused work storage and stable driver frames retain caller-arena lifetime. Block/control callbacks still recurse outside the large dispatch frame; their bounded regression probes pass, without an arbitrary-depth claim. Grouped programs check through 65,536; mixed calls format through 65,536 but checking at that checkpoint still aborted in lowerer `call` at 1,024. Q-061 remains open for that confirmed path and remaining control/liveness traversal; no new limit or external review is claimed.
Audit these paths separately with finite public/generated source inputs before claiming whole-frontend bounded native-stack processing. Prefer explicit continuations preserving existing syntax, evaluation/query order, diagnostics and OOM behavior. A new depth rejection requires a normative decision; Q-059's type-traversal resolution does not authorize one.
The [ordinary-call increment](source-expression-depth-audit.md#ordinary-call-argument-continuations) shares call arguments with scalar continuations, preserving signature/error priority, left-to-right consumption, loans, retained parents, CFG and host OOM behavior. Stable arena-owned states retain bounded builtin/control regression capacity. Build/units/format checks, exact ordinary conformance coverage and call-related CLI suites pass. A separate alternating struct/field program still aborts at 1,024 before and after; builtin/variant/place, aggregate/control and remaining liveness/read/assignment paths keep Q-061 open. No semantic or depth limit changes and no fresh external review are claimed.
The [struct/value-field increment](source-expression-depth-audit.md#struct-construction-and-value-field-continuations) preserves declaration-order initializer checks, receiver lookup and deferred annotation queries, nominal/static/slice length rules, loans and host OOM. Independent shallow/deep comparisons, output-arena failure cleanup, exact ordinary conformance coverage and public CLI parity pass. The former struct/field abort is repaired; at that checkpoint nested array literals still aborted at 4,096 before and after. Remaining array/variant/place/control callbacks and liveness/read/assignment walks keep Q-061 open. No semantic or new depth limit changes are made. Independent read-only Claude core/follow-up reviews found no concrete defects, without running tests or establishing whole-Q-061 completion.
The [array-continuation increment](source-expression-depth-audit.md#array-list-and-repetition-continuations) preserves list inference/consumption/check priority, repetition bounds/Copy rules, emission/loans and host OOM. Independent comparisons and deep sibling/error/OOM tests pass; the former pure-list failure at 4,096 now accepts. Variant-payload/call alternation still aborts at 256 before and after; remaining native callbacks and liveness/read/assignment walks keep Q-061 open. No new semantic or depth limit changes. All 1,793 ordinary conformance cases, 246 focused depth CLI checks and exact public check/lower parity (1,423/506) pass. Read-only Claude core/follow-up reviews found no production defects; their fixture gaps were corrected. Whole-frontend, loop/liveness and Phase 6 completion are not established.
The [enum-payload increment](source-expression-depth-audit.md#enum-payload-continuations) preserves lookup/arity-before-arguments, per-payload type/consumption/check order, empty/built-in construction, spans/loans and OOM. Independent shallow/deep/sibling and direct/public allocation tests pass; exact ordinary conformance coverage and final public check/lower parity (1,423/506) pass. The former enum-payload failure at 256 is repaired; nested assert still aborts at 1,024 before and after. Scoped read-only Claude reviews found no semantic defects; 331 core and 66 final supplementary CLI checks pass. Q-061 and Phase 6 remain open, with no semantic or new depth limit change.
The [boolean builtin increment](source-expression-depth-audit.md#boolean-builtin-operand-continuations) preserves assert/assume arity, non-consuming operands, type/error spans, unsafe registration and emission order, using shared continuations. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 282 focused depth checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up reviews found no production defect. Final span/counter unit checks pass. At that boolean checkpoint own/region argument callbacks still aborted at 1,024 before and after; remaining callbacks/walks keep Q-061 and Phase 6 open. No new semantic or depth limit changes.
The [consuming ownership builtin increment](source-expression-depth-audit.md#consuming-ownership-builtin-continuations) preserves own.take/free and region.destroy arity, explicit transfers, type/error priority, emission and OOM separation. All 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 351 frozen-core CLI checks pass; corrected OOM/expanded units pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews found no production defect. Final `own<bool>` CFG unit comparisons pass. At that consuming checkpoint atomic-new/take pairs and task.join still aborted at 1,024. Q-061, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change.
The [atomic operand increment](source-expression-depth-audit.md#atomic-operand-continuations) preserves new/take and ordinary update operand rules, cell/ordering/type priority, temporary loans, emission and host OOM separation through shared continuations. Build/units/format, all 1,793 ordinary conformance cases, public check/lower parity (1,423/506) and 33/635/234 targeted checks pass. Focused depth validation passes 270 checks in two subset runs (57/213), including exact rejections and temporary-loan updates through 65,536; mixed chains reach the existing E5101 instruction limit, with runtime/fuel checked through 1,024. Read-only Claude core/follow-up reviews found no production defect. At that checkpoint task.join still aborted at 1,024; other callbacks/walks, Q-060 full GC and Phase 6 gates remain open. No semantic/order-default/depth-limit change.
The [task.join increment](source-expression-depth-audit.md#task-join-operand-continuations) preserves consuming/type/result/void rules, spans, loans and host OOM through the shared driver. Build/units/format, exact ordinary conformance coverage, public check/lower parity, lifetime/related/CFG checks and 522 focused CLI checks pass, with valid call operands and exact rejections through 65,536 and runtime/fuel through 1,024. Read-only Claude core/follow-up reviews found no production or fixture defect. At that checkpoint a valid 16-level alternating join/spawn probe still aborted at 256 before/after, confirming the next spawn-argument callback. Other callbacks/walks, Q-060 full GC and Phase 6 gates remain open; no semantic/depth-limit change.
The [spawn increment](source-expression-depth-audit.md#task-spawn-argument-continuations) preserves scope/worker/arity/per-argument priority, moves, bound loans, emission and host OOM with shared continuations. Build/units/format, exact ordinary conformance coverage, public check/lower parity and lifetime/related/CFG/static-worker checks pass. The focused gate completes 497 distinct CLI checks across split runs, with original/formatted lower parity through 65,536, scalar/pair check through 65,536, mixed check through 32,768 then existing E5101, runtime/source-AIR/fuel through 1,024 and rejected positions through 65,536. Read-only Claude core/final follow-up reviews found no production or fixture defect, within their recorded scope. At that spawn checkpoint nested mutex.make/take aborted at 256/1,024 before/after and was next. Graph/place/control/liveness and multi-result callbacks, Q-060 full GC and Phase 6 exit gates remain open; no semantic/depth-limit change.
The [mutex make/take increment](source-expression-depth-audit.md#mutex-maketake-operand-continuations) preserves consuming/content/type priority, explicit moves, spans, loans, emission and host OOM. Build/units/format, lifetime/related/CFG and 310 focused CLI checks pass; scalar checks and original/formatted lower reach 65,536, mixed checks reach 32,768 then existing E5101, runtime/source-AIR/fuel reach 1,024 and rejected positions reach 65,536. All 1,793 ordinary conformance files have exact successful coverage. Frozen public check/lower parity passes (1,423/506) over `tests/conformance/**/*.aji`; read-only Claude core/final reviews found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. At that mutex checkpoint index operands aborted at 1,024 before/after; other walks, Q-060 and Phase 6 remain open. No semantic or depth-limit change.
The [scalar index operand increment](source-expression-depth-audit.md#scalar-index-operand-continuations) preserves base/type/operand priority, usize hints, bounds facts, unchecked state, loans, load/end order, spans and host OOM. Build/units/format and store-mode/array-argument/lifetime/CFG suites pass; exact ordinary conformance (1,793), public frozen parity (1,423/506), the original focused run passes 318 CLI checks (check through 32,768 then existing E5101 at 65,536; lower/fmt through 65,536; runtime/fuel through 1,024), and separate overlapping 30-call fuel/28-call CFG/deref/proven-context subsets pass. Read-only Claude core/final reviews found no production defect and their fixture/wording suggestions are covered. At that scalar-operand checkpoint the recorded nested-array base-index probe still aborted at 1,024 before/after; its subsequent repair is recorded below. Other place/control/liveness callbacks, Q-060 and Phase 6 remain open. No semantic or new depth-limit change.
The [raw-place base increment](source-expression-depth-audit.md#raw-place-base-continuations) repairs the recorded 1,024-level nested-array base failure using iterative field/index projections and one ancestor-name list. Borrow modes, parents, child-first ends, range ordering, facts, unchecked selection, spans and host OOM separation are preserved. Exact ordinary conformance coverage, public check/lower parity and 159 focused CLI calls pass; expanded units pass, and scoped read-only Claude core/final reviews found no production defect. Follow-up block/if probes confirm remaining parser aborts at 1,024 before/after. Q-061, Q-060 full GC validation and Phase 6 remain open; no semantic or depth-limit change.
The [shared control-parser increment](source-expression-depth-audit.md#shared-control-parser-continuations)
removes native expression/control re-entry through blocks/statements, conditions,
if/else-if, match/arms, select, loops, scopes, shield and lock. Deep mixed,
ungrouped-condition and wide ASTs, token EOF/deletion sweeps, scope/advice,
scratch and recovering/persistent OOM tests pass. All 1,793 ordinary conformance
files have exact successful coverage; public check/lower parity (1,423/506),
grammar/format/error/advice suites and 127 focused CLI calls pass. Scoped
read-only Claude reviews found no production defect. Arena backing/RSS figures
are informational, not an efficiency gate. Full block/if checks still abort at
1,024 in lowering; control/liveness and remaining callbacks, Q-060 full GC and
Phase 6 stay open. Q-062 separately logs a preserved grouped-statement gap.
The [pruned-SSA liveness increment](source-expression-depth-audit.md#pruned-ssa-liveness-continuations)
removes confirmed read/assignment/After native recursion, preserving first-use
kills, loop steps, sibling gates, rest-frame order and pruned join sets. Host
OOM now propagates instead of the former select fallback's silent read fact.
Exact ordinary conformance coverage, frozen public parity and the full 418-call
source liveness CLI suite pass through 65,536 scalar wrappers; nested blocks
still abort later in `blockBodyWant`/`expr`. Final expanded units pass (332/332).
Direct AST tests and scoped Claude reviews do not establish arbitrary control
lowering or the performance of repeated nested-loop rescans. Q-061, Q-060 full
GC validation and Phase 6 remain open; no semantic or accepted-depth change.
## Q-062 — Parenthesized block constructs without a statement terminator
**Open; existing source-parser behavior, not a new rule.** Spec 15 §4 makes
unparenthesized block constructs self-delimiting and requires semicolons for
ordinary expression statements; the reference grammar includes `expr ";"` in
`statement`. The parser also accepts a parenthesized block/if/match followed by another
statement without `;`, through the ordinary expression path's block-kind
fallback. Claude identified this during the Q-061 control-parser review.
A frozen HEAD `9534359` binary and the shared-control-parser candidate both
accept this complete source with exit 0 and no diagnostics:
```aji
module grouped
fn g() -> void effects [] {}
fn main() -> u64 effects [] {
(if true {} else {}) g();
return 0u64;
}
```
The Q-061 traversal repair deliberately preserves this behavior. A separate
spec/parser decision and positive/negative boundary tests are needed before
changing acceptance. This does not add a semantic rule or close Q-061.
## Q-063 — Superlinear lowering on deeply nested control constructs
**Open; known implementation performance limitation (2026-10-13).** The
[final source-depth probes](source-expression-depth-audit.md#closing-observation-and-performance-limitation-2026-10-13)
report superlinear elapsed time for nested `match`, `while` and especially
`shield`; nested `loop` (probed 2026-10-14) behaves the same: 7.2 s at 1,024
levels, 108 s at 4,096 (then the ordinary E5101), and no result after more than
ten minutes and about 480 MB at 16,384, where the agent stopped it. No
native-stack aborts or observed correctness defects. This
tracks resilience to adversarial source input separately from Q-061's repaired
stack-exhaustion defect.
The [2026-10-14 stage timings and sampled stacks](control-depth-performance-audit.md)
separate three causes: repeated enclosing-rest liveness searches dominate
mutable-match lowering (about 8× work per depth doubling at 256–512); textual
incoming-block-reference scans in `Lowerer.reaches` dominate no-mutation while
lowering and also appear for loop; shield relation maintenance dominates AIR
verification, independently of liveness. All 315 timed commands and five
profiled targets accept normally. This is a finite Debug profile, not a
portable timing bound or a whole-compiler complexity proof.
Q-060's full per-step validation is now closed by its composite audit.
Profiling for Q-063 is complete for these paths. The
[first optimization](control-depth-performance-audit.md#first-optimization-loop-exit-reference-index-2026-10-14)
indexes loop-exit references at instruction emission rather than repeatedly
scanning the whole function. Paired CPU-pinned Debug lowering at 512 levels
improves while by 3.22×, loop by 1.85× and mutable while by 1.80×, with exact
public check/lower and runtime/fuel compatibility. That slice preserved the
legacy reference policy; Q-064 now records its separate correction with
explicit CFG incoming edges.
The [second optimization](control-depth-performance-audit.md#second-optimization-negative-after-query-reuse-2026-10-14)
reuses one completed negative subtree After query while walking enclosing Rest
frames, with AST identity/name/construct guards. Paired Debug mutable-match
lowering at 512 levels falls from 30.982 to 0.635 seconds (48.77×), with 341 unit
tests, 1,799 conformance cases and exact source/AIR/runtime comparisons. This
preserves first-use kills, sibling exclusion and loop reads; it is not a global
variable-liveness cache. The
[third optimization](control-depth-performance-audit.md#third-optimization-indexed-resource-relations-2026-10-14)
indexes resource relations by endpoints and kind while preserving insertion
order. Removal touches only incident facts, and loan checks no longer scan
shield-order facts. Paired Debug source checking at 1,024 nested shields falls
from 12.154 to 5.073 seconds (2.40×), with 348 unit tests,
1,813 conformance cases and exact diagnostic/runtime/fuel comparisons. Index
storage increases peak RSS; the audit records the measured tradeoff. The
quadratic number of `.inner` facts and remaining assignment/read/positive-query
costs keep Q-063 open. A later optimization needs exact CFG/SSA,
diagnostic-order, host-OOM and runtime/fuel compatibility checks.
No source-depth limit, new diagnostic, verifier rule, AIR instruction or
language semantic change is introduced by recording this limitation.
## Q-064 — Loop-exit reference search confuses function and block names
**Closed; frontend diagnostic defect corrected (2026-10-14).** While
optimizing Q-063, a frozen pre-change Debug binary at `17cbe3e` accepts this
source in both `lower` and `check`, with exit 0:
```aji
module probe
fn after_2() -> void effects [] {}
fn main() -> u64 effects [] {
loop { after_2(); return 0u64; }
return 1u64;
}
```
Changing only the helper's name to `after_3` makes both commands reject the
statement after the loop with E7006 `unreachable`. Spec 15 §10 requires E7006
for expressions after unconditional divergence. The old `Lowerer.reaches`
searches instruction text for a generated exit name (`after_2` here), and
mistakes `call @after_2()` for an incoming reference to that block. Its
first-substring test also allows an earlier non-reference substring in one
instruction to mask a later genuine reference in that same instruction.
The Q-063 reference-index optimization initially preserved this behavior;
it did not make the collision a language rule. The separate correctness fix
replaces that compatibility index with a per-block incoming-edge bit, updated
from explicit target indices only after a terminator is successfully emitted.
Every terminator declares its successors; `select` reuses its existing outcome
metadata. Calls and operand names cannot supply or mask a block edge. The bit
counts syntactic edges, including edges from disconnected blocks; this is not
entry-reachability analysis or constant folding. A host allocation failure
publishes neither the instruction nor its edges.
The other confirmed direction was a false rejection: in
`fn f(after_2: bool) -> u64`, `while after_2 { return 1u64; } return 42u64;`
previously reported E7006 at the reachable return. The operand's earlier
`after_2` substring masked the real exit target in the conditional branch.
This now accepts, returning 42 for `false` and 1 for `true`.
Qualification: 342 unit tests, 1,808 conformance cases (nine new), 182 targeted
CLI checks, plus the diagnostic-reason, independent-error, CFG-provenance and
hosted smoke suites. All 2,858 `check`/`lower` comparisons on 1,429 pre-existing
public sources and 240 runtime/fuel comparisons match the frozen pre-fix
executable exactly. Fourteen of the eighteen new fixture comparisons change
intentionally: five false acceptances reject E7006 `unreachable`, and two
false rejections accept; two valid break cases retain exact output. Diagnostic
priority, source/package positions, formatting, function-local state and host
OOM are covered. Incoming metadata is also checked against independently
parsed AIR successors for ten lowering programs. The frozen textual predicate
remains only in compatibility tests, with its collisions explicitly tested as
old defects.
The [control-depth audit](control-depth-performance-audit.md#correctness-follow-up-explicit-cfg-incoming-edges-q-064-2026-10-14)
records the implementation and evidence in
`/tmp/aji-q064-20261014-x_a6b4gb/`. Spec 15 §10 already requires the corrected
behavior: no new diagnostic, source rule, verifier rule, AIR meaning or runtime
instruction is introduced. Q-063's remaining performance work stays open.
+256
View File
@@ -0,0 +1,256 @@
# Assessment of the 2026-10-07 design review
Non-normative. Verification of [the original review](review-2026-10-07.md), which is left unchanged. This assessment neither accepts an RFC nor changes priorities, language rules or the benchmark. Routes below are recommendations for a subsequent proposal or owner decision, not newly scheduled implementation work.
## Scope and method
Checked against the current working tree on 2026-10-07: HEAD `715a8be` plus the uncommitted Q-034/P6-11 implementation (RFC 0036, **Proposed**). This matters for C9: borrow returns are now implemented for review; their RFC is not accepted. Earlier measurements refer to their recorded toolchain, not this working tree.
Read the relevant normative sections, diagnostic implementation, frontend mapping, std module registry and implementations, evaluation reporting code, public evaluation reports and B1 pre-registration. Ran existing negative fixtures for E2101, E2104 and reserved floating-point types. Measured bundles using the repository tooling during P6-11 validation. No private task statements, solutions, transcripts or held-out corpus were inspected. Private execution progress cannot be established from the public plan.
The five review questions are abbreviated below as **truth**, **existing coverage**, **consistency**, **mission**, and **payoff**. `confirmed`, `partly` and `wrong` describe observations, not approval of a proposal. Proposed benefits remain hypotheses unless a cited experiment measures them.
## Measurements and reading cost
Reproduction:
```sh
zig build agent-reference
uv run --with tiktoken --with tokenizers tools/agent_bundle_tokens.py --source
```
| Current generated material | cl100k_base | o200k_base | Qwen2.5 |
|---|---:|---:|---:|
| Quick Reference including navigation (`QUICK.md`) | 8,642 | 8,677 | 8,900 |
| Other source documentation | 64,160 | 64,359 | 65,733 |
| Full source documentation, excluding AIR | 72,802 | 73,036 | 74,633 |
| `library/std.md` (included above) | 26,454 | 26,556 | 26,950 |
| AIR reference (excluded from full source above) | 46,300 | 46,451 | 47,800 |
These are **available documentation**, not tokens every run consumes. P6-11 changed cl100k Quick Reference 8,518 → 8,642 (+1.46%) and full source 71,814 → 72,802 (+1.38%). The pre-stdlib full-source baseline recorded in the RFC sequence was 33,981; current cumulative growth is +114.24%. AIR did not grow in P6-11.
[P6A-9](../evaluation/results/2026-10-05-p6a-9.md) provides evidence for selective reading on its older bundle: source cells read the Quick Reference plus roughly 0.4–8.6k other tokens, with one partially measured Quick Reference read. It also reports IR-form diagnostics 9 → 0, accepted cells 4/6 → 5/6, and mixed cost results. It does **not** measure today's 72.8k bundle or std. Its frozen commit `591f0ae` contains neither the current `std/` source modules nor `src/frontend/stdlib.zig` (checked with `git ls-tree`). No private M/C programs need to be opened to establish that these modules were unavailable in those official runs. Subsequent uses, if any, are not established here.
Documentation follow-up: the opening Source Reference Bundle table in [agent/README.md](../agent/README.md) described approximately 26.8k total and omitted later files. Following owner discussion it is now explicitly labeled historical. Q-016 and Quick Reference also clarify the already implemented floating-point reservation. The measurement table above remains the assessment-time snapshot before that Quick Reference sentence was added.
### Follow-up: B1 excludes the current std
The public tag `b1-frozen` resolves to commit `268926ca0f46eb180de1b506be2c28e815bd60ae` (2026-10-06). Checked its tree, `docs/agent/source-bundle.txt` and `tools/eval/languages/aji_source.json`:
- No current `std/` modules or `src/frontend/stdlib.zig` exist in that tree.
- The source bundle manifest contains no `library/std.md`; the source-doc group contains only `language/` and `diagnostics/`.
- The declared compiler therefore cannot execute programs using the current bundled std APIs. B1 as publicly specified cannot measure their use or benefit, and its default documentation input cannot measure reading their reference.
The actual private freeze record and mounted artifacts were not inspected; the freeze mechanism records their hashes and supports documentation overrides, so the public tag alone cannot certify their exact bytes. This limitation does not make current std available in the declared frozen compiler. A later experiment must explicitly freeze a compiler containing std and its documentation, account for `library/` reads, and distinguish imported modules from called APIs and executed calls. Existing audit call data may supply some static usage facts; the required usage metric should be specified before that experiment's freeze, not retrofitted during B1.
This strengthens B1/B2: source documentation more than doubled, the front door exceeded its target, and neither P6A-9 nor the declared B1 treatment evaluates current std. It justifies measuring current std in a subsequent experiment; it does not establish a freeze policy or a benefit. The std reference's 26,454 tokens are smaller than the pre-stdlib full-source baseline of 33,981, despite accounting for a substantial part of the current total.
## Part A — Properties to retain
| ID | Truth and existing coverage | Consistency and mission | Payoff / limits |
|---|---|---|---|
| A1 | **confirmed**: spec 14 §4/§12, the evaluation protocol and public negative reports require falsifiability and held-out evidence. | Retain; supports auditability and guards against benchmark-specific features. | Essential discipline; public negative findings do not establish that MCC is impossible. |
| A2 | **confirmed**: JSON Lines, stable registry, effect suggestions and fuel are implemented. | Retain; explicitness, determinism and repairability. | Existing mechanism; its comparative economic benefit still needs measurement. |
| A3 | **confirmed**: spec 15 §1 retains semantic actions at the source boundary. P6-11 makes borrow origin explicit with `from`. | Retain; explicitness and a small trusted computing base. | Source removes observed IR costs without replacing verifier checks. |
| A4 | **confirmed** for enum matches: spec 15 §6 rejects missing variants and `_`; missing alternatives emit E7004. Integer matches have different rules. | Retain; verifier strength and local repairability. | An enum addition exposes incomplete consumers; no inference or extra feature is needed. |
| A5 | **partly**: the native smoke documents IR overhead and zero strong-agent ownership/borrow/resource/concurrency diagnostics; P6A-9 validates the frontend response. | Retain the evidence-driven decision, not the inference that safety semantics have no cost. | Strong-agent success was at a ceiling. Zero diagnostics does not measure prevented defects or prove remaining failures are all logical. |
| A6 | **confirmed**: spec 15 §1/§10, frontend/check pipeline and E7900 distinguish malformed lowering. | Retain; implementation simplicity, auditability and safety. | The verifier remains the acceptance boundary. Being outside the TCB does not make frontend bugs harmless to availability or diagnostic quality. |
## Part B — Verified concerns
### B1 — Growth versus evidence: partly
**Truth.** AIR 27,347 → 42,275 is +54.6%, as claimed. “Every phase adds about 10%” is too uniform: recorded increments range from 0.6% to 15.8%. The current cl100k AIR count is 46,300, about +9.5% since Phase 5; bytes grew 160,428 → 179,282 (+11.8%). The cited +11.8% must be distinguished from token growth. Native smoke's fixed documentation tax is confirmed. General MCC and comparative economic benefit remain unproved, but “no result shows a compression signal” omits the explicitly preliminary, repeated AIR/source signal on M in P6A-9.
**Existing coverage.** Spec 14 §3.7, bundle tooling, per-RFC complexity accounting, source selective reading and the accepted [B1 plan](../evaluation/b1-heldout-plan.md) already address this risk. B1 measures stack-level capability compression; D1 explicitly excludes a claim about H4. A public pre-registration is not evidence that its private runs have finished.
**Consistency.** Measuring total and actually read documentation is aligned with AGENTS.md. Spec 14 §3.2 concerns adding semantic features when existing primitives suffice; it does not prohibit reusable libraries composed from those primitives. Section 8's restriction on near-duplicate APIs is relevant but requires establishing the duplication.
**Mission.** Controlling growth can improve implementation simplicity and machine repairability; removing useful contracts merely to reduce tokens can hurt both.
**Payoff.** The concern survives. Measurement and accurate bundle navigation are inexpensive. Neither the success nor failure of the current selective-reading strategy follows from the available size alone; future analysis needs actual reads, retries and cost per accepted solution, failures included.
### B2 — Std scope before measurement: partly
**Truth.** The size comparison is correct: current spec 16 has 9,184 words against spec 15's 9,553. The compiler registry has **19 source modules**. Quick Reference §§10–14 mention **18**: bytes, math, utf8, encoding.hex, encoding.base64, fmt, hash, hashmap, hashset, heap, io, io.reader, io.writer, path, option, result, vec and deque. The numeric `std.map` module is available in the full std reference but is not named in Quick Reference. These modules were unavailable at the official P6A-9 freeze; present-day M/C uses are not verified.
**Existing coverage.** The separate std plan, owner-requested foundation merge, complexity sections and on-demand `library/std.md` make the expansion visible. Most APIs are safe `.aji` composition; prerequisite features such as linear aggregates, buffers and static function parameters are separate semantic changes.
**Consistency.** Std is not automatically contrary to the mission. Its opportunity cost and near-duplicate operations merit review under spec 14 §8. The already recorded owner request is not superseded by this review.
**Mission.** Reuse may reduce generated code and improve safety and repairability; more contracts increase reading and choice costs.
**Payoff.** Unknown for the present API set. Audit overlapping contracts and aggregate public usage/reading data before consolidation; do not infer useful scope from word counts or inspect private tasks to choose APIs.
### B3 — Mechanical repairs: partly
**Truth.** Text edits are absent from [Diagnostic](../../src/diag.zig); current repair candidates serialize kind names. [Effect suggestions](../../src/verifier/effects.zig) produce the sorted union of declared effects and missing effects found for that function, based on current callee declarations. Repairing a callee can expose a new missing effect in its caller on the next check. These are not a global one-pass effect repair.
**Existing coverage.** Spec 10 §3 describes non-binding structured suggestions and prohibits automatic semantic modification. It does not forbid richer optional edit data. E7004 already names missing alternatives, but does not select their bodies.
**Consistency.** Explicit agent-applied edits are compatible. A diagnostic code does not establish a unique intended repair: an owner may need to remain usable later; effects can be avoided by changing an operation; missing arms may need error handling rather than trapping. Code-specific eligibility needs precise conditions.
**Mission.** Accurate edit candidates can improve machine repairability and deterministic feedback.
**Payoff.** Plausible for a restricted subset, not established as cheap for every listed code. Source ranges, module files, generic specializations, repeated diagnostics and conflicting edits are real implementation work. C1 needs a narrower proposal.
### B4 — Lexical borrow scopes and conflict locations: partly
**Truth.** Lexical scopes and the structural repair cost are confirmed. E2101/E2104 expose `borrow` and `conflicts_with` SSA identities, a primary source position and `air_line`/`air_col`; they do **not** expose the earlier conflicting source span. E4302 reports the outstanding task identity. See [borrow verification](../../src/verifier/borrow.zig), [source mapping](../../src/frontend.zig) and the reproduction below.
**Existing coverage.** Borrow lifetime is already specified in spec 03/08/15 and illustrated in the Quick Reference. Rich conflict locations remain an implementation/API gap. Spec 14 §3.5 already recommends relevant previous state.
**Consistency.** Better facts fit AGENTS.md. Spec 14 §3.4 favors bounded local reasoning and requires justification for large inference; it does not categorically ban all non-lexical lifetime analysis. Keeping lexical scopes is a defensible design choice without that stronger claim.
**Mission.** Related locations improve repairability and auditability.
**Payoff.** Earlier definition and task-spawn locations are a bounded, promising first step. Computing a block that can safely enclose a borrow is a separate analysis, particularly across calls, reborrows and task loans; it is not just source-position reporting.
### B5 — Determinism gaps: partly
**Truth.** Q-016 and Q-017 are open future work. Usable floating-point operations creating a current determinism gap are **wrong**: spec 07 §8.4 reserves f32/f64; the AIR parser rejects them with E0006/`reserved_type`. The source frontend exposes no floating-point type (unknown source types reject with E7002).
**Existing coverage.** Spec 11 §4 explicitly says deterministic replay already works from the run record, seeds and quantum, including weak-memory choices. Q-017 is the deferred hosted/native replay file format. Q-016's review-time wording “exist” was misleading without the reserved-status qualification; the documentation follow-up above corrects it.
**Consistency.** Retaining reserved types and clarifying docs is consistent; no new semantics are needed. Keeping Q-016 open records the rules required before future activation.
**Mission.** Documentation clarity improves explicitness; current deterministic execution is not waiting for these decisions.
**Payoff.** A brief source reference/status clarification is cheap. Closing Q-016 solely because types remain reserved would erase the unresolved future specification work.
### B6 — Source contracts and logic: partly
**Truth.** P6-6 is pending. Spec 13 §1 sketches requires/ensures/invariants and four statuses, but **neither source nor AIR currently implements function pre/postcondition declarations and their status reports**. Existing assert, guard, unsafe assume and bounds facts already cover limited logic; the verifier also checks effects, capability use and structural obligations. “Memory, not logic” is too absolute.
**Existing coverage.** Spec 13 records the direction, and spec 10 §6.1 reports implemented runtime/proven checks while reserving contract statuses for a later extension. That report is not an implemented general contract engine.
**Consistency.** A contract feature needs a vertical RFC, explicit effects/failure, AIR feature/version review and the memory/concurrency checklist wherever applicable. Its selection cannot be justified by assuming unobserved smoke failures were logical.
**Mission.** Potentially improves verifier strength and explicitness, while adding verifier state, syntax and trusted logic.
**Payoff.** Unproved and expensive. A small independently motivated fragment is worth investigating; there is no evidence here that it should be the next major feature.
### B7 — Behavioral abstraction and std variants: partly
**Truth.** No runtime function values, closures or traits are exposed. Static function parameters are already enough for the cited hash/equality/comparator cases: [HashMap](../../std/hashmap.aji) takes pure ref-key hash/equal functions; [BinaryHeap](../../std/heap.aji) takes a pure comparator. [HashSet](../../std/hashset.aji) already composes HashMap. These are source generics, not separate built-in collection operations.
**Existing coverage.** Spec 15 §18 and RFC 0029 define exact signatures, declared effects and specialization. Runtime-selected or captured behavior is outside that mechanism.
**Consistency.** Check existing generic composition first, as AGENTS.md requires. No new trait or closure feature follows from these examples.
**Mission.** Existing static policies preserve explicitness and implementation simplicity. Consolidation could reduce learning cost if observable contracts really coincide.
**Payoff.** The hypothesis that absent behavioral abstraction explains std growth is not established. Numeric maps and general owning-key maps have different representations and policy/ownership costs; measure concrete duplication before proposing removal or merger.
### B8 — Dense normative prose: confirmed
**Truth / existing coverage.** Spec 15 §13/§17 contains dense paragraphs; the Quick Reference and selective bundle compensate but still direct uncertain readers to normative rules.
**Consistency / mission.** Splitting rules into short subsections or tables without changing their meaning is compatible and improves explicitness, auditability and repairability.
**Payoff.** A focused editorial task is inexpensive. Preserve normative terms and tested examples; remeasure bundles. A semantic RFC is unnecessary for presentation alone.
### B9 — Application test support: partly
**Truth.** There is no implemented `test fn` or `aji test`, and spec 12 defines no package test entry. Planned tooling mentions tests but does not implement application discovery.
**Existing coverage.** Applications can already put assertions in ordinary entry programs and run them with fuel, grants and schedule seeds; `aji explore` can enumerate scheduler/weak-memory outcomes. Conformance infrastructure supplies repeated seeded schedules. Thus deterministic application testing is possible, but has no dedicated discovery/reporting interface.
**Consistency / mission.** A test runner can improve determinism and repairability. Start by assessing CLI/manifest discovery using ordinary functions or entries before introducing a source keyword.
**Payoff.** Plausible tooling value; evidence does not show that language syntax is necessary. Grant binding, entry instantiation, fuel exhaustion and test isolation/order still need contracts.
## Part C — Proposal dispositions and routes
| ID | Disposition | Suggested destination; no adoption here |
|---|---|---|
| C1 | Defer pending incidence, repair-cost and workflow evidence | RFC 0038 retained as Proposed; no implementation recommendation |
| C2 | Existing functionality; optional reporting refinement | Evaluation task only if a concrete missing metric is identified |
| C3 | Owner policy option; payoff unknown | Owner decision/DD after considering existing std direction |
| C4 | Owner policy option; numeric threshold unjustified | Owner decision/DD plus tooling task if adopted |
| C5 | Retain, split factual locations from repair analysis | RFC for related locations first |
| C6 | Research candidate; sequencing/payoff unproved | P6-6 RFC exploration, not immediate implementation |
| C7 | Research candidate; compare tooling-only alternative | CLI/manifest design first; RFC if source syntax is needed |
| C8 | Reserved-type policy already implemented | Documentation clarification completed; Q-016 stays open for future activation |
| C9 | Evaluation emphasis valid; priority change is owner policy | Existing B1 track and possible owner/DD decision |
Updated count after RFC review: **1 concrete RFC candidate** (C5), **1 deferred candidate** (C1), **2 exploratory candidates** (C6/C7), **3 owner policy options** (C3/C4/C9), and **2 proposals substantially covered already** (C2/C8). Seven ideas remain recorded with qualifications; they are not seven approved or economically validated changes. The original benefit-per-cost ordering is not supported by the available evidence.
### C1 — Optional exact edits
**Truth / existing coverage:** absent edit API; existing suggestions provide some ingredients. **Consistency:** explicit application and public effects can be preserved. Missing-arm `trap` insertion chooses failure behavior; move insertion may invalidate later uses. **Mission:** potentially repairability. **Payoff:** insufficiently supported to recommend implementation. Published native smoke, P6A-9 and P5-0 reports do not report E3101; P6A-9's E7006 reasons are unspecified. This establishes no measured incidence of the eligible Copy-move subset. Unreported errors are not verified zeros.
RFC 0038 is therefore retained with a recommendation to defer work, preserving formal Proposed status. Its byte offsets and file hash identify an exact edit for a programmatic applicator, but `expected: "[]"` does not identify a unique string replacement. Context plus edit line/column, or an explicitly invoked application command, remain design alternatives rather than adopted fixes. Resume review only after aggregate eligible per-run incidence with a defined denominator, evidence of material repair cost, and validation of the actual application workflow. No arbitrary N% is set from these reports; any owner-selected threshold and minimum sample size must precede a new cohort's evaluation. M/C may only check regression and cannot select or tune the feature. Frozen evaluation inputs remain untouched.
**Independent measurement prerequisite: stable E7006 reasons.** At the review baseline, frontend E7006 diagnostics did not provide a stable `reason` discriminator. The move rejection in [lower.zig](../../src/frontend/lower.zig) exposes `name`/`type`, but the same rejection site can cover Copy values and other non-linear forms, and E7006 also covers unrelated constructs across frontend stages. Parsing `message` would violate the machine-readable intent of spec 14 §3.5 and cannot supply a reliable Copy-move incidence metric.
The review proposed a separate diagnostic-schema task, independent of RFC 0038's edits or application workflow, with these completion conditions:
- Specify stable `reason` values and coverage in spec/reference, distinguishing Copy-move rejection from borrowed/non-Copy moves and other covered invalid constructs. Keep E7006's code/kind and the language's accepted/rejected sets unchanged.
- Emit reasons from explicit frontend error classification, not message parsing or simply assigning one reason to every use of the shared code. Check JSON serialization, original source provenance and positive/negative examples for each specified reason; valid generic Copy transfer remains accepted.
- Keep missing/unclassified reasons explicitly unknown in measurements. Do not relabel historical records or infer their reasons from prose; adding fields to future runs does not recover old data.
- Separately extend evaluation reporting to aggregate affected source runs by `(code, reason)`, alongside existing code counts, with the agreed denominator/cutoff. Merely adding `reason` does not change `_diagnostic_codes`, which currently counts codes only. Both changes must precede the relevant future experiment's freeze.
The reason field improves machine repairability on its own; the reporting follow-up enables the Copy-move branch of 0038's evidence condition. E3101's code-level incidence can already be counted without this prerequisite. The assessment itself assigned no implementation or adoption. Subsequent language work implements the independent schema/reporting increment under [DD-017](decisions.md#dd-017--stable-e7006-reasons-before-repair-frequency-analysis) and [P6-7](../plan/phase-6-source-language.md): every E7006 has a registered reason, and ajieval reports observed occurrences and affected runs with unknown reasons/log availability retained. Code totals are unchanged. The reporting covers the entire recorded transcript; a future cohort must still specify its pre-acceptance cutoff, agent/toolchain strata and missing-data policy. No new experiment, repair-cost evidence or application-usability result is supplied; RFC 0038 remains Proposed with the deferral recommendation.
### C2 — Diagnostic statistics
**Truth:** “one smoke run only” is **wrong**. [report.py](../../tools/eval/ajieval/report.py) implements `_diagnostic_codes` for both controlled events and native transcripts, and `profile` exposes counts per run; checkpoint reports categorized counts. [Harness documentation](../evaluation/harness.md) describes both. **Existing coverage:** substantial. **Consistency / mission:** aggregate measurement supports auditability without changing semantics. **Payoff:** identify whether the missing requirement is cohort aggregation, persistent raw counts, or counting only before first acceptance. Current counts scan recorded outputs; they do not promise the proposed pre-acceptance cutoff. Count occurrences separately from distinct failures and repair cycles. Do not rank the roadmap by raw code frequency alone: task exposure, repeated identical checks, truncation and early failure bias the counts, while successfully prevented errors can be invisible.
### C3 — Std freeze
**Truth:** growing std has a real documentation cost; benefit is not established. **Existing coverage:** remaining std work is already backlog and the foundation was explicitly requested by the owner. **Consistency:** a future scope gate is compatible, but this assessment cannot revoke that direction. **Mission:** potentially simplicity/auditability; reduced reuse may increase generated code and repairs. **Payoff:** not “free”: delayed reusable APIs and independent development are opportunity costs. An owner decision could define a gate and exceptions after weighing both, without accessing private tasks or altering frozen inputs.
### C4 — Quick Reference cap
**Truth:** the review-time front door exceeds the example 8k threshold by 642 cl100k tokens (688 after the floating-point clarification). **Existing coverage:** the plan targets 5–8k and tooling measures size, without a hard source cap. **Consistency:** a documentation CI policy is compatible and changes no language semantics. **Mission:** bounded context and repairability, provided essential rules remain discoverable. **Payoff:** an exact threshold is not empirically justified; trimming can transfer cost to more reads. Any adopted cap needs a pinned measurement convention, baseline transition, exceptions and clarity/example-coverage checks. Track full bundle and actual reads alongside it.
### C5 — Related locations
**Truth / existing coverage:** at the review baseline, the second source location was missing despite SSA conflict identities. **Consistency:** factual locations are compatible; a suggested enclosing block is not automatically a proven fact about a valid repair. **Mission:** explicitness and repairability. **Payoff:** scope the first RFC to previous borrow origin and outstanding task/spawn locations, preserving primary location, stable codes and deterministic ordering through source/AIR mapping and modules. Test reborrows, call-returned borrows, regions, task loans and merged provenance. Defer block-enclosure analysis until its meaning, feasibility and soundness are specified. A diagnostic extension alone need not change ownership semantics.
The public native smoke reports six E2101 occurrences in AIR command output; P5-0 reports two in a strong agent's source run, repaired in one cycle. These support the relevance of borrow feedback, not a measured economic benefit of related positions. Review supports RFC 0037's bounded scope and the need to carry the original spawn through cancelled-handle transitions. Source variable names may help later; they remain outside scope rather than being inferred from SSA names.
Subsequent language work prepares RFC 0037's implementation and spec integration together under [DD-018](decisions.md#dd-018--factual-related-positions-without-choosing-a-repair)/P6-7. Each identified covered conflict receives one factual record; primary selection and deduplication remain unchanged, and cancelled-join handles retain spawn provenance. Related source mapping never guesses a position. The implementation/tests and measured bundle growth are recorded in the plan; they supply no new empirical repair-cost result. Formal RFC status remains Proposed for owner adoption. This follow-up is authorized language work, not implementation inferred from this assessment.
### C6 — Integer contracts
**Truth / existing coverage:** declaration support remains pending; guard/assert are existing alternatives for local checks. **Consistency:** no unproved predicate may silently gain an unspecified runtime meaning. Define mathematical versus fixed-width arithmetic/overflow, evaluation timing, old-state capture, supported expressions, traps, effect requirements, interprocedural checking and behavior under concurrency/resource obligations. Distinguish decidable proof from executable runtime checking; not every possible contract is executable. Review AIR format-0 extension rules and register any new feature. **Mission:** verifier strength. **Payoff:** high and unknown, including solver/TCB and source/AIR bundle growth. A focused P6-6 RFC should compare existing primitives before recommending a language extension or priority.
### C7 — Application tests
**Truth / existing coverage:** dedicated discovery is absent; deterministic execution machinery exists. **Consistency:** reusing execution does not eliminate new entry, grants, isolation, ordering, aggregation and CLI contracts. Compare a manifest/runner over ordinary entries with `test fn`; the latter is a source feature and must land vertically. **Mission:** determinism and repairability. **Payoff:** evaluate authoring and repair cost before choosing syntax. Specify fuel and schedule behavior using existing deterministic limits, not wall-clock termination.
### C8 — Floating point
**Truth / existing coverage:** reservation is already normative and implemented. **Consistency:** add a short status clarification to Quick Reference/Q-016 rather than pretending floating-point semantics were decided. **Mission:** explicitness. **Payoff:** cheap documentation work; no float implementation or new reservation RFC is required. Keep the question open until NaNs, rounding, fused operations and related future behavior are specified or the owner permanently drops the types.
### C9 — Evaluation priority
**Truth:** evaluation remains essential; C9's ordering predates the current completed P6-11 implementation. **Existing coverage:** B1 is accepted and P7/P8 are already held; the owner separately requested the std merge and source resumption. B1 D1 measures a stack signal rather than H4. **Consistency:** future priority changes require an owner decision and must respect independent held-out authoring and frozen inputs. **Mission:** auditability and empirical control of complexity. **Payoff:** completing public aggregate analysis is valuable, but stopping every independent source improvement is not shown to be cost-free or beneficial. Preserve the distinction between an unvalidated benefit hypothesis and a requirement that no development occur before evidence.
## Reproductions and next review steps
```sh
zig-out/bin/aji check tests/conformance/phase0/reject/float_reserved.air
zig-out/bin/aji check tests/conformance/source/borrow_returns/parent_access.aji
zig-out/bin/aji check tests/conformance/source/borrow_returns/region_live_reset.aji
git ls-tree -r --name-only 591f0ae -- std src/frontend/stdlib.zig
```
The three checks reject with E0006/`reserved_type`, E2101 and E2104 respectively. Borrow diagnostics contain SSA conflict identities and only one source position, confirming the location gap. The historical tree query returns no current std modules.
Existing evaluation harness self-tests also passed: `python3 -m unittest discover -s tests` in `tools/eval/`, 22 tests, one skipped (the freeze test requires a clean repository). They use public `dev-echo` fixtures and mock providers, not held-out runs. The suite emits ResourceWarnings about unclosed files/sockets; no harness changes were made for this review.
Recommended sequence, subject to the existing owner plan:
1. Correct the factual basis in future discussions: reserved floats, existing diagnostic counts, generic policies, old versus current bundle, and B1 versus H4.
2. Continue owner review of the bounded C5 proposal in RFC 0037. Retain RFC 0038 without implementation pending its incidence, repair-cost and application-workflow conditions. Do not implement either RFC from this assessment.
3. Route B8, the historical bundle table and C8's status wording to documentation maintenance. Route any precisely identified C2 remainder to evaluation tooling after respecting freeze rules.
4. Keep C6/C7 as researched alternatives and C3/C4/C9 as explicit owner policy choices; neither approve semantics nor change the roadmap here.
The original review identifies a real growth/measurement risk and a concrete diagnostic repair gap. Its strongest immediate contributions are better evidence accounting and related source locations; it does not establish a current floating-point determinism bug, missing diagnostic statistics, or a need for new behavioral abstractions.
Following owner discussion, the bounded C5 and C1 proposals were written as [RFC 0037](../rfcs/0037-borrow-diagnostic-related-locations.md) and [RFC 0038](../rfcs/0038-bounded-diagnostic-edits.md), both **Proposed**, with no implementation or acceptance implied at drafting. The three requested documentation clarifications are complete. Generated bundle measurements after the Quick Reference sentence: cl100k Quick 8,688, other source 64,160, full source 72,848; o200k 8,723 / 64,359 / 73,082; Qwen2.5 8,954 / 65,733 / 74,687. AIR and std reference sizes were unchanged by those clarifications. Subsequent schema/reporting and related-position increments are recorded above. C3/C4/C9 remain owner policy options.
The subsequent RFC review supports 0037 and recommends deferring 0038 as described above; formal adoption remains the owner's decision. The reviewed drafts had 2,010 and 2,381 words respectively (`wc -w`), disproportionate to the small diagnostic extension. At spec integration, express the schema and code-to-role/eligibility mapping as a few table rows plus indispensable invariants; keep rationale, alternatives and test matrices in RFCs/tests and remeasure bundle growth. Compactness must still preserve source-map fallback, deterministic ordering and task-spawn provenance. The evidence/workflow qualification added to 0038 is outside the bundles and is not itself language growth.
+202
View File
@@ -0,0 +1,202 @@
# Design review — 2026-10-07
Non-normative. An external review of the spec, the plan and the evaluation results, written for another agent to check and evaluate. It changes nothing; every proposal still needs an RFC, a `DD-NNN` entry or a plan task before it has any effect.
## Scope and limits
Read in full: spec 01, spec 14, spec 15 §1, §6, §9–§11, §13–§15 (parts), spec 10 §1–§6, `docs/agent/quick-reference.md`, `docs/agent/README.md`, `docs/plan/README.md`, `docs/design/decisions.md`, `docs/design/open-questions.md` (index), `docs/evaluation/results/2026-10-05-native-smoke.md`.
Skimmed by headings only: spec 03, 04, 05, 07, 07a, 08, 13, 16. Claims that touch these are marked **unverified**.
Not read: the RFCs (except their titles), `src/`, the conformance corpus, `docs/evaluation/protocol.md`, the P6A-9 and P5-0 results.
Every claim below has an **evidence** line. The reviewing agent should check it and mark the claim `confirmed`, `wrong` or `partly`.
## How to evaluate this document
For each item, answer:
1. Is the observation true? Check the evidence.
2. Does the repository already address it somewhere this review did not read?
3. If true, is the proposal consistent with `AGENTS.md`? In particular: no inferred effects in public contracts, no compiler flags that change semantics, no features tuned to benchmark tasks (spec 14 §12).
4. Does it improve at least one of the mission properties in `AGENTS.md` (explicitness, verifier strength, determinism, repairability, safety, simplicity, auditability)?
5. Is it cheaper than its expected gain? Use the same cost categories as spec 14 §5.
## Part A — What is right (keep)
| ID | Observation | Evidence |
|---|---|---|
| A1 | The central hypothesis is stated as falsifiable and is tested with a held-out benchmark, an anti-overfitting rule and published negative results. | spec 14 §4, §12; native-smoke results "No compression signal at this difficulty" |
| A2 | "Agent proposes, verifier decides" is carried through: stable codes, JSON Lines diagnostics, `suggested_effects`, deterministic runs bounded by fuel. | spec 10 §2; DD-009, DD-013; quick reference §1 |
| A3 | The source/AIR boundary rule is sharp and checkable: source may hide mechanics (SSA, CFG, `borrow.end`, frame storage, feature header) and must not hide semantics (authority, allocation, move, consumption, sync, effects, tasks, cancellation, failure). | spec 15 §1 |
| A4 | Exhaustive enum `match` without `_` makes adding a variant a compile error everywhere it matters. | spec 15 §6 "Enums" |
| A5 | Bringing Phase 6A forward was decided from data: the measured cost of Aji/AIR was hand-written IR, not the safety semantics. Strong agents hit no ownership, borrow, resource or concurrency diagnostics. | native-smoke "Diagnostics" and "Reading" §2 |
| A6 | The frontend is outside the TCB, and malformed lowered AIR is reported as a compiler bug (`E7900`), not as a program error. | spec 15 §1, §10 |
## Part B — Concerns
Severity: **high** means a risk to the project hypothesis; **medium** means measurable agent cost; **low** means quality or clarity.
### B1 — Language and std grow faster than the evidence that growth pays (high)
- Bundle growth: 27.3k tokens (Phase 2 baseline) → 42.3k tokens (Phase 5), about +55 %. Every phase adds about 10 %, and growth only produces a CI warning.
- The native smoke measured a fixed documentation read of about 33k tokens per Aji run. Rust runs read none.
- No result shows a compression signal yet. E-A, E-1 and B1 are not done.
- Spec 14 §3.2 says a feature should not be added when existing primitives suffice. Spec 14 §8 says nearly identical APIs should be avoided unless benchmarks show a benefit.
Evidence: `docs/agent/README.md` milestone table; `tools/agent_bundle_tokens.py` output ("+11.8 % since Phase 5"); native-smoke "Cost" table; `docs/plan/README.md` evaluation table.
**Question for the reviewer:** does the Source Reference Bundle (`/docs` front door plus selective reading) actually stay small? This review did not get token counts for it: the tokenizers were not installed.
### B2 — Standard library scope before measurement (high)
- RFC 0016–0035 add a large std: deque, numeric map, general key map, set, binary heap, buffered files, lexical paths, hashing, text encodings, integer formatting. Spec 16 is about 9.2k words, almost as large as spec 15 (9.6k).
- Each collection is a set of operations and outcomes an agent must learn, and is part of what an agent may read.
- The plan already moved std into a separate track and recorded the merge as an owner request (2026-10-06/07).
Evidence: `docs/rfcs/` listing; `wc -w docs/spec/*.md`; `docs/plan/README.md` "Standard library track".
**Question for the reviewer:** which std modules does the Quick Reference expose, and were any of them used in P6A-9 or the M/C regression runs?
### B3 — Deterministic repairs still cost a round-trip (medium)
- `E3101` already computes the full effect list (`suggested_effects`). The agent copies it back by hand.
- Spec 10 §3 defines `repair_candidates` as kind names only (`{"kind": "move_reset_after_use"}`), with the rule "Suggestions never modify semantics automatically".
- Several source diagnostics have exactly one mechanical fix:
- `E3101`: replace the `effects [...]` list;
- `E7003`: insert `move`;
- `E7006` for `move` on a copyable value: delete `move`;
- `E7004`: add the missing arms.
Evidence: spec 10 §3; spec 15 §9 "Effects", §10 code table; quick reference §1, §4.
### B4 — Lexical borrow scopes push structural edits onto the agent (medium)
- A named borrow lives until the end of its block. To end it earlier, the agent adds an inner `{ … }` block.
- This is simple to state and simple to verify. The cost is that `E2101`/`E2104` repairs are structural edits whose correct location the agent must find itself.
- **Not a proposal to adopt non-lexical lifetimes.** Those would add inference, which conflicts with spec 14 §3.4.
Evidence: spec 15 §9 "Borrow scopes"; quick reference §4, §6 (region example).
**Question for the reviewer:** do `E2101`/`E2104` diagnostics already carry the span of the conflicting earlier borrow? (spec 08 not read in full.)
### B5 — Open determinism gaps (medium)
- Q-016 (floating-point determinism) and Q-017 (replay file format) are open.
- `f32`/`f64` appear in spec 02. **Unverified:** whether they are reserved or usable.
- Spec 14 §3.6 promises "same program, same input, same grants, same seed … same observable result".
Evidence: `docs/design/open-questions.md` index; `grep f32 docs/spec/02-types-and-values.md` (line 20).
### B6 — No source contracts; the verifier covers memory, not logic (medium)
- Spec 13 defines `requires`/`ensures`. P6-6 (contracts in source) is `todo`.
- The smoke showed that strong agents make almost no memory or resource errors. If the remaining errors are logical, the verifier currently cannot help with them.
Evidence: spec 13 lines 9–21; `docs/plan/phase-6-source-language.md` line 14; native-smoke "Diagnostics".
**Unverified:** the current status of spec 13 contracts in AIR.
### B7 — No behavioral abstraction pushes variants into std (medium)
- There are no user traits, closures or function values (spec 15 §15: "No user traits, overloads, type inference …"). Only qualified named functions may be passed to `task.spawn`, and static function parameters exist (RFC 0029).
- Anything parameterized by behavior (comparator, hash, visitor) needs either a static function parameter or a separate built-in. That may partly explain the size of B2.
Evidence: spec 15 §14 (line 511), §15 (line 523), §18; RFC 0029 title.
**Question for the reviewer:** are static function parameters (spec 15 §18) enough for comparator/hash use? If so, can some std variants be expressed as one generic module?
### B8 — The normative source-language text is hard for an agent to read (low)
- Several spec 15 sections are dense single paragraphs with many rules, e.g. §13 (name mangling) and §17 (dynamic buffers).
- The Quick Reference compensates, but when an agent is unsure it is directed to the normative text.
Evidence: spec 15 lines 481, 558.
### B9 — Tests are not a language-level construct (low)
- Tests live in the conformance infrastructure (`expect`/`phase`/`spec` headers, DD-010). An agent writing an application has no in-language way to state and run its own deterministic tests, including under N schedules.
Evidence: DD-010; quick reference sections 1–8 (no test construct).
**Unverified:** whether spec 12 (packages and build) defines a test entry point.
## Part C — Proposals
Ordered by estimated benefit per cost. Each states the concern it answers and how to measure it.
### C1 — Exact text edits in diagnostics (answers B3; cheap)
Add an optional field to diagnostics whose fix is unique and mechanical:
```json
{"code": "E3101", "edits": [{"file": "main.aji", "range": [12, 1, 12, 14], "replacement": "effects [io.read, io.write]"}]}
```
- The compiler never applies the edits. The agent applies them explicitly, so spec 10 §3 ("never modify semantics automatically") holds.
- Initial set: `E3101`, `E7003`, `E7006` (`move` on a copyable value), `E7004` (missing arms, each `=> { trap; }`).
- Not for borrow conflicts. There, more than one fix is correct.
- Effects stay declared in the public signature. This is not effect inference (`AGENTS.md`).
Measure: repair iterations per accepted solution on the M/C regression corpus, before and after. Per `AGENTS.md`, M/C may show that nothing broke, but they never decide the question.
### C2 — Per-code diagnostic statistics across all runs (answers B1; cheap, evaluation tooling only)
- Record in the harness, for every run, the count of each diagnostic code before acceptance.
- Use it as the input that ranks language work. If most iterations are `E3101` and `E2101`, those are the roadmap.
- Today this breakdown exists for one smoke run only.
Measure: none needed; this is the measurement.
### C3 — Freeze std growth until B1 is analyzed (answers B1, B2; free)
- No new std modules until the B1 held-out analysis.
- Fixes and spec integration of already accepted RFCs continue.
### C4 — Hard budget for the Quick Reference (answers B1; cheap)
- Cap, for example, the Quick Reference at 8k tokens as a CI failure, not a warning.
- A feature that needs room must shrink or move something else to the selective-reading layer.
Risk: pressure to make the reference terse to the point of ambiguity. Mitigation: the budget covers the front door only; the full spec is unchanged.
### C5 — Both spans in borrow-conflict diagnostics (answers B4; medium cost)
- `E2101`, `E2104`, `E4302`: report the span of the earlier borrow, the span of the conflicting use, and the innermost block in which the earlier borrow could be enclosed.
- Facts only, not edits: there is more than one valid fix.
First check B4's question: this may already exist.
### C6 — Decidable source contracts as the next major semantic feature (answers B6; high cost)
- A small decidable fragment: linear integer arithmetic over indices, lengths and counts in `requires`/`ensures`.
- Anything not proved becomes an explicit runtime check, listed in `aji report` (spec 10 §6.1 already reports runtime vs proven checks).
- Prioritize this over new std modules.
Needs a full RFC with the `Agent complexity impact` section and the memory/concurrency checklist where it applies.
### C7 — `test fn` in source (answers B9; medium cost)
- Deterministic in-language tests with fuel and `--schedules N`, run by `aji test`.
- Grants are declared per test, with the same `main`-parameter rule.
- Reuses the existing run record. No new runtime semantics.
### C8 — Close Q-016 before any task needs floating point (answers B5)
The simplest deterministic option is to keep `f32`/`f64` reserved in `.aji` 0.1 and say so in the Quick Reference.
### C9 — Prioritize B1 over P6-11 and further std work (answers B1; free)
- H4 is expected only on medium tasks, where a weaker model understands the task but fails on resources, cancellation or concurrency (`docs/plan/README.md` roadmap item 5).
- Until such tasks are measured, language changes are optimized without signal.
## Part D — Suggested next steps for the reviewing agent
1. Verify every **unverified** item and every reviewer question above. List the outcome per ID.
2. Count how many C proposals survive the evaluation questions at the top.
3. For surviving proposals, pick the destination:
- C1, C5, C6, C7: RFC;
- C3, C4, C9: owner decision or `DD-NNN`;
- C2: plan task in the evaluation track;
- C8: resolution of Q-016.
4. Do not start implementation from this document alone.
+258
View File
@@ -0,0 +1,258 @@
# Runtime value-depth audit
Non-normative evidence at 53030ef, separate from Q-059's compiler type traversals. No acceptance limit or runtime rule is proposed here.
Generate TYPE as `"array<" * 32768 + "u8" + ",1>" * 32768`:
```air
module depth.zero
air 0
lang 0.1
features [arrays, ownership]
fn @main() -> void
effects []
entry:
%a = local.alloc TYPE
local.zero %a
ret
```
Every array length is one. The accounted value/frame size is one byte, and `aji check` accepts with no output. `aji run --fuel 8` aborts with exit -6, no JSON run record and a symbolized traceback containing 9,997 zeroValue frames. The input has three instructions; the failure occurs inside materialization, not because fuel is exhausted. Tests use the ordinary 8-MiB native stack; only child core capture is disabled. No timeout ends the run.
This confirms native recursion in zeroValue on a verified input. An iterative fix must retain zero initialization, value shape, heap/root lifetimes, allocation failure handling, collection safety and instruction/fuel accounting. A new accepted-depth limit or trap would require a normative decision; none is added by compiler-side repairs.
At the initial baseline, deepCopy/copyAll, valueBytes and collection/serialization were inspection candidates only: the zero-materialization failure prevented probing them. The executed results below supersede that status for copying, collection, value sizing and output serialization. All five confirmed failure paths now have iterative repairs. Q-060 remains open for the closing call-path audit; the earlier increments record the failures that led to each repair.
## Zero-materialization repair
The implementation now fills zeroable arrays and named structs in the original preorder, using explicit continuations only for pending siblings. Single-child edges need no continuation. Result payloads remain in the execution heap; temporary traversal metadata uses a separate host arena and is released before the next instruction safe point. A partially built value is not published to the local cell if an allocation fails.
The preserved invariant is complete initialization without aliasing independent array/struct payloads. Spec 07a's local.zero verifier rule (zeroable type, no live borrow) and spec 08 §13's whole-local initialization remain unchanged. All leaves have the same integer type/zero bits or false boolean, and aggregate declaration/variant identities and field/element order are unchanged. No runtime rule, Aji allocation authority, opcode, effect, feature, diagnostic code, trap, accepted-depth limit or fuel/scheduler event is introduced. Existing enum/capability zero rejects remain E1001 in AIR and E7006/zero_not_zeroable in source; the public zero_enum/capability_not_zeroable cases and their source analogues remain rejection examples.
Unit tests traverse 32,768 single-element arrays and a 32,768-declaration chain with heterogeneous pending siblings, empty-record leaves and three-byte arrays. A constrained payload allocator fails after allocating the root and proves that the old local value survives the failed instruction. The new zero_structure_siblings AIR/source pair checks complete mixed zeroing followed by a write and unchanged independent fields. Forty generated shallow mixed-type runs produce byte-identical old/new records.
An additional verified deep-program unit test pins fuel 0/1/2 as exact limit records and fuel 3 as successful completion, with matching instruction counts at the ordinary collection threshold.
The original 32,768-level input now returns `{"status":"returned","value":null}` under fuel 8 at the ordinary collection threshold. This is not a claim that all deep runtime paths work. Two follow-up probes are independently confirmed:
- With collection before every instruction, the same program aborts without JSON inside Copier.value/items (4,997/4,998 symbolized frames). Its ordinary run succeeds, isolating the collector's recursive payload copy from zero construction.
- Adding `%v = local.load %a` immediately after zeroing aborts without JSON inside deepCopy/copyAll (4,998 frames each), under the same fuel 8. Storage-to-SSA copying still requires its own iterative traversal.
Both probes retain the ordinary native stack limit and disable only child core capture, with no wall-clock termination. Evidence comes from the runner exit status and Zig's symbolized stderr, not a saved core dump. Q-060 stays open for copying, sharing-preserving collection/result copying, accounted-value queries and output serialization.
## Storage/value-copy repair
DeepCopy now visits aggregate/array payloads in the original preorder using explicit pending-sibling continuations. CopyAll keeps its root-list order and invokes that traversal for each root. Every occurrence gets a fresh payload, even when the input reuses one payload more than once. Aggregate declaration/variant identity and scalar bits/types are preserved; owner, mutex, graph and other identity leaves remain shallow, just as before. This is distinct from the collector, which must preserve sharing. Temporary traversal storage is released before the next instruction safe point; allocation failure does not publish a partial local.store value.
The invariant is unchanged storage/SSA value independence, alongside unchanged ownership identity and explicit loan rules. Spec 07a's local.store/local.load/load/store rules and spec 08's type/initialization/borrow checks are unchanged. The mixed Copy-record/enum/array AIR/source pair copies into and out of local storage, changes one repeated row without affecting the other, restores from a snapshot, and checks that a later store does not mutate the snapshot. Existing read_uninitialized and copy_overlapping AIR cases remain rejected with E1010/E2101; there is no new rejection or diagnostic code. Aji authority/effects, deterministic instruction/fuel counts, accepted syntax/types and runtime traps remain unchanged. No new limit or bundle text is introduced.
Unit tests copy 32,768 alternating array/aggregate levels with pending siblings, empty payloads, variant identities and signed integer bits. They mutate one of two complete copies, independently test reused source payloads within one value, preserve explicit owner/mutex/graph identities, and force a mid-copy payload allocation failure while retaining complete old local storage. A verified deep programme pins exact fuel 0–4 boundaries: local.load still consumes one instruction. Forty-two mixed-type old/new runs have identical records.
The previously crashing 32,768-level zero/local.load/ret programme now returns normally under fuel 8 at the ordinary collection threshold. Adding local.store back to the same local forces an ordinary threshold collection and aborts without JSON in Copier.value/items (4,997/4,998 symbolized frames, zero deepCopy frames). This confirms the next failure without collection instrumentation. The collector/result copier, accounted-value queries and output serialization remain Q-060 work.
## Sharing-preserving copy repair
The collector and run-result copier now use explicit continuation jobs for payload elements, cell values, graph objects, projection paths and mutex views. Each shell enters its existing forwarding map before descendants are visited. Completed roots therefore retain shared cells/payloads, SSA-backed storage, slice ranges, buffer identity/capacity, mutex/guard identity and graph cycles. Metadata, race shadows and weak-memory views are copied before the old execution heap is released. Result copying uses the same traversal. Unlike storage/value copying, repeated references intentionally resolve to the same new object. Temporary jobs/maps remain in the caller's temporary arena, while payloads remain in the destination heap; the original depth-first destination allocation order is retained.
The invariant is that all reachable execution state survives collection with identical identity relationships and values, and every externally returned root has completed copying. The original verifier type/ownership/initialization/loan rules and runtime safe points are unchanged. The positive mixed Copy-record/enum/array AIR/source examples still return 42; read_uninitialized and copy_overlapping remain E1010/E2101 rejection examples. No new diagnostic, effect, Aji allocation charge, feature, trap, accepted-depth limit, runtime rule, fuel step or schedule event is added. A failed copier is discarded and its arenas released; this does not introduce transactional collection or retry guarantees.
Unit tests free the old heap before inspecting forwarded backing cycles, shared payloads, places/slices, buffers, mutex guards/views, graph cycles and race-shadow paths/epochs. An allocator probe fails every copier allocation request in turn and checks propagated OutOfMemory and arena cleanup. Separate internal-representation tests traverse 32,768 payload/cell levels with siblings; these are not claimed as typed source programs. Verified deep-program tests pin exact fuel 0–5 boundaries, ordinary threshold collection, per-instruction collection, and returned payloads after the execution heap is freed. The formerly crashing deep CLI store programme now returns null, and the original zero programme also passes with per-instruction collection.
Validation: unit/format checks, test-extended and all 1,787 ordinary conformance cases pass. Per-instruction collection additionally passes 57 focused run cases across phases 1/2/4/5 and source runtime_values, plus all 26 phase-3 run cases with stress 16 (each applicable schedule quantum). Old/new records match exactly for 42 mixed-value runs and 104 runs across mutex/channel/graph/buffer/atomic fixtures and eight schedule seeds. The full per-instruction conformance run is additional validation, still running at this checkpoint.
Two follow-up failures are independently verified on the same ordinary native stack, disabling only child core capture:
- Returning the 32,768-level array succeeds through interpretation/result copying in unit tests, but CLI output aborts with exit -6 and no JSON. The trace starts at std.json.Stringify's fixed 256-level nesting stack (BitStack index 32, length 32) and contains 256 writeValue frames. This is a serialization failure, not a demonstrated native-stack overflow in writeValue; its recursion still needs removal or independent audit.
- Allocating an owner for the same loaded array using own.new with fuel 16 and an eight-byte heap grant aborts with exit -6, no JSON and 10,001 valueBytes frames. The value's accounted size is one byte. This confirms native recursion in runtime value sizing after zeroing, loading and collection now complete.
Q-060 remains open for valueBytes and output serialization. No normative or agent-bundle text changes in this increment.
## Runtime value-size repair
ValueBytes now iterates the first-element chain of fixed value arrays, composing their positive lengths into a checked factor. Scalar, capability, graph-reference, built-in enum and nominal leaf accounting remains unchanged; named types still delegate to the existing module size query. A zero-sized leaf yields zero even if the length factor overflows, matching the original inner-to-outer checked multiplication. A nonzero leaf with an overflowing factor still yields null. ArrayBytes continues to query the element before multiplying by the dynamic count, so a zero count cannot mask an overflowing element. The traversal uses constant state and allocates no temporary or payload storage.
The invariant is equality with spec 08 §7.1's static accounted size, including nominal maximum enum payloads, zero-sized records and overflow. The existing heap/region/graph charge, failure, release and sixteen-byte graph-header rules remain unchanged (spec 03 §18–§24); authority is still explicit. Fixed value arrays have positive lengths (spec 07 §8.8), and runtime-sized backing arrays are not allocatable SSA values (spec 03 §19.2). No verifier acceptance rule changes. The existing overflowing_array_chain AIR/source rejection pair still reports E5101. The new nested_allocation_quota AIR/source run pair returns 42: twelve-byte nested content fits exactly, a second live allocation fails budget_exceeded, zero-sized content still fits, and freeing restores authority for a repeated allocation. No new code, trap, effect, feature, semantic flag, accepted-depth limit or bundle text is introduced. Fuel, instruction count, collection safe points, ownership transfer and deterministic outcomes are unchanged.
Unit tests compare scalar/nominal/built-in/capability/iref leaves under mixed array lengths against static accounting, preserving inactive enum payload maxima. Query-only inputs cover 32,768 wrappers, overflowing factors with zero/nonzero leaves and zero dynamic counts; shared payloads compactly represent these queries without claiming verified exponential constructions. A verified 32,768-level own.new programme pins exact fuel 0–6 boundaries under ordinary and per-instruction collection. A one-byte grant takes success, a zero-byte grant takes the error edge, and both executions terminate with the original instruction counts. The formerly crashing CLI probe now returns null with grants one and eight; grant zero retains its explicit failure trap. The successful deep run and both new conformance examples pass with collection before every instruction.
Validation: unit/format checks, test-extended and all 1,789 ordinary conformance cases pass. Ten old/new quota records for the new AIR/source pair are identical. Another 426 generated runs independently compute expected charges for scalar/record/enum contents, mixed fixed arrays, individual/repeated/zero-count owners and island/arc headers; every boundary outcome matches that oracle and the old interpreter's record. These are generated runtime robustness inputs, not model-evaluation or held-out tasks. The earlier full per-instruction collector conformance run remains additional validation in progress.
Q-060 remains open for output serialization at the fixed std.json.Stringify nesting stack and the still-recursive writeValue traversal. Q-059's uncached nominal query audit is separate; this repair does not claim to close it.
## Runtime value JSON repair
WriteValue now emits the complete value through a raw-value boundary in the outer std.json.Stringify. An explicit pending-sequence stack traverses arrays, record fields and enum payloads; the outer stringify never stores their nesting in its fixed 256-level table. Field order, variant/payload shape, decimal integer representation, escaping, whitespace and opaque handles retain their existing encoding (spec 07a, Run result). The public writer API and diagnostic schema are unchanged.
The invariant is byte-identical encoding of existing runtime values without traversing opaque identity handles or mutating returned payloads. Traversal metadata lives in a temporary host arena, released on success and failure; it adds no Aji allocation, authority, effect, fuel charge or collection point. Writer errors propagate as before; metadata allocation failure uses the existing WriteFailed interface. No recovery after partial output is promised. The CLI still buffers a complete run record before publishing it. Verifier rules are unchanged: the new returned_mixed_json AIR/source pair returns an enum containing records, nested arrays, signed integers and empty values; the existing source borrow_returns/main_return rejection retains E7006. No new rejection, trap, feature, depth limit or normative/bundle text is introduced.
Unit tests compare exact bytes with the ordinary Zig encoder in 112 combinations of whitespace, Unicode escaping, string-array, nonportable-number and optional-field options, wrapped between other fields in an outer object. Existing Aji raw decimal integers are preserved even when string mode for nonportable numbers is selected. A codec-only 32,768-level mixed record/variant/array value checks pending siblings and empty leaves against independently constructed bytes; it is not claimed as an executed source programme. Allocation failures check temporary-arena cleanup, and fixed-capacity writers fail at every byte boundary with the exact expected prefix. Another test fills the outer stringify's 256-level table, writes a nested runtime value and then continues and closes the outer containers.
The verified 32,768-level returned-array programme now produces the complete 65,568-byte CLI record, including its newline, in both deterministic and hosted profiles under fuel 8. Unit tests write its outcome after execution-heap release under ordinary and per-instruction collection. Hosted tests also compare both new shallow examples with the old CLI, using fuel rather than wall-clock termination.
Validation: all units, format checks, test-extended and the complete current set of 1,791 ordinary conformance cases pass (the prior 1,789-case full run plus the two added cases). Both added cases pass in Debug with collection before every instruction. Forty-four old/new shallow run records are byte-identical. At this checkpoint the earlier Debug per-step run had no completion result after 785 passing records and its process handle was missing; a namespace-limited process check failed to identify it before a replacement ReleaseSafe run was started. The later host-process inspection below corrects the mistaken inference that the Debug run had ended. Neither incomplete run is counted as a full pass.
Q-060 remains open for a closing call-path audit. Inspection shows that the public verify wrapper returns diagnostics without replacing the caller's module with verifyModule's derived-cache result, while interp.run accepts a verified module without rebuilding those caches. Runtime nominal size queries can therefore reach the uncached fallback tracked by Q-059. Whether this yields a failure on a verified cache-free library input is unverified; the mixed codec test above is not evidence for that path. No fresh Claude review was available for this increment.
## Cache-free runtime size-query path
The [nominal size-query increment](air-type-depth-audit.md#cache-free-nominal-accounted-size-queries) removes the recursive fallback reached by runtime size callers when a public verify caller retains its original module. A direct constructed 32,768-declaration query independently reproduces the old fallback failure and now returns one byte. Parsed, verified cache-free programmes at nominal depths 1,024 and 4,096 run successfully both before and after the repair; no old runtime failure at those depths is claimed. The distinction between query-only and fully verified inputs is retained.
Runtime queries now pass their host allocator and propagate temporary metadata OutOfMemory before authority charging or result publication. Temporary state is released after each query; arithmetic null, zero-sized content, maximum enum payloads and allocation failure/release rules keep their meanings. A verified quota test compares 54 cached/cache-free outcome pairs (108 runs), including exact fuel boundaries and per-instruction collection. The original verify and run APIs remain usable without derived caches. No normative, bundle, feature, code, trap or accepted-depth change is introduced. Q-060 remains open for the closing traversal audit and additional full per-step validation; Q-059's uncached nominal property queries remain separate work.
## Live-process and progress-output correction (2026-10-10)
Host-namespace inspection identifies both full per-step runs as live: Debug
PID 376545 writes `collector-gc-conformance.jsonl` (1,612 complete passing
records at inspection), and ReleaseSafe PID 458411 writes
`value-json-gc-safe-conformance.jsonl` (1,610). `/proc` inside the command
sandbox cannot see these host PIDs, although the approved `ps` command lists
them. A missing tool handle plus that namespace-limited check was insufficient
evidence of termination. Neither process was stopped or restarted in this audit.
The conformance runner's 4-KiB stdout buffer can also retain completed records
and leave an unrelated final record partially visible while later cases run.
It now flushes after each completed case, preserving record bytes/order and
exit status while exposing progress promptly. A separate current ReleaseSafe
`source/std` per-step run uses this writer; it is additional focused validation,
not a restart or a full-suite pass. No wall-clock timeout ends any run. A GDB
attach for read-only stack inspection was rejected by the host's ptrace policy.
Q-060 remains open until the traversal/lifetime audit and full validation have
terminal evidence. Q-059's [compiler inventory](type-traversal-inventory.md)
is now resolved; the earlier statements about its open query paths are historical.
## Closing runtime paths and error-exit cleanup
The production path inventory covers verified interpreter state, not arbitrary
fabricated host values. Arrays/aggregates have finite materialized structure;
backing-cell and closed-graph cycles use the copier's forwarding maps.
| Path | Handling |
|---|---|
| Zero construction, storage/SSA copying | Explicit pending-sibling continuations; no recursive payload descent. |
| Collector/result copying | Forwarded shells plus jobs for cells, payloads, graph objects, paths and mutex views. Each root finishes before escaping. |
| Accounted value/type size | Array cursor and checked factor; nominal type queries use the iterative cache-free/cached path closed by Q-059. |
| Place projections, slice bytes | Flat index-path loops and byte loops. |
| Endpoint/atomic/mutex/buffer selectors | Their remaining self-calls follow at most one borrow on verified inputs: verifier operations require a direct handle or exactly a borrow of that handle. Resource/graph selectors already inspect one such place directly. |
| Task frames, channel roots, authorities | Explicit frame/root/parent loops; the existing call-depth limit is 1,024. |
| Race shadows, weak-memory views/messages | Flat entries/path copies and message loops. |
| Runtime JSON | Pending sequences inside one raw-value boundary; opaque handles are not traversed. |
The lifetime inspection finds a separate host-error defect: `run` releases its
execution arena only after successful result copying. A verified 1,024-byte
array program, through a private allocator seam retaining the old run body,
fails at result `Copier.ensureItems`; the controlled execution backing allocator
records 259,888 allocated bytes and zero freed bytes. These are host allocator
counters, not Aji authority charges. The failing unit assertion reproduces the
missing cleanup before the repair.
Execution-arena cleanup is now deferred on every run exit, still before output
and host cleanup and after complete returned-value copying/statistics on success.
The invariant is that returned payloads survive in the caller arena while all
execution-owned blocks are released on success or propagated host OOM. Collection
continues to discard its failed new arena; its successful replacement inherits
the same backing allocator. The private test seam exposes no public option or
semantic flag. The production allocator remains page-backed. There is no retry,
transactional collection or output rollback guarantee.
Verifier initialization/ownership/borrow rules, runtime safe points, Aji quota
charges, effects, traps, scheduling and fuel are unchanged. The existing
zero_structure_siblings and returned_mixed_json AIR/source pairs remain valid;
read_uninitialized/copy_overlapping still reject E1010/E2101. No new diagnostic
is added: OutOfMemory remains a host error and no partial Outcome is returned.
The public run API and successful records retain backward compatibility.
Failure tests cover every caller-arena and execution-backing request, including
result copying and fresh collection arenas, under ordinary and per-instruction
collection. All failed/completed heaps have equal allocated/freed counters;
successful arrays remain readable after heap release. Units, format checks,
test-extended and all 1,793 ordinary conformance cases pass with exact coverage.
Twenty-nine old/new deterministic/hosted CLI pairs retain exact records and
independently expected fuel boundaries/values at depths 0–32,768. The full
per-instruction runs and the focused std run remain live validation; Q-060 and
Phase 6 are not closed by these ordinary results. No fresh Claude review is claimed.
## Per-step validation observation (2026-10-11)
Host inspection now confirms Debug PID 376545 and the additional source/std
PID 1456454 are still running. ReleaseSafe PID 458411 is absent. Its
`value-json-gc-safe-conformance.jsonl` has 1,789 complete distinct passing
records, without duplicates, but its terminal exit status is unavailable.
Compared with the current 1,793-file corpus, it lacks the AIR/source
`returned_mixed_json` pair and source generic identity-growth 31/63 cases.
`value-json-gc-safe-current-observation.json` records that comparison.
Two current ReleaseSafe `--collect-every-step` filtered runs complete with
exit 0 and exactly those four passing cases, no missing/extra/duplicate or
nonpassing records (`gc-current-missing-cases.audit.json`). The generic growth
cases are verifier rejections, not additional runtime executions. This supplies
current focused coverage of the absent cases; it does not establish terminal
success for the historical run or a full current-binary GC suite pass. No live
run was restarted or stopped and no wall-clock timeout ended a test.
Q-060 and the Phase 6 full-validation gate remain open.
## Full per-step validation launch (2026-10-13)
A new full ReleaseSafe run starts from HEAD `3154588` (full revision in
`provenance.json`), Zig 0.17.0, and an isolated snapshot of the current build
inputs and all 1,793 conformance files. The command is:
```sh
zig build conformance -Doptimize=ReleaseSafe -- --json --collect-every-step
```
The runner compares ordinary and collect-before-every-instruction run records
for each runtime test and each configured schedule. Accept/reject cases still
participate in full corpus coverage; they do not execute the collector.
Artifacts are in `/tmp/aji-q060-gc-20261013-x7tp0ee4/`: `provenance.json`,
`inputs.sha256.json`, `expected-tests.json`, `conformance.jsonl`, `stderr.log`,
and `status.json`. User systemd unit `aji-q060-gc-20261013-x7tp0ee4.service`
owns the process independently of the interactive session. On completion,
`exit.json` records the command's exit status before coverage auditing;
`audit.json` checks exact coverage, duplicates, nonpassing records and unchanged
snapshot input hashes. No wall-clock timeout ends the run; test fuel headers
and the runner's existing default fuel remain in force.
Launch is not a full pass. Q-060 remains open until terminal exit 0 and the
complete coverage audit are recorded. Phase 6's owner-confirmed exit rescoping
is separate from this remaining hardening check.
## Full per-step validation result (2026-10-14)
The full current-binary per-step collection gate is met by composite coverage on
one frozen snapshot (HEAD `3154588`, ReleaseSafe, `--collect-every-step`; the
snapshot's input hashes are unchanged). The original single run (`zig build
conformance -- --json --collect-every-step`) completed 1,643 distinct passing
records, then stalled for many hours on `source/std/fmt_i64_vectors.aji`
(12,358,702 interpreter steps; about 2.7-2.9 ms per step under collection, in
fuel-limited timing of the same file at 50,000 and 100,000 steps). The 150
remaining tests were run one per process with the same binary, flags and
snapshot (`--filter`, eight at a time). All 150 exited 0 with exactly one
passing record each.
The audit over both result sets: 1,793 expected, 0 missing, 0 extra, 0
nonpassing, 0 disagreements; the three tests both processes completed overlap
and agree. No wall-clock timeout ended any run; the six vectors took roughly
4-5 hours each.
Limit of this evidence: the single original process had not reached a terminal
exit status when this result was recorded. It was stopped by the operator after
about 22 hours (1,646 records, all passing, no failure) and is not part of the
composite; the composite alone carries the closure. The result adds no normative depth limit,
trap or diagnostic.
## Cheaper per-step collection for vector suites (2026-10-14)
Six vector suites (`fmt_i64/isize/u64/usize_vectors`, `text_base64/hex_vectors`,
roughly 12 million steps each) made `--collect-every-step` take about 4-10
hours per test. The conformance header `gc: skip` now runs such a test normally
under that mode, and each has a sampled `_gc` sibling (20-21 vectors: limits,
tail and evenly spaced inputs) that is collected at every step. The full
suites still run in ordinary and `--stress` modes. The corpus is 1,799 tests;
all pass, and the thirteen vector files complete under per-step collection in
about 48 minutes. This changes which inputs are collected per step, not the
collector, the language or any diagnostic; the Q-060 validation result above
used the original full suites.
+62
View File
@@ -0,0 +1,62 @@
# Source diagnostic repair and independent-error collection
Non-normative work item following the owner's 2026-10-09 proposal. This does not change accepted syntax, type inference or diagnostic collection. Governing text: spec 15 §4/§10, spec 10 §2 and spec 14 §12; implementation: `src/frontend/{parse,lower}.zig`. RFC 0038's programmatic repair candidates remain a separate, deferred proposal.
## Evidence and limits
The owner reports 15 GLM-5.3-flash sessions on four public dev tasks: of 52 rejected checks, the first diagnostic was E7001 in 30, E7005 in 10 and E7006 in six. Missing var annotations, lossy casts and Rust-style negation were frequent. These aggregates are supplied observations, not independently audited runs. First-code counts are not counts of all errors; one model family does not establish a language-inference policy. No task implementation, private corpus or frozen experiment is inspected or changed for this investigation. The proposed threefold reduction in E7001 checks is an experiment target, not a demonstrated effect.
Twelve minimal current-language probes confirm: prefix `!`, missing var type, `mut slice<T>`/`ref slice<T>`, an omitted range end, `[zero; N]` and `&` in arguments/bindings reject E7001; a non-widening integer cast rejects E7005. Three syntactically invalid functions yield one E7001; two independently invalid casts yield one E7005. Crucially, `let x = 1u64` already accepts: let inference is specified, and its annotation must not be demanded by a repair hint. These are generic syntax probes, not dev-task reproductions.
## First increment: explicit advice without syntax aliases
Use the existing optional `repair_candidates` envelope (spec 10 §3), rather than introducing parallel hint/suggested envelope fields. Register stable candidate kinds selected by the rejecting rule, with additive explanatory hint text and explicitly ordered suggested alternatives inside each candidate. A hint explains an applicable rule; suggested text is a context-local alternative, not an automatically applicable edit or a claim that the resulting program verifies. Preserve codes, positions, expected/found and messages. Pin candidate field order, types and applicability in spec/reference before implementation; test the structured fields through CLI/package paths, not message parsing. RFC 0038's edits remain separate and deferred.
| Rejected context | Candidate advice | Constraint |
|---|---|---|
| prefix `!` at expression start | hint: Aji boolean negation is `not` | no advice for valid `as!`; parser-only advice cannot assert a bool operand or translate Rust integer complement |
| `var name =` without an annotation | hint `write var name: T = expression` | parser does not know the initializer's type; let is excluded |
| `mut slice<T>` / `ref slice<T>` in a type position | suggested `slice_mut<T>` / `slice<T>` | recognize the entire type context; retain the actual element spelling |
| omitted range end | hint requiring an explicit upper bound | only suggest `name.len` after proving the receiver is the suitable named slice; repeating a general receiver can change evaluation |
| `&place` / `&mut place` | hint about explicit ref/mut arguments or ref/mut bindings | argument replacement and binding-statement replacement are different; `let r = ref x` is invalid |
| lossy `as T` | ordered alternatives `as!`, `as%` | checked versus truncating conversion is a semantic choice; never choose one automatically |
| `[zero; N]` | hint to initialize named, typed zeroable storage first | no invented element type or implicit constructor |
Expression and type context must come from the parser/lowerer, not substring searches over messages. Keep accepted contract-free AIR and source spellings unchanged. Any byte-edit schema additionally needs exact source ranges/context and applicability rules; the proposed strings alone do not provide that.
## Second increment: independent errors without partial compilation
Investigate parser recovery only between complete top-level declarations. Balanced token delimiters and actual declaration syntax are stronger boundaries than a keyword at the start of a line: static function selections may contain fn, and a broken delimiter may prevent establishing an independent next item. Emit at most one syntax error per failed item; if independence cannot be established, stop. Discard the entire erroneous module and never lower or verify a partial AST. Three balanced function bodies with separate expression errors must produce three E7001s; one broken expression must not manufacture additional errors in that item. Import/header/lexical failures need explicit stopping rules.
For lowering, first validate module names/types/signatures, then investigate collection across independent function bodies. Discard failed bodies and emit no AIR when any source error exists. Specify state reset, generic-specialization failures, dependency suppression, packages, diagnostic ordering and fixed collection bounds before extending the current first-error result. A global signature failure cannot safely be treated as an independent body failure. Two invalid casts in different valid-signature functions are the minimal positive collection target; dependent callers and malformed generic bodies are negative cascade cases.
Preserve one diagnostic per code/source location and the E7900 rule replacing all other diagnostics on an internal frontend error, including imported/std failures. Check/run/report/explore/lower must return identical source diagnostic sets for an erroneous module; fmt still refuses syntactically invalid input. No recovery stub may reach the AIR verifier. Multi-error collection changes previously rejected diagnostic multisets: audit existing conformance, hosted and rejection-twin expectations, and record the compiler/diagnostic version in subsequent evaluation conditions.
## Order and validation
1. Specify and implement structured advice with applicability tests and unchanged acceptance.
2. Add a compact Quick Reference table describing current Aji spellings; measure bundle growth and compile its Aji examples. Include the already-supported let inference.
3. Complete the recovery design and implement it with parser/lowering/package/CLI tests.
4. Have the evaluation owner rerun public dev tasks after the changes; retain both first-code and full diagnostic counts, model/tool settings and frozen input identities. Do not modify a frozen matrix in place.
Var inference remains an optional language-policy question. No change is adopted from these aggregates; the first increment can reduce repair burden while retaining explicit var annotations. Contract research and its full P6-6 exit criterion remain open.
## First increment delivered (2026-10-09)
Nine registered kinds now provide contextual E7001/E7005 advice through `repair_candidates`; argument and binding borrows are separate. Fixed hints and alternative units are specified in spec 10/15 and the registry. Enum variant payloads, `&&`, unsupported block comments, incomplete types and other nearby spellings have explicit exclusion tests. No syntax alias, var inference, inferred slice end or automatic cast selection was added.
Validation: 1735/1735 conformance, including exact `.advice` JSON goldens for all kinds; 161 CLI/package advice checks; unit/registry tests, grammar, formatter, hosted smoke and format checks. Independent Claude review caught the enum-payload context and confirmed the static candidate lifetime correction. At this increment's boundary, multi-error collection was still pending; its delivery follows below. The public dev measurement remains pending.
Bundle growth versus the pre-increment generated bundle (whose Quick Reference matched HEAD): Quick Reference `cl100k_base` 8955 → 9237 (+282, 3.15%), `o200k_base` 8991 → 9272, Qwen2.5 9233 → 9515. Full Source Reference Bundle excluding AIR: 77358 → 78582 (+1224, 1.58%), 77594 → 78815 and 79315 → 80563 respectively. The table and machine advice registry account for this explicit cost; the proposed reduction in repair rounds has not been measured.
## Second increment delivered (2026-10-09)
Spec 15 §10 now defines delimiter-bounded parser recovery, first-error phase stops, collection across validated function bodies, deterministic order and the fixed 32-diagnostic limit. Every failed item/body contributes only its first error. A broken header/import or uncertain delimiter boundary stops collection; no partial AST/AIR reaches another stage. The first failing imported file carries its recovered list. Bodies start with fresh state; failed constants/features/linearity accumulations are restored. Calls read validated signatures, so a bad callee does not create a caller error. Later instances of a failed template are skipped. E7900 still replaces other diagnostics and carries no advice.
Check/lower/run/report/explore and syntax-only fmt now carry the applicable JSON Lines lists. The 12 original mini-probes preserve acceptance and every prior first-diagnostic field; the three-function syntax probe grows from one to three records, and the two-cast probe from one to two. These are compiler observations, not measurements of model repair rounds.
Validation: full conformance 1760/1760; all 25 independent-error fixtures; 234 CLI/package collection checks, 163 advice checks and 5975 formatter checks over 1442 files (770 accepted AIR outputs remain identical). Unit tests compare the next function's complete output/constant tags with fresh lowering after failed borrow/scope/loop bodies, pin constant/feature rollback and no output on error, and test std failure collapse to E7900. Remaining CI Python hosted/oracle checks passed (38 commands, including examples under 200 schedule seeds); source construct coverage remains 121/121. Evaluation harness self-tests also passed (41 tests, one skipped), using scripted/mocked providers rather than model runs. The reason suite's stale void-parameter expectation now pins the earlier E7005, its registry scan selects only the reason section, and the defensive void/never move guard is unit-tested. Claude found no remaining implementation defects after review.
Combined bundle cost for both increments: Quick Reference `cl100k_base` 8955 → 9255 (+300, 3.35%), `o200k_base` 8991 → 9290 and Qwen2.5 9233 → 9534. Full Source Reference Bundle excluding AIR: 77358 → 79072 (+1714, 2.22%), 77594 → 79306 and 79315 → 81059. The second increment adds 18 Quick Reference and 490 full-source tokens in `cl100k_base`; the cost documents recovery boundaries and the JSON Lines contract instead of adding language syntax.
The implementation is ready for a new pinned public dev condition. Gobang is not installed/exposed in this workspace, so no model runs or claimed threefold improvement are recorded here. The evaluation owner should confirm that its tool wrapper retains every diagnostic JSON line and freeze the new compiler commit, docs hashes, model/settings and tool behavior before rerunning the same four public dev tasks. Compare checks/turns and first-code/full-code counts separately; retain the earlier condition unchanged. Ajieval's inspected single-object readers are for documentation/Gobang tool envelopes, not raw compiler stdout; that does not verify the external Gobang wrapper. P6-12 remains open for this measurement, and P6-6 remains open in full.
File diff suppressed because it is too large. Load diff
+60
View File
@@ -0,0 +1,60 @@
# Compiler type-traversal inventory
Non-normative closing inventory for Q-059, at d98ddbc plus the companion
`typeOfNoFail` repair. The [executed audit](air-type-depth-audit.md) records
individual failures, compatibility comparisons and allocation tests.
Scope: finite parsed AIR/source type syntax, resolved nominal declaration
graphs, type diagnostics, canonical output and audit reports. Native stack
depth must not grow with anonymous type nesting or nominal graph depth on
these paths. This does not promise constant memory/time, bounded expression
or statement nesting, or bounded processing of fabricated cyclic host pointers.
| Production path | Traversal / remaining bound |
|---|---|
| AIR `parseType`, compound construction (`src/air/parse.zig`) | Pending constructor frames; no recursive child parse. |
| AIR `Type.eql`, `inner`, classification (`src/air/module.zig`) | Cursor comparison or one-node inspection; names stop at declaration identity. |
| Verifier `accountedSize`, `SizeMemo.size`, `ValueSizes.visit` (`src/verifier/budget.zig`) | Affine anonymous fold, explicit nominal continuations and inner-node loop; nominal cycle depth changes exactly as before. |
| `wellFormed`, `argumentLengths`, finite layouts (`src/verifier/types.zig`) | Anonymous cursors and nominal DFS frames; graph-owner stops and ordered diagnostics retained. |
| Nine structural properties, dependencies, height/witness summaries (`src/air/properties.zig`) | Anonymous cursor/mode transitions plus monotone nominal worklist; summary saturation at 65/34 is unchanged. |
| Public uncached property queries | Temporary prepared module, allocator/error API; no recursive raw fallback. Prepare once for repeated nominal queries to avoid repeated whole-module preparation. |
| `bounded` (`src/air/properties.zig`) | Remaining production recursion checks `depth >= 64` before descent; cached nominal reads use height. |
| AIR canonical/diagnostic type printer, report capability collector (`src/air/print.zig`, `src/report.zig`) | Explicit suffix stack or anonymous cursor; declaration roots enumerated separately. |
| Source `typeExpr` (`src/frontend/parse.zig`) | Explicit constructors/argument continuations, including speculative advice parsing. |
| Source formatter, generic-use detector (`src/frontend/format.zig`, `src/frontend/generics.zig`) | Token spans / AST work entries; reflective visitation queues children rather than recursively visiting type syntax. |
| Source type-position and Copy-content scans (`src/frontend/type_positions.zig`, `src/frontend/type_properties.zig`) | Anonymous cursors, explicit nominal argument/member continuations and indexed cycle paths. |
| Source resolution, text, AIR conversion, equality (`src/frontend/lower.zig`) | Pending constructors/suffixes, fresh output-target cursor or two comparison cursors. |
| Source linearity, signature feature discovery, SSA zero | Iterative chains; the existing module-sized feature-discovery guard remains. Unsupported zero leaves reject before emission. |
| Source optional `queryAnnotation` (formerly `typeOfNoFail`) | Validate chain/leaf before allocation, then build fresh output nodes iteratively. Only names/arrays are recognized. Unknown stays `null`; the [Q-061 host-OOM follow-up](source-expression-depth-audit.md#external-review-and-host-oom-follow-up) propagates allocation failure separately, without a diagnostic or published partial type. |
| Source `forbiddenIn` | Remaining recursion checks `depth > 32` before descent; named cached distance prunes unreachable witnesses. Calls to annotation resolution use the iterative path above. |
| Generic headers/substitution/static arguments | `headerType`/`headerArgument` and `ty`/`instantiate` retain their existing guards at 64. Static-function argument resolution re-enters guarded instantiation; reflective specialization intercepts `ast.Type` before visiting its representation. |
| Composed specialization identities | Iterative prefix/leaf/suffix writer. Substitution can return an already composed type deeper than one guarded `ty` traversal, so identity emission must not rely on that guard. Existing key-size checks retain their postorder spans. |
Prepared reads have an explicit precondition. `verifyModule` discards caller
caches; `types.check` prepares its module before type queries and subsequent
borrow/init/bounds stages. Source lowering uses its separately prepared
`property_module`. Raw public APIs prepare temporary facts rather than silently
using the prepared-only API. Replacing declarations invalidates both caches.
The recursive `Reference*` derivations, `referenceSize`, `referenceTypeHint`
and AIR-property `witness` are shallow test oracles, not production call paths.
A textual self-call census was used as a search aid, followed by inspection of
delegated and mutually recursive paths; it is not itself a proof. The module
import graph has a separate existing depth-256 guard and does not traverse
type syntax. Recursive expression parsing, expression queries and generic
expression transformation remain outside this type-depth claim and are logged
separately as inspection-only Q-061.
Validation combines the increment-specific independent shallow oracles,
32,768/65,536-level helper and CLI probes, nominal cycles/shared graphs,
allocation failures and exact diagnostic/canonical-output comparisons. The
latest field-expression probe is deliberately shallow (`r.x.len`) with a deep
annotation: it catches a type walk missed by plain parameter checks. Its CLI
integration also checks formatting, source/AIR checking, lowering, report parity
and scalar execution. It does not materialize a deep runtime value.
Q-060 separately tracks runtime value/copy/collector/JSON traversal and its
unfinished full collection-before-each-instruction validation. Neither this
inventory nor the compiler tests close that runtime gate or the Phase 6 exit
review. Claude's earlier review covers uncached nominal properties only;
subsequent frontend repairs have prepared review requests, not a received review.
+4
View File
@@ -91,6 +91,10 @@ These hold for the whole toolchain, not only deterministic mode:
- `std.testing.allocator` in unit tests to catch leaks. - `std.testing.allocator` in unit tests to catch leaks.
- No global mutable state; pass allocators and `std.Io` explicitly. - No global mutable state; pass allocators and `std.Io` explicitly.
Structural queries share a per-module table over resolved nominal declarations. A reverse-dependency worklist computes the existing boolean predicates, saturated traversal height and nearest forbidden source-element depth; named queries then read that immutable table. Existential properties start false, universal properties true, height increases and witness distance decreases to their existing depth limits. Cycles therefore terminate without a traversal timeout; existing layout/type checks still decide rejection. The verifier rebuilds the table rather than trusting one supplied by a caller. Source lowering builds it after finite-layout checking, preserves diagnostic order and uses the same declaration snapshot. The witness search retains field order and its depth-32 boundary, pruning subtrees with no reachable witness. Tests count evaluations and compare the cached predicates against uncached derivations on small acyclic modules. This changes implementation cost, not AIR meaning, ownership classes or runtime behavior.
The budget stage separately memoizes accounted sizes by nominal index and depth. Including depth preserves the previous cutoff and overflow diagnostics exactly, with at most V × (V + 2) nominal states; shared paths no longer expand exponentially. Verification returns a module carrying read-only caches for subsequent report/interpreter queries. Replacing a module's declarations invalidates its caches. Standalone uncached property/size helpers retain their recursive derivations for small differential tests.
## Zig conventions ## Zig conventions
- Zig 0.17.0, formatted with `zig fmt`. - Zig 0.17.0, formatted with `zig fmt`.
+7
View File
@@ -35,6 +35,7 @@ Planned header extensions (added by the phase that needs them):
| `stdin:` / `vfs:` / `seed:` / `stdout:` / `stderr:` / `file:` / `blocked:` | P2 (implemented) | deterministic world inputs and expected observable output | | `stdin:` / `vfs:` / `seed:` / `stdout:` / `stderr:` / `file:` / `blocked:` | P2 (implemented) | deterministic world inputs and expected observable output |
| `grant:` / `not_instantiated:` | P2 (implemented) | capability grants for `@main`; expected instantiation failure | | `grant:` / `not_instantiated:` | P2 (implemented) | capability grants for `@main`; expected instantiation failure |
| `fuel:` | P0 (implemented) | instruction limit; default 1 000 000 (spec 11 §7.1) | | `fuel:` | P0 (implemented) | instruction limit; default 1 000 000 (spec 11 §7.1) |
| `gc: skip` | implemented | under `--collect-every-step` the test runs without collection; only for vector suites whose step count (about 12 million, roughly 2.8 ms per step under collection) makes per-step collection impractical. Each such test has a sampled `_gc` sibling that is collected at every step, so the same code paths stay covered. Ordinary and `--stress` runs execute the full suite |
| `seed:` / `schedules:` / `quantum:` | P3 | scheduler seed / schedule budget / instructions per forced scheduling point (spec 11 §7.2) | | `seed:` / `schedules:` / `quantum:` | P3 | scheduler seed / schedule budget / instructions per forced scheduling point (spec 11 §7.2) |
| `profile:` | P2 | runtime profile (`hosted`, `deterministic`, …) | | `profile:` | P2 | runtime profile (`hosted`, `deterministic`, …) |
@@ -47,3 +48,9 @@ Every run test is executed twice by the runner from P0-12 onward and the outputs
## Diagnostics as API ## Diagnostics as API
Diagnostic JSON is a stable interface. Snapshot tests on the full JSON (not only the code) belong in unit tests next to the pass that emits them, so field renames are caught. Diagnostic JSON is a stable interface. Snapshot tests on the full JSON (not only the code) belong in unit tests next to the pass that emits them, so field renames are caught.
`python3 tests/hosted/source_diagnostic_reasons.py` checks stable E7006 categories, generic/package propagation and serialization. From `tools/eval`, `python3 -m unittest discover tests` checks reporting alongside the harness. `ajieval summary` reports observed `(code, reason)` occurrences and affected runs with log coverage; `profile` and `checkpoint` expose per-run pairs. Existing compact code extraction is preserved. Only whole JSON diagnostic lines classify a reason: unparsed or historical records remain unknown; new reason strings are retained. Missing logs are unavailable. These counts cover the recorded command outputs, not a pre-acceptance cutoff or the true frequency of unobserved errors; future cohort methodology must specify those separately.
`python3 tests/hosted/related_locations.py` checks factual E2101/E2104 definitions and E4302 spawns in public AIR/source rejects, exact definition coordinates (including parameters and second split results), independent annotation-map reconstruction, existing source deduplication, generics and explicit packages. Unit tests cover typed JSON/key order, absent related mappings and repeated cancelled-join handle replacement through the lowered-source pipeline. `zig build conformance -- --filter cancel_join --stress 200 --collect-every-step` exercises accepted cancellation counterparts under deterministic schedule seeds and several quanta. These checks add no repair or lifetime inference.
The CLI JSON reader rejects duplicate members instead of silently overwriting them; targeted capability-kind and live-guard cases check the stable machine `kind` and separate payload identities. Pipeline unit tests also parse those records with duplicate fields forbidden. `verifier.expectCodes` checks that all its diagnostics have distinct payload names that do not shadow the envelope (`diag.expectUniqueFields`). The conformance runner validates every final source/AIR diagnostic after lowering and mapping, including frontend-added fields, and parses its serialized JSON with duplicate members forbidden. This adds no production/runtime check.
+1
View File
@@ -10,6 +10,7 @@ Non-normative. Empirical validation of the Aji hypothesis stated in [spec 14](..
| [harness.md](harness.md) | Agent scaffold and run recorder (E0-3): task format, evaluator contract, run record, commands | | [harness.md](harness.md) | Agent scaffold and run recorder (E0-3): task format, evaluator contract, run record, commands |
| [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 | | [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 | | [../agent/README.md](../agent/README.md) | Agent Reference Bundle: contents, measurement, growth policy, milestones |
| [dev-tasks/](dev-tasks/) | Public dev tasks. `dev-echo` and `dev-netprobe` check the harness. `dev-intervals`, `dev-lru` and `dev-shards` (family `failure-calibration`) cover collections with invalid input, an owning cache and sharded concurrency; their failures calibrate `ajieval classify --suggest`. Each has a public evaluator over a Python model and a Rust reference under `reference/`. [dev-failure-plan.json](dev-failure-plan.json) runs them. Dev material: never evidence, and the language is not tuned to them |
## Integrity rules (protocol §7, §29; spec 14 §12) ## Integrity rules (protocol §7, §29; spec 14 §12)
+14
View File
@@ -0,0 +1,14 @@
{
"comment": "Dev failure-calibration matrix (dev set; never evidence): runs whose failures calibrate `ajieval classify --suggest`. Run from tools/eval: python3 -m ajieval matrix ../../docs/evaluation/dev-failure-plan.json",
"tasks": ["dev-tasks/dev-intervals", "dev-tasks/dev-lru", "dev-tasks/dev-shards"],
"languages": ["aji_source", "aji_air", "rust", "zig"],
"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": "dev-tasks/evaluate.py",
"evaluator_hash_path": "dev-tasks",
"out": "../../tools/eval/runs-dev-failure"
}
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""Evaluator for dev-intervals (dev set; public).
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout
"""
import os
import random
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import devlib # noqa: E402
LIMIT = 1 << 63
def number(tok):
if not tok or not tok.isascii() or not tok.isdigit() or (len(tok) > 1 and tok[0] == "0"):
return None
v = int(tok)
return v if v < LIMIT else None
def model(text):
"""Reference semantics: the sorted list of disjoint, non-touching intervals."""
ivs, out = [], []
lines = text.split("\n")
if text.endswith("\n"):
lines.pop()
if text == "":
lines = []
for line in lines:
parts = line.split(" ")
cmd, args = parts[0], parts[1:]
nums = [number(a) for a in args]
if None in nums:
out.append("error")
elif cmd in ("add", "remove") and len(nums) == 2 and nums[0] < nums[1]:
a, b = nums
keep = []
for x, y in ivs:
if cmd == "remove" or y < a or x > b:
if y <= a or x >= b:
keep.append((x, y))
else:
if x < a:
keep.append((x, a))
if y > b:
keep.append((b, y))
else:
a, b = min(a, x), max(b, y)
if cmd == "add":
keep.append((a, b))
ivs = sorted(keep)
elif cmd == "covered" and len(nums) == 1:
out.append("yes" if any(x <= nums[0] < y for x, y in ivs) else "no")
elif cmd == "count" and not args:
out.append(str(len(ivs)))
elif cmd == "total" and not args:
out.append(str(sum(y - x for x, y in ivs)))
elif cmd == "list" and not args:
out.append(" ".join(f"{x}-{y}" for x, y in ivs) or "empty")
else:
out.append("error")
return "".join(o + "\n" for o in out)
def gen(rng, n, lo, hi, invalid=0.0):
lines = []
for _ in range(n):
r = rng.random()
if r < invalid:
lines.append(rng.choice(["", "add", "add 1", "add 3 3", "add 5 2", "remove 01 4", "add -1 4", "covered",
"covered x", "count 1", "list now", "total ", " total", "add 1 2", "Add 1 2",
f"add 0 {LIMIT}", f"covered {LIMIT + 5}", "add 1 2 3", "add\t1 2", "remove 2 1"]))
continue
k = rng.random()
a = rng.randrange(lo, hi)
b = a + rng.randrange(1, max(2, (hi - lo) // 8))
if k < 0.35:
lines.append(f"add {a} {b}")
elif k < 0.55:
lines.append(f"remove {a} {b}")
elif k < 0.75:
lines.append(f"covered {rng.randrange(lo, hi)}")
else:
lines.append(rng.choice(["count", "total", "list"]))
return "\n".join(lines) + ("\n" if rng.random() < 0.8 else "")
def case(text):
return (text, model(text))
PUBLIC = [case("add 10 20\nadd 20 25\ncovered 24\nremove 12 14\nlist\ncount\ntotal\nadd 5 5\n")]
rng = random.Random(20261007)
HIDDEN = [
case(""),
case("list\ncount\ntotal\ncovered 0\n"),
case("add 0 1\nadd 2 3\nadd 1 2\nlist\nremove 0 3\nlist\n"),
case(f"add 0 {LIMIT - 1}\ntotal\ncovered {LIMIT - 2}\ncovered {LIMIT - 1}\nlist\nremove 1 {LIMIT - 2}\nlist\ntotal"),
case("add 5 10\nremove 0 100\nadd 1 2\nadd 3 4\nadd 5 6\nadd 2 3\nlist\ncount\nadd 4 5\nlist\n"),
case("add 7 9\n\nadd 9 11\nlist\nadd 1 2 \nlist"),
case(gen(rng, 60, 0, 100, invalid=0.25)),
case(gen(rng, 400, 0, 1000, invalid=0.05)),
case(gen(rng, 700, 0, 1 << 40, invalid=0.02)),
case("\n".join(f"add {2 * i} {2 * i + 1}" for i in range(1400)) + "\ncount\ntotal\ncovered 2799\ncovered 2798\n"),
]
if __name__ == "__main__":
devlib.evaluate(devlib.Spec("intervals", heap=4 << 20, fuel=400_000_000, public=PUBLIC, hidden=HIDDEN))
@@ -0,0 +1,6 @@
# Interface
- Source: `main.air`, a text AIR module.
- Entry point: `@main(%in: cap<io.read>, %out: cap<io.write>, %heap: cap<mem.alloc>)`; any return type.
- The program is run as `aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.air`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
@@ -0,0 +1,19 @@
#!/bin/sh
# Public test: the example from the task statement.
rec=$(aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'add 10 20
add 20 25
covered 24
remove 12 14
list
count
total
add 5 5
' main.air)
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
expected=$(printf "%s" 'yes
10-12 14-25
2
13
error
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,6 @@
# Interface
- Source: `main.aji`, an `.aji` module.
- Entry point: `main(input: cap<io.read>, out: cap<io.write>, heap: cap<mem.alloc>)`; any return type.
- The program is run as `aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.aji`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
@@ -0,0 +1,19 @@
#!/bin/sh
# Public test: the example from the task statement.
rec=$(aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'add 10 20
add 20 25
covered 24
remove 12 14
list
count
total
add 5 5
' main.aji)
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
expected=$(printf "%s" 'yes
10-12 14-25
2
13
error
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,6 @@
[package]
name = "intervals"
version = "0.1.0"
edition = "2021"
[dependencies]
@@ -0,0 +1,5 @@
# Interface
- Cargo package `intervals` in this directory; the binary is `target/debug/intervals`.
- The program reads standard input and writes standard output, as the task describes.
- Only the standard library is available (no network, `--offline`).
@@ -0,0 +1 @@
fn main() {}
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Public test: the example from the task statement.
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'add 10 20
add 20 25
covered 24
remove 12 14
list
count
total
add 5 5
' | ./target/debug/intervals) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'yes
10-12 14-25
2
13
error
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,4 @@
# Interface
- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`.
- The program reads standard input and writes standard output, as the task describes.
@@ -0,0 +1 @@
pub fn main() void {}
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Public test: the example from the task statement.
zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'add 10 20
add 20 25
covered 24
remove 12 14
list
count
total
add 5 5
' | ./main) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'yes
10-12 14-25
2
13
error
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,57 @@
# Task: interval set
Development task (dev set). Its results are not evidence about any language.
Write a program that maintains a set of non-negative integers, described as half-open intervals, and answers queries about it. The program reads commands from standard input, one per line, and writes its answers to standard output.
## Input
The input is a sequence of lines separated by `\n`. If the input ends with `\n`, that final `\n` does not start another line. The input is at most 24 KiB and has at most 2000 lines. It may be empty.
A **number** is written in decimal with the ASCII digits `0`–`9`. It has no sign, no leading zeros (except the number `0` itself), and is less than 2^63 = 9223372036854775808.
A line is a valid command when it is exactly one of the forms below: the command word, then the stated number of arguments, each separated by exactly one space. There are no other spaces or characters.
| Command | Meaning | Output |
|---|---|---|
| `add A B` | requires `A < B`; adds every integer x with A ≤ x < B to the set | nothing |
| `remove A B` | requires `A < B`; removes every integer x with A ≤ x < B from the set | nothing |
| `covered X` | is X in the set? | `yes` or `no` |
| `count` | the number of maximal intervals the set consists of | the number |
| `total` | how many integers the set contains | the number |
| `list` | the maximal intervals in increasing order | `A-B` for each maximal interval [A, B), separated by single spaces; `empty` if the set is empty |
A **maximal interval** is a half-open interval [A, B) contained in the set such that neither A − 1 nor B is in the set. For example, after `add 1 3` and `add 3 5`, the set consists of one maximal interval, `1-5`.
Any other line, including an empty line, an unknown command, a wrong number of arguments, a malformed number, a number of 2^63 or more, and `add` or `remove` with `A ≥ B`, is **invalid**. For an invalid line the program writes `error` and leaves the set unchanged.
## Output
One output line for each command that produces output and for each invalid line, in input order. Every output line ends with `\n`. Nothing else is written to standard output.
## Example
Input:
```text
add 10 20
add 20 25
covered 24
remove 12 14
list
count
total
add 5 5
```
Output:
```text
yes
10-12 14-25
2
13
error
```
The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. Hidden tests check the requirements above, including invalid input.
@@ -0,0 +1,6 @@
[package]
name = "intervals"
version = "0.1.0"
edition = "2021"
[dependencies]
@@ -0,0 +1,55 @@
use std::collections::BTreeMap;
use std::io::{Read, Write};
const LIMIT: u64 = 1 << 63;
fn number(t: &str) -> Option<u64> {
if t.is_empty() || !t.bytes().all(|b| b.is_ascii_digit()) || (t.len() > 1 && t.starts_with('0')) || t.len() > 19 {
return None;
}
t.parse::<u64>().ok().filter(|&v| v < LIMIT)
}
fn main() {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).unwrap();
let mut lines: Vec<&str> = input.split('\n').collect();
if input.ends_with('\n') || input.is_empty() {
lines.pop();
}
let mut set: BTreeMap<u64, u64> = BTreeMap::new(); // start -> end, disjoint, non-touching
let mut out = String::new();
for line in lines {
let parts: Vec<&str> = line.split(' ').collect();
let nums: Option<Vec<u64>> = parts[1..].iter().map(|t| number(t)).collect();
let Some(nums) = nums else { out.push_str("error\n"); continue };
match (parts[0], nums.as_slice()) {
("add", &[a, b]) | ("remove", &[a, b]) if a < b => {
let (mut a2, mut b2) = (a, b);
let hit: Vec<(u64, u64)> = set.range(..=b).filter(|&(_, &y)| y >= a).map(|(&x, &y)| (x, y)).collect();
for (x, y) in hit {
set.remove(&x);
if parts[0] == "add" {
a2 = a2.min(x);
b2 = b2.max(y);
} else {
if x < a { set.insert(x, a); }
if y > b { set.insert(b, y); }
}
}
if parts[0] == "add" { set.insert(a2, b2); }
}
("covered", &[x]) => out.push_str(if set.range(..=x).next_back().map_or(false, |(_, &y)| x < y) { "yes\n" } else { "no\n" }),
("count", &[]) => out.push_str(&format!("{}\n", set.len())),
("total", &[]) => out.push_str(&format!("{}\n", set.iter().map(|(x, y)| y - x).sum::<u64>())),
("list", &[]) => {
let s: Vec<String> = set.iter().map(|(x, y)| format!("{x}-{y}")).collect();
out.push_str(if s.is_empty() { "empty" } else { "" });
out.push_str(&s.join(" "));
out.push('\n');
}
_ => out.push_str("error\n"),
}
}
std::io::stdout().write_all(out.as_bytes()).unwrap();
}
@@ -0,0 +1,19 @@
#!/bin/sh
# Public test: the example from the task statement.
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'add 10 20
add 20 25
covered 24
remove 12 14
list
count
total
add 5 5
' | ./target/debug/intervals) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'yes
10-12 14-25
2
13
error
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,15 @@
{
"id": "dev-intervals",
"version": "1",
"set": "dev",
"family": "failure-calibration",
"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"}
},
"limits": {"tool_calls": 80, "total_tokens": 1500000, "wall_seconds": 1800, "command_timeout": 120},
"concurrency": false
}
+113
View File
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
"""Evaluator for dev-lru (dev set; public).
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout
"""
import os
import random
import re
import sys
from collections import OrderedDict
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import devlib # noqa: E402
TOKEN = re.compile(r"[a-z0-9]{1,16}")
def model(text):
lines = text.split("\n")
if text.endswith("\n"):
lines.pop()
cap = int(lines[0].split(" ")[1])
cache = OrderedDict() # least recent first
hits = misses = evictions = 0
out = []
for line in lines[1:]:
parts = line.split(" ")
cmd, args = parts[0], parts[1:]
if not all(TOKEN.fullmatch(a) for a in args):
out.append("error")
elif cmd == "put" and len(args) == 2:
k, v = args
if k in cache:
out.append("ok")
elif len(cache) == cap:
old, _ = cache.popitem(last=False)
evictions += 1
out.append(f"evict {old}")
else:
out.append("ok")
cache[k] = v
cache.move_to_end(k)
elif cmd == "get" and len(args) == 1:
k = args[0]
if k in cache:
hits += 1
cache.move_to_end(k)
out.append(cache[k])
else:
misses += 1
out.append("miss")
elif cmd == "peek" and len(args) == 1:
out.append(cache.get(args[0], "miss"))
elif cmd == "del" and len(args) == 1:
out.append("ok" if cache.pop(args[0], None) is not None else "miss")
elif cmd == "stats" and not args:
out.append(f"size {len(cache)} hits {hits} misses {misses} evictions {evictions}")
elif cmd == "dump" and not args:
out.append(" ".join(reversed(cache)) or "empty")
else:
out.append("error")
return "".join(o + "\n" for o in out)
def token(rng, alphabet="abcdefghijklmnopqrstuvwxyz0123456789", lo=1, hi=16):
return "".join(rng.choice(alphabet) for _ in range(rng.randint(lo, hi)))
def gen(rng, cap, n, keys, invalid=0.0):
pool = [token(rng, lo=1, hi=8) for _ in range(keys)]
lines = [f"capacity {cap}"]
for _ in range(n):
r = rng.random()
if r < invalid:
lines.append(rng.choice(["", "put a", "put A 1", "get", "get a b", "peek -", "del " + "x" * 17, "stats now",
"dump 1", "put a 1", "put a 1 ", "Get a", "put a\t1", "put é 1", "evict a", "get a_b"]))
continue
k = rng.choice(pool)
c = rng.random()
if c < 0.4:
lines.append(f"put {k} {token(rng)}")
elif c < 0.7:
lines.append(f"get {k}")
elif c < 0.8:
lines.append(f"peek {k}")
elif c < 0.9:
lines.append(f"del {k}")
else:
lines.append(rng.choice(["stats", "dump"]))
return "\n".join(lines) + ("\n" if rng.random() < 0.8 else "")
def case(text):
return (text, model(text))
PUBLIC = [case("capacity 2\nput a 1\nput b 2\nget a\nput c 3\npeek b\ndump\nget b\nstats\nput a 9\nget a\ndel zz\n")]
rng = random.Random(20261008)
HIDDEN = [
case("capacity 1\ndump\nstats\nput k v\nput k w\nget k\nput j x\ndump\nget k\nstats\n"),
case("capacity 3\nput a 1\nput b 2\nput c 3\nget a\nput d 4\ndel c\nput e 5\ndump\nstats"),
case("capacity 2\nput a 1\npeek a\nput b 2\nput c 3\ndump\nput b 7\nput d 8\ndump\n"),
case("capacity 4\n\nput a 1\nput a 1 2\nput " + "z" * 16 + " " + "9" * 16 + "\nget " + "z" * 16 + "\nput " + "z" * 17 + " 1\nstats\n"),
case(gen(rng, 3, 80, 6, invalid=0.2)),
case(gen(rng, 10, 600, 30, invalid=0.05)),
case(gen(rng, 50, 1200, 200, invalid=0.02)),
case(gen(rng, 1000, 1400, 900, invalid=0.01)),
case("capacity 1000\n" + "".join(f"put k{i} v{i}\n" for i in range(1000)) + "put kx vx\ndump\nstats\n"),
]
if __name__ == "__main__":
devlib.evaluate(devlib.Spec("lru", heap=4 << 20, fuel=400_000_000, public=PUBLIC, hidden=HIDDEN))
@@ -0,0 +1,6 @@
# Interface
- Source: `main.air`, a text AIR module.
- Entry point: `@main(%in: cap<io.read>, %out: cap<io.write>, %heap: cap<mem.alloc>)`; any return type.
- The program is run as `aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.air`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Public test: the example from the task statement.
rec=$(aji run --fuel 400000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'capacity 2
put a 1
put b 2
get a
put c 3
peek b
dump
get b
stats
put a 9
get a
del zz
' main.air)
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
expected=$(printf "%s" 'ok
ok
1
evict b
miss
c a
miss
size 2 hits 1 misses 1 evictions 1
ok
9
miss
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,6 @@
# Interface
- Source: `main.aji`, an `.aji` module.
- Entry point: `main(input: cap<io.read>, out: cap<io.write>, heap: cap<mem.alloc>)`; any return type.
- The program is run as `aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin TEXT main.aji`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
- The heap budget is 4194304 bytes of live allocations; the run stops after 400000000 executed instructions.
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Public test: the example from the task statement.
rec=$(aji run --fuel 400000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:4194304 --stdin 'capacity 2
put a 1
put b 2
get a
put c 3
peek b
dump
get b
stats
put a 9
get a
del zz
' main.aji)
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
expected=$(printf "%s" 'ok
ok
1
evict b
miss
c a
miss
size 2 hits 1 misses 1 evictions 1
ok
9
miss
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,6 @@
[package]
name = "lru"
version = "0.1.0"
edition = "2021"
[dependencies]
@@ -0,0 +1,5 @@
# Interface
- Cargo package `lru` in this directory; the binary is `target/debug/lru`.
- The program reads standard input and writes standard output, as the task describes.
- Only the standard library is available (no network, `--offline`).
@@ -0,0 +1 @@
fn main() {}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Public test: the example from the task statement.
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'capacity 2
put a 1
put b 2
get a
put c 3
peek b
dump
get b
stats
put a 9
get a
del zz
' | ./target/debug/lru) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'ok
ok
1
evict b
miss
c a
miss
size 2 hits 1 misses 1 evictions 1
ok
9
miss
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,4 @@
# Interface
- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`.
- The program reads standard input and writes standard output, as the task describes.
@@ -0,0 +1 @@
pub fn main() void {}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Public test: the example from the task statement.
zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'capacity 2
put a 1
put b 2
get a
put c 3
peek b
dump
get b
stats
put a 9
get a
del zz
' | ./main) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'ok
ok
1
evict b
miss
c a
miss
size 2 hits 1 misses 1 evictions 1
ok
9
miss
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,69 @@
# Task: least-recently-used cache
Development task (dev set). Its results are not evidence about any language.
Write a program that simulates a key–value cache of bounded size which evicts the least recently used key. The program reads commands from standard input, one per line, and writes its answers to standard output.
## Input
The input is a sequence of lines separated by `\n`. If the input ends with `\n`, that final `\n` does not start another line. The input is at most 32 KiB and has at most 1500 lines.
The first line is always `capacity C`, where C is a decimal number with 1 ≤ C ≤ 1000 and no leading zeros. It produces no output. Every later line is a command.
A **token** is 1 to 16 characters, each an ASCII lowercase letter `a`–`z` or digit `0`–`9`. Keys and values are tokens.
A line is a valid command when it is exactly one of the forms below: the command word, then its arguments, each separated by exactly one space. There are no other spaces or characters.
| Command | Effect | Output |
|---|---|---|
| `put K V` | If K is in the cache, its value becomes V. Otherwise, if the cache holds C keys, the least recently used key L is removed first, then K is added with value V. In both cases K becomes the most recently used key. | `evict L` if a key was removed, otherwise `ok` |
| `get K` | If K is in the cache, K becomes the most recently used key. | the value of K, or `miss` |
| `peek K` | Nothing changes. | the value of K, or `miss` |
| `del K` | Removes K if it is in the cache. | `ok` if it was removed, otherwise `miss` |
| `stats` | Nothing changes. | `size S hits H misses M evictions E` |
| `dump` | Nothing changes. | the keys from the most to the least recently used, separated by single spaces; `empty` if the cache is empty |
**Recency** changes only through `put` and a `get` that finds its key. S is the number of keys in the cache. H and M count the `get` commands that found and did not find their key; `peek` is not counted. E counts the keys removed by `put`; `del` is not counted.
Any other line, including an empty line, an unknown command, a wrong number of arguments, or an argument that is not a token, is **invalid**. For an invalid line the program writes `error` and changes nothing.
## Output
One output line for each command and for each invalid line, in input order. Every output line ends with `\n`. Nothing else is written to standard output.
## Example
Input:
```text
capacity 2
put a 1
put b 2
get a
put c 3
peek b
dump
get b
stats
put a 9
get a
del zz
```
Output:
```text
ok
ok
1
evict b
miss
c a
miss
size 2 hits 1 misses 1 evictions 1
ok
9
miss
```
The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. Hidden tests check the requirements above, including invalid input.
@@ -0,0 +1,6 @@
[package]
name = "lru"
version = "0.1.0"
edition = "2021"
[dependencies]
@@ -0,0 +1,61 @@
use std::collections::HashMap;
use std::io::{Read, Write};
fn token(t: &str) -> bool {
(1..=16).contains(&t.len()) && t.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
}
fn main() {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).unwrap();
let mut lines: Vec<&str> = input.split('\n').collect();
if input.ends_with('\n') {
lines.pop();
}
let cap: usize = lines[0]["capacity ".len()..].parse().unwrap();
// key -> (value, last use); recency is the use counter.
let mut map: HashMap<String, (String, u64)> = HashMap::new();
let (mut clock, mut hits, mut misses, mut evictions) = (0u64, 0u64, 0u64, 0u64);
let mut out = String::new();
for line in &lines[1..] {
let parts: Vec<&str> = line.split(' ').collect();
let args = &parts[1..];
if !args.iter().all(|a| token(a)) {
out.push_str("error\n");
continue;
}
clock += 1;
match (parts[0], args) {
("put", [k, v]) => {
if map.contains_key(*k) {
out.push_str("ok\n");
} else if map.len() == cap {
let old = map.iter().min_by_key(|(_, (_, t))| *t).map(|(k, _)| k.clone()).unwrap();
map.remove(&old);
evictions += 1;
out.push_str(&format!("evict {old}\n"));
} else {
out.push_str("ok\n");
}
map.insert(k.to_string(), (v.to_string(), clock));
}
("get", [k]) => match map.get_mut(*k) {
Some((v, t)) => { *t = clock; hits += 1; out.push_str(&format!("{v}\n")); }
None => { misses += 1; out.push_str("miss\n"); }
},
("peek", [k]) => out.push_str(&format!("{}\n", map.get(*k).map_or("miss", |(v, _)| v.as_str()))),
("del", [k]) => out.push_str(if map.remove(*k).is_some() { "ok\n" } else { "miss\n" }),
("stats", []) => out.push_str(&format!("size {} hits {hits} misses {misses} evictions {evictions}\n", map.len())),
("dump", []) => {
let mut keys: Vec<(&String, u64)> = map.iter().map(|(k, (_, t))| (k, *t)).collect();
keys.sort_by(|a, b| b.1.cmp(&a.1));
let s: Vec<&str> = keys.iter().map(|(k, _)| k.as_str()).collect();
out.push_str(if s.is_empty() { "empty" } else { "" });
out.push_str(&s.join(" "));
out.push('\n');
}
_ => out.push_str("error\n"),
}
}
std::io::stdout().write_all(out.as_bytes()).unwrap();
}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Public test: the example from the task statement.
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'capacity 2
put a 1
put b 2
get a
put c 3
peek b
dump
get b
stats
put a 9
get a
del zz
' | ./target/debug/lru) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'ok
ok
1
evict b
miss
c a
miss
size 2 hits 1 misses 1 evictions 1
ok
9
miss
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,15 @@
{
"id": "dev-lru",
"version": "1",
"set": "dev",
"family": "failure-calibration",
"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"}
},
"limits": {"tool_calls": 80, "total_tokens": 1500000, "wall_seconds": 1800, "command_timeout": 120},
"concurrency": false
}
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Evaluator for dev-shards (dev set; public).
Besides the output, two gates cover the concurrency requirement:
uses_concurrency the source starts threads or tasks (a coarse static check);
hidden for Aji, every hidden case runs under three schedule seeds.
usage: evaluator.py WORKSPACE LANGUAGE TASK_DIR -> JSON verdict on stdout
"""
import collections
import os
import random
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import devlib # noqa: E402
WORD = re.compile(r"[A-Za-z]+")
SPAWN = {
"aji_air": r"\btask\.spawn\b",
"aji_source": r"\btask\.spawn\b",
"rust": r"thread::(spawn|scope)|\.spawn\(",
"zig": r"Thread\.spawn|std\.Thread",
}
def model(text):
lines = text.split("\n")
if text.endswith("\n"):
lines.pop()
w = int(lines[0].split(" ")[1])
per = [[0, 0] for _ in range(w)]
counts = collections.Counter()
for k, line in enumerate(lines[1:]):
words = [m.lower()[:16] for m in WORD.findall(line)]
per[k % w][0] += 1
per[k % w][1] += len(words)
counts.update(words)
out = [f"worker {i} lines {l} words {n}" for i, (l, n) in enumerate(per)]
out.append(f"distinct {len(counts)}")
out += [f"{word} {c}" for word, c in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].encode()))[:10]]
return "".join(o + "\n" for o in out)
def gen(rng, w, n, vocab):
words = ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(1, 20))) for _ in range(vocab)]
lines = [f"workers {w}"]
for _ in range(n):
parts = []
for _ in range(rng.randint(0, 6)):
word = rng.choice(words) if rng.random() < 0.8 else rng.choice(words[:5])
if rng.random() < 0.2:
word = word.upper() if rng.random() < 0.5 else word.capitalize()
parts.append(word)
parts.append(rng.choice([" ", " ", ", ", ". ", "-", " ", "1", "'", "\t", "_"]))
lines.append("".join(parts))
return "\n".join(lines) + ("\n" if rng.random() < 0.8 else "")
def case(text):
return (text, model(text))
PUBLIC = [case("workers 2\nThe cat sat.\nthe CAT, the hat\na-b-c\n")]
rng = random.Random(20261009)
HIDDEN = [
case("workers 1\n"),
case("workers 8\nalpha\n\n...\nBeta beta\n"),
case("workers 3\nabcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopXYZ\nx1y2z3\n"),
case("workers 4\nb a\na b\nc\nb\n"),
case(gen(rng, 2, 50, 12)),
case(gen(rng, 5, 400, 80)),
case(gen(rng, 8, 600, 600)),
case(gen(rng, 7, 550, 1500)),
case("workers 6\n" + "".join(rng.choice(["a", "b b", "", "C", "d.e"]) + "\n" for _ in range(1990))),
]
def gates(ws, lang):
return {"uses_concurrency": devlib.source_matches(ws, lang, SPAWN)}
if __name__ == "__main__":
devlib.evaluate(devlib.Spec("shards", heap=16 << 20, fuel=800_000_000, public=PUBLIC, hidden=HIDDEN,
extra_gates=gates, schedule_seeds=(0, 1, 2)))
@@ -0,0 +1,6 @@
# Interface
- Source: `main.air`, a text AIR module.
- Entry point: `@main(%in: cap<io.read>, %out: cap<io.write>, %heap: cap<mem.alloc>)`; any return type.
- The program is run as `aji run --fuel 800000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin TEXT main.air`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
- The heap budget is 16777216 bytes of live allocations; the run stops after 800000000 executed instructions. The program may spawn tasks (effect `task.spawn`); the evaluator runs it under several schedule seeds (`--schedule-seed N`), and the output must be the same for each.
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Public test: the example from the task statement.
rec=$(aji run --fuel 800000000 --grant in=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin 'workers 2
The cat sat.
the CAT, the hat
a-b-c
' main.air)
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
expected=$(printf "%s" 'worker 0 lines 2 words 6
worker 1 lines 1 words 4
distinct 7
the 3
cat 2
a 1
b 1
c 1
hat 1
sat 1
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,6 @@
# Interface
- Source: `main.aji`, an `.aji` module.
- Entry point: `main(input: cap<io.read>, out: cap<io.write>, heap: cap<mem.alloc>)`; any return type.
- The program is run as `aji run --fuel 800000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin TEXT main.aji`. Standard input is TEXT; the bytes written to standard output appear in the run record's `stdout` field, and the run must end with `"status":"returned"`.
- The heap budget is 16777216 bytes of live allocations; the run stops after 800000000 executed instructions. The program may spawn tasks (effect `task.spawn`); the evaluator runs it under several schedule seeds (`--schedule-seed N`), and the output must be the same for each.
@@ -0,0 +1,20 @@
#!/bin/sh
# Public test: the example from the task statement.
rec=$(aji run --fuel 800000000 --grant input=io.read --grant out=io.write --grant heap=mem.alloc:16777216 --stdin 'workers 2
The cat sat.
the CAT, the hat
a-b-c
' main.aji)
got=$(printf '%s' "$rec" | python3 -c 'import json,sys; r=json.load(sys.stdin); print(r.get("stdout","") if r.get("status")=="returned" else "<status "+str(r.get("status"))+">", end="")') || { echo "FAIL: no run record"; echo "$rec"; exit 1; }
expected=$(printf "%s" 'worker 0 lines 2 words 6
worker 1 lines 1 words 4
distinct 7
the 3
cat 2
a 1
b 1
c 1
hat 1
sat 1
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,6 @@
[package]
name = "shards"
version = "0.1.0"
edition = "2021"
[dependencies]
@@ -0,0 +1,5 @@
# Interface
- Cargo package `shards` in this directory; the binary is `target/debug/shards`.
- The program reads standard input and writes standard output, as the task describes.
- Only the standard library is available (no network, `--offline`).
@@ -0,0 +1 @@
fn main() {}
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Public test: the example from the task statement.
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'workers 2
The cat sat.
the CAT, the hat
a-b-c
' | ./target/debug/shards) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'worker 0 lines 2 words 6
worker 1 lines 1 words 4
distinct 7
the 3
cat 2
a 1
b 1
c 1
hat 1
sat 1
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,4 @@
# Interface
- Source: `main.zig`, built with `zig build-exe main.zig` into `./main`.
- The program reads standard input and writes standard output, as the task describes.
@@ -0,0 +1 @@
pub fn main() void {}
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Public test: the example from the task statement.
zig build-exe main.zig 2>&1 || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'workers 2
The cat sat.
the CAT, the hat
a-b-c
' | ./main) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'worker 0 lines 2 words 6
worker 1 lines 1 words 4
distinct 7
the 3
cat 2
a 1
b 1
c 1
hat 1
sat 1
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,53 @@
# Task: sharded word count
Development task (dev set). Its results are not evidence about any language.
Write a program that counts words in its standard input using several concurrent workers, then merges their results.
## Input
The input is a sequence of lines separated by `\n`. If the input ends with `\n`, that final `\n` does not start another line. The input is at most 24 KiB and has at most 2000 lines.
The first line is always `workers W`, where W is a decimal number with 1 ≤ W ≤ 8 and no leading zeros. Every later line is a **text line**; text lines are numbered from 0. Text lines contain only ASCII characters other than `\n`.
A **word** is a maximal run of ASCII letters (`A`–`Z`, `a`–`z`) in a text line, converted to lowercase. A word longer than 16 letters counts as its first 16 letters. Every other character separates words. There are at most 2000 distinct words.
## Concurrency requirement
The program MUST start W workers (threads or tasks) that run concurrently. Text line k is assigned to worker k mod W. Each worker counts the words of its own lines only. After all workers have finished, the results are merged. The output must not depend on how the workers are scheduled.
## Output
1. For each worker i from 0 to W − 1: `worker i lines L words N`, where L is the number of text lines assigned to worker i and N the number of words in them.
2. `distinct D`, where D is the number of distinct words in the whole input.
3. Up to 10 lines `word count` for the most frequent words: by count, highest first; equal counts in increasing byte order of the word.
Every output line ends with `\n`. Nothing else is written to standard output.
## Example
Input:
```text
workers 2
The cat sat.
the CAT, the hat
a-b-c
```
Output:
```text
worker 0 lines 2 words 6
worker 1 lines 1 words 4
distinct 7
the 3
cat 2
a 1
b 1
c 1
hat 1
sat 1
```
The repository contains a README with the program's interface for this language and a public test script, `sh test.sh`, which must pass. Hidden tests check the requirements above.
@@ -0,0 +1,6 @@
[package]
name = "shards"
version = "0.1.0"
edition = "2021"
[dependencies]
@@ -0,0 +1,53 @@
use std::collections::HashMap;
use std::io::{Read, Write};
fn words(line: &str) -> Vec<String> {
line.split(|c: char| !c.is_ascii_alphabetic())
.filter(|w| !w.is_empty())
.map(|w| w.to_ascii_lowercase().chars().take(16).collect())
.collect()
}
fn main() {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input).unwrap();
let mut lines: Vec<&str> = input.split('\n').collect();
if input.ends_with('\n') {
lines.pop();
}
let w: usize = lines[0]["workers ".len()..].parse().unwrap();
let text = &lines[1..];
let results: Vec<(usize, usize, HashMap<String, u64>)> = std::thread::scope(|s| {
let handles: Vec<_> = (0..w)
.map(|i| {
s.spawn(move || {
let (mut l, mut n, mut m) = (0, 0, HashMap::new());
for line in text.iter().skip(i).step_by(w) {
l += 1;
for word in words(line) {
n += 1;
*m.entry(word).or_insert(0) += 1;
}
}
(l, n, m)
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
let mut out = String::new();
let mut total: HashMap<String, u64> = HashMap::new();
for (i, (l, n, m)) in results.into_iter().enumerate() {
out.push_str(&format!("worker {i} lines {l} words {n}\n"));
for (k, v) in m {
*total.entry(k).or_insert(0) += v;
}
}
out.push_str(&format!("distinct {}\n", total.len()));
let mut top: Vec<(String, u64)> = total.into_iter().collect();
top.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.as_bytes().cmp(b.0.as_bytes())));
for (k, v) in top.into_iter().take(10) {
out.push_str(&format!("{k} {v}\n"));
}
std::io::stdout().write_all(out.as_bytes()).unwrap();
}
@@ -0,0 +1,20 @@
#!/bin/sh
# Public test: the example from the task statement.
cargo build -q --offline || { echo "FAIL: build"; exit 1; }
got=$(printf '%s' 'workers 2
The cat sat.
the CAT, the hat
a-b-c
' | ./target/debug/shards) || { echo "FAIL: the program exited with an error"; exit 1; }
expected=$(printf "%s" 'worker 0 lines 2 words 6
worker 1 lines 1 words 4
distinct 7
the 3
cat 2
a 1
b 1
c 1
hat 1
sat 1
')
if [ "$got" = "$expected" ]; then echo PASS; else echo "FAIL"; echo "--- expected"; printf '%s' "$expected"; echo "--- got"; printf '%s' "$got"; exit 1; fi
@@ -0,0 +1,15 @@
{
"id": "dev-shards",
"version": "1",
"set": "dev",
"family": "failure-calibration",
"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"}
},
"limits": {"tool_calls": 80, "total_tokens": 1500000, "wall_seconds": 1800, "command_timeout": 120},
"concurrency": true
}
+95
View File
@@ -0,0 +1,95 @@
"""Shared evaluator code for the dev-set tasks that use a line-oriented
stdin → stdout interface (dev-intervals, dev-lru, dev-shards).
These tasks and their evaluators are public because they are dev-set
material (protocol §7): they exist to produce realistic failures for
harness and classifier work, never evidence about the language.
An evaluator calls `evaluate(spec)` and prints the JSON verdict:
builds the program builds or verifies;
public the public cases (the ones in test.sh) pass;
hidden every hidden case passes;
+ any extra gates the task adds (e.g. uses_concurrency, schedules).
"""
import json
import os
import re
import subprocess
import sys
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
AJI = os.path.join(REPO, "zig-out", "bin", "aji")
NATIVE_TIMEOUT = 60 # Rust/Zig binaries only; Aji runs end by fuel (spec 11 §7)
class Spec:
"""binary: the Rust package/binary name; heap: the Aji mem.alloc
budget in bytes; fuel: the Aji instruction budget per case."""
def __init__(self, binary, heap, fuel, public, hidden, extra_gates=None, schedule_seeds=(0,)):
self.binary, self.heap, self.fuel = binary, heap, fuel
self.public, self.hidden = public, hidden
self.extra_gates = extra_gates or (lambda ws, lang: {})
self.schedule_seeds = schedule_seeds
def build(ws, lang):
if lang == "rust":
cmd = ["cargo", "build", "-q", "--offline"]
elif lang == "zig":
cmd = ["zig", "build-exe", "main.zig"]
else:
cmd = [AJI, "check", "main.aji" if lang == "aji_source" else "main.air"]
return subprocess.run(cmd, cwd=ws, capture_output=True).returncode == 0
def run(ws, lang, spec, text, schedule_seed=0):
"""The program's stdout for one input, or None if it did not complete."""
if lang in ("aji_air", "aji_source"):
src, inp = ("main.aji", "input") if lang == "aji_source" else ("main.air", "in")
argv = [AJI, "run", "--fuel", str(spec.fuel), "--schedule-seed", str(schedule_seed),
"--grant", f"{inp}=io.read", "--grant", "out=io.write", "--grant", f"heap=mem.alloc:{spec.heap}",
"--stdin", text, src]
p = subprocess.run(argv, cwd=ws, capture_output=True, text=True)
try:
rec = json.loads(p.stdout)
except json.JSONDecodeError:
return None
return rec.get("stdout") if rec.get("status") == "returned" else None
exe = f"./target/debug/{spec.binary}" if lang == "rust" else "./main"
try:
p = subprocess.run([exe], cwd=ws, input=text, capture_output=True, text=True, timeout=NATIVE_TIMEOUT)
except (subprocess.TimeoutExpired, OSError):
return None
return p.stdout if p.returncode == 0 else None
def passes(ws, lang, spec, cases, seeds=(0,)):
return all(run(ws, lang, spec, inp, s) == expected for inp, expected in cases for s in seeds)
def source_matches(ws, lang, patterns):
"""True if the program's source mentions one of the language's patterns
(a coarse static gate for requirements tests cannot observe)."""
files = {"aji_air": ["main.air"], "aji_source": ["main.aji"], "zig": ["main.zig"]}.get(lang)
if files is None:
files = [os.path.join(r, f) for r, _, fs in os.walk(os.path.join(ws, "src")) for f in fs if f.endswith(".rs")]
text = ""
for f in files:
try:
with open(os.path.join(ws, f)) as fh:
text += fh.read()
except OSError:
pass
return re.search(patterns[lang], text) is not None
def evaluate(spec):
ws, lang = sys.argv[1], sys.argv[2]
gates = {"builds": build(ws, lang)}
gates["public"] = gates["builds"] and passes(ws, lang, spec, spec.public)
seeds = spec.schedule_seeds if lang in ("aji_air", "aji_source") else (0,)
gates["hidden"] = gates["builds"] and passes(ws, lang, spec, spec.hidden, seeds)
gates.update(spec.extra_gates(ws, lang))
print(json.dumps({"accepted": all(gates.values()), "gates": gates}))
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env python3
"""One evaluator command for a plan over several dev tasks: runs the
task's own evaluator.py with the harness's arguments.
usage: evaluate.py WORKSPACE LANGUAGE TASK_DIR
"""
import os
import sys
ws, lang, task = sys.argv[1:4]
os.execv(sys.executable, [sys.executable, os.path.join(task, "evaluator.py"), ws, lang, task])
+30
View File
@@ -161,6 +161,20 @@ For the smoke test it also records the cause, decided before any language change
- `model_capability` - `model_capability`
- `task_ambiguity` - `task_ambiguity`
### Advisory suggestions and improvement triage
```sh
python3 -m ajieval classify RUN_DIR --suggest [--auto-accept] # needs TYPESAFE_API_KEY
python3 -m ajieval calibrate runs/
python3 -m ajieval triage runs/ [--plan PLAN.json] [--json]
```
`classify --suggest` asks TypeSafe Jev, a System One classifier, for the category, the place the failure was caught and the cause. The answer is stored as `classification_suggestion` with per-option probabilities and confidence; it is not a classification. The questions and their option descriptions are defined once, in `ajieval/jev.py`. The state sent is minimal: task id, outcome, diagnostic codes, and the tails of the last three failing commands. Only failed runs of the `dev` and `validation` sets are sent; a `test`-set run is refused before any request, because sending it to a third party would disclose the held-out corpus (protocol §29).
`calibrate` compares suggestions with human classifications per question: agreement overall and among the suggestions the thresholds would accept. Thresholds, proposal minimums and routes live only in `tools/eval/triage.json`. Until it says `"calibrated": true`, `--auto-accept` does nothing. After that, a suggestion whose every confidence meets its threshold becomes the classification, marked `"source": "jev"`; human labels are never overwritten.
`triage` groups classified failures by (cause, language, category). A group becomes a proposal only when it has at least `min_events` runs across `min_tasks` tasks and `min_agents` agents, so one model struggling on one task never proposes anything (protocol §38). Each proposal is routed by cause to a layer. Diagnostic text, agent bundle, documentation and harness changes go to a reviewed patch or issue. A `language` cause goes only to an open-question entry carrying the evidence; an RFC is the owner's decision. `model_capability` is logged only. With `--plan`, proposals are withheld while that frozen plan still has cells to run, because changing Aji mid-experiment is online tuning. Triage reports; it never edits the specification, the bundle or the code.
## Track B: native agents ## Track B: native agents
```sh ```sh
@@ -191,6 +205,7 @@ Per agent:
| `codex` | `codex exec --json`; `approval_policy=never`; web search off; product features off (multi-agent, apps, browser, computer use, plugins, skills, goals, hooks…) | off (Codex `workspace-write` sandbox) | | `codex` | `codex exec --json`; `approval_policy=never`; web search off; product features off (multi-agent, apps, browser, computer use, plugins, skills, goals, hooks…) | off (Codex `workspace-write` sandbox) |
| `claude` | `claude -p --output-format stream-json`; tools limited to `Bash`, `Read`, `Edit` and `Write`; `--strict-mcp-config`; slash commands off | off (networkless shell wrapper) | | `claude` | `claude -p --output-format stream-json`; tools limited to `Bash`, `Read`, `Edit` and `Write`; `--strict-mcp-config`; slash commands off | off (networkless shell wrapper) |
| `opencode` | `opencode run --pure --format json`; no MCP; `webfetch`, `websearch` and `task` off; no LSP downloads | off (networkless shell wrapper) | | `opencode` | `opencode run --pure --format json`; no MCP; `webfetch`, `websearch` and `task` off; no LSP downloads | off (networkless shell wrapper) |
| `gobang` | `gobang run --json-events --in-place /work`; configuration written to the fresh HOME; documentation at `/docs` | off (gobang's own bubblewrap sandbox; the model has no shell) |
**Networkless shell.** Inside the sandbox, the real shell binaries (`/usr/bin/bash`; `sh` follows its symlink) are replaced by wrappers. Each wrapper runs the command in a nested bubblewrap with a fresh, empty network namespace and without the resolver socket. The CLI process keeps the network to reach its backend. Every process a tool starts through a shell, `python3` sockets included, has neither network nor DNS. The live check is the dev task [`dev-netprobe`](dev-tasks/dev-netprobe/), which all three agents pass. **Networkless shell.** Inside the sandbox, the real shell binaries (`/usr/bin/bash`; `sh` follows its symlink) are replaced by wrappers. Each wrapper runs the command in a nested bubblewrap with a fresh, empty network namespace and without the resolver socket. The CLI process keeps the network to reach its backend. Every process a tool starts through a shell, `python3` sockets included, has neither network nor DNS. The live check is the dev task [`dev-netprobe`](dev-tasks/dev-netprobe/), which all three agents pass.
@@ -216,6 +231,21 @@ Per agent:
A first-generation snapshot is not available in Track B. There is no cost in dollars either: on subscriptions there is no honest cost per solution, so Track B reports success, time, tool calls and context. Economics stays with Track A. A first-generation snapshot is not available in Track B. There is no cost in dollars either: on subscriptions there is no honest cost per solution, so Track B reports success, time, tool calls and context. Economics stays with Track A.
### gobang
gobang (a sibling repository) is an Aji-native harness: the model works through typed tools bound to the toolchain instead of a shell, and gobang's own verification gate decides when it is done. It is another agent product in Track B, so its runs are never evidence for H4 either; what it measures is the harness, against the other agents, ideally on the same model.
```sh
PATH=/path/to/gobang/zig-out/bin:$PATH ZAI_API_KEY=… python3 -m ajieval native --task DIR --language aji_source \
--agent gobang --model glm-5.3-flash --evaluator CMD --out runs/
```
- **Model ids.** `claude-*` uses the Anthropic API (`ANTHROPIC_API_KEY`); any other id uses GLM via z.ai (`ZAI_API_KEY`); `fixture:PATH` replays a gobang scenario file without a network, for harness self-tests.
- **Key.** Unlike the other agents, gobang has no credential file: the key's variable is passed into the sandbox with `--setenv` and named, never valued, in the configuration. Its value appears in no record. It is visible to the user's own processes in the bubblewrap command line while the run lasts. A missing key stops the run before anything is created.
- **Isolation.** gobang runs aji and test commands in a nested bubblewrap sandbox with every namespace unshared, so tool processes have no network even though the sandbox shares it for the model API; there is no shell wrapper.
- **Transcript.** `transcript.jsonl` is gobang's journal (`--json-events`). Tool calls, token usage (input including cached, cached, output) and the model come from its events. The repair metrics come from gobang's toolchain tools, not from guessed shell commands: `aji_check` and `aji_run` count as `aji check` and `aji run` with aji's exit code for their outcome, `run_tests` as the configured test commands. The documentation tools are presented as reads of `/docs/<file>`, so the documentation metrics count them like a file read.
- **State.** gobang keeps its session state under `/tmp/gobang` inside the sandbox, so the evaluated repository contains only the solution. `metrics.agent_facts` carries `gobang_state` and `gobang_reason` (COMPLETED, FAILED, BLOCKED, INFRA_FAILED …) and the hash of gobang's prompts.
## Agent and evaluation status (Track B, `metrics`) ## Agent and evaluation status (Track B, `metrics`)
How the agent's session ended and what the evaluator says about the repository are recorded separately, so that a transport problem after a finished solution is not read as a failure of the solution, and a cut-off reply is not read as a normal exit. How the agent's session ended and what the evaluator says about the repository are recorded separately, so that a transport problem after a finished solution is not read as a failure of the solution, and a cut-off reply is not read as a normal exit.
+2 -1
View File
@@ -141,7 +141,7 @@ Targets for Phase 6A, measured on dev tasks:
## Standard library track ## Standard library track
At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is next. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs. At the owner’s request (2026-10-06), reusable std APIs were implemented in a separate work branch. On 2026-10-07 the owner requested adoption/merge of the completed STD-0..7 intermediate foundation and resumption of source-language work; Q-034/P6-11 is implemented for review (RFC 0036 Proposed), and P6-8 implements the source formatter. Q-040 is resolved by explicit block statement boundaries (DD-016, spec 15 §4), one P6-1/P6-2 ambiguity; larger syntax/contracts work retains its separate spec gate. Remaining std milestones stay in the backlog. [Standard library plan](standard-library.md) defines the bootstrap, prerequisites (`linear_aggregates`, general modules and generics), Std 0.1/0.2/0.3 and the public integration gate. P7/P8 remain on hold pending B1 analysis; this track does not change frozen evaluation inputs.
## Task conventions ## Task conventions
@@ -159,6 +159,7 @@ At the owner’s request (2026-10-06), reusable std APIs were implemented in a s
| P2 | done (exit review in the phase file) | | P2 | done (exit review in the phase file) |
| P3 | done (exit review in the phase file); P3-10, P3-11 moved to P7 | | P3 | done (exit review in the phase file); P3-10, P3-11 moved to P7 |
| P6A | done (exit review in `phase-6-source-language.md`; P6A-9 [results](../evaluation/results/2026-10-05-p6a-9.md)): the agent-facing source language over AIR is the architecture | | P6A | done (exit review in `phase-6-source-language.md`; P6A-9 [results](../evaluation/results/2026-10-05-p6a-9.md)): the agent-facing source language over AIR is the architecture |
| P6 | done (exit review in `phase-6-source-language.md`); contracts (P6-13) and literal same-code twins (P6-14) deferred by owner decision (2026-10-13; RFC 0039, Q-053) |
| P4 | done (exit review in the phase file) | | P4 | done (exit review in the phase file) |
| P5 | done (exit review in the phase file): atomics through every layer; litmus 20/20 exact against the independent oracle; race detector on every run test | | P5 | done (exit review in the phase file): atomics through every layer; litmus 20/20 exact against the independent oracle; race detector on every run test |
| B1 | the first held-out benchmark after Phase 5 (owner decision, 2026-10-06): pre-registration [`b1-heldout-plan.md`](../evaluation/b1-heldout-plan.md) Accepted; private side: independent author → references → symmetric calibration → freeze → 162 runs | | B1 | the first held-out benchmark after Phase 5 (owner decision, 2026-10-06): pre-registration [`b1-heldout-plan.md`](../evaluation/b1-heldout-plan.md) Accepted; private side: independent author → references → symmetric calibration → freeze → 162 runs |
+752 -11
View File
@@ -123,23 +123,764 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a
**Open, not blocking:** **Open, not blocking:**
- P6A-7 twins of the remaining conformance tests, added gradually; - P6A-7 twins of the remaining conformance tests, added gradually;
- Q-023;
- harness: documentation accounting for partial reads; where the status fields are recorded. - harness: documentation accounting for partial reads; where the status fields are recorded.
## Tasks (full Phase 6) ## Tasks (full Phase 6)
| ID | Status | Task | Depends | Output | Done when | | ID | Status | Task | Depends | Output | Done when |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| P6-1 | todo | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous | | P6-1 | doing | Complete the source grammar: expressions, `match`, `borrow` blocks, `task.scope`, `select`, `defer`, `?`, generics, lifetimes, contracts, attributes | — (may start after P2) | `reference/grammar.ebnf`, spec 01 | every construct in `examples/` is covered; grammar is LL(k) or otherwise documented as unambiguous |
| P6-2 | todo | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics | | P6-2 | doing | Lexer and parser with spans | P6-1 | `src/frontend/{lex,parse}.zig` | all `examples/` parse; syntax errors are registered diagnostics |
| P6-3 | done (RFC 0021 Implemented) | Explicit package modules, direct imports and qualified nominal types | P6-2 | `src/frontend/modules.zig`, spec 15 §14 | deterministic graph/name resolution; source/AIR and CLI tests | | P6-3 | done (RFC 0021 Implemented) | Explicit package modules, direct imports and qualified nominal types | P6-2 | `src/frontend/modules.zig`, spec 15 §14 | deterministic graph/name resolution; source/AIR and CLI tests |
| P6-4 | done (RFC 0022 Implemented) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed | | P6-4 | done (RFC 0022 Implemented) | Type checking and monomorphized generics with structural constraints (`Copy`, `Send`, `Share`, `Freeze`, `Local`) | P6-3 | `src/frontend/generics.zig`, spec 15 §15 | generic code instantiates deterministically; constraint violations diagnosed |
| P6-5 | todo | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) | | P6-5 | doing | Lowering to AIR: control flow, `?`, `defer` cleanup edges, borrow blocks, task scopes | P6-4 | `src/frontend/lower.zig` | lowered AIR verifies; lowering is a pure function (same input ⇒ same AIR bytes) |
| P6-6 | todo | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN | | P6-6 | moved to P6-13 (owner confirmed 2026-10-13; spec gate: Q-054, RFC 0039 Draft) | Contracts: `requires`/`ensures`/invariants → contract table; status classification | P6-5 | frontend + verifier | each contract reported as PROVEN_STATICALLY / CHECKED_AT_RUNTIME / ASSUMED_UNSAFE / UNPROVEN |
| P6-7 | todo | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | every conformance reject test has a source-level twin with the same code | | P6-7 | done for diagnostic source mapping; literal same-code criterion moved to P6-14 (owner confirmed 2026-10-13, Q-053) | Source spans in diagnostics for verifier errors on lowered AIR | P6-5 | `src/diag.zig`, lowering | verifier diagnostics on lowered `.aji` carry mapped source positions; the original exhaustive same-code twin criterion is tracked in P6-14 |
| P6-8 | todo | Formatter | P6-2 | `aji fmt` | idempotent; output parses to the same AST | | P6-8 | done | Formatter for implemented source syntax | P6-2 | `aji fmt`, spec 15 §11 | token/comment/declaration preservation; idempotence, identical AIR and CLI write/check tests |
| P6-9 | todo | Port reference programs and examples to `.aji` | P6-5 | `tests/programs/`, `examples/` | exit criterion passes | | P6-9 | done | Port reference programs and examples to `.aji` | P6-5 | `tests/conformance/source/programs/`, `examples/` | all five source/AIR reference pairs and every example source/package pass |
| P6-11 | todo | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics | | P6-11 | done (implementation; RFC 0036 Proposed) | Source functions/calls returning borrows with explicit `from` origin; Q-034 | P6-3/4 | spec 15, binding/call/return lowering, Quick Reference and source/AIR conformance | origin/lifetime and temporary-end rules specified; valid/rejected returned views use existing verifier/interpreter semantics |
| P6-10 | todo | Phase exit review | all | plan status | exit criterion passes | | P6-12 | doing (advice/collection delivered; dev measurement pending) | Structured source repair advice and independent diagnostic collection; owner proposal 2026-10-09 | P6-2/4/7 | [repair plan](../design/source-diagnostic-repair.md), spec 15 §10, parser/lowering and CLI | advice applicability and additive fields specified/tested; independent item/body errors collected without partial AIR or cascades; bundle growth and public dev effect measured |
| P6-10 | done (owner confirmed deferral of P6-6/P6-7, 2026-10-13) | Phase exit review | all | plan status | exit criterion passes (exit review below) |
| P6-13 | todo (deferred out of Phase 6) | Contracts, split from P6-6: blocked on RFC 0039 (Draft), Q-054, Q-055 owner decisions | owner | frontend + verifier | as P6-6 |
| P6-14 | todo (deferred out of Phase 6) | Literal same-code source twins, split from P6-7: blocked on the Q-053 criterion decision | owner | `tools/source_reject_twins.py` | `--require-complete` passes or Q-053 amends the criterion |
The [standard-library track](standard-library.md) implements nineteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. STD-7a/RFC 0033 implements bounded std.io composition with explicit progress, resource loans and exact effects; conformance, GC/schedule, CLI and documentation checks pass. STD-7b/RFC 0034 implements safe owning buffered file adapters with explicit finish/discard and first-error/no-retry behavior; conformance, GC/schedule, CLI and documentation checks pass. STD-7c/RFC 0035 adds pure caller-buffer lexical paths and Copy component ranges; conformance, GC/schedule, CLI and documentation checks pass. The owner adopts STD-0..7 as an intermediate foundation and resumes language work (2026-10-07); remaining std system/service milestones stay in the backlog. Existing `from`-returns remain unimplemented (Q-034). These increments do not complete Phase 6. The [standard-library track](standard-library.md) implements nineteen compiler-pinned modules and qualified standard enum names. STD-3/RFC 0021 completes P6-3 with explicit manifest source mapping, acyclic linking, direct qualified names, imported struct literals and task workers. Dependency fetching/resolution is separate package work; STD-4/RFC 0022 completes explicit generics and structural constraints. STD-5/RFC 0023 adds whole-value linear structs/enums/fixed arrays, complete unpack/match, explicit exchange and ownership-preserving allocation failure through all layers (spec 15 §16). STD-6a/b/RFC 0024 resolves Q-036 with initialized buffer<T> and safe std.vec, explicit growth, returned failure ownership and draining (spec 15 §17). STD-6c/RFC 0025 adds safe owning Deque with existing source primitives. STD-6d.1/RFC 0026 adds pure std.hash; STD-6d.2/RFC 0028 adds safe owning U64Map<V> after the explicit error_values prerequisite (RFC 0027). STD-6d.3/RFC 0029 adds explicit static function parameters for general hash/equality/order operations with existing AIR calls/workers. STD-6d.4/RFC 0030 implements the general owning-key std.hashmap contract; its full GC/stress validation passes and Q-037 is resolved. STD-6d.5/RFC 0031 implements general owning std.hashset with duplicate input return; its conformance, GC/schedule, CLI and documentation checks pass. STD-6d.6/RFC 0032 implements safe owning std.heap with explicit order; conformance, GC/schedule, CLI and documentation checks pass. STD-7a/RFC 0033 implements bounded std.io composition with explicit progress, resource loans and exact effects; conformance, GC/schedule, CLI and documentation checks pass. STD-7b/RFC 0034 implements safe owning buffered file adapters with explicit finish/discard and first-error/no-retry behavior; conformance, GC/schedule, CLI and documentation checks pass. STD-7c/RFC 0035 adds pure caller-buffer lexical paths and Copy component ranges; conformance, GC/schedule, CLI and documentation checks pass. The owner adopts STD-0..7 as an intermediate foundation and resumes language work (2026-10-07); remaining std system/service milestones stay in the backlog. P6-11 implements explicit borrowed returns over the existing AIR; RFC 0036 remains Proposed pending owner adoption (Q-034). These increments do not complete Phase 6.
## P6-11 implementation review (2026-10-07)
RFC 0036 remains Proposed for owner adoption; its spec integration and implementation are prepared together. Borrow functions preserve explicit origins through ordinary/generic/package calls; exact-mode ref/mut bindings retain a named parent. Named returns transfer only their owned ancestor chain, and ordinary verifier/interpreter semantics decide provenance, aliasing, task loans and traps. Static function parameter borrow contracts and borrow joins stay outside this task.
Validation: full conformance 1,135/1,135 with no failures or pending tests; 56 focused conformance cases including a frozen Phase 1 AIR twin and four canonical AIR goldens; per-step collection and 200 schedule seeds across four quanta for the concurrent fixture; 61 generic regression cases; unit tests, format and bundle/example checks; CLI integration 133 checks, generic/module integration 20/36 checks, hosted smoke. Independent read-only review by Claude found a misleading feature diagnostic when spawning a borrow-returning function and missing array bounds in unused generic signatures. Both were fixed and independently rechecked. Added cases cover those failures, valid generic bounds, normal scope/shield/lock returns, an unjoined task and lock-guard escape. Source construct coverage is 119/119. Quick Reference/source budget is recorded in RFC 0036 and docs/agent/README.md. P6-8 is implemented below; larger syntax/contracts work still needs its separate spec gate.
## P6-8 formatter (2026-10-07)
`aji fmt` formats one source file without linking, specializing, verifying or running it; `--check` emits a JSON status, and explicit `--write` atomically replaces a regular file while preserving permissions. Libraries and semantically rejected programs remain formattable. Original token spellings, comments and declaration order are retained; output is re-tokenized before exposure, and layout traversal is iterative. No syntax, AIR feature, verifier/runtime state or diagnostic code is added. Invalid syntax reports the existing E7001. The CLI contract and layout are spec 15 §11; the public-corpus/CLI script runs in CI.
Validation: unit tests and Zig formatting pass, including 10,000-term expressions, comments/CRLF, continuation indentation and statement groups. The formatter CLI suite passes 3,146 checks over 853 public files: 844 parse and format idempotently, nine existing syntax-error fixtures report E7001, and 548 successful lowerings retain byte-identical AIR. The suite also checks explicit writes, unchanged inode/mtime, permissions, symbolic/hard links, FIFO rejection, JSON/exit codes and a source run. Full conformance remains 1,135/1,135. Independent read-only review by Claude identified layout/comment handling defects; fixes were independently rechecked and covered by unit cases. Original source files are not rewritten. Documentation budgets are recorded in docs/agent/README.md. Review found the separate existing block-statement ambiguity Q-040; resolving its syntax belongs to P6-1/P6-2 and is not inferred by the formatter. This increment does not complete Phase 6.
## P6-1/P6-2 block boundary increment (2026-10-07)
Q-040 is resolved in spec 15 §4 and the grammar (DD-016): leading bare `if`, `match` and `{…}` finish before outer expression operations in statement/tail position. The enclosing `}` selects a tail, `;` an explicit discard, otherwise a block statement must yield `void` or diverge. This E7006 guard prevents silent reinterpretation of former expressions such as `{2i64} -3i64`; parenthesized continuations and nested expression contexts remain available. The parser marks block statements, ordinary/generic lowering checks the guard, and the formatter derives line boundaries from statement spans. No AIR feature, diagnostic code or verifier/runtime state is added. P6-1/P6-2 remain open for the rest of their grammar work.
Validation: full conformance passes 1,154/1,154 with no failures or pending tests, including 19 focused source cases covering stores, other unary starts, tails, explicit contexts/discards, generic bodies, mixed diverging/value branches and lexical borrow ends. Unit tests, Zig formatting, bundle/example checks and 120/120 construct coverage pass. The formatter/CLI suite passes 3,267 checks over 872 public files: 860 parse idempotently, 12 syntax-error fixtures reject with E7001, and 557 successful lowerings preserve byte-identical AIR. A before/after comparison over the original 853 public files finds no exit-code changes and identical AIR for all 548 successful lowerings. Independent read-only review by Claude found the silent value-discard risk in the initial design; the guard fixes it, and final review found no remaining issues. Budgets are recorded in docs/agent/README.md; frozen evaluation inputs are unchanged.
## P6-7 E7006 reason increment (2026-10-07)
DD-017/spec 15 §10 registers 28 stable E7006 categories, explicitly selected at all 130 frontend rejection sites. Borrowed and non-materializable moves cannot be counted as `move_copy`; permitted generic Copy transfers remain accepted. The compiler rejects future unclassified E7006 emissions at compilation. The JSON field follows existing code-specific fields, retaining their values, positions and messages. No code, rejection rule, language/AIR syntax or verifier/runtime state changes. P6-7 remains open for its source-span/twin requirements.
ajieval summary adds occurrences and affected runs by `(code, reason)`, with log availability; profile/checkpoint expose per-run counts. Code totals and the historical compact-code extraction stay intact. Whole JSON records provide reasons; historical, malformed or unparsed records remain unknown and missing logs remain unavailable. These are observed outputs over the entire transcript, without a pre-acceptance cutoff; they do not establish repair cost or justify implementing RFC 0038. New cohort timing, strata and missing-data policy remain evaluation decisions. Frozen evaluation inputs and historical records are unchanged.
Validation: full conformance passes 1,154/1,154; CLI passes 130 checks including 72 public E7006 fixtures, generic/package cases, deterministic serialization and non-E7006 preservation. A comparison over 872 public files finds no changes beyond the new reason: all 557 accepted AIR outputs and every original diagnostic payload remain identical. The 26 ajieval self-tests pass (one environment skip), including historical uncertainty, unknown future reasons, native transcripts, code-total conservation, run incidence and checkpoint JSON. Independent read-only review by Claude found no defects in the extension; its registry-scope suggestion was incorporated. Bundle growth is recorded in docs/agent/README.md. This completes the independent instrumentation prerequisite, not RFC 0038 or Phase 6.
## P6-7 related-position increment (2026-10-07)
RFC 0037/DD-018 prepares spec integration and implementation of one factual `related_locations` record on identified E2101/E2104 conflicts and E4302 tasks. Existing definition positions identify selected borrows; each task loan carries constant-sized spawn metadata through cancelled-join handle replacement. Typed JSON appends the array after the old envelope. Each related position maps independently, including imports and specializations; absent mappings omit source coordinates while retaining AIR coordinates. Primary fields, first-conflict selection and source duplicate suppression are unchanged; no block/repair inference, code, syntax, feature, transfer rule or runtime change is introduced. RFC 0037 remains Proposed for owner adoption; P6-7 remains open for the remaining span/twin work.
Validation: unit tests and full conformance pass, 1,160/1,160 with no failures or pending tests, including six new source/AIR positive/rejected counterparts and repeated cancelled joins. CLI passes 267 checks/161 context records, covering public rejects, function parameters, second split results, call-result definitions, exact source mapping from public annotations, generics and packages. Unit tests cover typed/key-ordered JSON, missing mappings, two cancelled-handle replacements and deduplication retaining the first conflict. Cancellation conformance passes with collection before every instruction and 200 schedule seeds under multiple quanta. Across 1,199 original public AIR/source/std/example files, removal of only the appended metadata recovers byte-identical outputs and exit codes, including all 701 successful check/lower outputs. Source construct coverage remains 120/120. Independent read-only review by Claude found no implementation issues. Bundle measurements are recorded in docs/agent/README.md; frozen evaluation inputs remain untouched. No repair-cost experiment or RFC 0038 implementation is included.
## P6-7 diagnostic-envelope correction (2026-10-07)
DD-019/spec 10 §2 fixes three legacy duplicate-field emissions discovered during compatibility review: E3202 unsupported narrowing and E7002 unknown source capability kinds use `capability_kind`, preserving the stable envelope `kind`; E2102 unlock with a live child borrow reports `borrow` and `guard` separately. Consumers previously reading a capability payload from the duplicate `kind` must use `capability_kind`; former last-key-wins readers retain the selected E2102 borrow identity. Codes, rejection/transfer rules, primary positions, messages, guard/loan state and deterministic execution are unchanged. No new syntax, feature or repair is introduced; P6-7 remains open.
Validation: the new pipeline test reproduces a failure before correction and passes afterwards; unit tests and full conformance pass, 1,162/1,162 with no failures or pending tests, including a source unknown/known capability pair. All final source/AIR diagnostics are checked for noncolliding fields and parsed as JSON with duplicate members forbidden, after frontend fields and source mapping. CLI passes 271 checks/161 context records with a strict JSON reader and targeted checks for all three corrected forms. Across the 1,199-file compatibility baseline, only the two known legacy AIR collision records change beyond the earlier related metadata; all successful outputs and exit codes remain identical. Independent read-only review by Claude found no missed emission or implementation defect; its recommendation to validate final mapped records is implemented in conformance. Budgets are recorded in docs/agent/README.md; frozen evaluation inputs and historical reports are unchanged.
## P6-2 source scope-name increment (2026-10-07)
Q-041 is resolved in spec 15 §7 (DD-020): source scope names are lexical identifiers, used only as the named first operand of `task.spawn`. Ordinary plain/moved value use rejects E7006 `invalid_expression`, with `name` and `type: scope`, before any misleading E7003 transfer hint. Borrowing and assignment retain their existing reasons; non-name/wrong-type spawn operands retain E7005. Ordinary shadowing, saved completion identity, live-child/loan checks and function-local AIR scope flow are unchanged. Formerly accepted aliases and scope-valued expressions now reject. No new source syntax, diagnostic code/reason, feature or verifier/runtime state is introduced. P6-2 remains open for its remaining block forms.
Validation: unit tests and full conformance pass, 1,186/1,186 with no failures or pending tests, including 24 new source fixtures (four runs, twenty rejects). New cases cover aliases, block/branch/scope yields, aggregates, arguments, specialized bodies, shadowing, outer/nested scope lookup and unjoined children. Scope tests pass with 200 schedule seeds and collection before every instruction; the strengthened return case joins a task holding a ref loan, while break/continue cases join mutable loans. CLI diagnostics pass 206 checks over 88 public E7006 fixtures, including exact imported generic locations, unchanged alternate reasons and deterministic/hosted runs at three quanta. Formatter checks pass 3,359 assertions over 900 public files, with 888 parsed files, 12 syntax-error fixtures and 565 identical successful AIR outputs. Coverage remains 120/120. Across 1,208 original public source/AIR/std/example files, all 2,084 check/lower outputs and exit codes are byte-identical, including 560 successful source lowerings. Independent read-only Claude review found no accepted bypass or cleanup regression; its immutable-assignment spec clarification is included. Bundle growth is recorded in docs/agent/README.md; frozen evaluation inputs remain unchanged. This completes Q-041, not Phase 6.
## P6-9 executable examples (2026-10-07)
Four legacy examples now use implemented source syntax: disjoint parallel map, Island channel transfer, atomic publication and a bounded journal. The hello package now enters through `.aji`, retaining its AIR counterpart. All 27 example source files are checked through 24 standalone entry points and two explicit packages, including the module helper. Five larger source/AIR reference pairs already live in `tests/conformance/source/programs/`; their stress validation completes this task. P6-10 remains open.
No language/spec, AIR, diagnostic, verifier or interpreter rule changes. Existing ownership, borrow, effect, capability and task rules enforce explicit joins, resource consumption and release/acquire ordering; existing source rejects such as `layer9/reject/use_after_send.aji` retain E2001. Previously unparsable examples become executable. The journal creates a fresh file, checks length/offset before writing, documents its payload-only CRC and blocks further appends after partial I/O failure; explicit close remains required. This is an application example, not a durable-log contract or an implementation of source `requires`/`ensures`.
Validation: unit tests and full conformance pass, 1,186/1,186. All five reference pairs pass with 200 schedule seeds and collection before every instruction. New CI checks pass 3,662 CLI calls: every example/package, independent journal encoding/CRC/offset checks, overflow without writes, partial hosted writes, and concurrent source/AIR record equality at 200 seeds across three quanta. Linux raises the failed file's quota before retry to verify poisoning; the branch without `prlimit` also passes, retaining the original quota. Independent Claude review found the old-file offset error and two integration issues; these are corrected. A separate formatter correction preserves spaces in unpack/grouped range forms, with a failing-before/passing-after unit test and CLI AIR-fidelity test. Source Bundle hashes are unchanged for all 16 files; Quick Reference, AIR and token budgets do not grow. Frozen evaluation inputs remain unchanged.
## P6-5 fields named `len` (2026-10-07)
The implementation follow-up from P6-9 is resolved: nominal values and `ref`/`mut` receivers dispatch `.len` through ordinary field access, using the declared field type. Array field types are also available to inference for chained access such as `header.len.len`. Arrays and slices, including slices of structs, retain their built-in length behavior. Spec 15 §5 already defines these rules; no spec, bundle, AIR, verifier or interpreter change is required.
Existing borrow/load/end and whole-value ownership rules remain authoritative: reading a Copy field succeeds, conflicting borrows reject E2101, and projecting a linear field rejects E1001. Missing struct fields now produce E7002 with `type` and `field`, replacing the misleading array/slice E7005. Enum field access and type mismatches retain E7005. A struct length field does not prove slice bounds: the out-of-bounds regression still traps T0008. This restores specified source behavior without changing accepted AIR semantics or runtime state.
Validation: full conformance passes 1,201/1,201, including all 15 new cases; the new cases also pass with collection before every instruction. Unit tests, generic CLI integration (32 checks), formatting checks and coverage (120/120) pass. The formatter passes 3,437 checks over 916 public files, with 582 identical successful AIR outputs. Imported generic fields preserve declared types, source locations and source/AIR run-record parity. Across 1,233 original public files, all 2,134 check/lower results agree after normalizing absolute versus relative diagnostic file paths; all 570 successful source lowerings are byte-identical. Independent read-only Claude review found no remaining issues. P6-5 remains open for its other source-layer work.
## P6-7 block positions and lifetime twins (2026-10-07)
Generated block labels now carry the explicit source span of their creating construct, including branch joins, loop headers/exits/steps and short-circuit expressions. E3002 at a resource-state join therefore identifies the source construct instead of falling back to 1:1. Annotations expose label positions; canonical AIR and verifier/runtime rules are unchanged. Existing source-location deduplication now preserves errors on distinct constructs. The borrowed-buffer-element fixture consequently expects both allocation and destruction diagnostics.
Eight Phase 2 AIR rejection twins and five successful source runs cover owner/region/resource lifetimes and explicit release. Eleven further rejects cover every join form and distinct diagnostics. The CI CLI suite checks exact primary/AIR positions, label annotations, code parity and imported generic provenance. Existing ownership and borrow invariants, explicit cleanup and deterministic execution remain authoritative; no spec, diagnostic code, bundle or evaluation input changes. P6-7 remains open for the remaining twins.
Validation: unit tests and full conformance pass, 1,225/1,225; all 24 new cases pass with per-instruction collection. Lifetime CLI checks pass 188 assertions, related-location checks 301, coverage 120/120 and formatting checks pass. The formatter checks 940 public files with 606 identical AIR outputs. Across 916 original public sources, check outcomes and all 421 accepted canonical AIR outputs are unchanged; four diagnostic outputs gain source positions, one also recovering a previously suppressed error. Independent read-only Claude review found no remaining issues.
The parser-range follow-up is resolved in the P6-2 increment below.
## P6-2 complete parser ranges (2026-10-07)
Twelve parser sites now finish parsing their bodies/operands before capturing the node's end. Nested type closers track the consumed first half of `>>` independently of the token cursor. These changes restore complete block, prefix, `move` and `if` ranges, including cancellation arms; syntax, acceptance rules, primary diagnostic positions and canonical AIR are unchanged.
Three unit regressions failed before the correction and pass afterwards. They check exact ranges, AST containment, file/namespace provenance, comments, CRLF and nested closers. The existing CI formatter suite also validates nonempty ordered annotation ranges and reconstruction of canonical AIR across successful public lowerings. No normative document, bundle or evaluation input changes; P6-2 remains open for its remaining grammar work.
Validation: unit tests, formatting checks and full conformance pass, 1,225/1,225. Across 940 public sources, all check/lower outputs and exit codes remain unchanged, including 606 successful canonical lowerings. The formatter passes 4,139 checks; lifetime and related-position CLI suites pass 188/301 checks. Independent read-only Claude review found no remaining issues.
## P6-5 whole-array argument increment (2026-10-07)
Q-023 is resolved in spec 15 §5 / DD-021. Explicit temporary arguments preserve the array for a known ref/mut array parameter, including specialized and imported calls; other arguments and borrow bindings retain slice behavior. Shared reborrows and child-first temporary cleanup use existing AIR primitives. Exact types/lengths/modes, aliasing, bounds, named retained origins and task loans remain authoritative. Local whole-array bindings cannot serve as array-borrow origins or task loans; forwarding an existing array-borrow parameter can. No syntax, instruction, code, feature, verifier/runtime state or frozen evaluation input changes. Source bundle growth is recorded in docs/agent/README.md; AIR is unchanged. P6-5 remains open.
Validation: 32 new conformance cases pass with per-instruction collection and 200 scheduler seeds; full conformance is 1,257/1,257 and unit tests pass. CLI integration passes 85 checks, including deterministic/hosted and package provenance. Formatter checks 971 public files (963 parsed, eight existing syntax errors, 624 identical AIR outputs); source coverage is 121/121. Old/new CLI comparison over the 940 preceding public sources retains all diagnostic outputs and 606 successful canonical lowerings. Independent read-only Claude review passes.
## P6-2 dereferenced argument places (2026-10-07)
The existing grammar (`place = … | "*" unary`) and spec 15 §5 permit `ref *p` / `mut *p` as call arguments. The parser formerly rejected the leading `*`, although `ref (*p)` worked. Inline borrow parsing now admits that existing dereference production, preserving postfix binding and stopping before outer binary/cast operations. Other invalid prefix operands remain syntax errors. No normative rule, syntax form, diagnostic code, bundle, feature, verifier/runtime state or evaluation input changes; P6-2 remains open.
The invariant is unchanged borrow mode, aliasing, provenance and child-first temporary cleanup through existing AIR verification. Runtime and deterministic interpreter semantics are unchanged. Positive source examples forward shared/mutable scalar, array and generic parameters; rejected examples retain E7005 for invalid referents/modes, E2101 for aliasing, and E7006 for misplaced/unchecked borrows. Former syntax errors for these grammatical places now reach those semantic checks; previously accepted source retains canonical AIR. Two parser regression groups failed before the fix and cover precedence, complete ranges, comments and CRLF. Formatter checks compare bare and parenthesized spellings and preserve canonical AIR.
Read-only review also found a missing formatter space in grouped `ref (*p)` / `mut (*p)` arguments. The grouped-form regression failed before correcting the keyword spacing; both spellings now preserve tokens and canonical AIR. The separate existing source type-position gap is recorded as Q-042 without changing its semantics here.
Validation: 12 new conformance tests pass with per-instruction collection; full conformance is 1,269/1,269 and unit tests 126/126. Formatter passes 4,357 checks over 983 public files (975 parsed, eight existing syntax errors, 631 identical AIR outputs); source coverage stays 121/121. Old/new CLI comparison over the 971 preceding public sources preserves all diagnostics and 624 successful canonical lowerings. Final independent Claude review passes.
## P6-2 structural type positions (2026-10-07)
Q-042/spec 15 §10 closes source annotation gaps using the verifier's existing pure position predicates. Nested borrows, non-value content, fields/payloads, local annotations and known unused generic/static-contract constructors reject E7005 at their own annotation; restrictions involving unknown parameters wait for substitution. Graph-content properties retain E2111. The invariant remains that second-class borrows cannot be stored or nested in forbidden positions. AIR independently enforces the same rule; no ownership transfer, runtime allocation/cleanup or deterministic interpreter behavior changes.
Thirty-four conformance fixtures cover valid runs/unused headers, forbidden positions, specialization and graph-diagnostic preservation. CLI checks exercise exact fields/positions, all diagnostic commands, package reachability and source/AIR/hosted parity. Existing invalid-source fixtures now expect the earlier E7005. No syntax, code, feature, verifier/runtime state or evaluation input changes; source bundle growth is recorded in docs/agent/README.md. Q-043 records the separately reproduced Copy-content validation gap. P6-2 remains open; the historical P6A-12 checkpoint does not establish completeness for the current language.
Validation: full conformance 1,303/1,303; all 34 new fixtures also pass with per-instruction collection. Unit tests and formatting checks pass. CLI integration passes 74 checks, existing generics/buffers/linear suites pass, and formatter passes 4,453 checks over 1,015 public files (1,007 parsed, eight existing syntax errors, 631 identical AIR outputs). Source coverage remains 121/121. Comparison of 983 preceding public sources finds only five expected invalid-type diagnostic changes, with no check acceptance changes and all other canonical lowerings identical. All 333 public AIR files preserve check diagnostics and acceptance. Independent Claude review passes after clarifying feature-gate precedence.
## P6-2 dynamic owning-array content (2026-10-08)
Q-043/spec 15 §10 enforces the existing Copy-content requirement for source `own_array<T>` annotations and `own.array` repeated values before AIR emission. One AST property query follows nominal fields/payloads and generic parameter states without calling lowering recursively. User type names precede built-ins; imported fields use their declaring namespace. Unused generic/static headers reject provable linear content; unknown parameters defer to substitution. A query-local cache shares completed branches, keeps positive witnesses final and rechecks negative results whenever a new positive proof is learned. Parameter-state queries repeat until that generation stabilizes; memo lookup is a linear scan, trading peak cost for implementation simplicity. Parameter rotations and deep nominal chains cannot hide a known linear leaf; iref content remains phantom and graph-root properties retain E2111.
The preserved invariant is that repeated dynamic heap arrays contain Copy values, so bulk release cannot destroy nested resources. AIR independently retains the same type/operation checks; allocation budgets, initialization, owner transfer, explicit release and deterministic interpreter behavior are unchanged. Valid Copy allocations run with explicit release; rejected annotations and repeated linear values report E7005 with `constraint` and `type_constructor`. Existing invalid-source codes/priority may change, including Copy violations preceding simultaneous layout errors. No syntax, code, feature, verifier/runtime state or evaluation input changes. Source bundle growth is recorded in docs/agent/README.md; P6-2 remains open.
Validation: full conformance 1,335/1,335; all 32 new fixtures also pass with per-instruction collection. Unit tests pass 128/128, including counted acyclic/cyclic diamond queries; the cyclic case failed before the cache correction. CLI integration passes 119 checks with exact annotations/value positions, nested package imports and source/AIR/hosted parity. Formatter passes 4,563 checks over 1,047 public files (1,039 parsed, eight existing syntax errors, 638 identical AIR outputs); source coverage remains 121/121. Comparison of all 1,017 preceding public sources preserves every check/lower result and all 631 successful canonical lowerings. No AIR verifier/runtime files change. Independent Claude review passes after checking shadowing, generic rotations, cache invalidation and the complete declaration snapshot used by the shared Copy predicate.
## P6-2 inferred array literals (2026-10-08)
Q-045/spec 15 §5/§10 applies the existing member-position rule to each inferred array element before construction and the exact verifier Copy predicate to repetitions. Borrow elements reject E7006 invalid_literal; forbidden constructors and non-Copy repeats reject E7005 at the value with structured fields. Element validity precedes expected-type agreement; annotation errors still reject first. Existing linear lists preserve explicit moves and complete-value transfer, including missing-move and duplicate-owner diagnostics.
The invariants are that second-class borrows cannot become stored members and repetition cannot duplicate a linear value. AIR still independently checks the same rules. No allocation, lifetime, task transfer, cleanup, deterministic interpreter behavior, syntax, code/reason, feature, verifier/runtime state or evaluation input changes. Valid linear lists explicitly unpack/release their owners; Copy and temporary-slice programs run unchanged. Invalid-source errors formerly reaching E1001/E0006/E7900 now stop earlier; the preceding own.array borrow-array fixture now rejects at its literal. New source tests and CLI/package/profile checks cover the changes. Source bundle growth is recorded in docs/agent/README.md; Q-046 records the separate inferred-wrapper audit, and P6-2 remains open.
Validation: full conformance 1,364/1,364; all 29 new fixtures pass with per-instruction collection. Unit tests pass 128/128. CLI integration passes 152 checks covering exact positions/fields, all diagnostic commands, never-valued calls, generic package provenance, source/AIR/hosted parity and formatter idempotence; the preceding own.array suite remains 119/119. Formatter passes 4,664 checks over 1,078 public files (1,070 parsed, eight existing syntax errors, 642 identical AIR outputs); source coverage remains 121/121. Comparison of 1,049 preceding public sources finds only two expected invalid-program diagnostic changes, with unchanged acceptance and every other canonical lowering identical. No AIR verifier/runtime files change. Independent Claude review passes.
## P6-2 inferred constructor content (2026-10-08)
Q-046/spec 15 §10 validates inferred content before forming constructor results/outcomes. `own.new` and region storage require Copy using the verifier's exact property predicate; `own.pack` excludes root borrows while retaining whole linear transfers and failure recovery. Void/never arguments reject E7005 at the argument instead of malformed AIR/E7900 or a null-block panic. Existing explicit-move checks precede these checks. `own.array` retains its Copy fields/priority, mutexes retain element rules and endpoint feature gates, and graph content retains the verifier's existing E2111/E1001 precedence. Generic failures locate the substituted value in template source, including imported modules.
The preserved invariants are that second-class borrows cannot become owned content and Copy-only allocation cannot hide or destroy a linear value. AIR independently enforces the same type, property and ownership rules. Allocation authority/budgets, ok/err payloads, explicit release, resource recovery, runtime state and deterministic interpreter behavior are unchanged. Positive runs release linear contents and distinguish successful/failed packing; rejected tests cover nonvalues, borrows, owners, nominal values and tasks. No new syntax, code/reason, feature, verifier state or evaluation input changes. Source bundle growth is recorded in docs/agent/README.md; P6-2 remains open, with the separate Q-044 property-query cost audit outstanding.
Validation: full conformance passes 1,422/1,422, units and Zig formatting pass. The 58 new conformance fixtures pass with collection before every instruction; the new CLI suite passes 302 checks across diagnostic commands, exact fields/locations, imported generic templates, source/AIR/hosted runs and formatter fidelity. Existing owning-array, literal and linear CLI suites pass 119, 152 and 49 checks. The formatter corpus passes 4,862 checks on 1,134 public files (1,126 parsed, eight existing syntax errors, 657 identical successful AIR outputs); the two final graph regression fixtures additionally preserve formatted AIR in CLI checks. Independent read-only review by Claude confirmed the constructor-specific rules and identified the existing feature-dependent graph diagnostic, covered by paired fixtures. Comparison with the previous compiler on 1,078 existing public sources changes one invalid region allocation from E1001 to E7005; accepted programs retain byte-identical AIR. The former compiler successfully lowered 642 of these sources, including that invalid program. Source coverage remains 121/121.
## P6-2 non-value operands (2026-10-08)
Q-047/spec 15 §10 distinguishes typed operation inputs from divergent control flow. Never-valued operands reject E7005 at the operand with expected/found fields before later inputs or instruction emission; existing void mismatches remain unchanged. This covers calls, operators, aggregate inputs, conditions, ranges/indices, sizes, atomics, channels and stored values. `select` checks send values before endpoint borrows. Return/tail/statement/branch divergence remains valid. Variable assignment by name and var initialization retain ordinary binding/annotation checks; divergence skips a frame store just as it already did an SSA update. Place writes require a value: accepting a divergent RHS would otherwise bypass target checks, a regression found and corrected during independent read-only review with Claude. Attempted emission after unconditional divergence reports E7006 unreachable; a unit test verifies that the terminated block remains intact.
The preserved invariants are that no missing value becomes an operand or store and no write/borrow is emitted after control flow terminates. AIR independently retains its type, ownership, lifetime and effect/capability rules. Runtime cleanup, abnormal-path resource handling, deterministic execution and accepted-source canonical AIR are unchanged. Positive cases cover variable receivers in SSA/frame storage, normal/trapping branch paths, ownership and returned views; rejected cases cover non-value inputs and malformed place targets. Former compiler aborts now produce a diagnostic or valid variable-receiver divergence. Invalid diagnostic order may change, including place RHS errors before unknown targets. No new syntax, diagnostic code/reason, feature, verifier/runtime state or evaluation input changes. Source bundle growth is recorded in docs/agent/README.md. P6-2 remains open; Q-048 is the separately reproduced store-mode gap, and Q-044 remains an implementation-cost audit.
Validation: full conformance passes 1,497/1,497; unit tests and Zig formatting pass. The 75 new fixtures pass with collection before every instruction and the CLI suite passes 635 checks, including exact positions/fields across diagnostic commands, source/AIR/hosted trap/return parity, formatting and imported generic reachability. Existing constructor/literal/owning-array/linear CLI suites pass 302/152/119/49 checks. Final comparison on 1,136 preceding public sources (659 successful old lowerings) has zero changed check or canonical lower outputs. The formatter corpus passes 5,098 checks on the first 1,200 public files (1,192 parsed, eight existing syntax errors, 676 identical AIR outputs); CLI formatting covers all 75 new fixtures, including the eleven later additions. Source coverage remains 121/121.
## P6-2 source place access modes (2026-10-08)
Q-048/spec 15 §10 rejects stores through shared borrows, and checks explicit `mut` bindings/arguments before whole-array-to-slice conversion. Scalar stores require exactly `mut<T>`; dereferenced slices reject. E7005 carries expected/found borrow types at the place (binding/store) or argument. Existing whole-array E7006 and RHS evaluation order remain. Valid exclusive stores, shared reborrows, projections, array/slice views and owned content use unchanged AIR. Previously accepted `mut` bindings through shared fields/indices/ranges now reject; invalid argument diagnostic details can change.
The preserved invariant is that explicit `mut` cannot create exclusive access from shared access. AIR independently enforces borrow/store modes, aliases, lifetimes and linear content/projection restrictions. No runtime state, allocation, cleanup, deterministic interpreter behavior, syntax, code/reason, feature or evaluation input changes. Positive source/AIR runs exercise scalar/field/index/range writes and owning content; rejected cases cover shared modes and retained verifier rules. Q-049 records the separate unresolved Copy-let frame-content policy. Bundle growth is recorded in docs/agent/README.md; P6-2 remains open.
Validation: full conformance passes 1,543/1,543; units and Zig formatting pass. The 46 new fixtures pass with collection before every instruction; CLI integration passes 348 checks, including exact fields/positions, diagnostic commands, formatting, imported generic templates and source/AIR/hosted execution. Existing array-argument/non-value/linear/borrow-return CLI suites pass 85/635/49/133 checks. Comparison on 1,211 preceding public sources (673 successful old lowerings) changes only the message of two rejected inputs; accepted AIR is byte-identical. All eleven new runtime fixtures also retain the previous compiler's AIR. The formatter corpus passes 5,289 checks on 1,257 public files (1,249 parsed, eight existing syntax errors, 686 identical AIR outputs); coverage remains 121/121. Independent read-only review by Claude approved the access-mode checks and confirmed the two diagnostic-message changes.
## P6-2 nominal query cost (2026-10-08)
Q-044 replaces repeated nominal walks with a shared property table and memoizes the earlier AIR accounted-size query by index/depth. The invariant is exact structural classification: existing tag rules, graph/iref boundaries, ownership classes, diagnostic ordering and depth guards remain. The verifier rebuilds caches rather than trusting callers; lowering classifies only after finite-layout checks. No verifier rule, AIR meaning, diagnostic/code/reason, source syntax, feature, interpreter state, allocation/cleanup behavior or bundle text changes. Nominal size states have the documented polynomial bound V × (V + 2), preserving the former depth-dependent calculation. Valid deep diamonds/phantom nodes and rejected cycles, oversized values, annotations and constraints have source/AIR fixtures; runtime allocation uses the checked cache.
Validation: units and Zig formatting pass; full conformance is 1,560/1,560, with all 17 new fixtures also passing collection before every instruction. Counted tests cover shared/cyclic queries, witness visits and layout rejection before classification; 256 small mixed graphs compare cached predicates, witnesses, depth guards and sizes against uncached derivations. CLI integration passes 110 checks, including source/AIR/hosted execution, actual allocation accounting, imported types and diagnostics. Existing generic/content/store-mode suites pass 32/302/348 checks. Old/new comparison changes zero outputs on 1,257 public sources (686 old lowerings) and 333 public AIR checks. Coverage remains 121/121. Claude independently ran units and approved review. P6-2 remains open; Q-049 is a separate owner-policy question.
## P6-1/P6-2 grammar surface increment (2026-10-08)
DD-022 synchronizes the grammar/spec 15 with implemented wrappers, binary literals, negative patterns, parenthesized places, declared borrow-return calls and list/arm delimiters. Ordered statement, header-brace and typed-built-in choices are documented; no LL(k) claim is made. Q-050 rejects empty qualified enum payload lists with E7001 at `(`, including generic/grouped/built-in variants and patterns. Ordinary `f()`, bare variants, non-empty payloads and outcome bindings retain their rules. No AIR, verifier/runtime, ownership/concurrency, feature or diagnostic-code changes.
Validation: units and Zig formatting pass; full conformance is 1,594/1,594, and all 34 new fixtures pass collection before every instruction, including select schedules. CLI integration passes 288 checks for syntax locations, packages, formatting and source/AIR execution. Old/new comparison changes zero check/lower outputs on 1,269 public sources (695 old lowerings); source coverage remains 121/121. The public formatter corpus passes 5,435 checks on 1,303 files, preserving 709 lowered outputs. Claude independently reviewed the change and reran units and CLI checks. Bundle growth is recorded in docs/agent/README.md. P6-1/P6-2 remain open; future syntax still needs its RFCs, and Q-051 is a separate ordinary-effect validation task.
## P6-2 effect-name diagnostic increment (2026-10-08)
DD-023 resolves Q-051: ordinary effect declarations validate the existing registry after signature types/from and before body lowering. Templates/static contracts replace incorrect E0006 with E7002; `name` and `effect` identify the atom. Declaration/parameter positions and prior signature/template check order remain. Registered atoms, flat effect sets, static-contract uniqueness, effect coverage, explicit capabilities and AIR E0004 remain unchanged. No new code/reason, syntax, feature, verifier/runtime, ownership/concurrency or evaluation input changes.
Validation: units and Zig formatting pass; full conformance is 1,618/1,618, and all 24 new fixtures pass collection before every instruction. CLI integration passes 236 checks, including unused/package headers, diagnostic priority, formatter preservation, source/AIR execution, instantiation and independent AIR rejection. Existing generic/static-function/grammar suites pass 32/25/288 checks. Old/new comparison on 1,303 public sources (709 old lowerings) changes only the two corrected E0006 fixtures, preserving their primary positions and `name`; accepted AIR is byte-identical. Claude independently reviewed the change and ran units/fixtures and all 236 CLI checks. Bundle growth is recorded in docs/agent/README.md; P6-2 remains open.
## P6-7 CFG resource-provenance correction (2026-10-08)
Rejection-twin work exposed accepted source that ended a task loan after cancelled-handle transfer through a block parameter. DD-024 resolves Q-052: task loans/scopes, guard parents and shield order now follow simultaneous CFG transfers, with a fixed point for later predecessors and backedges. Existing concurrency invariants and diagnostic codes apply; interpreter behavior and valid source lowering are unchanged. This enforces existing AIR format-0 rules, with no new source concept, syntax or feature.
Validation: units and Zig formatting pass; full conformance is 1,642/1,642. All 24 new AIR/source fixtures pass schedule stress and collection before every instruction. A counted 63-handle rotation test verifies convergence and retained spawn provenance. CLI integration passes 146 checks, including exact source/package/generic positions, three loan rejection twins and both correlated scope/task permutations; existing related-location and lifetime suites pass 349/188 checks. Old/new comparison changes zero diagnostics on 1,327 existing public sources and 338 AIR files, preserving all 715 old source lowerings. Claude wrote independent regressions and reviewed the implementation with additional loop/permutation/cancellation probes. Source bundle size is unchanged; AIR growth is recorded in docs/agent/README.md. The exhaustive rejection-twin inventory and P6-7 remain open.
## P6-7 exhaustive rejection inventory (2026-10-08)
`tools/source_reject_twins.py` discovers all 199 public AIR rejection files, including new tests without manual metadata. The audited manifest verifies 27 same-code pairs: 13 new source fixtures, three existing source links and 11 existing lifetime/CFG pairs. It also records four mandatory E7xxx analogues and 15 cases without an implemented source spelling; these remain unmet rows alongside 153 pending audits. Q-053 records the conflict between the literal same-code criterion and spec 15's source boundary. The criterion and P6-7's doing status are unchanged; `--require-complete` fails.
Pairs compare operation/site, resource family, identity roles and stable rule facts, then independently check marked primary/related source positions against canonical AIR annotations. Early declaration errors and function budget sites have explicit checks; raw errors use spec 15 §10's exact duplicate projection. Cancellation witnesses preserve the reviewed regression context. Manual rule audits remain necessary. CI runs both the partial checker and 21 negative/positive checker regressions, including wrong operation, ordering, resource family, source position, related role and cancellation context. No compiler, verifier, runtime, normative rule, diagnostic code or reference bundle changes.
Validation: unit tests and Zig formatting pass; full conformance is 1,655/1,655. All 13 new source fixtures pass collection before every instruction. The pair checker verifies 27/199 and reports incomplete coverage; its completion gate rejects that inventory. Existing borrow-return, related-position and source-coverage checks pass (133, 355 and 121/121 respectively). Claude independently audited Phase 0–1 cases and reviewed the checker; its false-pair findings are covered by regression probes.
## P6-7 public rejection-twin audit (2026-10-08)
Verified same-code coverage is 91/199 across ownership/resources, borrows, effects/capabilities, tasks, graphs, atomics, linear aggregates and buffer operations. The inventory retains 0 pending, 45 prescribed E7xxx analogues and 63 AIR-only cases; those 108 classified cases do not meet the literal same-code exit criterion (Q-053). P6-7 remains doing.
The [checker documentation](../../tests/conformance/README.md) records the diagnostic-fact, independent-position and context witnesses. Named type tables preserve the nominal diamond; early cycle pairs pin the two artifacts that exist before lowering. Five CFG loan pairs pin original AIR, source and canonical lowering after a manual shape review: single br handoff, lend/plain merge, loop-carried loans, cancelled-handle forwarding and parent access after handoff. The final direct cbr/switch arm-argument cases are AIR-only under spec 15 §4, supported by inspection of lowering and every branch argument in the 740 successful lowerings of the preceding 1,352 public source fixtures. Ordinary atomic access now has a full-AIR twin: a shared field read retains the same load/type/use facts; its reported operand must be the actual load operand. The task-parameter feature pair validates each full repair header before comparing its missing closure; unrelated declared features do not decide that rule. Reserved channel endpoint elements retain their feature/construct at channel.make. The linear swap pair compares named enum tables and pins the array/unpack and specific arm where the old value leaks. Source-boundary analogues retain exact fields and independent markers; the nominal-call analogue records its local rather than linked declarations. The guard-unlock pair retains the returned view's mutex.borrow ancestor through the generated unlock. Fingerprints attest unchanged artifacts, not audit correctness, and introduce no provenance or lifetime analysis.
Validation: full conformance is 1,713/1,713; unit tests, Zig formatting, all 62 checker regressions and the 91-case source/AIR position check pass. All 66 source reject_twins fixtures and five atomic_access fixtures pass collection before every instruction; source coverage remains 121/121. The completion gate still rejects partial same-code coverage. Claude independently reviewed the feature/CFG witnesses, all remaining classifications and the atomic operand checks. New probes reject another scalar or borrow mode, an unrelated borrow reported as the operand, and inconsistent raw/source identities. Existing Git attributes force LF for pinned artifacts.
The frontend ordinary-dereference E4202 now adds concrete found and use fields, retaining the code, message, primary position and early failure. CLI tests pass 33 checks; comparison with the previous compiler passes 52, including generic/package provenance, first-error selection, untouched alternative errors and identical valid AIR. No SSA identity or AIR location is fabricated for a frontend rejection. Atomic access invariants, verifier/runtime rules and deterministic execution remain unchanged; valid reads use explicit atomic.load orderings. The schema is additive; the source bundle grows by 30 tokens (docs/agent/README.md). Q-053 remains the owner decision on the literal criterion; there are no unaudited public rows.
## P6-7 nested-size rejection twins (2026-10-09)
Five Q-058 regression cases now have verified source/AIR twins with identical E5101 budget facts: finite nested value size, one-GiB anonymous content with an unrelated named declaration, mutex wrapper/content, checked-u64 size overflow and a local frame one byte over the limit. The nominal-context pair additionally compares the complete type declarations. Existing markers, canonical/annotated lowering, raw AIR diagnostic projection and independent source coordinates are checked by the regular twin tool. Same-code coverage is 96/205; 45 E7xxx analogues and 63 AIR-only cases remain unmet.
One row remains pending: nested_size_cycle_overflow.air reports E5101 before finite-layout validation, while the same source declaration necessarily rejects earlier with E1003. A separate source fixture preserves that actual code; it is not falsely linked as an E5101 twin. The current inventory's E7xxx analogue category cannot represent this earlier verifier-code rejection. Q-053's literal completion decision remains open; no rejection rule or diagnostic is changed for coverage. Full conformance passes 1765/1765; sixteen nested-size cases also pass with collection before every instruction. All 62 checker regressions pass, and source construct coverage stays 121/121. No fresh Claude review was available for this increment. P6-7 remains doing.
The final size row is now explicitly classified as `source_early`, retaining its authorable cyclic-array shape and unlike E5101/E1003 codes. The inventory tool pins both reviewed artifacts, AIR budget facts and source type facts, checks independent declaration markers, and requires lower/check rejection parity without fabricated AIR coordinates. It does not infer cycle equivalence or waive the same-code completion gate. All 205 AIR rows are classified: 96 same-code, 45 E7xxx analogues, one source-early analogue and 63 AIR-only; zero pending. Eight new failure probes cover artifact/fact/position drift, lower/check disagreement and a category that cannot satisfy `--require-complete`. All 70 checker regressions and 16 focused GC conformance cases pass. No compiler/normative/bundle changes or fresh Claude review. Q-053 and P6-7 remain open.
## P6-1 source specification consistency (2026-10-09)
The [Q-059 type-depth audit](../design/air-type-depth-audit.md) confirms a parser native-stack failure on a 37-KB, 4,096-depth AIR parameter type. Pending anonymous constructors now use an explicit arena-backed stack, preserving grammar, feature/member-gate order and diagnostic positions. Unit tests parse 32,768 levels and check deep unknown/malformed leaves; all unit/format checks and 1,765/1,765 conformance cases pass, and 364 public AIR checks preserve exact old/new outputs. The old crashing input now accepts. A 16,384-depth check still fails in the verifier's recursive size evaluation, so Q-059 remains open. No normative/bundle/feature/code change or new acceptance limit; no fresh Claude review was available.
The [Q-059 size-query increment](../design/air-type-depth-audit.md#size-query-repair) gives verifier sizing explicit continuations, iterates inner-budget visits and caches anonymous wrapper identities without changing size arithmetic or nominal cycle depth. Unit cases cover 32,768 anonymous/nominal levels, zero leaves, overflow/null caching, constructor identity and forged-cache rebuilding. The existing full 1,765-case snapshot, four new AIR/source zero/overflow fixtures and sixteen focused GC/quota cases pass; together the full/focused runs cover all 1,769 current conformance cases. Unit/format checks and test-extended pass, and 364 pre-existing AIR checks preserve exact old/new output. The new rejection twin brings P6-7 to 97/206, with zero pending, 45 source-error analogues, one source-early analogue and 63 AIR-only cases. A 16,384-depth probe now reaches the next failure in wellFormed; Q-059 and the phase stay open. No normative/bundle/feature or diagnostic code change, and no new syntax-depth limit; no fresh Claude review was available.
The [Q-059 type-validity increment](../design/air-type-depth-audit.md#type-validity-and-finite-layout-repair) iterates anonymous position/length checks and finite-layout DFS, preserving graph stops, wrapper gates, enum payload order and sibling traversal after cycle back edges. Unit tests cover 32,768 anonymous/nominal levels and ordered cycle diagnostics; all unit/format checks and 1,769/1,769 conformance cases pass. Exact old/new exit/stdout/stderr comparisons pass on 366 public AIR files and 48 generated mixed cyclic graphs. The 16,384-depth CLI probe now passes wellFormed and aborts in Module.isLinearType, confirming the next property traversal failure. Q-059 and Phase 6 remain open; no normative/bundle/feature/code change or new syntax-depth limit, and no fresh Claude review was available.
The [Q-059 anonymous property-query increment](../design/air-type-depth-audit.md#anonymous-property-query-repair) iterates linearity, structural predicates and dependency discovery, with explicit Send/Share transitions and unchanged saturated height/witness summaries. Unit cases cover 32,768 anonymous levels and phantom dependencies, 65,536 alternating ref/mutex edges, and saturation boundaries. Unit/format checks, test-extended, all 1,769 conformance cases and exact old/new comparisons on 366 public AIR files pass. Complete checking accepts 32,768 nested arrays; separate probes now verify failures in Type.eql at 65,536 and diagnostic printType at 32,768. Q-059 and Phase 6 remain open. No normative/bundle/feature/code change or new syntax-depth limit; no fresh Claude review was available.
The [Q-059 equality/printing increment](../design/air-type-depth-audit.md#type-equality-and-printing-repair) iterates structural type comparison and emits canonical suffixes through an explicitly allocated compiler stack. Constructor/leaf identities, array lengths, AIR spelling and diagnostic payloads remain unchanged. Deep unit cases cover equality/inequality and varied-length canonical round trips at 65,536 levels, plus allocation/writer errors. Unit/format checks, test-extended, all 1,769 conformance cases and exact old/new output comparisons on 366 public AIR files pass. The previous CLI failures now finish: equality at 65,536 accepts; invalid atomic content at 32,768 returns one E1001 with its complete found type. Q-059 remains open for uncached nominal/query call-path audits, with no normative/bundle/feature/code change or new depth limit. No fresh Claude review was available.
The [Q-059 report audit](../design/air-type-depth-audit.md#audit-report-traversal) confirms and removes recursion from capability-kind collection: `aji report` now completes for a verified 65,536-depth parameter. The scan sites, nominal-name boundary, deduplication and sorting remain unchanged. Unit/format checks, all 1,769 conformance cases and exact report-command output comparisons on 366 public AIR files pass. Call-path inspection confirms retained verifier/property caches but leaves low-level uncached nominal APIs open. A separately verified runtime zero-materialization crash is recorded as [Q-060](../design/runtime-value-depth-audit.md), with no new acceptance/trap limit. No fresh Claude review was available.
Spec 15's initial Phase 6A limits now point to its existing extensions. Its introductory diagnostic rule follows §10 and construct-specific codes; widening reports source E7005 while AIR retains E1002, including the corrected Quick Reference entry. Multi-result bindings include complete unpacking, byte escapes agree with the later exact list, and grammar comments locate graph access in §8. Old incremental limits link buffers/borrow returns to §17/§19. No grammar production, semantic rule or implementation changes. Six existing public fixtures confirm the reported code and deterministic successful AIR; Claude independently audited the corrections. The reference bundle rebuilds; source growth is +50/+47/+58 tokens across the three tokenizers, with unchanged Quick Reference token counts, AIR and std (docs/agent/README.md). P6-1/P6-5 remain open for their unimplemented surfaces.
## P6-6 contract spec gate (2026-10-09)
Q-054/RFC 0039 Draft identifies the missing executable contract model. Public probes at `94414da` demonstrate identical audit reports for mandatory/bypassable assertions, effects-empty mutation and ambient task.cancelled observation, E3001 after consuming an observed owner, and E0001 versus E0006 for candidate unfeatured/featured AIR headers. All runs use fuel 10,000. Claude independently audited the architecture and compatibility constraints. Predicate rules, old/result lifetime, coverage, statuses and type/module invariant boundaries need concrete normative rules before implementation; function contracts alone do not complete P6-6. Q-055 records the historical header-compatibility question from source inspection, without claiming an executed old-parser result. No compiler, semantic rule, registry, conformance fixture or normative bundle changes.
The next design increment prefers leading `contract.pre/old/post` operations, isolated uses currently E0004, with no entry predecessors, contract-only snapshots and per-return access checks. The candidate specifies pending-return dispatch, ordinary fuel/quantum accounting and temporary observations without resurrecting consumed values. Current ordinary observations before returning an owner accept and preserve 42; observing its old binding after a call transfer rejects E2001. Verified invariant probes return width 10 after a repaired exclusive update, expose an invalid mid-update Copy and trap T0003 in a shared reader. Source struct-zero rejects E7006, while AIR struct-zero accepts; Q-056 records that separate surface question. Claude independently reviewed the candidate and identified dispatch/availability clarifications. A body use of an unknown snapshot additionally yields E5001; use only by a post yields E0004s alone. Q-055 retains the invalid body-use rejection-code audit. All twelve targeted probes match their reported results, and local documentation links/diff checks pass. These are current-language probes of design obligations, not conformance tests for an implemented contract feature. Type/module boundaries, predicate closure and status rules remain open; Draft status and the full P6-6 exit criterion are unchanged.
The purity increment supplies a closed opcode/type candidate, authority-free Copy Data (including opaque iref identity), and greatest-fixed-point call closure. Read-only linear-record fields are admitted without loading owners/capabilities; auxiliary mut helpers can write fresh frame scratch, proved from entry signature restrictions and ordinary borrow rules. No write-summary subsystem or totality proof is claimed. Current probes confirm a scratch/helper/hash predicate (1), linear count read (7), identity after graph destruction (1), accepted Copy capability extraction, and E1001 for borrowed linear variant/nested owner inspection. Mutual recursion returns 1; nontermination is stopped by fuel and recursive frame exhaustion by T0007. Claude independently reviewed the freshness proof and identified the need to freeze predicate classification under §8.7; proposed feature dependencies and immutable classifications are explicit. Q-057 records the missing non-consuming observation surface required before full contract coverage. Type/module invariants, audit statuses, diagnostics and vertical implementation remain open; RFC 0039 stays Draft and normative bundles are unchanged.
RFC 0040 Draft develops Q-057 as a separate vertical prerequisite: selective shared enum dispatch and nested scalar/array owner views. Explicit `match ref place` creates only named payload views; skipped payloads stay owned, with no partial moves or general borrowed block joins. Current probes confirm a legal 65-payload enum returning 0 and E5101 for its value match. Unknown enum-view forms report E0004 alone; isolated owner-view forms report E0004, and a used owner-view result also reports E5001. All seven baseline probes are checked with the existing compiler; executed programs use fuel 10,000. Q-055's dependent-error interpretation remains open. These Draft rules allocate no feature/code and change no normative bundle, compiler or conformance fixture; type/module invariants, contract statuses and full P6-6 delivery remain open.
Claude independently reviewed RFC 0040; corrections preserve existing E0004 name lookup, distinguish E2102 SSA origins from E2108 frame roots, count unreachable ingress and clarify unchanged complete-state joins and pattern-binder status. Three further source probes independently confirm both ref-parameter place spellings (combined result 6), wrong SSA-root return E2102 and Copy-frame escape E2108. All ten probes confirm only current-language constraints, not the proposed operations' implementation.
The [invariant-boundary research](../design/contract-invariant-boundaries.md) advances RFC 0039's type/module gate. Five baseline probes confirm projected scalar mutation, a library-wrapper bypass and independent-root drift (all return 1), plus E0001 for a new declaration and E0004 for a new type constructor. Claude's independent review identified the need for explicit in-place update of borrowed linear representations; extraction/replacement alone can require new allocation authority. The checked-type candidate separates unvalidated representation updates from persistent shared claims and requires stable observations, callback effects/loan checks and pending-result validation. Module state-root and boundary-only relations retain distinct scopes; exact metadata, source rules, statuses/proofs and vertical delivery remain open. No feature, normative bundle or implementation changes; P6-6 remains doing.
Eight further compatibility probes independently reproduce Claude's findings: exact predicate-bearing type spellings in seven positions report E0004 alone, while an opcode-first make/take/result-use shape reports E0004 twice and E5001. All thirteen current-language cases match their recorded outcomes; runs use fuel 10,000. Stable closure membership must be justified separately from point-in-time predicate purity so future interior-mutable reads cannot silently invalidate persistent claims. No complete AIR0 compatibility or implemented invariant is claimed.
Final review identified the need for instruction-internal observation places: ordinary AIR borrow.ref rejects Copy scalar and Copy struct SSA roots with E1001 (two independently verified probes, fifteen total). The candidate states evaluation-scoped materialization without widening general addressability or frame-content rules; RFC 0039 Copy ref-bindings use the same requirement. Exact activation-slot accounting remains a gate. Copy extraction preserves the original checked claim but gives the plain copy no claim; shared interior-mutable interfaces remain outside stable observations. No implementation is authorized by the research.
The [accounting/status candidate](../design/contract-accounting-and-status.md) proposes locals plus snapshot plus maximum simultaneous observation-place storage, separately bounded virtual return bindings, and a restricted proof classifier with unchanged predicate execution. Explicit assumed/documented modes retain ordinary legality checks; only assumptions require an unsafe boundary, and documentation grants no truth guarantee. Nine frame/stage baselines and five mode/unsafe baselines match the existing CLI (runs use fuel 10,000); none tests an implemented contract feature. Claude's independent review led to body-independent pre proof costs, explicit Copy/linear make accounting and total pre-types linearity queries, including invalid cycles. Exact proof-cost conventions, diagnostic collection, report/source/module schema and owner adoption remain gates. RFC 0039 stays Draft; P6-6 and its full four-status/invariant exit criterion remain open.
The [proof/report refinement](../design/contract-proof-and-report.md) closes the candidate's opcode/node cost conventions and function/value row grammar, with deterministic fallback precedence and source metadata distinguished from AIR-derived truth. Fifteen research vectors and a finite independent truth oracle confirm their stated costs/results; five current-language CLI probes confirm canonical report equivalence, run independence, eligible scalar/view operations and the limit-vector structure (runs use fuel 10,000). A report component vector pins field order and site totals across four statuses. Claude independently checked the cost derivations, status/field ordering and feasibility; review corrected a target-width assumption and clarified unreachable origins and assumed-call accounting. These are design evidence, not implemented contract conformance. Module-claim metadata, source clause elaboration, diagnostic collection, owner adoption and full vertical delivery remain open; RFC 0039 stays Draft and P6-6 remains doing.
The [module/source candidate](../design/contract-source-and-module-state.md) develops persistent caller-owned module state without globals or visibility, separate boundary-only relations, narrow checked-type bindings, explicit operations and clause elaboration. Claude's review identified namespace hijacking and old/capture ambiguities; the reserved type.checked prefix preserves accepted checked modules/types, and eager old/document matching is explicit. Nineteen current-language baselines verify names/static applications, namespace collisions and reserved bindings, complete source rejections, Copy/linear/checked witness shapes and flat/tree record packing (runs use fuel 10,000). These constrain the proposal and do not implement contracts. Rooted-state owner selection, checked properties/ABI/positions, mangling/inventory schema, source/diagnostic/dispatch integration and vertical validation remain gates; RFC 0039 stays Draft and full P6-6 remains doing.
The property/type-position audit exposed a pre-existing accounted-size defect ([Q-058](../design/open-questions.md#q-058--finite-anonymous-types-truncated-by-the-size-cycle-guard)): anonymous array/atomic/mutex edges incorrectly consumed a nominal-cycle depth budget. Corrected finite type sizes now enforce existing value/frame and allocation quotas. AIR/source boundary and rejection fixtures, a named-record heap quota pair and cached/uncached/cyclic unit checks cover the fix; a separate unverified native-recursion concern is recorded as Q-059. This correction adds no contract syntax, feature or adoption decision; checked properties and the remaining full P6-6 gates stay open.
The [property/inventory refinement](../design/contract-source-and-module-state.md#representation-properties-and-positions) specifies candidate complete representation/position checks, inherited properties, recursive endpoint gates, dedicated representation traversal, forbidden zero manufacture, size versus ABI and representation-only result rendering. The inventory's universal raw-R proof is distinct from construction-site proofs and supplied declaration provenance. Twelve prior property baselines match `4cda448`; eight new reproducible vectors verify ordinary identity/content restrictions and the Range predicate. The report research component includes six sites, seven boundaries and three checked identities with distinct type/site proofs. These are current-language/design checks, not implemented contracts. Claude's earlier property audit is incorporated; the live Herdr channel is unavailable for fresh review. Mangling/source-map, diagnostics/dispatch, compatibility and owner model selection remain gates; RFC 0039 stays Draft and full P6-6 remains doing.
The [naming/provenance candidate](../design/contract-source-and-module-state.md#generated-names-and-source-provenance) fixes full descriptor bytes, ordinary-first collision allocation, emission categories and clause/witness maps. Three current-language naming groups pass ten CLI checks; seven proposed descriptors agree under two SHA-256 implementations. The [diagnostic refinement](../design/contract-accounting-and-status.md#collection-at-returns) preserves ordinary return/leak facts while isolating virtual post checks, orders required P/S subpasses, and bounds shortest real-call witnesses. Five executed return baselines and six graph vectors independently verify current constraints and proposed selection. No semantic/code/registry change is made; the vectors are not new-contract conformance. Binding/source-reason/trap schemas, Q-055 compatibility, owner adoption and full vertical implementation remain gates; RFC 0039 stays Draft and full P6-6 remains doing.
The [AIR binding candidate](../design/contract-air-bindings.md) supplies prefix/type/operation grammar, explicit root/form identity, exact shared adaptation, snapshot-use checks and proposed E8001 reasons/fields. Eighteen current-language probes verify view/alias/never-call constraints and isolated E0004 rejection of complete candidate prefixes. Claude independently reproduced all eighteen and the nine descriptor hashes/order cases; review clarified linear checked root access, repeated Copy-place budgets, SSA/root priority, source dedup positions and stable return-fact ordering. This is non-normative design evidence, with no implementation or registry change. Source reasons, trap/dispatch schema, compatibility, owner adoption and vertical tests remain gates; RFC 0039 stays Draft and P6-6 remains doing.
The [runtime/context candidate](../design/contract-runtime-and-context.md) specifies frame continuations, normal completion only after validation, free normalization before quantum checks, depth/fuel precedence, traced pending roots and exact additive failure context. Six ordinary groups pass 16 CLI runs at quantum 1; nine fixture variants pass GC-every-step record comparison (13 schedule cases, 26 interpreter runs). Six hypothetical schema components are explicitly unimplemented. Claude independently reproduced the CLI records and reviewed the rules; corrections fixed old/make/modify modes, race context and AIR-only byte-identity exploration. No normative/compiler/registry/bundle changes are made. Source reasons, compatibility/model adoption, RFC 0040 observations and full vertical runtime tests remain gates; RFC 0039 stays Draft and full P6-6 remains doing.
The [source rejection/compatibility audit](../design/contract-source-errors-and-compatibility.md) proposes eight new E7006 reasons and retains existing source type/name/transfer codes, error collection and mapped verifier obligations. Ten executed current-language AIR0 probes preserve full diagnostics and distinguish dependent undefined results from independent SSA errors; neither the historical parser nor contract semantics is executed. Owner selection of the module-state model, Q-055 compatibility/version policy and RFC representations remains necessary before normative integration and vertical implementation. No fresh Claude review was available for this increment. RFC 0039 remains Draft; P6-6 remains doing.
## P6-12 pointer-sized cast guidance (2026-10-09)
Public development feedback identifies u8 → usize and usize → u64 casts rejected without explaining the target-independent rule. Spec 02 §2 already excludes usize/isize from widen, including conversions that fit under every current target. The registered numeric_cast_modes hint now states that rule, keeping the original E7005 message/fields and checked/wrapping alternatives. Source/Quick Reference cast tables explain it too; no semantic widening extension is adopted. Pointer identity as casts now follow the same source rejection instead of leaking AIR E1002 without advice. Six rejection fixtures and an explicit checked/wrapping runtime case cover the rule; hosted advice tests pass 208 checks including source API parity and fixed-width identities. Bundle growth is measured in agent/README.md. Parameter-mutability and array-to-slice advice from the same feedback remain open work; no new dev/model experiment or repair-round benefit is claimed.
Validation of cast guidance: units/format checks and all 1,776 conformance cases pass. Comparison of 1,403 pre-existing source files changes only the registered hint; all 500 accepted lowerings remain byte-identical.
## P6-12 parameter and array-call advice (2026-10-09)
Public development feedback now has two narrowly registered candidates. E7001 at `mut name:` in a function parameter distinguishes value/local storage from an exclusive `mut<T>` contract, without choosing for the agent. An ordinary-call E7005 for a bare named, non-linear array with matching slice elements suggests the explicit `ref` or `mut` prefix required by the known parameter. Array expressions/projections, unlike elements, intrinsic/task operands and earlier name/move/arity failures are excluded. Generic/static specializations and imported calls retain the same rule and source provenance. Existing messages, payloads, code/location, accepted syntax/inference and loan lifetime remain unchanged. Prefix advice is not a verification claim: by-value parameter arrays still require an addressable local place.
The exclusivity/lifetime invariants, verifier transfer rules, explicit borrow creation/end and deterministic runtime are unchanged (spec 03; spec 15 §5). A positive source run covers mutable local copies, exclusive parameters and shared/exclusive slices; six rejection cases cover the triggers and nearby exclusions. Hosted advice tests pass 299 checks, including source API/package parity and generic/static repaired programs; whole-array integration passes 85 checks. Bundle growth is measured in agent/README.md. No language synonym, automatic conversion, semantic adoption or new dev/model experiment is introduced; the external repair-round measurement remains pending.
Validation: units/format checks and all 1,783 conformance cases pass; independent source-error collection passes 234 CLI checks. The six original trigger/exclusion diagnostics retain their complete envelopes after removing only the new candidate field.
Old/new comparison of 1,410 pre-existing source files preserves every diagnostic envelope after removing only the two new registered candidates, and all 501 accepted lowerings remain byte-identical. Advice is additionally emitted for the existing std/implicit_borrow rejection; its E7005 facts are unchanged. No fresh Claude review was available. P6-12 still awaits external development-run measurements.
## P6-1 runtime value-depth repair (2026-10-09)
The [Q-060 zero-materialization increment](../design/runtime-value-depth-audit.md#zero-materialization-repair) fills zeroable values iteratively, retaining field/element order, declaration identities, independent payloads, whole-local publication, allocator errors and fuel/scheduling. Unit cases cover 32,768 array/nominal levels with pending siblings and an allocation failure; a mixed AIR/source run pair checks initialization and subsequent writes. The original fuel-8 probe now returns normally and forty shallow mixed-type old/new records are identical. Follow-up probes independently confirm recursive local-load copying and sharing-preserving collection failures. Q-060 and Phase 6 remain open; no normative/bundle/feature/code change or new depth limit. No fresh Claude review was available.
Validation: all units/format checks, test-extended and 1,785/1,785 conformance cases pass; both new mixed-type cases also pass with collection before every instruction. A verified 32,768-level unit probe pins exact fuel 0–3 boundaries and instruction counts. Source/AIR semantics and bundle size are unchanged; the separate deep collector/copy failures are retained in Q-060.
## P6-1 runtime storage/value copying (2026-10-09)
The [Q-060 storage/value-copy increment](../design/runtime-value-depth-audit.md#storagevalue-copy-repair) replaces recursive aggregate/array copying with pending-sibling continuations. Every source payload occurrence remains independently copied; scalar/variant/declaration facts, identity handles, allocator errors and instruction/fuel counts remain unchanged. Deep unit cases cover 32,768 alternating levels, siblings/empty fields, duplicate payloads, identity leaves and failed local.store publication. A mixed Copy-record/enum/array AIR/source pair and 42 exact old/new run comparisons cover observable copying. The prior deep local.load probe now returns, while an added local.store independently reaches the remaining collector failure under its ordinary threshold. Units/format checks, test-extended and all 1,787 conformance cases pass. No normative/bundle/feature/code change or new depth limit; Q-060 and Phase 6 remain open. No fresh Claude review was available.
## P6-1 collector/result-copy depth repair (2026-10-09)
The [Q-060 sharing-preserving copy increment](../design/runtime-value-depth-audit.md#sharing-preserving-copy-repair) iterates payloads/cells/graphs and preserves forwarding identities, backing storage, projection paths, slice ranges, buffer metadata, mutex views and race shadows. Roots complete copying before execution resumes or a result escapes. Tests inspect cycles/sharing after freeing the old heap, fail each copier allocation request, traverse 32,768 internal payload/cell levels, and execute verified deep programmes under ordinary/per-step collection with exact fuel boundaries and live returned payloads. No normative/bundle/feature/code change or new depth limit is introduced.
Units/format checks, test-extended and all 1,787 ordinary conformance cases pass. Per-step collection passes 57 focused run cases plus 26 phase-3 run cases with stress 16; 146 old/new mixed-value and identity/schedule records are identical. The full per-step conformance run is still running at this checkpoint. Follow-up probes independently confirm valueBytes recursion on own.new and JSON output failure at std.json.Stringify's fixed nesting stack. Q-060 and Phase 6 remain open. No fresh Claude review was available.
## P6-1 runtime value-size depth repair (2026-10-09)
The [Q-060 runtime value-size increment](../design/runtime-value-depth-audit.md#runtime-value-size-repair) replaces recursive array-value queries with a constant-state checked factor and unchanged leaf accounting. Zero-sized leaves, true overflow, maximum enum payloads and dynamic-count ordering retain their existing meanings; heap/region/graph charges and failure/release rules are unchanged. Deep verified allocation tests pin fuel 0–6 and zero/one-byte grant boundaries under ordinary/per-step collection. A nested-quota AIR/source pair checks exact charges, zero-sized contents, allocation failure and restored authority.
Units/format checks, test-extended and all 1,789 ordinary conformance cases pass; the deep allocation and new pair also pass per-step collection. Ten new-pair quota records and 426 generated allocation-oracle runs match the old interpreter exactly. The earlier full per-step collector suite remains in progress. No normative/bundle/feature/code change or accepted-depth limit; Q-060 remains open for serialization, and Phase 6/contract gates remain open. No fresh Claude review was available.
## Runtime value JSON serialization (2026-10-10)
The [Q-060 JSON increment](../design/runtime-value-depth-audit.md#runtime-value-json-repair) emits nested values through explicit sequence continuations and one outer raw-value boundary, preserving field order, escaping, whitespace/options, integer bytes and opaque handles. Host traversal metadata is released on error or completion; Aji authority, payload ownership, fuel, collection and verifier rules are unchanged. Tests cover 112 option combinations, mixed 32,768-level codec values, outer nesting at the stringify boundary and writer/allocation failures. A new AIR/source enum/record/array result pair pins the existing run-record shape, and the original deep verified return now produces a complete record in deterministic and hosted profiles.
Units/format checks, test-extended and all 1,791 current ordinary conformance cases pass; the added pair also passes per-step collection in Debug. Forty-four old/new shallow records are byte-identical. The prior full Debug collector run has no completion result (785 passing records); its process disappeared, and a replacement full ReleaseSafe per-step run is in progress, retaining safety checks. No incomplete run is counted as a pass. There is no normative/bundle/feature/code change or new depth limit. Q-060's closing call-path audit and Q-059's uncached nominal queries remain open; the cache-free public runtime entry concern is inspection-only. Phase 6/contract gates remain open. No fresh Claude review was available.
## Cache-free nominal runtime size queries (2026-10-10)
The [Q-059 nominal size increment](../design/air-type-depth-audit.md#cache-free-nominal-accounted-size-queries) replaces recursive uncached sizing with temporary explicit continuations. The internal Zig query API now takes a host allocator and propagates metadata OutOfMemory separately from arithmetic overflow; runtime callers propagate it before authority charging. Cached reads, the static metric, quota/release behavior and instruction accounting are unchanged. The old direct 32,768-declaration query aborts; the new query returns one byte. Parsed, verified cache-free programmes at nominal depths 1,024 and 4,096 run successfully before and after, retaining six instructions; no old runtime failure at those depths is claimed.
Units/format checks, test-extended and all 1,791 ordinary conformance cases pass. Tests compare 7,168 shallow queries with an independent arithmetic oracle, fail every temporary metadata allocation and check cached success/null and partial-cache behavior. Fifty-four cached/cache-free quota/fuel/collection pairs (108 verified runs) have identical outcomes and instruction counts. All 370 public AIR checks preserve exact old/new exit/stdout/stderr. No normative/bundle/feature/code change or depth limit is introduced. The earlier full ReleaseSafe per-step suite remains in progress; Q-059's nominal property queries, Q-060's closing audit and Phase 6/contract gates remain open. No fresh Claude review was available.
Both new copy cases also pass with collection before every instruction; their shallow sharing-preserving GC behavior is covered separately from the retained deep collector failure.
## Cache-free nominal property queries (2026-10-10)
The [Q-059 property increment](../design/air-type-depth-audit.md#cache-free-nominal-property-queries) repairs all nine reproduced recursive uncached nominal queries. Public queries explicitly receive a compiler allocator and propagate OutOfMemory; temporary preparation uses the existing fixed points, while cached/terminal reads allocate nothing. Ownership, concurrency, verifier acceptance, runtime accounting and diagnostic facts remain unchanged. Deep queries, 18,432 independent-oracle comparisons, allocation cleanup and public generic-argument acceptance/rejection tests pass.
Units/format checks, test-extended and the 1,791-case property-engine conformance snapshot pass. All 370 AIR and 1,421 source CLI checks, plus 506 accepted lowerings, retain exact old/new outputs. Final full conformance after the public helper correction passes all 1,791 cases with exact corpus coverage. The earlier full ReleaseSafe per-step suite also remains in progress. No normative/bundle/feature/code change or depth limit is introduced; Q-059's closing audit, Q-060's closing validation and Phase 6/contract gates remain open. No fresh Claude review was available.
A subsequent read-only Claude review against the property base 897f538 found no defects in the classifications, worklist, cache preconditions or allocator/error lifetime. It did not build or run tests and did not observe the expanded suite. The helper-name wording and repeated-query preparation guidance are corrected; this does not review later source-parser changes.
## Source type-syntax parser (2026-10-10)
The [Q-059 source parser increment](../design/air-type-depth-audit.md#source-type-syntax-parser) replaces recursive type/argument parsing with explicit array and argument-list frames, preserving static function arguments, sibling order, split angle positions, syntax failures and slice repair candidates. Unit tests inspect deep mixed types and static arguments and fail parser metadata allocations. The old 16,384-array source crashes in parsing; the new parser allows formatting, while full checking confirms the next failure in `usesGenerics`. A deep invalid slice annotation now returns its original E7001 candidate instead of crashing. The existing generic guard is not imposed on monomorphic syntax.
Units/format checks and all 1,791 conformance cases pass with exact corpus coverage. Hosted grammar/advice suites pass 288/299 checks; formatter integration passes 6,072 checks over 1,467 public files. All 1,421 source checks and 506 accepted lowerings preserve exact old/new outputs, as do 156 targeted syntax/argument/error probes; deep formatting is idempotent. No normative/bundle/feature/code change or new acceptance limit is introduced. Q-059's source AST/closing audit, Q-060's closing validation and Phase 6/contract gates remain open. No fresh Claude review was available.
## Source generic-use detection (2026-10-10)
The [Q-059 generic-use increment](../design/air-type-depth-audit.md#source-generic-use-detection) visits immutable AST fields/payloads through explicit work entries, retaining the original markers and field/element order. Metadata OOM propagates and pending entries are released; monomorphic syntax gains no new depth limit. Independent shallow comparisons (387), deep positive/negative types/expressions/blocks and work-allocation failure tests pass. The earlier failing source now passes usesGenerics and confirms the next failure in lower.resolveType at 16,384 array levels; complete checking at 4,096 still accepts.
Units/format checks and generic/static-function CLI integration (32/25) pass. All 1,791 conformance cases pass with exact corpus coverage; all 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr. No normative/bundle/feature/code change or semantic flag is introduced. Q-059's source lowering/closing audit, Q-060's closing validation and Phase 6/contract gates remain open. Claude's property review does not cover this increment.
## Source annotation resolution (2026-10-10)
The [Q-059 annotation-resolution increment](../design/air-type-depth-audit.md#source-annotation-resolution) lowers anonymous source types with explicit continuations. Constructor-before-child and content-after-child checks preserve the old error priority and spans; nominal identity and syntax are unchanged. Tests cover 1,736 independent shallow comparisons, 32,768 mixed annotation levels, leaf rejection and allocation-error cleanup. Type-position/Copy-content integration passes 74/119 checks; all units/format checks and 1,791 conformance cases pass with exact corpus coverage. All 1,421 public source checks and 506 accepted lowerings retain byte-identical old/new exit/stdout/stderr.
The complete 4,096-array check still accepts; 16,384 now reaches the next confirmed native-stack failure in type_properties.firstInvalid. No normative/bundle/feature/code change or accepted-depth limit is introduced. Q-059's source property/closing audit, Q-060's closing validation and Phase 6 gates remain open. No fresh Claude review of this increment is claimed.
## Source anonymous property scans (2026-10-10)
The [Q-059 source-property increment](../design/air-type-depth-audit.md#source-anonymous-property-scans) makes syntax scanning and anonymous-array linearity iterative, retaining own_array priority, graph stops and nominal fixed points. The two complete 16,384-level source checks that previously aborted now accept; deep non-Copy content returns the original E7005. Tests cover 2,160 independent shallow anonymous comparisons, 32,768-level queries and zero work allocations on anonymous paths.
Units/format checks, Copy-content/generic CLI integration (119/32) and byte-identical old/new checks/lowerings (1,421/506) pass; all 1,791 conformance cases pass with exact corpus coverage. A separate 8,192-declaration source confirms the remaining linear/declaration stack failure before and after this increment. Named-source repair, source Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed.
## Source nominal property continuations (2026-10-10)
The [Q-059 nominal-source increment](../design/air-type-depth-audit.md#source-nominal-property-continuations) replaces native argument/declaration recursion with explicit continuations, retaining environment/path binding, ordered fields/payloads and cache generation rules. The previously crashing 8,192-Copy declaration check accepts; linear content returns E7005. Independent ordered-cache comparisons cover 4,613 roots (three queries each), while deep mixed/cyclic graphs and allocation-failure cleanup pass.
Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact coverage and byte-identical old/new checks/lowerings (1,421/506) pass. A separate invalid-atomic source confirms typeText stack failure at 65,536 array levels. Source Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed.
## Source type text repair (2026-10-10)
The [Q-059 source text increment](../design/air-type-depth-audit.md#source-type-text-repair) removes recursive and repeatedly copied ancestor strings, preserving exact spelling/source nominal names and resource feature discovery. Its internal fallible APIs propagate host OOM instead of generating shortened type facts or AIR. The formerly aborting deep invalid-atomic check returns one E7005 with the complete 655,362-byte found type.
Units/format checks, 3,696 independent shallow comparisons, deep mixed output and failed-allocation/cleanup tests pass. Repair-advice/nonvalue/static-function integration (299/635/25) and old/new source checks/lowerings (1,421/506) pass; all 1,791 conformance cases pass with exact corpus coverage. A correct 65,536-array parameter accepts; a 16,384-array struct member independently confirms remaining airType native-stack failure. Source-to-AIR repair, Ty/query closing checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed.
## Source-to-AIR type conversion (2026-10-10)
The [Q-059 conversion increment](../design/air-type-depth-audit.md#source-to-air-type-conversion) replaces native recursion with an output-target cursor, preserving source/AIR type shape, constructor allocation order and error publication. Structs with 16,384/65,536 array levels now pass complete checking. Tests cover 2,352 independent shallow comparisons, 65,536-level construction without work allocation, and per-node OOM/order/cleanup equivalence.
Units/format checks, nominal/Copy-content/static-function integration (110/119/25), all 1,791 conformance cases with exact coverage and old/new checks/lowerings (1,421/506) pass. A separate return-equality input confirms the next failure in Ty.eql at 65,536 array levels. Equality/closing query checks, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code change or accepted-depth limit is introduced; no fresh Claude review is claimed.
## Source type equality (2026-10-10)
The [Q-059 equality increment](../design/air-type-depth-audit.md#source-type-equality) removes native recursion from Ty.eql without allocation or changed type identity. Independent shallow pair comparisons and separate deep trees cover equal contents and outer/interior/leaf differences. Complete 65,536-level equal returns accept; unequal leaves return one E7005 with exact full types and source position. Units/format checks and all 1,791 conformance cases pass with exact coverage; all 1,421 source checks and 506 accepted lowerings retain exact old/new exit/stdout/stderr. Closing source-query inventory, Q-060 validation and the independent Phase 6 gates remain open. No normative/bundle/feature/code or accepted-depth limit changes; no fresh Claude review is claimed.
## Remaining source linear queries (2026-10-10)
The [Q-059 query increment](../design/air-type-depth-audit.md#remaining-source-linear-queries) makes array linearity and signature feature discovery iterative, retaining the existing module-sized guard and prepared cache contract. Independent shallow comparisons, deep helper snapshots, units/format checks, source linear/nominal CLI integration (49/110) and all 1,791 conformance cases with exact coverage pass. All 1,421 source checks and 506 accepted lowerings retain exact old/new exit/stdout/stderr. A separate 16,384-level source zero probe confirms remaining Lowerer.zeroValue stack exhaustion before reaching its implemented E7006/zero_not_zeroable leaf rejection. Zero emission, specialization/call-path inventory, Q-060 validation and Phase 6 gates remain open. No source zeroability, normative/bundle/feature/code or accepted-depth limit changes; no fresh Claude review is claimed.
## Source SSA zero emission (2026-10-10)
The [Q-059 zero increment](../design/air-type-depth-audit.md#source-ssa-zero-emission) makes array zero generation iterative, preserving the implemented leaf classification and constant/splat ordering. Deep checks at 16,384/65,536 levels now return one E7006/zero_not_zeroable without stderr. Units/format checks, independent shallow emission/error comparisons, exact 1,024-level helper output, allocation failures, reason/independent-error integration (229/234) and all 1,791 conformance cases with exact coverage pass. All 1,421 source checks and 506 accepted lowerings retain exact old/new exit/stdout/stderr. Twelve generated programs retain exact lowering and 46 old/new fuel-boundary records with independently checked values. Specialization/call-path inventory, Q-056 policy, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code or accepted-depth limit changes; no fresh Claude review is claimed.
## Composed specialization identity (2026-10-10)
The [Q-059 identity increment](../design/air-type-depth-audit.md#composed-specialization-identity) repairs native failures on tiny expanding-substitution sources. Key emission is iterative; canonical bytes, postorder size/error-span checks, reuse/names and all existing specialization limits remain unchanged. Two permanent conformance cases and hosted CLI checks retain one E7006/implementation_limit at the call site across all rejection entry points.
Units/format checks, shallow/deep key-boundary and OOM tests, generic/static-function integration (42/25), and old/new checks/lowerings over the pre-existing source corpus (1,421/506) pass. The full 1,791-case snapshot plus the two focused additions cover all 1,793 current conformance files exactly. Closing call-path inventory, Q-056 policy, Q-060 validation and Phase 6 gates remain open. No normative/bundle/feature/code or accepted-depth limit changes; no fresh Claude review is claimed.
## Type-depth closing audit (2026-10-10)
Q-059 is resolved for the [compiler type-traversal inventory](../design/type-traversal-inventory.md). The final repair removes a confirmed `typeOfNoFail` failure reached through shallow field expressions; complete checks accept 16,384/65,536 nested field-array levels. At this historical checkpoint the query retained its type classification and OOM-to-null contract; the host-OOM follow-up below supersedes that error policy. Independent shallow/deep/allocation tests, units/format checks, all 1,793 conformance cases with exact coverage, nominal CLI integration (130 checks) and byte-identical old/new source checks/lowerings (1,423/506) pass.
This closes type descent, not arbitrary expression/statement recursion (inspection-only Q-061), Q-056 policy, Q-060's unfinished full per-step GC validation or Phase 6 exit review. No normative/bundle/feature/code or acceptance-limit changes; Claude's earlier nominal-property review does not cover these later frontend increments.
## Runtime error-exit cleanup (2026-10-10)
The [Q-060 closing inspection](../design/runtime-value-depth-audit.md#closing-runtime-paths-and-error-exit-cleanup) repairs an execution-arena leak when host OOM interrupts execution or result copying. Deferred cleanup retains the public API, successful output lifetime, fuel, quotas and collection safe points. Exhaustive caller/heap allocator failures pass under ordinary/per-step collection; units, format checks, test-extended, all 1,793 ordinary conformance cases with exact coverage and 29 exact old/new fuel/value CLI pairs pass.
The earlier Debug full GC process is also still live, as is ReleaseSafe; host namespace inspection corrects the previous termination inference. Conformance now flushes each completed result, and an additional focused std GC run has live progress. These are unfinished validation, not full passes. Q-060 and Phase 6 exit gates remain open; no normative/bundle/feature/code/acceptance-limit change or new Claude review is claimed.
## Source unary parser depth (2026-10-10)
[Q-061 probes](../design/source-expression-depth-audit.md) confirm native-stack aborts without JSON: 1,024 `not` prefixes fail in lowering, while 16,384/65,536 fail earlier in parsing. Direct unary-prefix parsing now uses explicit continuations, preserving the grammar, borrow/place boundary, AST spans, exact failures and host OOM propagation. Independent shallow-oracle (448 cases), 32,768 mixed-prefix, deep missing-operand and allocation-failure tests pass. Syntax-only formatting works through 65,536 prefixes; this does not close the confirmed lowering failure.
Build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 312 grammar CLI checks and 6,078 formatter checks pass. Old/new public source check/lower output remains identical (1,423/506). No normative/reference bundle, feature, code or acceptance-limit change; P6-2, Q-061's remaining expression/statement paths, Q-060 GC validation and Phase 6 exit review remain open. No fresh Claude review covers this increment.
## Source unary lowering and storage marking (2026-10-10)
[Q-061 unary operand lowering](../design/source-expression-depth-audit.md#unary-lowering-and-addressability-continuations) now uses explicit continuations for not/neg/deref/cast, preserving pre-operand negative zeros, the signed-minimum literal rule, operand/target checks, atomic-load diagnostics and instruction/span order. A separate confirmed storage-marking failure is repaired by a block/statement/expression/root worklist retaining the existing traversal order and storage policy. Generated full scalar checks/lowerings pass through 65,536 nodes; deep invalid direct dereferences retain inner E7005. Both worklists propagate host OOM without diagnostics or public partial AIR. No verifier/runtime/ownership/format/bundle/feature/code/acceptance-limit change.
Independent unary/addressability oracles, 32,768-node cases and allocation cleanup tests pass. Final build/units/format checks and all 1,793 ordinary conformance cases with exact coverage pass, as do 114 expression-depth, 635 non-value, 33 atomic-access, 312 grammar and 6,078 formatter CLI checks. Old/new public checks/lowerings (1,423/506) and 47 deterministic/hosted fuel/value records are exact. A new full check independently confirms the remaining 16,384-dereference query failure beneath a cast in peekType. Q-061's general queries, other expression/statement and generic paths remain open, as do Q-060's full per-step validation and Phase 6 exit review. No fresh Claude review covers this increment.
## Source expression type queries (2026-10-10)
The [Q-061 query increment](../design/source-expression-depth-audit.md#expression-type-query-continuations) replaces expression/built-in result recursion with explicit continuations, retaining classification, lazy fallback and callee priority. Its callee callbacks build qualified paths iteratively with one complete string. At this historical checkpoint, queries returned unknown on output/continuation OOM; the host-OOM follow-up below supersedes that policy. Host allocation counts need not match. No normative/bundle/feature/code/acceptance-limit or runtime/ownership change.
Independent shallow descent comparisons (703), deep structural/built-in/fallback cases, 65,536-field path construction and allocation cleanup tests pass. Final build/units/format checks and all 1,793 ordinary conformance cases with exact coverage pass, as do 139 expression-depth, 635 non-value, 33 atomic-access and 6,078 formatter CLI checks; old/new public checks/lowerings remain exact (1,423/506). The formerly crashing cast/dereference source now returns its inner E7005. A separate unsuffixed-binding probe accepts 1,024 negations but confirms the next native failure in useIn at 16,384. Q-061's expected-use, other expression/statement and generic paths, Q-060's full per-step validation and Phase 6 exit review remain open. Claude's earlier Q-059 property review does not cover this increment.
## Source expected-use queries (2026-10-10)
The [Q-061 expected-use increment](../design/source-expression-depth-audit.md#expected-use-query-continuations) replaces mutual expression/statement/block query recursion with explicit requests. Deferred comparison/shift/for hints preserve lazy search order; the outer rest cursor, top-level let rebinding barrier, cast hint removal and skipped kinds retain their original policy. The initial metadata-OOM-to-unknown policy is superseded by the host-OOM follow-up below; no new inference, normative/bundle/feature/code/acceptance-limit or runtime/ownership rule is introduced.
Independent shallow comparisons (967), 32,768-level unary/mixed/block helpers, deferred-hint allocation traps and worklist-OOM cleanup tests pass. Final build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 186 expression-depth, 635 non-value and 234 independent-error CLI checks pass; old/new public checks/lowerings remain exact (1,423/506). The previously crashing inferred-binding source accepts through 65,536 negations, while missing context retains E7007. Follow-up probes confirm separate native failures at 1,024 levels in binary lowering, parenthesized parsing and generic expression transformation. Q-061's remaining inventory, Q-060's full per-step validation and Phase 6 exit review remain open. No fresh Claude review covers this increment.
## Source binary operand lowering (2026-10-10)
The [Q-061 binary increment](../design/source-expression-depth-audit.md#binary-operand-lowering-continuations) shares scalar continuations with unary lowering, eliminating native re-entry on alternating operator trees. Eager operand type/error priority, instruction/span/name order and boolean RHS/join construction are retained; runtime short-circuit behavior and fuel remain unchanged. Worklist OOM propagates without public partial AIR. No normative/bundle/feature/code/acceptance-limit or ownership/runtime rule changes.
Independent binary/wrapper/context comparisons (6,048), deep left/right/mixed/boolean helpers and exact failed-allocation block prefixes pass. Build/units/format checks, all 1,793 ordinary conformance cases with exact coverage, 360 expression-depth, 635 non-value and 234 independent-error CLI checks pass; old/new public checks/lowerings remain exact (1,423/506). Arithmetic checks/lowerings accept through 65,536 operations. Boolean chains accept at 1,024; at 16,384 they reach the existing E5101 block limit (`max: 16384`, `found: 32769`), rather than aborting. Current probes retain separate parenthesized/generic failures at 1,024 levels; their callbacks and other expression/block paths still need repair/audit. Q-061, Q-060's full per-step validation and Phase 6 exit review remain open. No fresh Claude review covers this increment.
## Source query host-OOM follow-up (2026-10-10)
Claude's relayed read-only review covers the five Q-061 increments through
6945b51. It found no grammar/span/query/error/emission/CFG divergence, but
identified host OOM erased into unknown and subsequently reported as E7007.
The [follow-up](../design/source-expression-depth-audit.md#external-review-and-host-oom-follow-up) reproduces this with a recovering one-shot allocation failure
and makes the query/callback closure fallible. Unknown remains optional; lazy
lookup and source diagnostics without OOM are unchanged. No normative, bundle,
feature, code, acceptance-limit or runtime rule change.
The audit corrects worklist memory claims: buffers allocated in the caller arena
remain until arena destruction. It also lists the remaining non-scalar parser/
lowerer and liveness/read/assignment paths explicitly. Build/units/format
checks, all 1,793 ordinary conformance cases with exact coverage, 360
expression-depth and 234 independent-error CLI checks pass. Recovering failures
are covered at ten callers, twelve callbacks and every direct allocation in
three public-lowering fixtures; existing worklist/array-output failure loops
now assert OOM propagation and cleanup. Frozen old/new public checks/lowerings
remain exact (1,423/506). Generic transformation and parenthesized parsing still
have confirmed depth failures; Q-061, Q-060's full per-step validation and the
Phase 6 exit gates remain open. The existing review does not cover this repair.
## Source generic AST depth (2026-10-10)
The [Q-061 generic increment](../design/source-expression-depth-audit.md#generic-ast-transformation-continuations) replaces reflective expression/statement/block
cloning with typed work entries, retaining traversal/error/instance order, spans,
Copy-transfer and static-function/worker handling. Callee and constructor
callbacks retain their original ordering; qualified paths are built iteratively
with one complete allocation. Guarded type/instantiation re-entry retains its
existing limits. OOM propagates without public partial AST; buffers and nodes
retain caller-arena lifetime. No normative/bundle/feature/code/acceptance-limit
or ownership/runtime rule changes.
Independent shallow comparisons (1,760 expression contexts plus binding/
statement fixtures), deep mixed/callee/block/else-union and deepest-error helpers,
path/instance/worklist allocation failures and public recovering specialization
failures pass. Build/units/format checks, 497 expression-depth, 42 generic and 25
static-function CLI checks pass; frozen old/new public checks/lowerings remain
exact (1,423/506). All 1,793 ordinary conformance cases pass with exact coverage.
Full generic
scalar checks/lowerings accept through 65,536; deep qualified unknown calls
return exact E7002. Follow-up probes retain separate parser failures at 1,024
parenthesized/mixed-call levels and confirm Parser.exprPath failure at 16,384
qualified-variant fields. Q-061's remaining inventory, Q-060 validation and Phase
6 exit gates stay open. No external review covers this increment yet.
## Source parser constructor paths (2026-10-10)
The [Q-061 parser-path increment](../design/source-expression-depth-audit.md#parser-qualified-constructor-paths)
removes native recursion and intermediate prefix copies from Parser.exprPath.
Root classification, spelling, generic arguments, spans and syntax/error
priority remain unchanged; host OOM propagates separately from source errors.
Frozen baseline enum/struct constructor probes abort at 16,384 fields; repaired
CLI probes return exact E7002 through 65,536. Independent shallow path, deep
parser/spelling and failed-allocation cleanup tests cover this callback.
Build/units/format checks, all 1,793 ordinary conformance cases with exact
coverage and 577/312 expression-depth/grammar CLI checks pass; frozen old/new public checks/
lowerings remain exact (1,423/506).
No normative/bundle/feature/code/acceptance-limit or runtime/ownership rule
changes. Parenthesized and mixed-call parsing failures, remaining expression/
statement walks, Q-060 validation and Phase 6 exit gates remain open. This
increment has no external review yet.
## Source shared expression parsing (2026-10-10)
The [Q-061 parser increment](../design/source-expression-depth-audit.md#shared-expression-parser-continuations)
shares explicit precedence/cast/unary/postfix/primary continuations with groups,
call arguments, arrays, indices and struct fields. Grammar, spans, token/error
order and call/advice scopes are preserved. Reused work storage and stable
driver frames support native callback re-entry without retaining AST pointers
into scratch; host OOM remains separate from source diagnostics. No normative/
bundle/feature/code/acceptance-limit or ownership/runtime rule changes.
Independent shallow comparisons (4,160), 32,768 mixed levels with exact spans
and leaf E7001 advice, poisoned scratch/re-entry and recovering/persistent OOM
tests pass. Build/units/format checks, all 1,793 ordinary conformance cases with exact
coverage and 737/312/234 depth/grammar/independent-error CLI checks pass. The
formatter passes 6,078 checks; frozen old/new public checks/lowerings remain
exact (1,423/506). Grouped source checks reach 65,536; mixed-call formatting reaches
65,536. Block/if regression probes preserve accepted baseline output, including
256 levels; explicit-return forms improve from baseline aborts to formatting
at 256. These are bounded probes, not a whole-parser depth guarantee. At this
checkpoint, full mixed-call checking confirmed a lowerer `call` abort at 1,024; control/block
parsing, remaining expression/statement/liveness walks, Q-060 validation and
Phase 6 exit gates remain open. No external review covers this increment yet.
### Ordinary-call depth increment
The [Q-061 ordinary-call increment](../design/source-expression-depth-audit.md#ordinary-call-argument-continuations)
shares argument continuations with scalar operands. Signature/arity/origin
checks, left-to-right consumption, exact argument checks, temporary endings,
retained parents and instruction/span/CFG order are preserved. Stable states
live in the caller's arena; recovering/persistent OOM remains a host error and
arena backing is freed. No semantic/bundle/feature/code/limit changes.
Independent shallow/deep call and OOM tests, build/units/format checks and all
1,793 ordinary conformance cases with exact coverage pass. Call-related CLI
suites pass 133/85/42/25/635/234 checks. Frozen public checks/lowerings remain
exact (1,423/506). Bounded native `assert`/block/if probes
retain exact baseline outputs through 256; this does not claim whole-callback
safety. Direct/mixed/generic call checks and lowerings now reach 65,536 with
exact bounded values/fuel; 262 focused depth CLI checks pass. The mixed-call
abort at 1,024 is repaired, while a separate alternating
struct/field program still aborts there in both binaries. Remaining Q-061
callbacks/walks, Q-060 validation and Phase 6 exit gates remain open. No fresh
external review covers this increment.
### Struct/value-field depth increment
The [Q-061 struct/value-field increment](../design/source-expression-depth-audit.md#struct-construction-and-value-field-continuations)
shares constructor fields and value receivers with scalar/call continuations.
Declaration-order consumption, duplicate/unknown/missing-field priority,
receiver-first queries, deferred annotation checks and nominal/static/slice
length rules are preserved. Stable states remain in the caller's arena; host
OOM never becomes a source diagnostic, and backing failures free that arena.
Borrow/place helpers retain their existing rules and native callbacks.
Independent shallow (864) and 32,768-level mixed comparisons, recovering/
persistent OOM tests, build/units/format and all 1,793 ordinary conformance
cases with exact coverage pass. Call/ownership CLI checks (635/49/348/133/302/
152/42/234) and frozen public check/lower parity (1,423/506) pass. Bounded native
assert/block/if probes remain exact through 256. The focused depth CLI suite
passes 302 checks: pure/length/generic chains accept at 65,536; mixed chains
accept at 32,768 and reach the existing instruction limit at 65,536. The
struct/field abort at 1,024 is repaired; nested array literals still abort at
4,096 in both binaries.
No normative/bundle/feature/code/limit or ownership/runtime rule changes.
Remaining Q-061 callbacks/walks, Q-060 validation and Phase 6 exit gates remain
open. Independent read-only Claude core/follow-up reviews found no concrete
defects; neither ran tests or established whole-Q-061 completion.
### Array-expression depth increment
The [Q-061 array increment](../design/source-expression-depth-audit.md#array-list-and-repetition-continuations)
shares lists/repetitions with scalar/call/struct/field continuations, preserving
inference, explicit consumption, check order, spans, loans, Copy rules and OOM.
Independent comparisons (1,036), deep bounded-type/sibling/error and OOM tests,
build/units/format, exact ordinary conformance coverage and six targeted CLI
suites pass. The pure-list failure at 4,096 is repaired; enum-payload/call
alternation still aborts at 256 before and after. Focused depth CLI checks
(246) and frozen public check/lower parity (1,423/506) pass. Read-only Claude
core/follow-up reviews found no production defects; fixture gaps were corrected.
Q-061, Q-060 and Phase 6 remain open;
no normative/format/feature/code/bundle/limit or ownership/runtime change.
### Enum-payload depth increment
The [Q-061 enum increment](../design/source-expression-depth-audit.md#enum-payload-continuations)
shares payloads with scalar/call/aggregate continuations, preserving lookup,
arity, annotation/consumption/check order, spans, loans, empty/built-in rules
and OOM. Independent comparisons (720), deep sibling and allocator tests,
build/units/format, exact final conformance coverage and public check/lower
parity pass. Scoped Claude reviews found no semantic defects. The former
256-level abort is repaired; nested assert still aborts at 1,024 before and
after. Initial focused CLI checks (331) and final supplementary checks (66)
pass. Q-061, Q-060 and Phase 6 remain open. No normative/format/feature/
code/bundle/limit or ownership/runtime change.
### Boolean builtin operand depth increment
The [Q-061 boolean builtin increment](../design/source-expression-depth-audit.md#boolean-builtin-operand-continuations)
shares assert/assume operands with the expression driver, preserving arity,
non-consuming evaluation, type/error spans, unsafe registration and emission.
Caller-arena lifetime and host OOM separation remain explicit. Exact ordinary
conformance coverage (1,793), public check/lower parity (1,423/506), targeted
nonvalue/linear/independent-error checks (635/49/234), and 282 focused depth
checks pass. Expanded units and 69 supplemental checks pass; read-only Claude core/follow-up
reviews found no production defect. Final span/counter unit checks pass. Own/region argument callbacks still abort at 1,024 in
both binaries. No semantic/depth-limit change; Q-061, Q-060 full GC validation
and Phase 6 exit gates remain open.
### Consuming ownership builtin depth increment
The [Q-061 consuming builtin increment](../design/source-expression-depth-audit.md#consuming-ownership-builtin-continuations)
shares own.take/free and region.destroy operands with the expression driver.
Arity, explicit-name transfers, type/error priority, emission and host OOM
remain unchanged; buffers retain caller-arena lifetime. Corrected OOM and
expanded units, all 1,793 ordinary conformance cases, public check/lower parity
(1,423/506), targeted linear/nonvalue/inferred-content suites (49/635/302) and
351 frozen-core depth checks pass. 108 formatted-rejection checks pass; read-only Claude core/follow-up reviews
found no production defect. Final `own<bool>` CFG unit comparisons pass. At
that consuming checkpoint atomic-new/take pairs and task.join still aborted
at 1,024. No semantic/depth-limit change; Q-061, Q-060 full GC
validation and Phase 6 exit gates remain open.
### Atomic operand depth increment
The [Q-061 atomic operand increment](../design/source-expression-depth-audit.md#atomic-operand-continuations)
shares new/take and ordinary store/RMW operands with the expression driver,
retaining arity, consuming rules, cell/ordering/type priority, emission and
borrow endings. Load/fence and multi-result binding retain their existing
paths. Build/units/format, all 1,793 ordinary conformance cases, public
check/lower parity (1,423/506) and targeted checks (33/635/234) pass. Focused
depth validation passes 270 checks in two subset runs (57/213), through 65,536
for pairs, temporary-loan updates and exact rejections. Mixed chains reach the
existing E5101 instruction limit at 65,536; runtime/fuel is checked through
1,024. Read-only Claude core/follow-up reviews found no production defect.
At that atomic checkpoint task.join still aborted at 1,024. No semantic/order-default/depth-limit change; Q-061, Q-060
full GC validation and Phase 6 exit gates remain open.
### Task join operand depth increment
The [Q-061 task.join increment](../design/source-expression-depth-audit.md#task-join-operand-continuations)
uses consuming continuations, preserving arity/move/type priority, scalar/void
emission, spans, loans and host OOM. Build/units/format, all 1,793 ordinary
conformance cases, public check/lower parity (1,423/506), lifetime/related/CFG
checks (188/409/146) and 522 focused CLI checks pass. Valid scalar/void call
operands and rejected join chains reach 65,536; runtime/fuel reaches 1,024.
Read-only Claude core/follow-up reviews found no production or fixture defect.
At that join checkpoint alternating join/spawn still aborts at 256 before/after; its
argument callbacks and other walks keep Q-061 open. No semantic/depth-limit
change; Q-060 full GC and Phase 6 exit gates remain open.
### Task spawn argument depth increment
The [Q-061 spawn increment](../design/source-expression-depth-audit.md#task-spawn-argument-continuations)
preserves scope/worker/arity and per-argument checking, explicit consumption,
bound loans, CFG/emission and host OOM through shared continuations.
Build/units/format, exact ordinary conformance coverage, public check/lower
parity and lifetime/related/CFG/static-worker checks pass. The focused gate
completes 497 distinct CLI checks across an interrupted first run and a
terminal-success remaining-family run. Scalar/pair checks and all-family
lower/fmt AIR parity reach 65,536; mixed checks reach 32,768, then existing
E5101 at 65,536. Runtime/source-AIR/fuel checks reach 1,024; rejected family
positions reach 65,536; formatted accepted checks are repeated only through
1,024. Runtime uses quantum one/seed 7, with extra seeds 0/1 through 16.
Read-only Claude core/final follow-up reviews found no production or fixture
defect within their recorded scope. At this spawn checkpoint nested mutex.make/take aborts at
256/1,024 before/after and is next. Remaining graph/place/control/liveness and
multi-result callbacks keep Q-061 open; no semantic/depth-limit change. Q-060
full GC and Phase 6 exit gates remain open.
### Mutex make/take operand depth increment
The [mutex increment](../design/source-expression-depth-audit.md#mutex-maketake-operand-continuations)
preserves consuming/content/type priority, explicit moves, spans, loans,
emission and host OOM with the existing driver. Build/units/format and 310
focused CLI checks pass; scalar check and original/formatted lower reach
65,536, mixed check reaches 32,768 then existing E5101. Runtime/source-AIR/
fuel and formatted accepted checks reach 1,024; rejected positions reach
65,536. Lifetime/related/CFG suites and all 1,793 ordinary conformance
files with exact coverage and public frozen check/lower parity (1,423/506)
pass over `tests/conformance/**/*.aji`. Read-only Claude core/final reviews
found no production or fixture defect within their recorded scope. The filename-only follow-up subset passes 48 checks. At this mutex checkpoint index operands abort
at 1,024 before/after; other callbacks/walks, Q-060 and Phase 6 remain open.
No semantic or depth-limit change.
### Scalar index operand depth increment
The [index operand increment](../design/source-expression-depth-audit.md#scalar-index-operand-continuations)
preserves base/type/operand priority, usize hints, bounds facts, unchecked
state, loans, load/end order, spans and host OOM. Build/units/format and
store-mode/array-argument/lifetime/CFG suites pass. Exact ordinary conformance
coverage (1,793) and frozen public parity (1,423/506) pass. The original focused CLI run
passes 318 checks; both families check through 32,768 then reach existing
E5101 at 65,536. Original/formatted lower reaches 65,536; runtime/fuel and
repeated formatted accepted checks reach 1,024. Separate fuel follow-up passes
30 calls (10 lower, 20 source/AIR exhaustion); CFG/deref/proven contexts pass
28. These overlapping subsets do not establish a full current expression-suite
run. Read-only Claude core/final reviews found no production defect and their
fixture/wording suggestions are covered. The recorded nested-array base-index
probe still aborts at 1,024 before/after; place/range/borrow,
control/liveness and other paths, Q-060 and Phase 6 remain open. No semantic or
new depth-limit change.
### Raw place base depth increment
The [raw-place increment](../design/source-expression-depth-audit.md#raw-place-base-continuations)
repairs the recorded nested-array base failure at 1,024. Iterative field/index
projections preserve borrow modes/parents/ends, spans, field/bounds error
priority, range order, facts and unchecked selection. One ancestor list
replaces repeated full-list copies; caller-arena lifetime and host OOM
propagation remain explicit.
All 1,793 ordinary conformance cases, exact public check/lower parity
(1,423/506), store/array-argument/lifetime/CFG suites and 159 new focused CLI
calls pass. Expanded units pass; scoped read-only Claude core/final reviews found no
production defect. Documentation scope corrections are recorded in the audit. The whole accumulating expression-depth suite is not
claimed. Block/if parsing still aborts at 1,024 before/after; other callbacks
and liveness/read/assignment scans, Q-060 full GC validation and Phase 6 exit
review remain open. No normative, feature, bundle or accepted-depth change.
### Shared control parser depth increment
The [shared control parser](../design/source-expression-depth-audit.md#shared-control-parser-continuations)
uses one expression/control driver for block/statement, if/else-if, match/arms,
select, loops, scopes, shield and lock. Grammar, AST/spans, error/repair advice,
statement/tail boundaries and scoped state retain their former behavior; OOM
propagates without diagnostics or public partial AST. Unused entry wrappers and
multi-frame machinery are removed. No semantic/feature/bundle/depth-limit change.
Build/format, frozen public check/lower parity (1,423/506), grammar (312),
formatter (6,078), independent-error (234), repair-advice (299) and 127 new
focused CLI calls pass. Final expanded/follow-up units and all 1,793 ordinary
conformance cases with exact unique coverage pass. Arena backing measurements
are informational, include tokens/AST/work/slack, and do not assert efficiency
or a memory bound; the audit records the large mixed stress peak and separate
hosted RSS measurement. Read-only Claude core/follow-up/final reviews found no
production defect within their scoped inspections; they ran no tests. Parser-only coverage is distinguished from bounded lower/runtime
coverage and from the unrun whole accumulating expression-depth suite.
Full block/if checking at 1,024 now reaches a confirmed lowerer stack failure.
Q-062 logs the independently reproduced existing parenthesized-statement
boundary discrepancy. Q-061 lowering/control/liveness, Q-060 full per-step GC
validation and Phase 6 exit gates remain open.
### Pruned-SSA liveness depth increment
The [liveness increment](../design/source-expression-depth-audit.md#pruned-ssa-liveness-continuations)
replaces recursive read/assign/After walks with one reused allocator-explicit
workspace, preserving join sets, kills, sibling exclusion, loop scans, spans
and rest frames. Host OOM does not become a liveness fact or diagnostic.
Spec, verifier/runtime, AIR/features, syntax, bundles and depth limits stay
unchanged.
Build/format, exact ordinary conformance coverage (1,793), frozen public
check/lower parity (1,423/506), lifetime/CFG/independent-error/advice suites and
418 new CLI calls pass, including original/formatted AIR through 65,536 and
runtime/fuel through 1,024. Final expanded units pass (332/332).
Scoped read-only Claude reviews found no production divergence and ran no
tests. Deep direct-query tests are distinguished from full control lowering;
repeated nested-loop scans retain a quadratic worst case. Nested-block checks
still fail in `blockBodyWant`/`expr`: shared control lowering, other callbacks,
Q-060 full per-step GC and Phase 6 exit review remain open.
## Phase 6 exit review (2026-10-13)
Exit criterion (all reference programs and `examples/` authored as `.aji` and passing the corpus through the frontend): met. All five source/AIR reference pairs and every example pass; 1,793/1,793 conformance cases, unit tests and `zig fmt --check` pass at `f419063`; source construct coverage is 121/121 (519 run/accept, 904 reject tests). Codex's iterative lowering of block/if/match/select control is committed (`f419063`); its state-equivalence test tolerates the frozen reference's leaked arm scope on error exits, which is unobservable because `function()` resets scopes.
Not met and deferred, not claimed: P6-6 (contracts, RFC 0039 Draft) becomes P6-13 and P6-7's literal same-code criterion (97/206 verified; 45 E7xxx analogues, one source-early analogue and 63 AIR-only cases do not meet it, Q-053) becomes P6-14. Q-060 (full per-step GC validation) is closed (2026-10-14, composite coverage 1,793/1,793) and Q-063 (superlinear control lowering) remains open as hardening, outside the exit criterion. Q-061's native-stack-abort defect is [closed with explicit probe-coverage limitations](../design/source-expression-depth-audit.md#closing-observation-and-performance-limitation-2026-10-13). The exit rescoping was proposed by the agent and confirmed by the owner on 2026-10-13.
+2 -2
View File
@@ -127,7 +127,7 @@ RFC 0021 records invariants, diagnostics, compatibility, complete validation and
Explicit function/struct/enum generics specialize deterministically to ordinary AIR. Structural Copy/Send/Share/Freeze/Local constraints, header checking, nominal identity, direct-import visibility and fixed expansion limits are specified by spec 15 §15 and RFC 0022. Every concrete specialization passes ordinary ownership/effect/task verification; unused bodies make no validity promise for future types. The compiler registry adds safe Copy-only std.option/std.result with classification helpers. No allocation, implicit cleanup, AIR opcode or authority is added. Explicit function/struct/enum generics specialize deterministically to ordinary AIR. Structural Copy/Send/Share/Freeze/Local constraints, header checking, nominal identity, direct-import visibility and fixed expansion limits are specified by spec 15 §15 and RFC 0022. Every concrete specialization passes ordinary ownership/effect/task verification; unused bodies make no validity promise for future types. The compiler registry adds safe Copy-only std.option/std.result with classification helpers. No allocation, implicit cleanup, AIR opcode or authority is added.
The finite-layout E1003 check now traverses arrays, repairing a prior verifier gap with source/AIR fixtures. Existing source `from`-returns remain unimplemented and are logged as Q-034 rather than given an invented lifetime/binding contract. RFC 0022 records complete validation and source/AIR budget measurements. Next is STD-5: the independent linear_aggregates vertical feature, required before containers or option/result can own resources. P6-4's generic/structural specialization task is implemented on this branch; this does not complete Phase 6. The finite-layout E1003 check now traverses arrays, repairing a prior verifier gap with source/AIR fixtures. At STD-4, source `from`-returns remained unimplemented; P6-11 subsequently supplies the explicit lifetime/binding contract (RFC 0036 Proposed). RFC 0022 records complete validation and source/AIR budget measurements. Next is STD-5: the independent linear_aggregates vertical feature, required before containers or option/result can own resources. P6-4's generic/structural specialization task is implemented on this branch; this does not complete Phase 6.
## STD-5 verification ## STD-5 verification
@@ -193,4 +193,4 @@ All 1079 conformance cases pass, including 18 path fixtures. All path runtime fi
The owner requested a sufficient intermediate std stage, integration of the work branch and resumption of language development. STD-0 through STD-7 provide nineteen compiler-pinned safe source modules: math/bytes/hash, UTF-8/hex/Base64/formatting, option/result, Vec/Deque/U64Map/general HashMap/HashSet/BinaryHeap, bounded std.io, owning buffered file adapters and lexical paths. The branch also supplies explicit modules/generics, whole-value linear aggregates/initialized buffers, pure error values and exact static callable contracts, through source/AIR/verifier/interpreter and tests where applicable. RFCs 0016–0035 are adopted and implemented; their rules are integrated into spec/reference in the same merged change. The owner requested a sufficient intermediate std stage, integration of the work branch and resumption of language development. STD-0 through STD-7 provide nineteen compiler-pinned safe source modules: math/bytes/hash, UTF-8/hex/Base64/formatting, option/result, Vec/Deque/U64Map/general HashMap/HashSet/BinaryHeap, bounded std.io, owning buffered file adapters and lexical paths. The branch also supplies explicit modules/generics, whole-value linear aggregates/initialized buffers, pure error values and exact static callable contracts, through source/AIR/verifier/interpreter and tests where applicable. RFCs 0016–0035 are adopted and implemented; their rules are integrated into spec/reference in the same merged change.
This intermediate gate is sufficient to resume language work. It does not mark Std 0.1 complete: filesystem gaps, args/env, time/random wrappers, structured logs and CLI/storage exit examples remain STD-8; the public 5–10k LOC integration gate and network/JSON/HTTP/TLS milestones remain in the backlog. Frozen evaluation inputs and the private held-out corpus are untouched. Next source-language work is Q-034/P6-11 (explicit borrowed-return calls/bindings); P7/P8 retain their existing gate. This intermediate gate is sufficient to resume language work. It does not mark Std 0.1 complete: filesystem gaps, args/env, time/random wrappers, structured logs and CLI/storage exit examples remain STD-8; the public 5–10k LOC integration gate and network/JSON/HTTP/TLS milestones remain in the backlog. Frozen evaluation inputs and the private held-out corpus are untouched. Q-034/P6-11 now has an implementation for review with explicit borrowed-return calls/bindings (RFC 0036 Proposed); P7/P8 retain their existing gate.
+71 -6
View File
@@ -28,10 +28,10 @@ Draft registry. Codes are stable once released in a tagged compiler version.
|---|---|---| |---|---|---|
| E2001 | ownership.use_after_move | Value used after ownership transfer | | E2001 | ownership.use_after_move | Value used after ownership transfer |
| E2002 | ownership.double_consume | Linear value consumed twice | | E2002 | ownership.double_consume | Linear value consumed twice |
| E2101 | borrow.mutable_alias | Overlapping exclusive/shared borrow violation | | E2101 | borrow.mutable_alias | Overlapping exclusive/shared borrow violation; related definition when `conflicts_with` is identified (spec 10 §2) |
| E2102 | borrow.outlives_owner | Borrow may outlive backing storage | | E2102 | borrow.outlives_owner | Borrow may outlive backing storage |
| E2103 | memory.out_of_bounds | Access not proven in bounds | | E2103 | memory.out_of_bounds | Access not proven in bounds |
| E2104 | memory.region_generation | Reference belongs to invalidated region generation | | E2104 | memory.region_generation | Reference belongs to invalidated region generation; related definition when `conflicts_with` is identified (spec 10 §2) |
| E2110 | island.escape | Island-internal reference escapes island | | E2110 | island.escape | Island-internal reference escapes island |
| E2105 | borrow.not_ended | Owned borrow live at `ret`, or borrow state differs between edges into a block | | E2105 | borrow.not_ended | Owned borrow live at `ret`, or borrow state differs between edges into a block |
| E2106 | borrow.use_after_end | Borrow used or ended after it was ended | | E2106 | borrow.use_after_end | Borrow used or ended after it was ended |
@@ -47,7 +47,7 @@ Draft registry. Codes are stable once released in a tagged compiler version.
| E3002 | resource.leak | Linear resource has no terminal consumption path | | E3002 | resource.leak | Linear resource has no terminal consumption path |
| E3101 | effect.undeclared | Callee effect absent from caller contract | | E3101 | effect.undeclared | Callee effect absent from caller contract |
| E3201 | capability.missing | Required authority unavailable | | E3201 | capability.missing | Required authority unavailable |
| E3202 | capability.widen | Attempt to widen delegated authority | | E3202 | capability.widen | Attempt to widen delegated authority; unsupported narrowing forms identify `capability_kind` |
## E4xxx — Concurrency ## E4xxx — Concurrency
@@ -60,7 +60,7 @@ Draft registry. Codes are stable once released in a tagged compiler version.
| E4202 | atomic.ordinary_access | Atomic cell accessed by an ordinary load | | E4202 | atomic.ordinary_access | Atomic cell accessed by an ordinary load |
| E4203 | atomic.unsupported_width | Atomic width not implemented lock-free by the target | | E4203 | atomic.unsupported_width | Atomic width not implemented lock-free by the target |
| E4301 | task.live_child_escape | Scope exits with live child task | | E4301 | task.live_child_escape | Scope exits with live child task |
| E4302 | task.borrow_escape | Child task borrow can outlive parent storage | | E4302 | task.borrow_escape | Child task borrow can outlive parent storage; related spawn when `task` is identified (spec 10 §2) |
| E4303 | io.buffer_in_flight | Buffer accessed while async operation owns/borrows it | | E4303 | io.buffer_in_flight | Buffer accessed while async operation owns/borrows it |
| E4304 | sync.wait_while_locked | Suspending operation, spawn, or call of a waiting/spawning function while a lock guard is live | | E4304 | sync.wait_while_locked | Suspending operation, spawn, or call of a waiting/spawning function while a lock guard is live |
| E4305 | task.shield_order | Shield ended while a more inner shield is live | | E4305 | task.shield_order | Shield ended while a more inner shield is live |
@@ -87,11 +87,11 @@ Only problems that exist because of the frontend. Everything the verifier decide
| Code | Kind | Meaning | | Code | Kind | Meaning |
|---|---|---| |---|---|---|
| E7001 | source.syntax | Malformed `.aji` source | | E7001 | source.syntax | Malformed `.aji` source |
| E7002 | source.unknown_name | Undefined variable, function, type, field or variant | | E7002 | source.unknown_name | Undefined variable, function, type, field, variant or effect; an unknown capability kind is `capability_kind`, an unknown effect is `name` and `effect` |
| E7003 | source.missing_move | Named linear value consumed without `move` | | E7003 | source.missing_move | Named linear value consumed without `move` |
| E7004 | source.not_exhaustive | `match` misses an outcome, variant or default | | E7004 | source.not_exhaustive | `match` misses an outcome, variant or default |
| E7005 | source.type_mismatch | Expression has the wrong type in a source position | | E7005 | source.type_mismatch | Expression has the wrong type in a source position |
| E7006 | source.invalid_construct | Construct not allowed here | | E7006 | source.invalid_construct | Construct not allowed here; stable `reason` below |
| E7007 | source.ambiguous | Source meaning cannot be determined | | E7007 | source.ambiguous | Source meaning cannot be determined |
| E7900 | source.internal_compiler_error | The frontend produced invalid AIR for this construct: a compiler bug, not a program error; fields `air_code`, `air_message` | | E7900 | source.internal_compiler_error | The frontend produced invalid AIR for this construct: a compiler bug, not a program error; fields `air_code`, `air_message` |
@@ -111,3 +111,68 @@ Reported in trap records (spec 01 §6), not by the verifier.
| T0008 | trap.out_of_bounds | Runtime bounds check failed | | T0008 | trap.out_of_bounds | Runtime bounds check failed |
| T0009 | trap.unsafe_precondition | Unsafe precondition violated (detected) | | T0009 | trap.unsafe_precondition | Unsafe precondition violated (detected) |
| T0010 | trap.foreign_iref | An `iref` was used to access a graph it does not belong to | | T0010 | trap.foreign_iref | An `iref` was used to access a graph it does not belong to |
## Source repair candidate kinds
These stable kinds use spec 10 §3. `hint` MUST equal the registered text. Alternatives, when present, MUST use the unit below; hints alone are not replacements. Advice is selected at the rejecting rule, never by parsing diagnostic prose. Existing illustrative/non-source kinds are outside this registry.
| Kind | Code | Hint | Alternatives unit |
|---|---|---|---|
| `boolean_negation` | E7001 | Aji boolean negation is `not`; integer complement is not boolean negation. | none |
| `annotate_var_type` | E7001 | Write an explicit type: `var name: T = expression;`. `let` may infer its type. | none |
| `slice_mut_type` | E7001 | Write `slice_mut<T>` for a mutable slice type. | complete type |
| `slice_ref_type` | E7001 | Write `slice<T>` for a shared slice type. | complete type |
| `explicit_range_end` | E7001 | Write both slice bounds: `receiver[start..end]`; choose the upper bound explicitly. | none |
| `borrow_argument` | E7001 | Write `ref place` or `mut place` for an inline borrow argument. | prefix |
| `borrow_binding` | E7001 | Bind a borrow with `ref name = place;` or `mut name = place;`, rather than a let/var initializer. | none |
| `zero_storage` | E7001 | `zero` is only a whole var initializer: `var name: T = zero;`; T must be zeroable. | none |
| `numeric_cast_modes` | E7005 | The target-independent `as` rule excludes `usize`/`isize`, even when the value fits. Choose `as!` for a checked conversion (T0006 on overflow) or `as%` for a wrapping conversion. | operator |
| `parameter_mutability` | E7001 | Write `name: T` for a value parameter; use a local `var` for mutable storage, or `name: mut<T>` for an exclusive borrowed parameter. Choose the intended ownership contract. | none |
| `array_slice_argument` | E7005 | Pass an array as an explicit borrow: `ref array` for `slice<T>` or `mut array` for `slice_mut<T>`. The place and loan must still verify. | prefix |
Closed applicability:
- `boolean_negation`: lone `!` rejected at primary-expression start. Excludes `!=`, `as!` and `!` rejected after an expression (such as `panic!()`). It does not assert that the operand is boolean.
- `annotate_var_type`: `=` found where a `var` declaration requires its type colon. No advice for `let`, a missing name or other found tokens; no initializer type is guessed.
- Slice type kinds: a bare `mut`/`ref` parsed in type position immediately followed by `slice`. Attach at that `slice` token, retaining the caller's expected token. Emit one complete-type alternative only if the following `slice<...>` fragment parses as a single-argument slice type. Keep its token spellings (including nested types), remove comments/whitespace and separate adjacent word/number tokens by one space; replace the outer spelling by `slice_mut`/`slice` respectively. An incomplete/malformed fragment has hint only. Speculative parsing MUST NOT mutate the original tokens, including `>>`.
- `explicit_range_end`: `]` immediately after `..` in index syntax. No advice for an omitted start, inclusive `..=`, missing for-loop bound or another malformed expression. No receiver or `.len` alternative is guessed.
- Borrow kinds: `&` rejected as the first token of a call argument, excluding enum variant payloads (`borrow_argument`) or let/typed-var initializer (`borrow_binding`). Other expression contexts, including the second `&` in `a && b`, have no borrow advice. For an argument whose following token is an ordinary identifier, emit `["ref"]`; for `&mut` followed by an ordinary identifier, emit `["mut"]`. Other operands have hint only, including `&&x`. These prefixes do not imply that the referent/mode verifies; binding advice has no prefix alternative.
- `zero_storage`: keyword `zero` rejected at primary-expression start. Accepted typed-var zero initialization has no advice.
- `numeric_cast_modes`: integer `as` rejected by the lossless-widening rule, with unchanged `from`/`to`. Alternatives MUST be `["as!", "as%"]`. Non-integer casts and other E7005 rules have no such candidate.
- `parameter_mutability`: `mut` rejected where a function parameter name is required, immediately followed by an ordinary identifier and `:`. Hint only: value storage and an exclusive borrow have different ownership contracts. Other malformed parameter prefixes and incomplete `mut` spellings have no such advice.
- `array_slice_argument`: ordinary function-call argument type mismatch for a bare named, non-linear array whose element type equals the expected `slice<T>` or `slice_mut<T>` element type. Alternatives MUST be `["ref"]` for a shared slice and `["mut"]` for an exclusive slice. This is an explicit borrow prefix, not an implicit conversion or a guarantee that the place/loan verifies. Excludes other element types, array expressions/projections, existing borrow arguments, bindings/returns, intrinsics and task spawning (which requires a retained named loan). Earlier name/move/operand errors retain priority. The same rule applies to explicitly specialized generic/static functions and imported ordinary calls.
## E7006 reasons
These stable categories are part of the diagnostic API (spec 15 §10), not new rejection rules. One reason is selected at the rejection site; messages remain optional explanation.
| Reason | Meaning |
|---|---|
| `move_copy` | Explicit move of a plain Copy value; excludes borrows, void and never. |
| `move_borrow` | Explicit move of a borrow/view. |
| `invalid_move` | Move operand is void or never, rather than a materializable value. |
| `loop_control_outside_loop` | break or continue without an enclosing loop. |
| `zero_not_zeroable` | zero initialization of a type without a zero value. |
| `value_block_statement` | A bare block statement would implicitly discard a non-void value. |
| `unreachable` | Statement or expression after unconditional divergence. |
| `missing_return` | A value-returning function can fall through without a value. |
| `invalid_borrow` | A borrow requires an explicit binding, mode, named parent or argument form. |
| `invalid_borrow_return` | A borrow return violates source origin, binding, return or worker restrictions. |
| `duplicate_declaration` | Duplicate type, function, field, variant or parameter declaration. |
| `invalid_declaration` | An otherwise disallowed declaration shape, such as an empty enum. |
| `invalid_binding` | Invalid binding shape, rebinding or implicit borrow binding. |
| `invalid_assignment` | Assignment requires a mutable variable or a permitted stored element/field. |
| `invalid_place` | Expression is not an addressable place or uses an invalid unchecked projection. |
| `invalid_match` | Invalid, duplicate or misplaced pattern, outcome or select arm. |
| `invalid_unpack` | Invalid complete unpack or multi-result binding form. |
| `invalid_expression` | Value expression uses an unavailable form, such as scalar dereference of a slice. |
| `invalid_operation` | Invalid intrinsic/call, fallibility handler, multi-result handler or ordering spelling. |
| `invalid_literal` | Invalid literal shape, duplicate/missing initializer field or borrowed element. |
| `invalid_generic` | Invalid generic parameter, constraint, argument, entry point or application. |
| `invalid_static_function` | Static callable contract, parameter use or specialization is disallowed. |
| `implementation_limit` | A specified frontend/module/type/specialization size or depth limit is exceeded. |
| `invalid_module_mapping` | Invalid reserved, duplicate or excessive package module mapping. |
| `duplicate_import` | The same module is imported twice. |
| `import_cycle` | Cyclic module import. |
| `module_header_mismatch` | Mapped module header differs from its explicit provider name. |
| `trusted_unavailable` | A source program/template declares an unavailable trusted boundary. |
+64 -29
View File
@@ -1,21 +1,27 @@
(* Aji source language `.aji` 0.1 (Phase 6A). Normative together with (* Aji source language `.aji` 0.1. Normative together with
docs/spec/15-source-language.md. Decision record: RFC 0013. docs/spec/15-source-language.md. Initial decision record: RFC 0013.
Lexical conventions Lexical conventions
------------------- -------------------
- `//` starts a comment that runs to the end of the line. - `//` starts a comment that runs to the end of the line.
- Whitespace and line breaks separate tokens and are otherwise insignificant. - Whitespace and line breaks separate tokens and are otherwise insignificant.
- Keywords: module struct enum fn effects trusted from let var zero - Keywords: module struct enum type fn effects trusted from let var zero
if else while for in loop break continue return trap match select if else while for in loop break continue return trap match select
scope shield lock as cancelled ref mut move unchecked or and not scope shield lock as cancelled ref mut move unchecked or and not
true false recv send. true false.
- import is contextual after the module header; recv/send are contextual
inside select. They remain identifiers elsewhere. A lone `_` is not
an identifier; it is a wildcard/discard binding. `_name` is an identifier.
- as! and as% are single tokens: `as` immediately followed by `!` or `%`,
without whitespace.
- Every construct has one canonical spelling (spec 15 §1). - Every construct has one canonical spelling (spec 15 §1).
*) *)
module = "module" path { module_import } { item } ; module = "module" path { module_import } { item } ;
module_import = "import" path ";" ; (* contextual word, spec 15 §13/§14 *) module_import = "import" path ";" ; (* contextual word, spec 15 §13/§14 *)
item = type_decl | fn_decl ; item = type_decl | fn_decl ;
path = ident { "." ident } ; path = ident { "." member } ; (* module/effect paths allow keywords after `.` *)
name_path = ident { "." ident } ; (* qualified types and enum patterns *)
type_decl = struct_decl | enum_decl ; type_decl = struct_decl | enum_decl ;
struct_decl = "struct" ident [ type_params ] "{" [ field { "," field } [ "," ] ] "}" ; struct_decl = "struct" ident [ type_params ] "{" [ field { "," field } [ "," ] ] "}" ;
@@ -23,28 +29,29 @@ field = ident ":" type ;
enum_decl = "enum" ident [ type_params ] "{" variant { "," variant } [ "," ] "}" ; enum_decl = "enum" ident [ type_params ] "{" variant { "," variant } [ "," ] "}" ;
variant = ident [ "(" type { "," type } ")" ] ; variant = ident [ "(" type { "," type } ")" ] ;
fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } ] ")" "->" type [ "from" ident ] fn_decl = "fn" ident [ type_params ] "(" [ param { "," param } [ "," ] ] ")" "->" type [ "from" ident ]
"effects" "[" [ path { "," path } ] "]" "effects" "[" [ path { "," path } [ "," ] ] "]"
block ; (* `trusted` is reserved and rejected, E7006 *) block ; (* `trusted` is reserved and rejected, E7006 *)
param = ident ":" type ; param = ident ":" type ;
type_params = "<" type_param { "," type_param } ">" ; type_params = "<" type_param { "," type_param } ">" ;
type_param = ident [ ":" ( property { "+" property } | function_contract ) ] ; type_param = ident [ ":" ( property { "+" property } | function_contract ) ] ;
function_contract = "fn" "(" [ type { "," type } ] ")" "->" type function_contract = "fn" "(" [ type { "," type } [ "," ] ] ")" "->" type
"effects" "[" [ path { "," path } ] "]" ; "effects" "[" [ path { "," path } [ "," ] ] "]" ;
property = "Copy" | "Send" | "Share" | "Freeze" | "Local" ; property = "Copy" | "Send" | "Share" | "Freeze" | "Local" ;
type_args = "<" generic_arg { "," generic_arg } ">" ; type_args = "<" generic_arg { "," generic_arg } ">" ;
generic_arg = type | "fn" path [ application ] ; (* static function selection; spec 15 §18 *) generic_arg = type | "fn" path [ application ] ; (* static function selection; spec 15 §18 *)
application = "::" type_args ; (* explicit; no inference, spec 15 §15 *) application = "::" type_args ; (* explicit; no inference, spec 15 §15 *)
type = int_type | "bool" | "void" | "never" | path type = int_type | "bool" | "void" | "never" | name_path
| path type_args | name_path type_args
| "[" type ";" int_lit "]" | "[" type ";" int_lit "]"
| wrapper "<" type ">" | wrapper "<" type ">"
| "cap" "<" path ">" | "cap" "<" path ">"
| "file" "<" ( "read" | "write" | "append" ) ">" ; | "file" "<" ( "read" | "write" | "append" ) ">" ;
(* `>>` closes two type arguments: mut<file<write>> *) (* `>>` closes two type arguments: mut<file<write>> *)
wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array" wrapper = "ref" | "mut" | "slice" | "slice_mut" | "own" | "own_array"
| "task" | "sender" | "receiver" | "mutex" | "buffer" ; | "task" | "sender" | "receiver" | "mutex" | "buffer"
| "island" | "frozen" | "arc" | "iref" | "atomic" ;
int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize" int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
| "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ; | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" ;
(* `region`, `listener`, `stream`, `io_error`, `alloc_error`, (* `region`, `listener`, `stream`, `io_error`, `alloc_error`,
@@ -52,15 +59,36 @@ int_type = "u8" | "u16" | "u32" | "u64" | "u128" | "usize"
(* A built-in operation is a call whose callee is a dotted path: (* A built-in operation is a call whose callee is a dotted path:
`own.new(v, mem)`, `region.new(arena, v)`, `cap.narrow.budget(c, n)`. *) `own.new(v, mem)`, `region.new(arena, v)`, `cap.narrow.budget(c, n)`. *)
(* Statement/tail disambiguation (spec 15 §4): leading bare if_expr,
match_expr or block is consumed whole before choosing the production.
Next `}` makes it the tail, `;` explicitly discards its result, otherwise
it is a block_stmt whose result must be void or divergence (E7006).
No outer postfix/cast/binary continuation is consumed here; parenthesize
the construct for continuation. Nested expr contexts are unrestricted.
Other block_stmt forms end at their final `}`. Whitespace is irrelevant. *)
(* Other statements parse an expression first: the next `=` selects assignment,
`;` selects an expression statement, and `}` selects a tail. Lowering checks
that an assignment target is a place (E7006 invalid_assignment). This ordered
choice, with the block rule above, has no LL(k) bound on the common prefix.
In if/while conditions, match scrutinees, for bounds and lock places, a
following `{` starts the body rather than a struct literal. Parenthesized
expressions, call arguments and index expressions restore ordinary parsing.
Struct literals require an uppercase ASCII initial in the final name.
At a dot step only channel.make<T> and buffer.new<T> consume `<` as a type
argument; that choice commits to a typed call, with no comparison fallback.
Other expression `<` tokens are comparisons; generic calls use `::<...>`.
Arm bodies starting with `{` likewise consume the whole block first. *)
block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *) block = "{" { statement } [ expr ] "}" ; (* optional tail expression: the block's value *)
statement = "let" binding [ ":" type ] "=" expr ";" statement = "let" binding [ ":" type ] "=" expr ";"
| "var" ident ":" type "=" ( expr | "zero" ) ";" | "var" ident ":" type "=" ( expr | "zero" ) ";"
| ( "ref" | "mut" ) [ "unchecked" ] ident "=" ( place | borrow_call ) ";" (* borrow binding; buffer.view(b) / graph access also bind child borrows, spec 15 §17 *) | ( "ref" | "mut" ) [ "unchecked" ] ident "=" ( place | borrow_call ) ";" (* borrow binding; buffer.view(b) (§17) / graph access (§8) also bind child borrows *)
| place "=" expr ";" | place "=" expr ";"
| "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";" | "break" ";" | "continue" ";" | "return" [ expr ] ";" | "trap" ";"
| expr ";" | expr ";"
| block_stmt ; | block_stmt ;
binding = ident | "(" [ ( ident | "_" ) { "," ( ident | "_" ) } ] ")" ; (* complete unpack; pairs also split_at/compare_exchange *) binding = ident | binds ;
binds = "(" [ bind { "," bind } [ "," ] ] ")" ;
bind = ident | "_" ; (* complete unpack; pairs also split_at/compare_exchange *)
block_stmt = if_expr | match_expr | select_stmt | block block_stmt = if_expr | match_expr | select_stmt | block
| "while" expr block | "while" expr block
| "for" ident "in" expr ".." expr block | "for" ident "in" expr ".." expr block
@@ -70,15 +98,17 @@ block_stmt = if_expr | match_expr | select_stmt | block
| "lock" "ref" place "as" ident block "cancelled" block ; | "lock" "ref" place "as" ident block "cancelled" block ;
if_expr = "if" expr block [ "else" ( if_expr | block ) ] ; if_expr = "if" expr block [ "else" ( if_expr | block ) ] ;
match_expr = "match" expr "{" { arm } "}" ; match_expr = "match" expr "{" { arm } [ final_arm ] "}" ;
arm = pattern "=>" ( block | expr "," ) ; arm = pattern "=>" ( block [ "," ] | expr "," ) ;
pattern = "_" | int_lit (* integer matches only; `_` is required there *) final_arm = pattern "=>" expr ; (* final non-block arm may omit its comma *)
| path [ application ] "::" ident [ "(" ident { "," ident } ")" ] (* enum variant: Shape::Rect(w, h); no `_` in enum matches *) pattern = "_" | [ "-" ] int_lit (* integer matches only; `_` is required there *)
| ident [ "(" ident { "," ident } ")" ] ; (* outcome of a fallible operation: ok(n), closed *) | name_path [ application ] "::" ident [ payload_binds ] (* exhaustive enum variants; §6 *)
| ident [ binds ] ; (* outcome of a fallible operation: ok(n), closed *)
payload_binds = "(" bind { "," bind } [ "," ] ")" ; (* enum payload list MUST NOT be empty *)
select_stmt = "select" "{" { select_arm } "cancelled" [ "(" ident { "," ident } ")" ] "=>" ( block | expr "," ) "}" ; select_stmt = "select" "{" { select_arm } "cancelled" [ "(" [ ident { "," ident } [ "," ] ] ")" ] "=>" ( block [ "," ] | expr [ "," ] ) "}" ;
select_arm = "recv" "(" ident ")" "{" { arm } "}" select_arm = "recv" "(" ident ")" "{" { arm } [ final_arm ] "}"
| "send" "(" ident "," expr ")" "{" { arm } "}" ; | "send" "(" ident "," expr ")" "{" { arm } [ final_arm ] "}" ;
expr = or_expr ; expr = or_expr ;
or_expr = and_expr { "or" ( and_expr | "trap" ) } ; (* `e or trap`: the only fallible shorthand *) or_expr = and_expr { "or" ( and_expr | "trap" ) } ; (* `e or trap`: the only fallible shorthand *)
@@ -93,9 +123,12 @@ unary = ( "-" | "not" | "*" ) unary
| ( "ref" | "mut" ) [ "unchecked" ] place | ( "ref" | "mut" ) [ "unchecked" ] place
| "move" ident | "move" ident
| postfix ; | postfix ;
postfix = primary { application | "." member | "[" expr [ ".." expr ] "]" | call_args } ; postfix = primary { application | "." member [ typed_call_args ] | "[" expr [ ".." expr ] "]" | call_args } ;
member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *) member = ident | keyword ; (* after `.` a keyword is a name: task.cancelled *)
call_args = [ "<" type ">" ] "(" [ expr { "," expr } ] ")" ; call_args = "(" [ expr { "," expr } [ "," ] ] ")" ;
typed_call_args = "<" type ">" call_args ; (* only channel.make / buffer.new at the dot step *)
(* A variant may be followed only by a non-empty payload call;
payload-free variants MUST be bare. Payload arity is checked. *)
primary = int_lit | "true" | "false" | string primary = int_lit | "true" | "false" | string
| "struct" "." "unpack" (* contextual built-in call, §16 *) | "struct" "." "unpack" (* contextual built-in call, §16 *)
| ident | path [ application ] "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *) | ident | path [ application ] "{" [ field_init { "," field_init } [ "," ] ] "}" (* struct literal; uppercase final component *)
@@ -105,11 +138,13 @@ primary = int_lit | "true" | "false" | string
| "(" expr ")" | "(" expr ")"
| if_expr | match_expr | block ; | if_expr | match_expr | block ;
field_init = ident ":" expr ; field_init = ident ":" expr ;
borrow_call = "buffer" "." "view" "(" ident ")" borrow_call = name_path [ application ] call_args ; (* only declared `from` calls (§19), buffer.view (§17) and graph .at (§8) *)
| ( "island" | "frozen" | "arc" ) "." "at" "(" expr "," expr ")" ; place = ( ident | "(" place ")" ) { "." member | "[" expr [ ".." expr ] "]" } | "*" unary ;
place = ident { "." ident | "[" expr [ ".." expr ] "]" } | "*" unary ;
int_lit = digit { digit | "_" } [ int_type ] | "0x" hexdigit { hexdigit | "_" } [ int_type ] ; int_lit = digit { digit | "_" } [ int_type ]
| "0x" hexdigit { hexdigit | "_" } [ int_type ]
| "0b" bindigit { bindigit | "_" } [ int_type ] ;
bindigit = "0" | "1" ;
string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \r \t \0 \\ \" \xHH *) string = 'b"' { char | escape } '"' ; (* byte string; escapes \n \r \t \0 \\ \" \xHH *)
ident = ( letter | "_" ) { letter | digit | "_" } ; ident = ( letter | "_" ) { letter | digit | "_" } ; (* excluding keywords and lone `_` *)
keyword = ? any keyword listed under Lexical conventions ? ; keyword = ? any keyword listed under Lexical conventions ? ;
+1 -1
View File
@@ -447,4 +447,4 @@ Join normalizes absolute child alone, replacing base. Otherwise it normalizes ba
Both writers first validate all input bytes: NUL yields invalid_input, including in base when an absolute child replaces it. Invalid input precedes size_overflow, which precedes short_output. Every returned error leaves the entire destination unchanged. Success writes exactly the reported prefix, preserves the suffix and writes no NUL terminator. Only final normalized size must fit: a long component followed by `..` can normalize into one byte of output. Reverse measurement/emission needs fixed frame state and no intermediate buffer or allocation. Work is linear in supplied input/output bytes. Both writers first validate all input bytes: NUL yields invalid_input, including in base when an absolute child replaces it. Invalid input precedes size_overflow, which precedes short_output. Every returned error leaves the entire destination unchanged. Success writes exactly the reported prefix, preserves the suffix and writes no NUL terminator. Only final normalized size must fit: a long component followed by `..` can normalize into one byte of output. Reverse measurement/emission needs fixed frame state and no intermediate buffer or allocation. Work is linear in supplied input/output bytes.
Input borrows can overlap each other; destination must be disjoint. Explicit split_at permits source/output in one allocation. Existing type/borrow/task-loan/Send/Share checks apply, including no-op/short-output paths. No unsafe boundary, new language/AIR semantics or hidden effects are needed. Borrow-return source support (Q-034) remains separate. The [pure example](../../examples/std/path.aji) joins into a caller buffer and borrows basename/parent/extension from the returned prefix. The independent Python forward-stack oracle covers normalization/join/query/capacity/idempotence; hosted fixtures confirm filesystem authority remains independent. Input borrows can overlap each other; destination must be disjoint. Explicit split_at permits source/output in one allocation. Existing type/borrow/task-loan/Send/Share checks apply, including no-op/short-output paths. No unsafe boundary, new language/AIR semantics or hidden effects are needed. Ordinary source functions can return retained views under spec 15 §19; path queries retain their Copy range API. The [pure example](../../examples/std/path.aji) joins into a caller buffer and borrows basename/parent/extension from the returned prefix. The independent Python forward-stack oracle covers normalization/join/query/capacity/idempotence; hosted fixtures confirm filesystem authority remains independent.
+68
View File
@@ -0,0 +1,68 @@
# RFC 0036: Explicit source borrow returns
Status: Proposed\
Scope: P6-11 / Q-034; source 0.1 over existing format-0 ownership/arrays
The implementation, proposed spec integration and tests are prepared together. Only the owner moves this RFC to Accepted; implementation does not imply adoption.
## Motivation and precise invariant
AIR and the source declaration grammar already express `from`, but source calls could not retain the result. Functions can now expose borrowed elements and views without copying storage or giving away the owner. A result remains derived from exactly the named borrowed parameter; every owned borrow ends on each normal path or transfers with the result and its owned ancestors. Local-frame memory never escapes. Public effects and authority remain explicit.
## Normative integration
Spec 15 §19 contains the complete source rules and examples; §15/§17/§18 point to it. Existing declaration/expression grammar suffices: `from p`, `ref name = call(...);`, `mut name = call(...);`, `return name;` and a named function tail. The source bundle includes §19 in language/ownership.md; the Quick Reference has one checked example.
Borrow-return functions declare one borrowed origin with a compatible mode. Calls retain only a named borrowed origin and bind the result with the exact shared/exclusive mode. Other temporary arguments end after the call. Borrow-returning calls in ordinary value expressions/nested arguments reject; a return first binds any produced borrow and then names it. Branches can return directly but never merge borrow values. Unused generic signatures check what is known before specialization, while concrete substitutions check otherwise unknown modes. Static callable parameters still cannot carry borrow-return contracts.
## Verifier rule and implementation
Spec 08 §11.3 already checks roots, modes, live ancestor transfer and caller parent lifetime. Existing aliasing, task loans, initialization, region-generation and bounds checks remain authoritative. No verifier transfer state is added. The frontend tracks a bounded map from generated borrow identities to their immediate parents, including calls, split siblings, buffer/graph views and region outcome values. At a return it omits ends only for the result and ancestors, ends unrelated borrows in reverse order, and still emits structured scope/shield/lock exits. This map chooses cleanup mechanics; it cannot certify provenance. Frame and wrong-parameter returns reach the AIR verifier and are rejected there.
No new AIR instruction, feature or instruction meaning is added: signatures use `from %p`, calls produce the existing owned child, and `ret` transfers it. The contracts for `call`, `ret`, projections, reborrows and slice construction remain spec 07a/spec 08. Effects/capabilities, memory/concurrency access and trap behavior are unchanged. This completes source support for existing primitives rather than introducing an instruction as syntax sugar.
## Runtime and deterministic interpreter behavior
No interpreter/backend/runtime change, implicit heap allocation, refcount, destructor or unwinding. Returned identities refer to the caller's storage (or its explicitly allocated graph/region/buffer). Bounds violations retain T0008 and source mapping. Source and hand-written AIR have the same run record; deterministic/hosted profiles use the same verified contracts. Per-step collection and scheduler stress validate retained views and task lending.
## Valid and rejected examples
```aji
fn first(s: slice<u64>) -> ref<u64> from s effects [] {
ref item = s[0];
return item;
}
fn main() -> u64 effects [] {
let data = [42u64, 7u64];
ref s = data;
ref item = first(s);
return *item;
}
```
Replacing the body of first with `let n = 1u64; ref item = n; return item;` rejects E2108. Returning a child of another parameter rejects E2102. `first(ref data)` rejects E7006 with the named-parent repair. Mutating an exclusive parent while the returned child lives rejects E2101; calling through a task-loaned parent or lending its returned child twice rejects E4101. Ending the returned child in an inner block restores access to its parent.
## Diagnostics and compatibility
No new code or envelope. E7002 identifies unknown origins; E7005 identifies invalid origin/return types or modes; E7006 identifies missing from, invalid result/argument/return placement, main returns, borrow moves and spawning a borrow-returning function. The latter reports the source spawn directly instead of an unactionable feature-header error; task_borrow_returns remains reserved. Existing E2108/E2102/E2101/E2104/E3101/E4101 and T0008 retain their meaning and source/AIR locations. Validation also found that non-generic zero/oversized array annotations and repeated literals emitted invalid AIR; source type checking now reports E7005 for the existing format-0 1..2^32 bound instead of a compiler-bug diagnostic. Unused generic signatures also check these known bounds; formerly accepted invalid unused signatures now reject E7005. The exact maximum reaches the existing verifier shape budget (E5101) rather than a source type-size rejection when lowered. Existing valid source and AIR retain canonical lowering and behavior; formerly unimplemented from declarations become executable. Generic `move` on a borrow stays rejected. Existing libraries keep their Copy range APIs; this increment does not redesign them or complete Phase 6.
## Agent complexity impact
- New concepts: none in AIR; source now requires an explicit named parent for retained call results and transfers a named return's owned ancestors.
- Verifier/runtime state: none. Frontend signature metadata holds the from parameter index; mechanical ancestry is linear in generated borrow definitions, with ancestor walks bounded by the function's finite instruction graph.
- Syntax: no keyword, grammar production or AIR opcode. Two already existing binding forms now accept declared borrow-returning calls; return/function-tail names use the existing forms.
- Interactions: nominal package calls, explicit generic substitution, mutable/shared views, split siblings, owned buffers, regions, task loans and structured exits. No borrow joins, lifetime inference, callable lifetime parameters or aggregate borrows.
- Repairability: local E7xxx messages require named bindings and exact modes; provenance failures remain stable verifier codes at the return/call. Agents can end a view by placing it in an inner block.
- Existing primitives suffice: the AIR facility was implemented in Phase 1. Extending source completes its vertical path and avoids manually authoring SSA and borrow.end.
- Budget: source and Quick Reference measurements are recorded below. AIR bundle is unchanged. Detailed rules stay on demand in ownership.md. No empirical Model Capability Compression improvement is claimed and no private benchmark material was accessed.
## Alternatives considered
Promoting inline origin temporaries would invisibly extend their lifetimes and complicate repair and ordering. Ending them immediately would make every retained child invalid. Mandatory named parents reuse the established graph/buffer convention. Borrow-valued joins, implicit mode conversion and lifetime parameters would add semantic state beyond existing format 0. Returning named borrows and explicit branches covers the current primitive facility without those additions.
## Validation
The source conformance corpus covers direct/tail/branch returns, call forwarding, nested projection ancestors, split siblings, mutable slices, buffer views, region allocation outcome paths, generic contracts and task loans. Review adds normal returns through scope/shield/lock exits, rejection of an unjoined task and lock-guard escape at a borrow return, direct spawn rejection, and unused generic array bounds. An independent source twin compares with the frozen Phase 1 AIR borrow-return program. CLI integration checks canonical lowering, source/AIR records, packages with ordinary/generic qualified calls, imported diagnostic/trap provenance, profiles and audit/exploration commands. CI runs the integration script. Validation: unit tests and formatting pass; 56 focused conformance tests pass with per-step collection; the concurrent fixture also passes 200 schedule seeds across four quanta; the generic corpus passes 61/61. CLI integration passes 133 checks, existing generic/module integrations pass 20/36 checks, and hosted filesystem/stdin/TCP smoke passes. After review fixes, the full conformance run passes 1,135/1,135 with no failures or pending tests. Source construct coverage passes 119/119. Independent read-only review by Claude found the source spawn diagnostic defect and unused generic array-bound gap; both were corrected and independently rechecked, with no further findings in those fixes.
Measured cl100k growth from RFC 0035: Quick Reference 8,518 → 8,642 (+1.46%); other source documentation 63,296 → 64,160 (+1.37%); full source excluding AIR 71,814 → 72,802 (+1.38%). language/ownership.md is 1,834 tokens (previously 985). Corresponding o200k groups are 8,677 / 64,359 / 73,036; qwen2.5 groups are 8,900 / 65,733 / 74,633. AIR remains 179,282 bytes / 19 files / 51 sections; its source-bundle copy stays 46,300 / 46,451 / 47,800 tokens. Cumulative cl100k source growth over the pre-std 33,981 baseline is +114.24%, justified by completing an existing explicit lifetime facility; Quick Reference remains beyond the plan's current 5–8k target and front-door consolidation/selective reading remains separate work. These measurements precede the review's reserved-float clarification and validation fixes; the latter add 54 cl100k tokens, with current full source at 72,902 and Quick Reference at 8,688. Current counts are recorded in docs/agent/README.md. No empirical MCC benefit is inferred.
Loaded 100 of 1020 files, more files were not shown because too many files have changed in this diff. Show more