diff --git a/docs/design/open-questions.md b/docs/design/open-questions.md index 84fe3f0..e045089 100644 --- a/docs/design/open-questions.md +++ b/docs/design/open-questions.md @@ -392,3 +392,15 @@ The exhaustive inventory in `tools/source_reject_twins.py` keeps these rows visi 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. + +## 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. + +## Q-055 — Feature-gated AIR headers and frozen rejection codes + +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. diff --git a/docs/plan/phase-6-source-language.md b/docs/plan/phase-6-source-language.md index f20ad64..54c63ad 100644 --- a/docs/plan/phase-6-source-language.md +++ b/docs/plan/phase-6-source-language.md @@ -134,7 +134,7 @@ Lowering layers (P6A-3/4), each with accepted (golden AIR), rejected (`E7xxx`) a | 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-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 | doing (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 | doing | 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-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 | 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 | @@ -331,3 +331,7 @@ The frontend ordinary-dereference E4202 now adds concrete found and use fields, ## P6-1 source specification consistency (2026-10-09) 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. diff --git a/docs/rfcs/0039-verifier-visible-contracts.md b/docs/rfcs/0039-verifier-visible-contracts.md new file mode 100644 index 0000000..21eb7e1 --- /dev/null +++ b/docs/rfcs/0039-verifier-visible-contracts.md @@ -0,0 +1,103 @@ +# RFC 0039: Verifier-visible contracts + +Status: Draft +Scope: P6-6 — preconditions, postconditions, type/module invariants and audit classification +Language version: 0.1 +AIR version: gated format-0 extension under investigation; not approved + +This draft opens the spec gate. It neither changes the language nor completes P6-6. The evidence below is verified; the invariant is a proposed acceptance requirement. The representation is a candidate, and unresolved decisions prevent implementation. + +## Motivation and current evidence + +Spec 13 §1 and spec 08 §8 name four contract statuses, but do not define executable obligations. Spec 10 §6.1 and `src/report.zig` count checks, without a contract table. `src/air/module.zig` has no contract declarations. Source `requires`/`ensures` are outside the current grammar. + +These probes with the compiler at `94414da` establish constraints: + +```aji +// Variant A +fn positive(x: u64) -> u64 effects [] { + assert(x > 0u64); + return x; +} +// Variant B, substituted for A +fn positive(x: u64) -> u64 effects [] { + if x > 0u64 { assert(x > 0u64); } + return x; +} +fn main() -> u64 effects [] { return positive(0u64); } +``` + +After the same `module` header, both accepted variants produce identical `aji report` JSON. With fuel 10,000, A traps T0002 and B returns zero. A check count cannot establish mandatory coverage. + +An `effects []` function taking `mut` can write through it and return 42; calling it inside `assert` is accepted. Even a no-parameter effects-empty function can call `task.cancelled()` and observe ambient state. Empty effects or parameter restrictions alone do not establish observational purity. Borrowing an owner after `own.take(move owner)` rejects E3001; a postcondition cannot resurrect that owner. + +A candidate AIR `requires @predicate(%x)` header without a new feature rejects E0001 today; declaring unknown feature `contracts` instead rejects E0006 first. This difference matters to format-0 compatibility. + +The intended gains are verifier strength, explicit guarantees and truthful machine-readable audit status. No empirical agent-capability improvement is established. + +## Precise invariant + +Every claimed contract status must be derived from verified AIR. A predicate or frontend annotation alone is not evidence that every required execution boundary is covered. Contract evaluation must obey ordinary ownership, borrow, initialization, effects and authority rules; it cannot allocate implicitly or observe a consumed value. + +Preconditions cover every invocation, including entry instantiation, recursion and spawned workers. Postconditions cover every normal return, including implicit source returns; traps and execution limits do not claim a successful postcondition. Type/module invariant coverage must be specified independently rather than inferred from these two obligations. + +## Candidate normative rules + +The candidate source spelling is `requires { condition; }` and `ensures { condition; }`, after `effects [...]` and before the body. This retains blocks but deliberately moves the clauses and adds terminators compared with spec 13's illustrative example. Each condition is bool. These words are contextual in headers; `result` and `old(expression)` have meaning only in postconditions. Exact grammar and collision rules still need integration in spec 15. + +Safe contracts are enforced, and profiles may reject statuses without disabling checks. Predicate evaluation is read-only, with no heap/region allocation, authority use, ambient-state observation, synchronization, unsafe operation or ownership transfer; callees must satisfy the same restriction. This requires an opcode/call-closure rule in addition to `effects []`: effect-free `arc.clone`, endpoint duplication and `task.cancel` can change state, while `task.cancelled` has no parameter to restrict. The readable types and projection rules remain a gate decision. + +`old(expression)` captures a Copy observation after preconditions and before the body. Snapshots belong to the activation, use bounded frame storage, and do not retain borrows or copy an ownership graph. Postconditions may observe the actual result. Referencing a consumed input is rejected; taking an old scalar observation does not make the input available again. A returned exclusive view must not permit a postcondition to bypass its parent's alias restrictions. + +## AIR, verifier and runtime candidate + +Prefer feature-gated contract descriptors associated with function declarations and independently checked typed predicate bodies. The interpreter enforces preconditions at invocation and postconditions at normal return, so omitting an inline check cannot bypass a descriptor. Source lowering supplies the same descriptors, including generic/package specializations; the verifier checks their types, bindings and predicate restrictions without trusting the frontend. + +This adds semantic declaration constructs rather than an opcode solely for syntax sugar. Descriptor binding, snapshot production, return-value observation and execution order need a complete AIR grammar and transfer contract before publication. No existing instruction changes meaning. + +Predicate instructions consume ordinary fuel and quantum steps. False pre/post conditions need distinct stable traps; a predicate's own arithmetic/bounds trap retains its code. Snapshot/dispatch charging and cancellation ordering still need exact rules. Both runtime profiles execute the same contracts; policy may reject statuses but must not silently disable checks. + +The verifier must check contract access at the relevant boundary, including task loans, returned views and cleanup. A function-entry proof cannot stand in for a return-state proof. Limits on descriptor count, predicate traversal and total snapshot frame size must be explicit and tested with counted cases. + +## Status and diagnostics + +| Status | Required evidence | +|---|---| +| PROVEN_STATICALLY | a specified verifier proof of the obligation, including coverage | +| CHECKED_AT_RUNTIME | mandatory evaluation at every specified boundary | +| ASSUMED_UNSAFE | an explicit unsafe assumption and its visible boundary; never inferred from an empty effect list | +| UNPROVEN | no discharged obligation; no caller may rely on it as a fact | + +The initial proof calculus and whether unproven/assumed clauses may be accepted remain undecided. The audit table must identify clause, boundary, status and source/AIR position; existing assertion counts remain counts. Proposed E7xxx reason fields and new AIR/contract trap codes are not allocated by this draft. + +Valid target example: a function with `requires { x > 0u64; }` and `ensures { result == old(x); }` returning x; a positive argument succeeds and zero traps at entry. Rejected target example: a postcondition dereferencing an owner consumed by the body; the existing availability rule must still reject it. These are design targets, not current conformance fixtures. + +## Invariants and unresolved decisions + +Type invariants require a choice between enforcing every construction/write and introducing encapsulation plus checked publication boundaries. Spec 15 §14.1 currently permits imported construction and field access; function-boundary checks alone do not establish a value invariant. Exclusive mutation, nested aggregates, value.swap, outcomes, transfers and partial initialization all need explicit coverage rules. + +Module invariants need a definition of their roots and observation boundaries. Source 0.1 has no module-state declarations or visibility modifiers; neither nonexistent globals nor arbitrary private-state semantics may be inferred from spec 13's example. Loop invariants, if included by P6-6, need an explicit initiation/preservation/exit rule. Implementing function contracts alone leaves these requirements and P6-6 open. + +Remaining decisions: predicate language/types and totality; mutable/linear result views and cleanup order; snapshot limits; proof and assumption modes; invariant boundaries; AIR grammar and compatibility; traps, fuel and report schema. The RFC stays Draft until these have concrete rules and counterexamples. + +## Compatibility and integration + +An AIR0 implementation must preserve all earlier accepted behavior, canonical bytes and rejected codes (spec 07 §8.7). Preserving the old E0001 for an unfeatured header conflicts with §8.1's required E0006; replacing it with E0006 conflicts with §8.7. Q-055 records the existing trusted-header precedent, not an exception contracts may assume. An instruction-based form fits the E0004 exception; the header candidate requires an owner decision on compatibility policy or AIR1. + +On acceptance integrate spec 13 §1, spec 08 §8, spec 10 §6.1, spec 07/07a, spec 15, grammar, feature/error registries and the Quick Reference together. Delivery requires source/AIR positive and negative coverage, bypass attempts, generic/package/worker cases, borrow/loan/snapshot failures, deterministic profiles/schedules and independently verified audit statuses. No implementation is authorized by this Draft alone. + +## Agent complexity impact + +New concepts: boundary obligations, result/old observations and audit statuses. New verifier state: descriptor bindings, predicate restrictions, snapshot and return availability, plus the chosen invariant/proof state. New source forms: contract clauses and contextual result/old; diagnostic and AIR counts await a completed design. + +Assertions express individual checks today, but the probes show why they do not encode a public guarantee with verified coverage. The cost must be compared with keeping explicit checks and making no contract claim. No SMT solver, implicit allocation or effect inference is proposed. + +This Draft adds zero normative bundle tokens: it is outside both manifests. Before acceptance, measure Quick Reference, source and AIR growth with `zig build agent-reference` and `tools/agent_bundle_tokens.py`; report all three tokenizers and justify growth. Zero current growth is not an estimate of the delivered feature. + +## Memory/concurrency review obligations + +The acceptance change must demonstrate: preserved availability/alias/loan invariants; independent AIR boundary-access rules; runtime coverage/order; valid and rejected source/AIR examples; diagnostic/trap codes; deterministic fuel/schedule behavior; and legacy compatibility. These are requirements for the completed design, not claims that the Draft has discharged them. Ordinary verifier/interpreter rules remain unchanged today. + +## Alternatives considered + +Frontend-generated asserts with annotations fail the coverage invariant. Inline contract instructions plus a boundary-coverage verifier could satisfy it, but require explicit entry/return and snapshot state. Callee-enforced descriptors avoid that bypass class while enlarging interpreter invocation semantics. A format-1 design remains an alternative if format-0 compatibility cannot be proved.