From 21500678584c042f7e18f77e6b19110f6702211e Mon Sep 17 00:00:00 2001 From: Atoma Date: Thu, 22 Oct 2026 15:43:12 +0000 Subject: [PATCH 1/6] Atoma Phase 0/1: frontend extract+check, subset gates G8-G10, Agda soundness (store-free core) - tools/atoma: std.zig.Ast frontend (extract doc-comment contracts, subset check with 21 E-* codes), src-hash command, canonicaliser + mutation ops - examples/atoma/frame-v1: verified frame parser (11 tests, 4 targets), Face A/B .cspec at the same seam hash, 14 discharged VCs, negative corpus (20 diagnostics / 17 codes), verify.sh gates G1-G11 + receipt - verification/atoma: Bv/Lin/Core/Soundness under agda --safe --without-K; the adequacy theorem for the store-free core fragment, with the refinement gap stated as a non-claim - docs/spec: specification v0.1 with the claims ledger, soundness statement, worked example, roadmap with falsifiers, and reproduction appendix Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .gitignore | 2 + docs/spec/ATOMA-SPEC.adoc | 1511 +++++++++++++++++ docs/spec/README.adoc | 18 + examples/atoma/frame-v1/README.adoc | 88 + examples/atoma/frame-v1/abi/FrameAbi.idr | 377 ++++ examples/atoma/frame-v1/abi/FrameAbi.ipkg | 22 + examples/atoma/frame-v1/abi/Linearity.idr | 40 + .../atoma/frame-v1/fixtures/violations.zig | 91 + examples/atoma/frame-v1/spec/face-a.cspec | 30 + examples/atoma/frame-v1/spec/face-b.cspec | 31 + examples/atoma/frame-v1/spec/layout.cspec | 60 + examples/atoma/frame-v1/src/atoma.zig | 67 + examples/atoma/frame-v1/src/frame_parse.zig | 586 +++++++ examples/atoma/frame-v1/tools/layout.sh | 26 + .../atoma/frame-v1/tools/layout_check.zig | 47 + .../atoma/frame-v1/tools/layout_negative.zig | 33 + .../atoma/frame-v1/tools/layout_witness.zig | 92 + .../frame-v1/vc/V1_needle_drop_requires.smt2 | 11 + .../atoma/frame-v1/vc/V1_no_underflow.smt2 | 14 + .../frame-v1/vc/V2_mutant_off_by_one.smt2 | 16 + .../vc/V2_needle_drop_payload_bound.smt2 | 15 + .../atoma/frame-v1/vc/V2_slice_in_bounds.smt2 | 17 + .../atoma/frame-v1/vc/V3_intcast_range.smt2 | 15 + .../frame-v1/vc/V3_needle_drop_ffi_bound.smt2 | 11 + .../atoma/frame-v1/vc/V4_maxplus_bound.smt2 | 16 + .../frame-v1/vc/V5_magic_wire_order.smt2 | 17 + .../frame-v1/vc/V5_mutant_wrong_endian.smt2 | 17 + .../frame-v1/vc/V6_mutant_offset_drift.smt2 | 16 + .../atoma/frame-v1/vc/V6_padding_zeroed.smt2 | 16 + .../frame-v1/vc/V7_post_payload_len.smt2 | 20 + .../frame-v1/vc/V8_premise_satisfiable.smt2 | 12 + examples/atoma/frame-v1/vc/gen_vcs.py | 276 +++ examples/atoma/frame-v1/verify.sh | 216 +++ .../atoma/frame-v1/witness/agda-report.txt | 5 + .../frame-v1/witness/phase0.receipt.json | 1 + .../atoma/frame-v1/witness/subset-report.txt | 1 + examples/atoma/frame-v1/witness/vc-report.txt | 22 + .../frame-v1/witness/violations-report.txt | 21 + tools/atoma/.zig-version | 1 + tools/atoma/build.zig | 41 + tools/atoma/src/canon.zig | 637 +++++++ tools/atoma/src/frontend.zig | 662 ++++++++ tools/atoma/src/main.zig | 253 +++ verification/atoma/agda/Bv.agda | 146 ++ verification/atoma/agda/Core.agda | 258 +++ verification/atoma/agda/Lin.agda | 158 ++ verification/atoma/agda/Soundness.agda | 228 +++ verification/atoma/check-agda.sh | 43 + 48 files changed, 6303 insertions(+) create mode 100644 docs/spec/ATOMA-SPEC.adoc create mode 100644 docs/spec/README.adoc create mode 100644 examples/atoma/frame-v1/README.adoc create mode 100644 examples/atoma/frame-v1/abi/FrameAbi.idr create mode 100644 examples/atoma/frame-v1/abi/FrameAbi.ipkg create mode 100644 examples/atoma/frame-v1/abi/Linearity.idr create mode 100644 examples/atoma/frame-v1/fixtures/violations.zig create mode 100644 examples/atoma/frame-v1/spec/face-a.cspec create mode 100644 examples/atoma/frame-v1/spec/face-b.cspec create mode 100644 examples/atoma/frame-v1/spec/layout.cspec create mode 100644 examples/atoma/frame-v1/src/atoma.zig create mode 100644 examples/atoma/frame-v1/src/frame_parse.zig create mode 100755 examples/atoma/frame-v1/tools/layout.sh create mode 100644 examples/atoma/frame-v1/tools/layout_check.zig create mode 100644 examples/atoma/frame-v1/tools/layout_negative.zig create mode 100644 examples/atoma/frame-v1/tools/layout_witness.zig create mode 100644 examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 create mode 100644 examples/atoma/frame-v1/vc/V1_no_underflow.smt2 create mode 100644 examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 create mode 100644 examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 create mode 100644 examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 create mode 100644 examples/atoma/frame-v1/vc/V3_intcast_range.smt2 create mode 100644 examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 create mode 100644 examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 create mode 100644 examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 create mode 100644 examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 create mode 100644 examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 create mode 100644 examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 create mode 100644 examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 create mode 100644 examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 create mode 100644 examples/atoma/frame-v1/vc/gen_vcs.py create mode 100755 examples/atoma/frame-v1/verify.sh create mode 100644 examples/atoma/frame-v1/witness/agda-report.txt create mode 100644 examples/atoma/frame-v1/witness/phase0.receipt.json create mode 100644 examples/atoma/frame-v1/witness/subset-report.txt create mode 100644 examples/atoma/frame-v1/witness/vc-report.txt create mode 100644 examples/atoma/frame-v1/witness/violations-report.txt create mode 100644 tools/atoma/.zig-version create mode 100644 tools/atoma/build.zig create mode 100644 tools/atoma/src/canon.zig create mode 100644 tools/atoma/src/frontend.zig create mode 100644 tools/atoma/src/main.zig create mode 100644 verification/atoma/agda/Bv.agda create mode 100644 verification/atoma/agda/Core.agda create mode 100644 verification/atoma/agda/Lin.agda create mode 100644 verification/atoma/agda/Soundness.agda create mode 100755 verification/atoma/check-agda.sh diff --git a/.gitignore b/.gitignore index 638db641..845e0cf5 100644 --- a/.gitignore +++ b/.gitignore @@ -95,6 +95,7 @@ sync_report*.txt # Hypatia scan cache (local-only) .hypatia/ .zig-cache/ +zig-out/ target/ node_modules/ _build/ @@ -142,5 +143,6 @@ verification/proofs/coq/*.vos verification/proofs/coq/*.glob verification/proofs/coq/.*.aux # Agda compiled proof artifacts +*.agdai verification/proofs/agda/*.agdai diff --git a/docs/spec/ATOMA-SPEC.adoc b/docs/spec/ATOMA-SPEC.adoc new file mode 100644 index 00000000..d736fdbd --- /dev/null +++ b/docs/spec/ATOMA-SPEC.adoc @@ -0,0 +1,1511 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += Atoma +:subtitle: A verifier for Zig at the Idris2 ABI seam — specification v0.1 +:toc: +:toclevels: 3 +:sectnums: +:icons: font +:source-highlighter: highlight.js + +[abstract] +-- +Atoma proves properties of Zig code that crosses a C ABI boundary, starting from +the contract already written in Idris2 and extending to a deliberately small, +checkable subset of Zig. It follows the shape of Ada/SPARK and Rust/Creusot: one +name for the subset, the contracts and the toolchain; Zig is the language, Atoma +is what checks it. + +Three artefacts are normative: the contract IR (`.cspec`), the canonical bytes +of that IR (BLAKE3-addressed), and the SMT verification conditions derived from +them. Everything else — the CLI, the canonicaliser, the VC generator — is +untrusted plumbing that can be replaced without weakening a proof. + +This document is the design specification. It is deliberately explicit about +which of its own claims are machine-checked in this repository +(<>), and which are specified but not yet discharged. Nothing +here is a claim of full functional correctness for Zig. +-- + +:sectnums!: + +[[claims-ledger]] +== Status and claims ledger + +[cols="1,1,3,2", options="header"] +|=== +| Claim | Status here | Evidence | Where it fails loudly + +| Face A and Face B elaborate to the same Core Spec IR bytes +| *checked* +| gate G5: both faces hash to `blake3:f5f97a7b…265756` +| G5 exits non-zero on divergence + +| A one-token spec change changes the digest (equivalence is not vacuous) +| *checked* +| gate G5 divergence probe: `blake3:d49201f2…ffca70` +| G5 fails if the probe matches + +| Every declared size/align/offset/padding range holds on x86_64, aarch64, riscv64, wasm32 +| *checked* +| gate G3: 60 compiler-witnessed rows in `spec/layout.cspec` +| `@compileError` inside the witness aborts the gate + +| A pointer-width-dependent struct is rejected on wasm32 +| *checked* +| gate G4: `tools/layout_negative.zig` fails to compile for wasm32 +| gate G4 inverts: it fails if the bad struct is accepted + +| The example implementation is in the subset and passes its tests +| *checked* +| gate G1: 11/11 tests, Zig 0.15.2 and 0.16.0 +| `zig test` exit status + +| The example compiles for all four ABI target classes +| *checked* +| gate G2 +| `zig build-obj` exit status + +| The 14 SMT obligations of the worked example are valid +| *checked* (when z3 present) +| gate G7: 14/14, including 6 counterexample-producing queries +| G7 fails if any query returns an unexpected result + +| Linear handles are released exactly once on every path +| *checked* (model-level) +| `verification/atoma/agda/Lin.agda`, `theorem-rel-once` +| `agda --safe --without-K` rejects the module + +| No wraparound can be silently coerced to an integer +| *checked* (for `Fin 2^64`) +| `Bv.agda`: `word-inj`, `word-bound`, `no-bound-2^64` +| `agda --safe --without-K` + +| Specification mutants are distinct, content-addressed artefacts +| *checked* +| gate G6: 11 operators, 11 applied, 11 distinct +| G6 fails on collision + +| Face B is *derived* from the Zig source, not hand-maintained beside it +| *checked* +| gate G8: `atoma extract src/frame_parse.zig` reproduces `spec/face-b.cspec`, `blake3:ee4d77f0…eb2358` +| G8 fails on any drift; the fix is to re-extract and commit + +| The implementation is inside the subset, with every export contracted +| *checked* +| gate G9: 6 exports, 6 contracts, 0 `E-*` diagnostics +| `atoma check` exits 1 on any diagnostic + +| The subset checker is not vacuous +| *checked* +| gate G10: `fixtures/violations.zig` yields 20 diagnostics over 17 distinct codes +| G10 fails if the corpus is accepted or the counts drop + +| The VC generator is sound for the core fragment (the §6.3 theorem) +| *checked*, for the *store-free* fragment only +| gate G11: `Core.agda` + `Soundness.agda` typecheck under `--safe --without-K`, `blake3:e2b2f961…647249`; no postulates, no termination pragmas, no holes +| G11 fails to compile; the theorem's type states its fragment, so it cannot be read wider than it is + +| The checked theorem says something about a Zig program +| *no* — it relates `vc` to `safe`, both Agda functions +| §6.4 "the refinement gap"; the simulation from `Stmt` to the subset's operational semantics is unwritten +| nothing in the receipt claims it; listed as non-claim N3 + +| Mutants are *killed* at ≥ 95 % +| *not yet* — needs the ECHIDNA loop +| Phase 1 exit criterion, §10 +| the score is computed by `echidna mutate`, not asserted here + +| The Idris2 contract module typechecks +| *not here* — no Idris2 in the authoring environment +| `abi/FrameAbi.idr` is normative text; gate F0.1 runs `idris2 --typecheck` +| F0.1 is a Phase 0 entry gate, currently unrun + +| `spec/face-a.cspec` is what `encode frameParse` actually prints +| *not yet* — it is a hand transcription of that output +| F0.1 diffs the extractor output against the checked-in file; the seam hash makes any difference visible +| the diff is non-empty, or the seam hash changes + +| The Dedukti witness typechecks and passes `coqchk` + `lean4checker` +| *no* — no `dkcheck`, Coq or Lean here +| `.dk` emission is specified in §7.4, not implemented +| receipt stays `INCOMPLETE (Warrant)` until it is +|=== + +The receipt written by `examples/atoma/frame-v1/verify.sh` says exactly this: +`schema atoma.receipt.v1`, `status INCOMPLETE`, `status_class Warrant`. It is +promoted to `COMPLETE / Receipt` only by the batch kernel check of §7.4. + +:sectnums: + +== Executive architecture + +Atoma has one specification surface, two front doors, and one trust boundary. + +.... + ┌───────────────────────────── TRUSTED SPECIFICATION ──────────────────────────────┐ + │ Idris2 (abi/*.idr) %default total · QTT 0/1/ω · no postulate, believe_me │ + │ Contract value ──► encode : Contract → String (canonical by construct) │ + └──────────────────────────────────┬───────────────────────────────────────────────┘ + │ Face A: extracted bytes + Zig source ──┐ │ ┌── Face B: //! @… or .zigspec + │ ▼ ▼ + │ ┌──────────────────────────────────────────────┐ + │ │ Core Spec IR (.cspec) │ + │ │ canonicalise → BLAKE3 → seam-equivalence │ + │ └───────────────┬──────────────────────────────┘ + │ │ + std.zig.Ast ──────┴──► subset check ────┤ + (syntax) │ │ comptime layout witness + AstGen → ZIR │ │ (@sizeOf/@offsetOf, per triple) + (fingerprint, optional) ▼ ▼ + ┌──────────────────────────────────────────────┐ + │ VC generator (untrusted, Ada/SPARK target) │ + │ AoRTE · bounds · layout · padding · linear │ + └───────────────┬──────────────────────────────┘ + │ SMT-LIB QF_BV / QF_ABV + ▼ + ┌──────────────────────────────────────────────┐ + │ ECHIDNA dispatch: Why3 · z3/cvc5 · Alethe │ + └───────────────┬──────────────────────────────┘ + │ proof trace + ▼ + ┌──────────────────────────────────────────────┐ + │ strict Dedukti .dk (content addressed) │ + └───────────────┬──────────────────────────────┘ + dkcheck ──────┤ + coqchk (0 extra │ BLAKE3(.dk) ──► Proof Burrower cache + axioms) ─────────┤ + lean4checker ─────┘ + ▼ + INCOMPLETE (Warrant) ──► COMPLETE (Receipt) +.... + +Five design rules follow from the architecture, and every later decision is +traceable to one of them: + +. *The contract is a value, not a comment.* Face A is an Idris2 term; Face B is + sugar that must produce the same term. Agreement is decided by a digest, so + agreement is checkable in CI without a prover. +. *The compiler is the only oracle for layout.* No tool re-implements the C ABI + layout rules. Idris2 declares, `@sizeOf`/`@offsetOf` witness, and the witness + is itself content-addressed. +. *Untrusted parts may be wrong without being unsound.* A buggy VC generator can + reject good code (annoying, visible) or accept bad code (caught by the kernel + checks and by mutation testing). It cannot manufacture a `COMPLETE` receipt. +. *Fail closed.* Every ambiguity — an unrepresented construct, a target without a + witnessed layout, a spec that cannot be canonicalised — is a hard error. +. *No ambient authority.* Memory, I/O and iteration all arrive through a handle + the caller passed; `MPR`'s capability footprint is a first-class line in the IR. + +== One Core Spec IR, two faces + +=== Face A: the Idris2 ABI module is the specification + +An ABI module declares a `Contract` value. The extractor is not a parser: it +prints `encode c` after typechecking, because `encode` is total and emits the +canonical form directly (de Bruijn levels for binders, decimal literals, one +space between tokens, `\n` per line). + +*Status:* the Idris2 toolchain is absent from the authoring environment, so +`spec/face-a.cspec` is a hand transcription of what `encode frameParse` prints, +not the extractor's own output. Gate F0.1 (`idris2 --typecheck`, then +`idris2 --exec extract`) replaces the transcription with the real bytes; the seam +hash makes any difference impossible to miss. Until then, the equivalence proved +in this repository is *between the two checked-in files*, and the only claim about +the Idris2 module is that it is the normative text they were transcribed from. + +The QTT quantities in the Idris2 signature are the source of the IR's `param` +quantities, and they carry the ABI's ownership story: + +[cols="1,1,4", options="header"] +|=== +| QTT | IR token | Meaning at the seam + +| `0` | `0` | erases at runtime: a ghost length, a layout proof, a refinement witness +| `1` | `1` | consumed exactly once: a linear handle, an output lease +| `ω` | `W` | borrowed for the call only: a capability token, a read-only region +|=== + +=== Face B: inline or sidecar contracts in Zig + +Two spellings, one grammar: + +[source,zig] +---- +/// //! @contract atoma.frame.parse +/// //! @kind extern +/// //! @param h W handle +/// //! @requires ( <= 12 ( len input ) ) +/// //! @ensures ( => ( = res 0 ) ( = ( magic out ) 0x5441 ) ) +export fn atoma_frame_parse(...) callconv(.c) Result { ... } +---- + +and a sidecar file `frame_parse.zigspec` holding the same body without the `///` +prefix. Rules: + +* A contract block attaches to the *next* declaration; a blank line detaches it. +* A sidecar is authoritative when both exist, and the mismatch is reported as + `E-SPEC-SHADOWED` rather than silently resolved. +* The grammar is the same `.cspec` grammar; there is no second language. + +*Status:* the inline form is implemented and is what G8 exercises; the sidecar +form and `E-SPEC-SHADOWED` are specified, not coded. `atoma extract` reads +`doc_comment` runs only, so a `.zigspec` today is a design note rather than an +input the toolchain accepts — stated here so that a reader of the grammar does +not over-read the implementation. + +[NOTE] +==== +Doc comments are not attached to declarations by `std.zig.Ast`; they are tokens in +the token list. Association is done by adjacency in the *untrusted* frontend, and +the result is hashed like any other spec. If the association is wrong, the digest +is wrong, and the seam gate fails — the failure is visible, not silent. +==== + +=== The core IR + +A `.cspec` file is a sequence of lines. `#` starts a comment; blank lines are +ignored. Tokens are separated by spaces; `(` and `)` are separate tokens. + +[cols="1,3,2", options="header"] +|=== +| Line | Grammar | Meaning + +| `cspec` | `cspec 1` | format version; must be first +| `contract` | `contract ` | identity, e.g. `atoma.frame.parse` +| `kind` | `kind extern` | `extern` = C-ABI export; `internal` = Zig-only helper +| `abisym` | `abisym ` | the `export fn` name the contract constrains +| `param` | `param [region]` | one ABI parameter, in declaration order +| `borrow` | `borrow shr\|mut ` | second-class borrow of a param +| `requires` | `requires ` | caller obligation; assumed, not proved +| `ensures` | `ensures ` | callee obligation; proved +| `invariant` | `invariant ` | loop invariant +| `assert` | `assert ` | inline proof obligation +| `assigns` | `assigns ` | regions the callee may write (set-valued) +| `cap` | `cap ` | MPR capability footprint (set-valued) +| `sort` | `sort ` | named sort declaration (set-valued) +| `field` | `field @ ` | one field row (set-valued) +| `layout` | `layout @ ` | whole-struct row (positional) +| `bound` | `bound steps ` / `bound hwm ` | MaxPlus cost, stack HWM +|=== + +Formulas are a first-order fragment over `Nat`, booleans, and the observation +functions `len`, `tag`, `magic`, `payload_len`, `zeroed`, `pad`: + +[source] +---- +fm ::= ( <= tm tm ) | ( < tm tm ) | ( = tm tm ) | ( != tm tm ) + | ( and fm fm ) | ( or fm fm ) | ( => fm fm ) | ( not fm ) + | ( forall ( %k : sort ) fm ) +tm ::= | | ( len ) | ( tag ) | ( magic ) + | ( payload_len ) | ( zeroed ) | ( pad ) + | ( + tm tm ) | ( - tm tm ) | ( * tm tm ) +---- + +`%k` is a de Bruijn *level* — 0 is the outermost binder of the enclosing formula. +Levels rather than names are used because the canonical form prints `%k`, so +alpha-invariance is a construction property rather than a renaming pass. v1 +forbids shadowing, so level and index coincide. Binder types must be atomic +(a declared sort); a compound binder type is rejected (`Error.MalformedBinder` +in `canon.zig`) rather than mis-scoped. + +=== Canonicalisation (the eight rules) + +Canonical form is defined by eight rules, implemented twice — once as `encode` +in Idris2 (normative) and once in `tools/atoma/src/canon.zig` (convenience, +differentially tested against a golden corpus): + +[cols="1,3,2", options="header"] +|=== +| Rule | Transformation | Why it is meaning-preserving + +| R1 | drop `#` comments and blank lines | lexically inert +| R2 | `(`/`)` are single-character tokens | parsing only +| R3 | one space between tokens, one `\n` per line, ASCII | whitespace is not semantic +| R4 | binder names → `%0`, `%1`, … | alpha-equivalence +| R5 | integers → unsigned decimal, no leading zeros, `0x`/`0b`/`_` accepted | literal identity +| R6 | *set-valued* lines sorted: `cap`, `assigns`, `field`, `sort` | these are sets; order is not semantic +| R7 | *positional* lines keep order: `param`, `borrow`, `requires`, `ensures`, `invariant`, `assert`, `layout`, `bound` | order **is** semantic at the seam: parameter order is the ABI, and clause order is the author's proof narrative +| R8 | digest = BLAKE3(domain ++ bytes), domains `atoma.cspec.v1`, `atoma.vc.v1`, `atoma.dk.v1` | domain separation +|=== + +`schema`-style sorting of `requires` is deliberately *not* done. Two contracts +with the same requires in a different order are the same proposition, but they +are different *documents*, and ABI review reads the order. Keeping the stricter +notion means the seam check can produce false negatives (a refusal to equate two +equivalent specs) and never a false positive on ordering. + +=== Hash-checked equivalence, and what it does not mean + +`atoma equiv face-a.cspec face-b.cspec` exits 0 iff the canonical bytes are +identical. In this repository: + +[source] +---- +$ atoma hash spec/face-a.cspec +blake3:ee4d77f0932619c5c1933d342f645a4eff85d9fead9fb0c1d9c8a0890feb2358 +$ atoma hash spec/face-b.cspec +blake3:ee4d77f0932619c5c1933d342f645a4eff85d9fead9fb0c1d9c8a0890feb2358 +$ atoma hash spec/layout.cspec +blake3:c75f72ce33010b457c8dc7f8c8514720904ddaeca9de0ce412cc7d61cf8accd1 +---- + +The verified artefact is *contract ∧ layout table*, because a drifted offset +must not be able to hide behind an unchanged contract: + +[source] +---- +face-a ++ layout = blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756 +face-b ++ layout = blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756 +---- + +*This is syntactic agreement, not semantic equivalence.* Two contracts that are +logically equivalent but differ in an unnormalised way produce different digests. +That is the safe direction: the check can refuse a correct pair, and cannot +accept an incorrect one — provided the eight rules are themselves +meaning-preserving, which is the one proof obligation the canonicaliser carries +and which is stated, not proved, in v0.1. + +== The verifiable Zig subset + +The subset is chosen so that every obligation is either discharged by SMT in +QF_BV/QF_ABV or proved once in the Agda metatheory. Anything that would need +separation logic, arbitrary heap reasoning, or a second solver is out. + +=== Classification + +[cols="3,1,1,1,3", options="header"] +|=== +| Construct | MVP | P2 | P3 | Soundness rationale + +| `u8..u64`, `i8..i64`, `usize` (local only) | ✔ | | | fixed-width, no UB in itself +| `enum(uN)` with explicit backing | ✔ | | | layout is stated, not inferred +| `extern struct` | ✔ | | | C-compatible by declaration; witnessed per target +| `struct` (non-extern), `union(enum)` | ✔ | | | internal only; never crosses the seam +| `packed struct`, `packed union` | ✘ | | | bit-level aliasing defeats the padding model +| `bool`, `usize`, `isize`, `anyopaque` in `extern` types | ✘ | | | width is target-dependent (measured: a `usize` field moves a struct from 24/8 to 12/4 — see F0.3) +| `*T`, `*const T`, `?*T` | ✔ | | | non-null by type (or explicitly optional); no arithmetic +| `[]T`, `[]const T` | ✔ | | | carries length; index bound is a VC +| `[*]T` | ◐ | | | allowed **only** when paired with an Idris2 ghost length that bounds every access +| `[*c]T` | ✘ | | | nullable, arithmetic-enabled, no provenance: banned outright +| `[*:0]T` (sentinel) | ✘ | | | length is a scan; unbounded work, no HWM bound +| pointer arithmetic (`p + i`) | ✘ | | | breaks region discipline and bounds +| `@ptrCast`, `@alignCast` | ✘ | | | type/alignment confusion; no obligation can recover it +| `@ptrFromInt` | ✘ | ✘ | ✘ | never; not even in P3 +| `@intFromPtr` / `@ptrFromInt` round-trip | ✘ | | | provenance loss +| `[N]T`, `[N:0]T` | ✔ | | | length in the type +| slicing `s[a..b]` | ✔ | | | two bound VCs; `b <= a` also checked +| `@sizeOf`, `@alignOf`, `@offsetOf`, `@bitSizeOf` | ✔ | | | comptime only, no runtime obligation +| `+ - *` and `<<` | ✔ | | | panic on overflow in safe modes; must be proved non-overflowing +| `+% -% *%` (wrapping) | ✘ | | | explicit wraparound is a bug unless modelled; requires an `Echo` residue proof +| `+%` with a written Echo witness | | ✔ | | lossy conversion with structured residue +| `@intCast` | ✔ | | | range VC required; panics otherwise +| `@truncate` | ◐ | | | allowed only with an explicit `Echo` type recording what was dropped +| `/`, `%` | ✔ | | | divisor ≠ 0 VC; `minInt / -1` VC for signed +| `@divTrunc`, `@divFloor`, `@rem`, `@mod` | ✔ | | | same obligations, named rounding +| float arithmetic | ✘ | | | NaN/rounding make the contract logic much weaker; out of scope +| `?T` + `orelse` | ✔ | | | total unwrap +| `.?` | ✘ | | | panics; banned +| `unreachable` | ✘ | | | UB in release; a proof of falsity must become an `assert`+`return` +| `error{X}` unions | ✔ | | | closed set; mapped to `enum(c_int)` at the seam +| `try`, `catch`, `errdefer` | ◐ | ✔ | | MVP: at most one fallible call, Phase 2: full linear discipline +| `defer` | ◐ | ✔ | | MVP: release-shaped only +| `while` with `invariant` + `decreases` | ✔ | | | bounded loops only; MaxPlus needs an explicit bound +| `for` over a slice | ✔ | | | bound is `len`, decreasing is structural +| recursion | ✘ | ✔ | | P2 requires a structural `@decreases` measure; no general termination +| `Allocator` as an explicit parameter | | ✔ | | MPR capability; no global allocator in MVP +| `std.heap.c_allocator` | ✘ | ✘ | ✘ | ambient OS authority; never in the subset +| global `var`, `threadlocal var` | ✘ | ✘ | | ambient mutable state; state belongs in a handle +| `volatile` | ✘ | ✘ | ✘ | defeats every reasoning principle here +| inline `asm` | ✘ | ✘ | ✘ | no model +| `@cImport` | ✘ | | | unbounded foreign surface; use explicit `extern` declarations +| function pointers / callbacks | ✘ | ◐ | | P2: only with a sealed, listed set of targets +| `comptime` functions | ✔ | | | evaluated, no runtime obligation +| generics | ✔ | | | monomorphised before extraction +| `async`, threads, atomics | ✘ | ✘ | ✘ | no concurrency model in v1 +| `@panic`, `std.debug.assert` | ✘ | | | panics; use `errdefer` + error return +| `extern` with non-C calling convention | ✘ | | | `.c` is required and checked + +|=== + +Legend: ✔ included · ◐ restricted (see the row) · ✘ excluded. + +=== Pointers, slices, and the ghost length + +The rule for `[*]T` is the only place the subset depends on a proof rather than a +type. A many-item pointer has no length, so every access `p[i]` needs `i < n` +where `n` is a length the compiler cannot see. Atoma requires `n` to arrive as an +Idris2 ghost (`input_len : U32` with `Eq (Len "input") (Var "input_len")` in the +contract). Without that equation, the pointer does not typecheck into the subset. + +`[]T` needs no ghost: the length is in the value, and the only obligation is +`i < s.len`, which is a QF_BV query. + +`[*c]T` is banned with no exceptions because three separate properties fail at +once: it is nullable (so no `?` discipline), it permits arithmetic (so no region +discipline), and it carries no length (so no bounds discipline). Recovering any +one of them requires the other two. + +=== Aliasing: a second-class borrow discipline + +Zig has no borrow checker, so Atoma imposes one at the seam, in the style of +`ephapax`'s L1/L2 regions: + +. *Regions are named and finite.* Every parameter belongs to a region mentioned + in the contract (`r0`, `r1`, …), and the region set is closed at the signature. +. *Borrows are second-class.* A borrow may be passed as an argument and used in + the callee; it may not be stored in a struct, returned, or captured by a + closure. There is no place for it to escape to. +. *Shared borrows may alias; mutable borrows may not.* Two `shr` borrows of the + same region are allowed. A `mut` borrow is exclusive: the contract may not + contain another borrow of the same region (`E-BORROW-EXCL`). +. *Regions are disjoint by declaration.* `assigns r1` means writes are confined + to `r1`; a write through an `r0` pointer is `E-REGION-WRITE`. +. *Quantities are checked, not suggested.* A `1` parameter must be consumed + exactly once on every path (`Lin.agda`). + +This is enough to prove the worked example's central alias property — the output +struct points into the caller's input buffer, and the contract says so — without +a separation-logic solver. It is explicitly *not* a general borrow checker: it +says nothing about heap aliasing inside a callee that allocates. + +=== ABI and layout + +Rules for anything that crosses the seam: + +* `extern struct` only; no `packed`, no `union` (a bare `union` at the seam is + `E-ABI-UNION`), no `usize`/`isize`/`bool`/slices/optionals-by-value. +* `enum(uN)` must name its backing integer; a bare `enum` is `E-ABI-ENUM`. +* Every integer is an explicit width. `c_int` appears only in a `callconv(.c)` + return position, and only where the C type is genuinely `int`. +* Padding is *declared*, not assumed. The layout table records padding ranges, + and every offset/range is confirmed by the compiler on each target. + +Measured layout facts for the worked example (compiler-witnessed, all four +targets; the full 60-row table is `spec/layout.cspec`): + +[cols="2,1,1,1,1,3", options="header"] +|=== +| Struct | Target | size | align | pad ranges | Notes + +| `FrameHeader` | all four | 16 | 4 | 6..8, 14..16 | target-independent: no pointers +| `FrameOut` | x86_64 / aarch64 / riscv64 | 32 | 8 | 6..8, 12..16, 28..32 | `payload` @16, `payload_len` @24 +| `FrameOut` | wasm32 | 20 | 4 | 6..8 | `payload` @12, `payload_len` @16 +| `BadOut` (`usize` field) | x86_64 | 24 | 8 | 1..8, 20..24 | rejected by the subset +| `BadOut` (`usize` field) | wasm32 | 12 | 4 | 1..4, 8..12 | the same declaration is *also* wrong here — hence F0.3 +|=== + +The `BadOut` row is the reason the ABI rule exists: a single `usize` field changes +both size and alignment, so a C header generated for one target is wrong on the +other. Atoma refuses the declaration rather than proving the wrong thing. + +=== Absence of Runtime Errors across `callconv(.c)` + +A panic inside an `export fn` is not a Zig-level error: it unwinds into foreign +code, which is UB unless the foreign code is Rust with `-C panic=abort` and a +guarantee, and even then it is a process abort. Atoma therefore discharges, for +every `export fn` in the subset: + +[cols="1,3,3", options="header"] +|=== +| Obligation | Encoding | Example VC in the worked example + +| no integer overflow | QF_BV: `¬(a ⊕ b = wrap)` | `V4_maxplus_bound` (cost arithmetic stays in range) +| no subtraction underflow | QF_BV: `a ≥ b` before `a - b` | `V1_no_underflow` +| no division by zero | QF_BV: `b ≠ 0` | (Phase 1, `crc32` has none) +| no `@intCast` truncation | QF_BV: `x < 2^w` | `V3_intcast_range` +| no out-of-bounds read/write | QF_ABV: `i + n ≤ len` | `V2_slice_in_bounds` +| no null unwrap | first-order | the `orelse` chain in `atoma_frame_parse` +| no `unreachable` | there is none in the subset | `canon` rejects the token +| no panic macro | there is none in the subset | `canon` rejects the token +| no uninitialised read | dataflow: every read dominated by a write | `atoma.zeroBytes(out)` precedes every field write +| no padding leak | QF_ABV over the struct byte range | `V6_padding_zeroed` +|=== + +`zeroed` and `pad` in the IR are observation functions, not predicates on +undefined memory: `pad out` is only satisfiable if the implementation wrote every +padding byte, which in Zig requires an explicit byte-level operation +(`atoma.zeroBytes`). A value assignment `out.* = .{...}` does not define padding +and therefore cannot discharge `pad`. + +=== Control flow, resources, and cost + +*Loops.* `while` requires an `@invariant` and a `@decreases` term. `for` over a +slice needs neither, because the bound and the variant are the slice length. +Unbounded loops are `E-LOOP-UNBOUNDED`. + +*Linear cleanup.* `defer` runs on every exit; `errdefer` runs only on error +exit. The canonical resource shape is acquire → `errdefer` release → fallible +steps → release, and `Lin.agda` proves that this shape releases exactly once on +every path, including paths that fail at the first step and paths that fail after +several. + +*Cost.* `bound steps` is a MaxPlus expression over the parameters. For +`crc32` it is `8 * len + c`, because the inner bit loop is exactly eight +iterations and the outer loop is one per byte. `bound hwm` is the maximum live +stack in bytes, computed from the largest simultaneously-live frame. + +== Idris2 ↔ Zig contract mapping + +[cols="3,3,3,2", options="header"] +|=== +| Idris2 (Face A) | Zig (Face B / implementation) | Obligation produced | Checked by + +| `MkParam "h" QW Handle` | `h: ?*const Handle` | tag check before use; no null deref | SMT + tests +| `MkParam "out" Q1 PtrOutFrame` | `out: ?*FrameOut` | non-null; exactly-once consumption | QTT + `Lin.agda` +| `MkParam "input_len" Q0 U32` | `in_len: u32` | ghost: used only in proofs, erased | typecheck +| `SliceU8` | `in_ptr: ?[*]const u8` | `len` equality from the ghost | IR equation +| `MkBorrow "input" Shared "r0"` | `[]const u8` derived from the pointer | no write through `r0` | `assigns` +| `MkBorrow "out" Mutable "r1"` | `*FrameOut` | exclusive write region | `assigns r1` +| `Le (Num 12) (Len "input")` | `if (buf.len < 12) return .truncated` | `buf.len ≥ 12` | `V1` +| `Lt (Var "input_len") (Num 0x100000000)` | `in_len: u32` | cast range | `V3` +| `Eq (MagicOf "out") (Num 0x5441)` | `out.magic = magic` | postcondition | `V7` +| `Le (PayloadLen "out") (Sub (Len "input") (Num 12))` | `out.payload_len = length` | postcondition | `V7` +| `Zeroed "out"` on error | `errdefer atoma.zeroBytes(out)` | all-or-nothing output | QF_ABV + tests +| `PadOf "out" = 0` | `atoma.zeroBytes(out)` before field writes | no padding leak | `V6` +| `MkField "crc" 8 4 4` | `crc: u32` at offset 8 | layout equality | comptime witness +| `Aligned 16 4` | `@sizeOf(FrameHeader) = 16`, `@alignOf = 4` | layout equality | comptime witness +| `MkBounds (Add (Num 12) (Mul (Num 8) (Len "input"))) 64` | the two loops | MaxPlus bound | QF_LIA (`V4`) +| `%foreign "C:atoma_frame_parse,libatoma"` | `export fn atoma_frame_parse` | symbol identity | seam gate +|=== + +Two rules make the table enforceable rather than aspirational: + +* *Every* `export fn` in the subset has a contract, or the build fails + (`E-UNCONTRACTED-EXPORT`). An uncontracted export is exactly the bug class the + tool exists to prevent. +* Every contract's `abisym` must resolve to an `export fn` of that name, or the + build fails (`E-DANGLING-CONTRACT`). Contracts cannot rot into comments. + +== Frontend: how Zig source becomes Core IR + +=== The options, measured + +[cols="2,2,2,2,3", options="header"] +|=== +| Approach | Sees | Cannot see | Churn exposure | Verdict + +| `std.zig.Ast` directly +| tokens, nodes, comments, doc comments +| types, layout, comptime evaluation, name resolution +| low for node *kinds*; the `parse` signature itself moved between 0.16 and 0.17 (`Mode` → `ParseOptions`) +| *primary* + +| typed ZIR (via `std.zig.AstGen.generate`) +| a compiler-internal instruction stream; measured: 23 instructions for a 4-line function +| types (ZIR is pre-`Sema`), layout, resolved calls +| **high**: `Zir.Inst.Tag` is a compiler detail; `Zir.inst_tracking_version` exists precisely because tracking is unstable +| *optional fingerprint only* + +| AIR +| the analysed, typed IR +| nothing — it is the real thing +| **total**: not exported by `std` at all (no `std/zig/Air.zig`); it is a compiler build artefact +| *never* + +| hybrid: `Ast` + comptime witness +| syntax from `Ast`; layout from the compiler itself via `@sizeOf`/`@offsetOf` +| semantic facts that need `Sema` (e.g. inferred error sets) +| low: two narrow, separately versioned surfaces +| *chosen* +|=== + +=== The decision, and why it survives churn + +Atoma takes syntax from `std.zig.Ast` and every *semantic fact it needs* from the +compiler, on demand, through a generated witness file: + +[source,zig] +---- +// tools/layout_witness.zig — the compiler checks the Idris2 declaration +comptime { + witness.check(FrameOut, "FrameOut", .{ + .size = 32, .alignment = 8, + .offsets = &.{ 0, 2, 4, 5, 8, 16, 24 }, + .pads = &.{ 6, 8, 12, 16, 28, 32 }, + }); +} +---- + +A declaration that does not hold is a `@compileError`, so the gate fails at +compile time on the offending target. The rows the compiler emits are transcribed +verbatim into `spec/layout.cspec` and hashed with the contract. + +This is resilient for a specific reason: *it never re-implements the compiler.* +Everything that changes between Zig releases — layout rules, calling conventions, +comptime evaluation, error-set inference — is answered by the compiler that ships +with the release. Atoma only parses syntax, and syntax is the most stable part of +Zig. When the syntax does change, the failure is a parse error in one file, not a +silently different proof. + +The unstable parts are quarantined behind two narrow surfaces: + +[cols="2,1,1,1,3", options="header"] +|=== +| API | 0.15.2 | 0.16.0 | 0.17.0 | Consequence + +| `callconv(.C)` | rejected | rejected | rejected | must be `.c` everywhere (measured on all three) +| `std.zig.Ast.parse` 3rd arg | `Mode` | `Mode` | `ParseOptions` | one-line shim, pinned per release +| `std.process.argsAlloc` | present | **removed** | **removed** | the `atoma` CLI is pinned to 0.15.2; the *verified example* builds on 0.15.2 and 0.16.0 +| `std.ArrayList(u8).init` | removed (unmanaged default) | removed | removed | use `ArrayListUnmanaged` with explicit allocator +| `std.io.getStdOut()` | removed | removed | removed | writer API reworked +|=== + +The last two rows are not hypothetical: they are the errors hit while building +this repository's own tooling, and they are why `.zig-version` pins the CLI while +the example is tested against two releases. + +=== ZIR as an optional fingerprint + +`std.zig.AstGen.generate` is public, and a standalone tool can call it: + +[source] +---- +$ ./zirprobe +ast ok, errors=0 nodes=18 +zir ok: instructions=23 strings=5 extra=72 +first 6 tags: extended declaration break_inline param dbg_stmt int +---- + +Atoma uses this in Phase 2 for one narrow job: detecting that a function's +*structure* changed between runs while its text did not (macro expansion, +`comptime` block evaluation). It is never used to derive types or layout, both of +which ZIR does not have, and ZIR is never treated as an authority — if the tag +set changes between Zig versions, the fingerprint is recomputed, and only cache +keys move. + +=== The two frontend commands + +The frontend is not a diagram in this document; it is +`tools/atoma/src/frontend.zig`, and the frontend proper is two commands. + +*`atoma extract [--symbol ]`* recovers Face B from the source. +It walks the `std.zig.Ast`, collects each `doc_comment` run immediately above an +`export fn`, and parses the directives in order: + +[cols="1,2,3", options="header"] +|=== +| Directive | Argument | Line emitted + +| `@contract` | dotted name | `contract` (required, exactly one) +| `@kind` | `extern` \| `internal` | `kind` (default `extern`) +| `@param` | `name qty sort [region]` | `param`, in source order +| `@borrow` | `name shr\|mut region` | `borrow` +| `@requires` | formula | `requires`, in source order +| `@ensures` | formula | `ensures`, in source order +| `@assert` | formula | `assert` +| `@assigns` | region | `assigns` (set-valued) +| `@cap` | `Cap region` | `cap` (set-valued) +| `@bound` | `steps ` \| `hwm ` | `bound` +|=== + +Five further directives are accepted as notes for humans and deliberately produce +no output line: `@abi`, `@decreases`, `@invariant`, `@linear`, `@frame`. They +document intent the compiler or a later phase enforces, and because they never +reach the canonical bytes they cannot drift the seam. Any other `@` word is +`UnknownDirective` — the frontend does not guess, which is the fail-closed rule +applied to its own input. + +Both `/// @x` and `/// //! @x` are accepted, because the directive block doubles +as the module-level documentation a Zig reader expects. Internal whitespace is +squashed, output lines are emitted in the fixed order above, and the result is +fed through the same canonicaliser as everything else — so extractor output and a +hand-written face agree iff they mean the same thing under the eight rules of +§2.4. Failure modes are explicit: `NoContract` (a directive block with no +`@contract`), `MultipleContracts` (two), `UnknownDirective` (a `@` word that is +not in the table). There is no silent skipping. + +The consequence is a one-way dependency: source → `spec/face-b.cspec` → seam +hash. `spec/face-b.cspec` carries a do-not-hand-edit header and G8 fails the +build if it drifts from what the extractor produces. This was not a theoretical +improvement. When the extractor first ran, the hand-written Face B had already +diverged from the source — an extra `requires` and an unbound `forall` — and the +correct repair was to regenerate the file, not to patch the parser. + +*`atoma check `* reports subset conformance. It is a token-level scan: +conservative, name-resolution-free, and explicitly *not* a type check. It emits +one line per diagnostic and exits 1 if any were produced, 3 on I/O or parse +failure. The codes are the subset's bans made readable: + +[cols="1,3,2", options="header"] +|=== +| Code | Fires on | Class + +| `E-PTR-C` | `[*c]T` anywhere | banned outright +| `E-PTR-CAST` | `@ptrCast`, `@alignCast` outside the allow-list | quarantined +| `E-PTR-INT` | `@ptrFromInt`, `@intFromPtr` | quarantined +| `E-CIMPORT` | `@cImport` | quarantined +| `E-PANIC` | `unreachable`, `@panic`, `std.debug.assert` | banned in exports +| `E-SAFETY-OFF` | `@setRuntimeSafety(false)` | banned +| `E-QUOTA` | `@setEvalBranchQuota` beyond the subset's budget | bounded +| `E-VOLATILE` | `volatile` | banned +| `E-ASM` | `asm` | banned +| `E-UNREACHABLE` | `unreachable` on a reachable path | banned +| `E-ABI-PACKED` | `packed struct` at the seam | banned +| `E-ABI-UNION` | `union` at the seam | banned +| `E-ABI-WIDTH` | a pointer-width-dependent field crossing the seam | requires a ghost +| `E-ALLOC-AMBIENT` | allocator obtained from ambient state | needs a capability +| `E-GLOBAL-VAR` | mutable global `var` | banned +| `E-OPTIONAL-UNWRAP` | `.?` on a payload that may be absent | needs a proof +| `E-UNCONTRACTED-EXPORT` | `export fn` with no directive block | banned +| `E-DANGLING-CONTRACT` | a directive block above a non-export | rejected +| `E-ABI-CALLCONV` | an explicit non-`.c` callconv at an export | rejected +| `E-ABI-NO-CALLCONV` | an `export fn` without `callconv(.c)` | rejected +| `E-PARSE` | the file does not parse | fatal +|=== + +Two properties matter more than the list. First, it is *conservative*: a false +positive costs a rename or a `@contract` line, a false negative costs a soundness +claim, and the checker is built to prefer the former. Second, it is +*non-vacuous*, and that is a gate rather than an assertion: `fixtures/violations.zig` +is a negative corpus of ~20 violations spanning 17 codes, and G10 fails if the +checker accepts it or if the code coverage drops (measured: 20 diagnostics, +17 distinct codes). + +What the checker cannot see is as important as what it can. It does not resolve +names, evaluate `comptime`, compute layout, or reason about data flow; those come +from the compiler witness (§5.2) and the VC pipeline (§7). A green `atoma check` +means "nothing on the ban list appears", never "this function is correct". + +== Semantics and soundness + +=== The core language + +Two grammars matter here, and confusing them is the easiest way to overclaim. +The *target* grammar is what the VC generator is specified to cover by the end of +Phase 2. The *checked* grammar is what `verification/atoma/agda/Core.agda` +formalises today, and it is a strict subset of the target. Every theorem in +§6.3 is stated over the checked grammar, so a reader cannot mistake a +specification for a proof. + +*Target grammar* (Phase 1–2 scope): + +[source] +---- +e ::= n | x | e ⊕ e | len(e) | e[e] | &x | *p | cast_w(e) +s ::= skip | x := e | s ; s | if e then s else s + | while e inv I dec V do s | assert φ | return e + | acquire x | release x | defer s | errdefer s | try s +σ ::= x ↦ v, … (store) +---- + +Small-step configurations are `⟨s, σ⟩`, `⟨ret v, σ⟩`, `⟨err c, σ⟩`, and the +absorbing `UB`. `UB` is reached exactly when: `e₁ - e₂` with `v₁ < v₂`; `e₁ + e₂` +outside `2^w`; `e[i]` with `i ≥ len`; `e / 0`; `cast_w(e)` out of range; a read +of uninitialised memory; a dereference of a released handle; or the token +`unreachable`. Every one of those has a VC schema in §6.2. + +*Checked grammar* (`Core.agda`): + +[source] +---- +Tm ::= lit n | var x | add Tm Tm | mul Tm Tm | sub Tm Tm | div Tm Tm +Fm ::= tt | le Tm Tm | eq Tm Tm | and Fm Fm | neg Fm Fm +Stmt ::= skip | bind Tm | seq Stmt Stmt | assert Fm | ite Fm Stmt Stmt +---- + +`exec : Stmt → Val → Val` is total and never inspects its own safety; +`safe : Stmt → Val → Bool` is a separate predicate. Keeping them apart is +deliberate: it is what lets a compensating bug in the evaluator be caught rather +than hidden inside the safety predicate. Two constructs carry the whole risk +model — `sub` is undefined when the subtrahend exceeds the minuend, `div` when +the divisor is zero — and they are exactly the two states the generator emits +obligations for. + +The checked fragment is *store-free*. `bind e` evaluates and discards, and `Tm` +has no constructor that reads a value a statement wrote. This is not a shortcut +taken to make the proof go through; it is the discipline the seam already +imposes. Path conditions are stated over parameters (`r0`); writes go to the +output region (`r1`); `assigns` keeps them disjoint. A store would require the +framing lemma — a statement that writes nothing mentioned by the path condition +preserves it — before `soundness` could be proved, and postulating that lemma +would be strictly worse than not formalising the store at all. + +=== The VC generator + +`vc : Contract → Stmt → List Obligation`, where +`Obligation = (premises : List Fm, goal : Fm)`, and validity is +`∀σ. σ ⊨ premises ⟹ σ ⊨ goal`. + +[cols="1,2,3", options="header"] +|=== +| Schema | Generated from | Shape + +| `vc-sub` | `a - b` | `pre ⟹ a ≥ b` +| `vc-add` | `a + b`, `a * b`, `a << k` | `pre ⟹ a ⊕ b < 2^w` +| `vc-div` | `a / b` | `pre ⟹ b ≠ 0` (and `¬(a = minInt ∧ b = -1)` for signed) +| `vc-cast` | `@intCast` to `w` | `pre ⟹ a < 2^w` +| `vc-idx` | `s[i]`, `p[i]` | `pre ⟹ i < len(s)` (or `i < ghost`) +| `vc-slice` | `s[a..b]` | `pre ⟹ a ≤ b ∧ b ≤ len(s)` +| `vc-pad` | struct leaves the seam | `pre ⟹ pad(x)` after `zeroBytes` +| `vc-post` | `ensures` block | `pre ∧ res = ok ⟹ φ` +| `vc-err` | error paths | `pre ∧ res ≠ ok ⟹ ψ` (e.g. output zeroed) +| `vc-inv` | loop invariant | entry, preservation, exit +| `vc-term` | `decreases V` | `V' < V` (MaxPlus order) +| `vc-vacuous` | every contract | `pre` is satisfiable +|=== + +`vc-vacuous` is not optional. A contradictory precondition makes every other VC +trivially valid, and a specification that proves nothing is worse than none. + +The checked generator implements four of these schemas — `vc-sub`, `vc-div`, +`vc-assert` (an `assert` becomes its own obligation) and the path-condition +refinement at `ite` — plus the recursive walk that carries the path condition +into subterms. Each hazard obligation is *guarded* by that path condition, so an +unguarded `len - 12` still emits an obligation; its premise is `tt`. Vacuity is +therefore a property of the premise rather than of whether an obligation exists, +which is precisely why `vc-vacuous` is a schema of its own. + +=== The soundness theorem + +Two statements live here. The first is machine-checked today; the second is the +Phase 2 target. They are not merged into one theorem, because the difference +between them is the entire remaining proof obligation. + +*Checked* (`Soundness.agda`, under `agda --safe --without-K`): + +[source] +---- +soundness : + ∀ (s : Stmt) (pc : Fm) (v : Val) → + AllValid (vc pc s) -- every emitted obligation holds in every state + → ⟦ pc ⟧f v ≡ true -- the entry state satisfies the path condition + → safe s v ≡ true -- `s` cannot reach UB from `v` +---- + +with `AllValid [] = ⊤`, `AllValid (o ∷ os) = OblValid o × AllValid os`, and +`OblValid (mkObl pre goal) = ∀ v → ⟦ pre ⟧f v ≡ true → ⟦ goal ⟧f v ≡ true`. +That last type is exactly what a solver answers when it returns UNSAT for +`premises ∧ ¬goal` with the variables universally quantified — which is why the +theorem composes with §7 instead of sitting beside it. + +*Target* (Phase 2; the checked statement is its `safe` component): + +[source] +---- +soundness-full : + ∀ {Γ c s} → + wellFormed Γ s -- the program is inside the subset + → kernel-valid (vc c s) -- every obligation is valid, checked by the + -- kernel chain of §7, not by a solver's say-so + → σ ⊨ pre c + → (¬ (⟨ s , σ ⟩ ⟶* UB)) -- (1) no undefined behaviour, ever + × (∀ σ' → ⟨ s , σ ⟩ ⟶* ⟨ ret ok , σ' ⟩ → σ' ⊨ post c) -- (2) postcondition + × (∀ σ' → ⟨ s , σ ⟩ ⟶* ⟨ err _ , σ' ⟩ → σ' ⊨ errpost c) -- (3) error postcondition + × consumed-exactly-once s σ -- (4) linear resources (Lin.agda) + × (∀ σ' → ⟨s,σ⟩ ⟶* σ' → steps ≤ bound c) -- (5) MaxPlus bound +---- + +Proof structure, in the order Phase 1 built it: + +. *Adequacy — done for the checked fragment.* `tm-safe` shows that every hazard + `tmObls` can see is discharged by a valid obligation, so `safeTm e v` holds; + `soundness` is then structural induction over statements, refining the path + condition at `assert` and at each branch of `ite`. `exec-id` supplies the one + state law the fragment needs: with no store, a statement leaves the valuation + alone, so a condition proved at entry is still true at every later point. That + lemma is true *only* store-free, and it is the exact reason the fragment is + drawn where it is. +. *Adequacy over words — done separately.* The bitvector gap is closed in + `Bv.agda` (`word-inj`, `word-bound`, `no-bound-2^64`, and the coercion bridge). + `Core.agda` reasons over `Nat`; the generator emits an explicit range + obligation at every lowering, so the two models meet at a stated side condition + rather than inside one conflated type. +. *Progress and preservation over a store, loops, and the heap — Phase 2.* +. *Linear accounting.* `consumed-exactly-once` is `Lin.exactly-once`; lifting it + over the statement structure needs the store the checked fragment does not + have, hence Phase 2. +. *MaxPlus composition.* `bound` is a monoid homomorphism from sequencing to + `max`/`+`, so the bound of a sequence follows from the bounds of its parts. + +*Status.* All four modules — `Bv`, `Lin`, `Core`, `Soundness` — typecheck under +`agda --safe --without-K`, with no `postulate`, no termination pragma, no rewrite +rule, no cubical primitive and no hole. Gate G11 re-runs the check and greps for +each forbidden construct independently of `--safe`, because a reader should not +have to take the flag's word for it. Two corollaries make the worked example +small enough to read: `guarded-safe` proves `len - 12` safe for every state +satisfying `12 ≤ len`, and `unguarded-not-valid` refutes the obligation for the +unguarded program with the state `λ _ → 0` — the same `buf_len = 0` model z3 +returns for `V1_needle_drop_requires`. + +=== The refinement gap, stated as a non-claim + +The checked theorem relates `vc` to `safe`: two Agda functions over the checked +grammar. It says nothing about a Zig program. Closing that gap needs a +refinement proof — a simulation between `Stmt` and the subset's operational +semantics — and, for anything the compiler rewrites, a compiler-correctness or +translation-validation argument. Atoma claims neither, and the roadmap does not +schedule them. + +The design compensates by keeping the untrusted step small. The seam admits only +bitvectors, slices with ghost lengths, disjoint named regions, and no aliasing; +that is small enough to review by hand in Phase 1, and it is the part a +mechanisation in Phase 2 would have to cover. What the theorem buys meanwhile is +still concrete: the *generator* is proved sound, so a false "discharged" verdict +cannot come from `vc` emitting the wrong obligation. It can come from the solver, +from the encoding of a VC into SMT-LIB, or from the refinement step — and each of +those is separately attacked (§7.2 for the encoding traps, the independently +written `vc/gen_vcs.py` for the re-derivation, G7's six counterexample-producing +queries for the solver). + +=== Why the Agda side is restricted + +The Dedukti-CIC subset is a *transport* constraint, not an aesthetic one. Every +feature outside it has no faithful encoding in Dedukti, so a proof that used it +could not be exported as a `.dk` witness, and therefore could not be checked by +`coqchk`/`lean4checker`. The restrictions: + +* no cubical primitives (no path types, no `--cubical`, no `--two-level`); +* no inductive-recursive or inductive-inductive definitions; +* no rewrite rules, no `{-# REWRITE #-}`; +* no `postulate`, no `{-# TERMINATING #-}`, no `--allow-unsolved-metas`; +* structural recursion only — well-founded recursion is replaced by an explicit + fuel argument (`Bv.agda`'s truncation is the worked instance: a structural + `modStep` on fuel rather than a `<-rec`). + +== Verification conditions to certificates + +=== The pipeline + +[cols="1,2,3,2", options="header"] +|=== +| Stage | Tool | Artefact | Content address + +| contract | Idris2 `encode` / `.zigspec` | `.cspec` | `atoma.cspec.v1` +| seam check | `atoma equiv` | digest pair | equality of the above +| subset check | Atoma frontend | `E-*` diagnostics | source hash +| layout witness | `zig build-obj` + `@compileLog` | `layout.cspec` rows | folded into the seam digest +| VC generation | Atoma (Ada/SPARK target) | `.smt2` per obligation | `atoma.vc.v1` +| solving | z3/cvc5 via ECHIDNA | `unsat` + proof trace | solver + version in the cache key +| Alethe → Dedukti | ECHIDNA exchange | `.dk` | `atoma.dk.v1` +| kernel check | `dkcheck`, then `coqchk` + `lean4checker --fresh` | receipt | batch digest +| cache | Proof Burrower | hit/miss | `BLAKE3(.dk)` +|=== + +=== The traps + +*Bitvector vs mathematical integer.* SMT reasons in `QF_BV` with modular +arithmetic; the specification is written in `Nat`. Every lowering therefore emits +a range obligation, and the Agda side states its lemmas over `Fin (2^w)` so the +two agree. The trap is real and it bit this repository: the first version of +`V3_intcast_range` had only the upper bound as a premise, and z3 correctly +returned *sat* with `buf_len_usize = 0`, because `0 - 12` wraps to `2^64 - 12` +in `BV64` even though it is obviously fine in `Nat`. The fix was to carry the +no-underflow premise into the bitvector query — the obligation that needs one +premise over `Nat` needs two over `BV`. + +*Empty types and vacuity.* A goal of type `⊥` is proved by anything; a premise of +type `⊥` proves everything. Two defences: `vc-vacuous` requires the premises to be +satisfiable, and the error type is non-empty by construction (`error{}` is +`E-EMPTY-ERRORSET` at the seam, because a function that cannot fail must return +`void`, not an uninhabited error union). + +*Off-by-one at the boundary.* `length <= avail` versus `length < avail + 1` +differs by exactly one byte and is the canonical CVE shape. The VC set contains +both the correct query and a mutant of it, and the mutant produces a model +(`buf_len = 2147483647, length = 2147483636`), not just a failure. + +*Layout drift.* A struct whose offsets are transcribed rather than witnessed +fails on one target only. `V6_mutant_offset_drift` shows the padding VC catching +a `payload` placed at 12 instead of 16. + +=== Specification mutation testing (≥ 95 %) + +Mutation testing answers the question the VCs cannot: *would this specification +have caught the bug?* For each specification mutant, rerun the whole pipeline; a +mutant is *killed* if any VC becomes invalid or any test fails. + +The eleven operators in `atoma mutate` (all applied, all distinct, gate G6): + +[cols="2,3", options="header"] +|=== +| Operator | What it weakens + +| `drop_last_requires` | one precondition — the classic vacuity-adjacent edit +| `drop_last_ensures` | one postcondition +| `tighten_le` | `≤` → `<` (over-strong: must become unprovable) +| `laxen_lt` | `<` → `≤` (under-strong: must be killed by tests) +| `off_by_one` | first literal in the last `ensures` +| `drop_cap` | removes a capability from the footprint +| `swap_region` | `r0` → `r1` (aliasing discipline) +| `qty_lax` | `1` → `W` (linearity weakening) +| `drop_padding` | removes the padding obligation from `layout` +| `drop_borrow` | removes a borrow declaration +| `widen_int` | `u16` → `u32` (ABI width drift) +|=== + +Scoring rules, so the number means something: + +. Denominator = applied mutants minus *equivalent* mutants, with the exclusion + list checked in and reviewed. An operator that produces a semantically + identical spec must be listed, not silently dropped. +. A mutant killed only by a test (not by a VC) still counts, but is reported in a + separate column, because it says nothing about the prover. +. The threshold is 95 % of non-equivalent mutants, plus 100 % on the + *vacuity* subset: a mutant that makes the precondition unsatisfiable must never + survive. + +This repository currently measures only the artefact half (11/11 distinct); the +kill half needs the ECHIDNA loop and is a Phase 1 exit criterion. + +=== From Alethe to Dedukti to a receipt + +`COMPLETE` is not awarded by a solver. It is awarded when the content-addressed +witness has been rechecked by kernels that share no code with the solver: + +[source] +---- +INCOMPLETE (Warrant) -- VCs discharged, .dk emitted, nothing else + │ + ├─ dkcheck .dk typechecks in Dedukti + ├─ coqchk (zero extra axioms) the statement is Coq-valid + ├─ lean4checker --fresh the statement is Lean-valid + │ + ▼ +COMPLETE (Receipt) -- bound to BLAKE3(.dk) and to the checker versions +---- + +The receipt records the digest *and* the TCB: Dedukti, Coq and Lean versions, and +the axiom list each kernel reported. A receipt that does not name its checkers is +a claim, not a receipt. + +== Worked example: a validated zero-copy frame + +All four artefacts live in `examples/atoma/frame-v1` and are exercised by +`verify.sh`. + +=== (a) The Idris2 ABI and contract + +`abi/FrameAbi.idr` defines the contract as a value: + +[source,idris] +---- +public export +frameParse : Contract +frameParse = MkContract + { name = "atoma.frame.parse" + , kind = "extern" + , abiSym = "atoma_frame_parse" + , params = [ MkParam "h" QW Handle + , MkParam "input" QW SliceU8 + , MkParam "input_len" Q0 U32 + , MkParam "out" Q1 PtrOutFrame ] + , borrows = [ MkBorrow "input" Shared "r0", MkBorrow "out" Mutable "r1" ] + , requires = [ Le (Num 12) (Len "input") + , Eq (Len "input") (Var "input_len") + , Lt (Var "input_len") (Num 0x100000000) + , Or (Eq (Var "h") (Var "null")) (Eq (TagOf "h") (Num handleTag)) ] + , ensures = [ Imp (Eq (Var "res") (Num 0)) (Eq (MagicOf "out") (Num frameMagic)) + , Imp (Eq (Var "res") (Num 0)) (Le (PayloadLen "out") (Sub (Len "input") (Num 12))) + , Imp (Neq (Var "res") (Num 0)) (Zeroed "out") + , Eq (PadOf "out") (Num 0) ] + , assigns = ["r1"] + , caps = ["Read r0", "Write r1"] + , bounds = MkBounds (Add (Num 12) (Mul (Num 8) (Len "input"))) 64 } +---- + +The linear wrapper makes the QTT discipline operational: + +[source,idris] +---- +parseFrame : (1 h : Handle) -> (0 ghostLen : Nat) -> (1 out : PtrOutFrame) + -> IO (Either Bits32 ()) +---- + +`1` on `h` and `out` means an implementation that drops or duplicates either is a +type error. `0` on `ghostLen` means the length proof erases and costs nothing at +runtime. + +The layout is declared, not derived: + +[source,idris] +---- +frameHeaderFields = + [ MkField "magic" 0 2 2 + , MkField "length" 2 2 2 + , MkField "flags" 4 1 1 + , MkField "tag" 5 1 1 + , MkField "crc" 8 4 4 + , MkField "reserved" 12 2 2 ] + +headerEndsAt : So (endOf frameHeaderFields == 16) +headerEndsAt = Oh +---- + +Only target-independent facts are proved in Idris2. `FrameOut` contains a pointer, +so its offsets differ on wasm32; those facts come from the compiler witness +instead of being asserted in a proof that would be false on one target. + +=== (b) The Zig implementation + +`src/frame_parse.zig` — the verified parser, trimmed to its load-bearing parts: + +[source,zig] +---- +fn parseInto(buf: []const u8, out: *FrameOut) ParseError!void { + // the linear obligation: exactly one of these two runs + errdefer atoma.zeroBytes(out); + + if (buf.len < HEADER_LEN) return error.Truncated; + + const magic = le16(buf.ptr, 0); + if (magic != MAGIC) return error.BadMagic; + + const length: u32 = le16(buf.ptr, 2); + if (buf[4] & ~FLAG_COMPRESSED != 0) return error.BadFlags; + if (le16(buf.ptr, 10) != 0) return error.BadReserved; + + const avail: u32 = @intCast(buf.len - HEADER_LEN); // V3: cast range + if (length > avail) return error.Truncated; // V2: bounds + + const payload = buf[HEADER_LEN .. HEADER_LEN + length]; + const want = le32(buf.ptr, 6); + const c = crc32Update(crc32Update(0xFFFF_FFFF, buf[0..6]), payload); + if (~c != want) return error.BadCrc; // V7: postcondition source + + atoma.zeroBytes(out); // V6: padding first + out.magic = magic; + out.length = @intCast(length); + out.flags = buf[4]; + out.tag = buf[5]; + out.crc = want; + out.payload = buf.ptr + HEADER_LEN; // zero copy + out.payload_len = length; +} +---- + +and the C shell, which carries every AoRTE obligation of the boundary: + +[source,zig] +---- +export fn atoma_frame_parse( + h: ?*const Handle, in_ptr: ?[*]const u8, in_len: u32, out: ?*FrameOut, +) callconv(.c) Result { + const handle = h orelse return .invalid_arg; + if (handle.abi_tag != HANDLE_TAG) return .invalid_arg; + const p = in_ptr orelse return .invalid_arg; + const dst = out orelse return .invalid_arg; + parseInto(p[0..in_len], dst) catch |e| return mapError(e); + return .ok; +} +---- + +Note what is *absent*: no `.?`, no `unreachable`, no `@ptrCast`, no allocator, no +global `var`, no `[*c]`, no `@setRuntimeSafety(false)`. The four `orelse` returns are the entire +null discipline, and they are total. + +`atoma.zeroBytes` is the one sanctioned pointer-cast-shaped operation in the +subset. Its soundness argument is one line and is checked by the padding VC: +`asBytes` yields exactly `@sizeOf(T)` writable bytes of a live object, and +`@memset` writes each once, so no byte of the target is undefined afterwards. + +=== (c) The generated VCs + +Fourteen obligations, generated and discharged by z3 from the `.smt2` artefacts in +`vc/` (gate G7). The table is the actual tool output: + +[cols="3,1,1,4", options="header"] +|=== +| VC | want | z3 | Meaning + +| `V1_no_underflow` | unsat | unsat | `buf.len - 12` cannot wrap once `len ≥ 12` +| `V1_needle_drop_requires` | sat | sat | without that premise: model `buf_len = 0` (the panic) +| `V2_slice_in_bounds` | unsat | unsat | `12 + length ≤ buf.len` +| `V2_needle_drop_payload_bound` | sat | sat | model `buf_len=12, length=1` — one byte past the end +| `V2_mutant_off_by_one` | sat | sat | `avail + 1` admits exactly one byte too many +| `V3_intcast_range` | unsat | unsat | `usize → u32` cast cannot trap +| `V3_needle_drop_ffi_bound` | sat | sat | called with a >4 GiB slice, it panics +| `V4_maxplus_bound` | unsat | unsat | `8·len + 12 < 2^32`, so the cost fits the domain +| `V5_magic_wire_order` | unsat | unsat | bytes `'A','T'` decode to `0x5441` +| `V5_mutant_wrong_endian` | unsat | unsat | the "obvious" `0x4154` is refuted by the same bytes +| `V6_padding_zeroed` | unsat | unsat | every padding byte keeps its `0x00` +| `V6_mutant_offset_drift` | sat | sat | `payload` @12 writes into the padding hole 12..16 +| `V7_post_payload_len` | unsat | unsat | success postcondition follows from the guard +| `V8_premise_satisfiable` | sat | sat | the precondition is not contradictory +|=== + +The whole VC set has one content address, +`blake3:72c74c012d527feab0988225098a7a110e35252794c67848ab13f010c75e3698`. +Eight queries are *discharged* (unsat: the obligation holds); six are +*counterexample-producing* (sat: either a deliberately weakened premise, or a +deliberate bug, with a model that names the failure). + +=== (d) How each bug class fails, and how mutation catches a weakened spec + +*Off-by-one slice bound.* Change the guard to `length > avail + 1`. `V2_slice_in_bounds` +is unchanged and still valid — the *implementation* changed, not the contract — so +the pipeline regenerates VCs from the new code, where the guard now only +establishes `length ≤ avail + 1`. The regenerated bound query becomes +`12 + length ≤ buf.len` under the weaker premise, z3 returns *sat*, and the model +is one byte past the end. In the worked example this is pinned as +`V2_mutant_off_by_one`. + +*Unzeroed padding.* Delete `atoma.zeroBytes(out)` before the field writes. Value +assignment leaves bytes 6..8, 12..16 and 28..32 undefined on 64-bit targets. +`V6_padding_zeroed` becomes *sat*: some padding byte is not `0x00` for some field +values. The same VC catches the subtler variant where a field was placed at a +drifted offset (`V6_mutant_offset_drift`), which is how a transcription error in a +layout table presents itself. + +*Leaked linear handle on an early error path.* If `atoma_iter_open` succeeds and a +later step returns before `atoma_iter_close`, the handle's `live` bit stays set and +`atoma_handle_destroy` returns `.busy`. The proof obligation is not an SMT query: +it is `Lin.agda`'s `theorem-rel-once`, instantiated with the body's step list, plus +the test `iterator leases are linear: leak is detected, close releases`, which +demonstrates the refusal at runtime. This is the deliberate split: *control-flow +linearity is proved once in the metatheory; its instantiation is checked by +quantities in Idris2 and by tests at the boundary.* + +*A weakened spec.* `atoma mutate` produces `drop_last_ensures`, which deletes the +`payload_len ≤ input_len - 12` clause. The implementation is untouched, the VCs +regenerate, and where the postcondition used to be checked there is now nothing to +check — so `V7` disappears from the obligation set. That is *not* a failed query; +it is a missing one. This is precisely why mutation testing is mandatory and why +"all VCs pass" is not a claim of correctness: a pipeline that only asks the +questions the spec contains cannot notice a deleted question. The kill test is +"does the *set* of VCs shrink or weaken?", which is answered by re-running the +mutation harness, not by the solver. + +*The vacuity escape.* `drop_last_requires` plus a contradictory remaining premise +would make every remaining VC trivially unsat. `V8_premise_satisfiable` is the +guard against this, and the mutation score treats "premise became unsatisfiable" +as an automatic kill regardless of what the other queries say. + +== Integration + +=== `zig build verify` + +A single step, ordered so that cheap failures come first: + +[source,bash] +---- +zig build verify + # 1 atoma extract Zig doc comments → Face B .cspec (G8) + # 2 atoma seam Face A vs Face B, hash equality (G5) + # 3 atoma subset E-* diagnostics over every export fn (G9, G10) + # 4 layout.sh comptime witnesses for each target (G3, G4) + # 5 atoma vc .cspec + core IR → .smt2 (G7 input) + # 6 agda the §6.3 theorem, --safe --without-K (G11) + # 7 echidna dispatch Why3 / z3 / cvc5 → Alethe → .dk + # 8 dkcheck, coqchk, lean4checker (§7.4) + # 9 atoma receipt write witness/.receipt.json +---- + +Steps 1–6 are implemented for the worked example as `verify.sh` (the same +sequence without the Zig build graph), which is why the receipt it writes has +real digests rather than placeholders. Step 2 compares Face A as *transcribed* +from the Idris2 module; regenerating Face A from Idris2 is F0.1 and still +unrun (§2.1). Steps 7–9 are Phase 1. The Zig build graph itself is Phase 1 work; +`verify.sh` remains the executable specification of what that step must do. + +=== `echidnabot` badges + +The badge must distinguish *what* was proved, not merely that something was: + +[cols="2,2,3", options="header"] +|=== +| Badge | Means | When + +| `atoma: phase0 · warrant` | contract and layout locked, VCs discharged, no kernel check | now +| `atoma: phase1 · warrant` | + AoRTE over the scalar/slice surface | Phase 1 +| `atoma: phase1 · receipt` | + `.dk` rechecked by coqchk and lean4checker | Phase 1 exit +| `atoma: phase3 · receipt · ` | full ladder, bound to a specific contract | Phase 3 +|=== + +A badge never says "verified". It names a phase, a class (Warrant or Receipt) and +the contract digest, so a reader can tell exactly which theorem is behind it. + +=== Proof Burrower cache + +Key: `BLAKE3(.dk)` under the `atoma.dk.v1` domain. Value: the kernel-check results +together with the checker identities and versions, because a receipt is only as +good as the kernels that produced it. A cache hit skips rechecking only when the +recorded TCB matches the current one; otherwise it is a miss. The cache never +stores a solver's claim, only a kernel's verdict. + +== Roadmap + +Each phase has an exit criterion that is a *gate*, a falsifier that says "this +phase failed", and a non-claim that bounds what the phase licenses. + +=== Phase 0 — Layout and signature lock + +*Goal:* the seam cannot drift silently. + +*Deliverables:* `.cspec` IR + canonicaliser; Idris2 contract module; comptime +layout witness for four target classes; seam-equivalence gate; mutation-artefact +sweep; VC set for the example; `extract`/`check` frontend; negative corpus. + +*Exit criteria:* gates G1–G11 green. *Met here* except F0.1 (Idris2 typecheck), +which is the one unrun gate, and G7/G11's conditional nature (they skip to +`not-run` without z3/agda rather than claiming a pass). + +*Falsifiers:* a face pair that hashes equal while the specs differ (canonicaliser +unsound); a layout row that the compiler confirms on x86_64 and rejects on wasm32 +without failing the gate; a `usize` field accepted at the seam; a `export fn` +whose directive block silently stops being a contract (G8 catches drift only +because it re-extracts, and it is worth asking what it would take to fool it); a +banned construct that the checker waves through (G10's corpus is the standing +attempt to fool it). + +*Non-claims:* nothing about runtime behaviour. Phase 0 proves that the *document* +and the *declaration* agree, and that the declaration matches the compiler on four +targets. + +=== Phase 1 — AoRTE and the scalar/slice FFI MVP + +*Goal:* every `export fn` in the subset is panic-free, and no UB state is +reachable. + +*Deliverables:* the full VC generator; ECHIDNA integration; `.dk` emission; +`dkcheck` + `coqchk` + `lean4checker` in CI; mutation kill score over the spec +corpus. `Core.agda` and `Soundness.agda` exist and check (§6.3) for the +*store-free* fragment; extending them to the store, `while`, and the two +postcondition clauses is the remainder of this phase's metatheory. + +*Exit criteria:* mutation kill ≥ 95 % on non-equivalent mutants, 100 % on +vacuity; a `COMPLETE (Receipt)` for `atoma.frame.parse`; the soundness theorem +covers store, loops and postconditions — still with no postulates and no holes. + +*Falsifiers:* a VC that is valid but whose Alethe trace does not reconstruct in +Dedukti (the pipeline is then not a proof pipeline); a killed mutant that required +a hand-written lemma (the automation is not general enough); any `believe_me`, +`postulate`, `Admitted`, `sorry` or `--allow-unsolved-metas` in the trusted tree. + +*Non-claims:* no heap, no allocation, no callbacks, no recursion. "AoRTE" here +means *for the subset*, and the subset is small on purpose. + +=== Phase 2 — Linear ownership and regions + +*Goal:* `defer`/`errdefer` discipline at scale, allocators as explicit +capabilities, bounded recursion. + +*Deliverables:* region inference for `assigns`; `ephapax`-style L1/L2 borrow +checking beyond the signature; `Allocator` capability threading under MPR; +`Echo` types on every lossy conversion (`@truncate`, error-code collapse, drops); +structural `@decreases` for recursion; ZIR fingerprints for cache keys. + +*Exit criteria:* a real FFI surface (more than one handle, more than one region) +verified end to end; a leak injected on an `errdefer` path is caught without a +test; the borrow discipline rejects a double-mutable-borrow fixture. + +*Falsifiers:* a leak that both the proofs and the tests miss; a region rule that +requires separation logic (the phase has overreached); an `Echo` witness that +cannot be expressed in the IR. + +*Non-claims:* still no concurrency, still no general heap reasoning, still no +claim about code outside the subset. + +=== Phase 3 — Cost, stack, and secrecy + +*Goal:* the resource and information-flow layer. + +*Deliverables:* `tropical-types` `MaxPlus` bounds as VCs over the cost domain +(not just the worked example's arithmetic); `occupancy-types` HWM with a stack +model; `secret-types` lattice noninterference including the padding rule (a +padding byte that still holds secret data is a leak, and `zeroBytes` is the fix, +so the padding VC becomes a *secrecy* VC as well); constant-time bounds for the +comparison paths that touch secrets. + +*Exit criteria:* a secret-dependent branch is rejected; a padding leak is rejected +by the secrecy analysis even when the memory-safety VC passes; MaxPlus bounds are +proved, not asserted. + +*Falsifiers:* a proven bound that a fuzz run exceeds (the cost model is wrong); a +constant-time claim that the generated code violates at `-O ReleaseFast`. + +*Non-claims:* Atoma never claims that Zig the compiler is correct, that LLVM is +correct, or that the target CPU honours the memory model. The TCB is named in +every receipt: Idris2, Agda, Dedukti, Coq, Lean, and their versions. + +=== Non-claims, collected + +. Not full functional correctness. Atoma proves safety properties and the + postconditions *you write*; it does not prove your postcondition is the right one. +. Not semantic equivalence of the two faces — only canonical-byte equality. +. Not a refinement theorem. `soundness` relates two Agda functions; the step + from `Stmt` to a compiled Zig function is reviewed, not proved (§6.4), and + `atoma check` is a token scan, not a type system. +. Not a borrow checker for heap data; regions are named and finite. +. Not sound for Zig outside the subset, and the subset is enforced by rejection, + not by best effort. +. Not a proof about the Zig compiler, LLVM, or the hardware. +. Not concurrency, not `async`, not atomics. +. Not a replacement for tests: mutation testing exists precisely because proofs + answer questions, and tests catch questions that were never asked. + +== Appendix A: reproducing every claim + +[source,bash] +---- +# tool (pinned to Zig 0.15.2; .zig-version) +cd tools/atoma && zig build test && zig build && ./zig-out/bin/atoma selftest + +# put the CLI on PATH +export PATH="$PWD/tools/atoma/zig-out/bin:$PATH" + +# the full Phase 0 gate: G1..G11 + receipt +cd examples/atoma/frame-v1 && ./verify.sh + +# individual gates +zig test src/frame_parse.zig # G1 +./tools/layout.sh # G3 +zig build-obj tools/layout_negative.zig -target wasm32-freestanding -fno-emit-bin # G4, must fail +atoma equiv spec/face-a.cspec spec/face-b.cspec # G5 +atoma extract src/frame_parse.zig --symbol atoma_frame_parse # G8 +atoma check src/frame_parse.zig # G9 +atoma check fixtures/violations.zig # G10, must exit 1 +python3 vc/gen_vcs.py # G7 + +# metatheory (G11) — four modules, --safe --without-K, no postulates +../../../verification/atoma/check-agda.sh +# equivalently, one module at a time: +cd verification/atoma/agda +for m in Bv Lin Core Soundness; do agda --safe --without-K "$m.agda" || exit 1; done +---- + +`verify.sh` exits 0 only when every gate that can run here passes, and writes +`witness/phase0.receipt.json` with the digests it observed — including +`"proof":{"modules":4,"srcset":"blake3:…","status":"checked"}`, so a receipt +binds the theorem it used. The status line still says `INCOMPLETE (Warrant)` on +purpose: `"proof":"checked"` means the *metatheory* typechecks, never that a Zig +program has a receipt. + +== Appendix B: repository map for this work + +[cols="2,4", options="header"] +|=== +| Path | What lives there + +| `tools/atoma/` | the CLI: `canon`, `hash`, `vc-hash`, `dk-hash`, `src-hash`, `extract`, `check`, `equiv`, `mutate`, `ops`, `selftest` +| `tools/atoma/src/frontend.zig` | `extract` (doc comments → Face B) and `check` (subset diagnostics) +| `examples/atoma/frame-v1/abi/` | Idris2 contract (Face A), package file, linearity negative tests +| `examples/atoma/frame-v1/spec/` | Face A and Face B `.cspec`, witnessed layout table +| `examples/atoma/frame-v1/src/` | `frame_parse.zig` (the verified function), `atoma.zig` (trusted runtime primitives) +| `examples/atoma/frame-v1/tools/` | layout witness, layout oracle, negative fixture, `layout.sh` +| `examples/atoma/frame-v1/vc/` | VC generator and 14 `.smt2` artefacts +| `examples/atoma/frame-v1/fixtures/` | `violations.zig`, the negative corpus G10 rejects +| `examples/atoma/frame-v1/witness/` | the Phase 0 receipt, the VC/subset/violations reports +| `verification/atoma/agda/` | `Bv.agda` (bitvector bridge), `Lin.agda` (linear cleanup), `Core.agda` (language + VC generator), `Soundness.agda` (the §6.3 theorem) +| `verification/atoma/check-agda.sh` | runs all four modules under `--safe --without-K` (gate G11) +|=== + +== Appendix C: glossary + +[cols="1,4", options="header"] +|=== +| Term | Meaning here + +| Warrant | a claim with VCs discharged but no kernel check; may still be wrong +| Receipt | a claim whose `.dk` witness passed `dkcheck`, `coqchk` and `lean4checker --fresh` +| Seam | the C ABI boundary between Idris2-described contracts and Zig implementations +| Face A / Face B | the Idris2-derived contract / the Zig-written contract +| Ghost length | a `0`-quantity length carried only for proofs, erased at runtime +| Region | a named, finite storage area (`r0`, `r1`) that bounds aliasing +| MPR | the syntactic capability footprint: what the callee may touch, stated up front +| Echo | the structured residue of a lossy conversion (`Echo f y := Σx, f x = y`) +| HWM | high-water mark: maximum simultaneously-live stack +| MaxPlus | the max-plus semiring used for worst-case cost bounds +| Vacuous | a specification whose premises are unsatisfiable, and which therefore proves nothing +|=== diff --git a/docs/spec/README.adoc b/docs/spec/README.adoc new file mode 100644 index 00000000..f549cafc --- /dev/null +++ b/docs/spec/README.adoc @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += Specification + +[cols="2,4", options="header"] +|=== +| Document | Contents + +| link:ATOMA-SPEC.adoc[ATOMA-SPEC] +| The design specification: Core Spec IR, the two contract faces, the verifiable + Zig subset, frontend extraction, the VC and certificate pipeline, the worked + example, and the phased roadmap with falsifiers and non-claims. +|=== + +Start with the *claims ledger* at the top of `ATOMA-SPEC.adoc`: it states which +of the document's own claims are machine-checked in this repository and which are +specified only. The executable counterpart of the specification is +`examples/atoma/frame-v1/`, whose `verify.sh` is the Phase 0 gate. diff --git a/examples/atoma/frame-v1/README.adoc b/examples/atoma/frame-v1/README.adoc new file mode 100644 index 00000000..7bcad78b --- /dev/null +++ b/examples/atoma/frame-v1/README.adoc @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += frame-v1 — the worked example + +A length-prefixed, CRC-protected frame is validated in place and described by a +C-ABI `extern struct` pointing back into the caller's buffer (zero copy). This +directory is the executable part of `docs/spec/ATOMA-SPEC.adoc` §8. + +== The four artefacts + +[cols="2,3", options="header"] +|=== +| Artefact | Path + +| (a) Idris2 ABI and QTT contract +| `abi/FrameAbi.idr`, `abi/FrameAbi.ipkg`, `abi/Linearity.idr` +| (b) Zig implementation +| `src/frame_parse.zig`, `src/atoma.zig` (trusted runtime primitives) +| (c) Verification conditions +| `vc/gen_vcs.py` → `vc/*.smt2` (14 artefacts) +| (d) Failure analysis +| §8.4 of the spec, backed by the `*_mutant_*` and `*_needle_*` queries +| (e) Subset checker and extractor +| `tools/atoma` (this repo's CLI), exercised by `fixtures/violations.zig` +| (f) The soundness theorem +| `../../verification/atoma/agda/{Core,Soundness}.agda` +|=== + +Two contract faces, one IR: + +[cols="2,3", options="header"] +|=== +| File | Source + +| `spec/face-a.cspec` | what `encode frameParse` prints (Idris2 is normative) +| `spec/face-b.cspec` | *extracted* from `src/frame_parse.zig` by `atoma extract`; do not hand-edit +| `spec/layout.cspec` | compiler-witnessed layout rows, 4 target classes +|=== + +== Run it + +[source,bash] +---- +./verify.sh # gates G1..G11, writes witness/phase0.receipt.json +---- + +Gates, in order: + +* *G1* 11 unit tests pass (Zig 0.15.2 and 0.16.0) +* *G2* compiles for x86_64, aarch64, riscv64, wasm32 +* *G3* 60 layout rows confirmed by the compiler +* *G4* the `usize`-across-FFI fixture is rejected on wasm32 +* *G5* Face A and Face B hash equal; a one-token edit diverges +* *G6* 11 mutation operators, 11 distinct artefacts +* *G7* 14 SMT obligations discharged by z3 (skipped, and recorded as `not-run`, + when z3 is absent) +* *G8* `atoma extract` reproduces `spec/face-b.cspec` byte for byte +* *G9* the implementation is subset-clean: 6 exports, 6 contracts, 0 diagnostics +* *G10* `fixtures/violations.zig` is rejected: 20 diagnostics over 17 codes +* *G11* the Agda metatheory typechecks under `--safe --without-K` (skipped, and + recorded as `not-run`, when agda is absent) + +G7 and G11 are the two gates that depend on tools outside this repository. They +never *pass* by being absent; the receipt records `not-run` and the status stays +`INCOMPLETE (Warrant)` either way. + +The receipt says `INCOMPLETE (Warrant)`. It is promoted to `COMPLETE (Receipt)` +only when the Dedukti witness has been rechecked by `coqchk` and +`lean4checker --fresh` — see §7.4 of the spec. + +== Wire format + +[cols="1,1,2", options="header"] +|=== +| Offset | Size | Field + +| 0 | 2 | magic: bytes `0x41 0x54` (`'A' 'T'`), i.e. little-endian u16 `0x5441` +| 2 | 2 | payload length, 0..65535 +| 4 | 1 | flags; bit 0 = compressed, all other bits must be 0 +| 5 | 1 | application tag +| 6 | 4 | IEEE CRC-32 over bytes 0..6 followed by the payload +| 10 | 2 | reserved, must be 0 +| 12 | len | payload +|=== + +The magic is `0x5441`, not `0x4154`: the *bytes* are the contract, and `0x4154` +would put `'T'` first. `test "wire order"` pins this, and `V5_mutant_wrong_endian` +shows the solver refuting the plausible mistake. diff --git a/examples/atoma/frame-v1/abi/FrameAbi.idr b/examples/atoma/frame-v1/abi/FrameAbi.idr new file mode 100644 index 00000000..37f3950f --- /dev/null +++ b/examples/atoma/frame-v1/abi/FrameAbi.idr @@ -0,0 +1,377 @@ +||| SPDX-License-Identifier: MPL-2.0 +||| SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +||| +||| FrameAbi — the normative ABI contract for the frame-v1 worked example. +||| +||| This module is Face A of the contract. It is *the* specification: the Zig +||| implementation, the C header and the SMT obligations are all derived from +||| the values declared here. `frameParse : Contract` is a value; the extractor +||| is `putStr (encode frameParse)`, and the bytes it prints are what +||| `spec/face-a.cspec` contains after canonicalisation. +||| +||| Discipline (checked by CI gate F0.1; see docs/spec/ATOMA-SPEC.adoc): +||| %default total — every definition must be total +||| no escape hatches — no trust-me casts, no axioms, no skipped +||| termination checks (the exact banned identifiers +||| are listed in docs/spec/ATOMA-SPEC.adoc §2 and are +||| scanned for by the proof-circumvention gate) +||| +||| STATUS: this module has NOT been typechecked in the authoring environment +||| (the Idris2 toolchain is absent there). It is normative text, and +||| `idris2 --typecheck abi/FrameAbi.ipkg` is the Phase 0 entry gate (F0.1). +||| Nothing in this repository claims it compiles until that gate runs. +||| +||| Naming: the toolchain is Atoma; the language it verifies is Zig. The C +||| symbol prefix, the contract namespace and the digest domains all use +||| `atoma` so that one name is load-bearing everywhere. + +module FrameAbi + +import Data.So + +%default total + +-------------------------------------------------------------------------------- +-- Quantities (QTT: 0 = erased ghost, 1 = linear, W = unrestricted) +-------------------------------------------------------------------------------- + +public export +data Qty = Q0 | Q1 | QW + +public export +renderQty : Qty -> String +renderQty Q0 = "0" +renderQty Q1 = "1" +renderQty QW = "W" + +-------------------------------------------------------------------------------- +-- Sorts. Deliberately tiny: every sort here is ABI-stable and has a fixed +-- width on every supported target, or is a ghost-only sort that never reaches +-- the wire. `USize` is absent on purpose (see §2.3 of the specification). +-------------------------------------------------------------------------------- + +public export +data Sort + = U8 | U16 | U32 | U64 + | Handle -- an opaque capability token, QTT-quantified + | SliceU8 -- (ptr, len) pair, ghost length, borrowed region + | PtrOutFrame -- a linear write lease into caller-owned memory + | Unit + +public export +renderSort : Sort -> String +renderSort U8 = "u8" +renderSort U16 = "u16" +renderSort U32 = "u32" +renderSort U64 = "u64" +renderSort Handle = "handle" +renderSort SliceU8 = "slice ro u8 r0" +renderSort PtrOutFrame = "ptr out_frame r1" +renderSort Unit = "unit" + +-------------------------------------------------------------------------------- +-- Terms and formulas. +-- +-- `Bound k` is a de Bruijn *level*: k = 0 is the outermost `Forall` binder of +-- the enclosing formula. Levels (not indices) are used because the canonical +-- form prints `%k` and v1 forbids shadowing, so levels and indices coincide and +-- alpha-invariance is obtained by construction rather than by a renaming pass. +-- +-- Integers are `Nat`; they are lowered to bitvectors of the declared width by +-- the VC generator, and every lowering emits an explicit range obligation. +-------------------------------------------------------------------------------- + +public export +data Tm + = Var String -- a free name: a parameter or a field of an output + | Num Nat + | Len String -- len(p): the ghost length of a slice parameter + | TagOf String -- tag(p): the capability tag of a handle + | MagicOf String -- magic(p): the magic field of an output struct + | PayloadLen String + | Zeroed String -- zeroed(p): every byte of *p is 0x00 + | PadOf String -- pad(p): every padding byte of *p is 0x00 + | Add Tm Tm | Sub Tm Tm | Mul Tm Tm + +public export +data Fm + = Le Tm Tm | Lt Tm Tm | Eq Tm Tm | Neq Tm Tm + | And Fm Fm | Or Fm Fm | Imp Fm Fm | Not Fm + | Forall Sort Fm + +-------------------------------------------------------------------------------- +-- Rendering. Total, structural, and emitting the canonical form directly: +-- * one space between tokens, no trailing spaces +-- * binder rendered as `%k` (R4 of the canonicalisation) +-- * integer literals rendered in decimal without leading zeros (R5) +-------------------------------------------------------------------------------- + +public export +renderTm : Tm -> String +renderTm (Var s) = s +renderTm (Num n) = show n +renderTm (Len s) = "( len " ++ s ++ " )" +renderTm (TagOf s) = "( tag " ++ s ++ " )" +renderTm (MagicOf s) = "( magic " ++ s ++ " )" +renderTm (PayloadLen s) = "( payload_len " ++ s ++ " )" +renderTm (Zeroed s) = "( zeroed " ++ s ++ " )" +renderTm (PadOf s) = "( pad " ++ s ++ " )" +renderTm (Add a b) = "( + " ++ renderTm a ++ " " ++ renderTm b ++ " )" +renderTm (Sub a b) = "( - " ++ renderTm a ++ " " ++ renderTm b ++ " )" +renderTm (Mul a b) = "( * " ++ renderTm a ++ " " ++ renderTm b ++ " )" + +public export +renderFm : Fm -> String +renderFm (Le a b) = "( <= " ++ renderTm a ++ " " ++ renderTm b ++ " )" +renderFm (Lt a b) = "( < " ++ renderTm a ++ " " ++ renderTm b ++ " )" +renderFm (Eq a b) = "( = " ++ renderTm a ++ " " ++ renderTm b ++ " )" +renderFm (Neq a b) = "( != " ++ renderTm a ++ " " ++ renderTm b ++ " )" +renderFm (And a b) = "( and " ++ renderFm a ++ " " ++ renderFm b ++ " )" +renderFm (Or a b) = "( or " ++ renderFm a ++ " " ++ renderFm b ++ " )" +renderFm (Imp a b) = "( => " ++ renderFm a ++ " " ++ renderFm b ++ " )" +renderFm (Not a) = "( not " ++ renderFm a ++ " )" +renderFm (Forall s f) = "( forall ( %0 : " ++ renderSort s ++ " ) " ++ renderFm f ++ " )" + +-------------------------------------------------------------------------------- +-- Contract structure +-------------------------------------------------------------------------------- + +public export +record Param where + constructor MkParam + name : String + qty : Qty + sort : Sort + +public export +renderParam : Param -> String +renderParam p = "param " ++ p.name ++ " " ++ renderQty p.qty ++ " " ++ renderSort p.sort + +public export +data Access = Shared | Mutable + +public export +data Borrow = MkBorrow String Access String -- param, access, region + +public export +renderBorrow : Borrow -> String +renderBorrow (MkBorrow p a r) = + "borrow " ++ p ++ " " ++ (case a of + Shared => "shr" + Mutable => "mut") ++ " " ++ r + +public export +record Bounds where + constructor MkBounds + steps : Tm -- MaxPlus worst-case step count + hwm : Nat -- high-water mark, in bytes of stack + +public export +record Contract where + constructor MkContract + name : String + kind : String -- "extern" for a C-ABI export + abiSym : String -- the Zig `export fn` name + params : List Param + borrows : List Borrow + requires : List Fm + ensures : List Fm + assigns : List String -- regions written + caps : List String -- MPR capability footprint + bounds : Bounds + +-- A fixed-order concatenation of rendered lines. `lines` is total and its +-- result is exactly the canonical byte string (modulo the trailing newline). +public export +lines : List String -> String +lines [] = "" +lines (x :: xs) = x ++ "\n" ++ lines xs + +public export +encode : Contract -> String +encode c = + lines (["cspec 1", + "contract " ++ c.name, + "kind " ++ c.kind, + "abisym " ++ c.abiSym] + ++ mapRender renderParam c.params + ++ mapRender renderBorrow c.borrows + ++ mapRender renderFm c.requires + ++ mapRender renderFm c.ensures + ++ mapRender (\s => "assigns " ++ s) c.assigns + ++ mapRender (\s => "cap " ++ s) c.caps + ++ ["bound steps " ++ renderTm (steps c.bounds), + "bound hwm " ++ show (hwm c.bounds)]) + where + mapRender : (a -> String) -> List a -> List String + mapRender f [] = [] + mapRender f (x :: xs) = f x :: mapRender f xs + +-------------------------------------------------------------------------------- +-- The contract itself +-------------------------------------------------------------------------------- + +public export +handleTag : Nat +handleTag = 0x41544D31 -- ASCII "ATM1" + +public export +frameMagic : Nat +frameMagic = 0x5441 -- the u16 whose little-endian bytes are 'A' 'T' + +public export +frameParse : Contract +frameParse = + MkContract + { name = "atoma.frame.parse" + , kind = "extern" + , abiSym = "atoma_frame_parse" + , params = + [ MkParam "h" QW Handle + , MkParam "input" QW SliceU8 + , MkParam "input_len" Q0 U32 + , MkParam "out" Q1 PtrOutFrame + ] + , borrows = + [ MkBorrow "input" Shared "r0" + , MkBorrow "out" Mutable "r1" + ] + , requires = + [ Le (Num 12) (Len "input") + , Eq (Len "input") (Var "input_len") + , Lt (Var "input_len") (Num 0x100000000) + , Or (Eq (Var "h") (Var "null")) (Eq (TagOf "h") (Num handleTag)) + ] + , ensures = + [ Imp (Eq (Var "res") (Num 0)) (Eq (MagicOf "out") (Num frameMagic)) + , Imp (Eq (Var "res") (Num 0)) (Le (PayloadLen "out") (Sub (Len "input") (Num 12))) + , Imp (Neq (Var "res") (Num 0)) (Zeroed "out") + , Eq (PadOf "out") (Num 0) + ] + , assigns = ["r1"] + , caps = ["Read r0", "Write r1"] + , bounds = MkBounds (Add (Num 12) (Mul (Num 8) (Len "input"))) 64 + } + +-------------------------------------------------------------------------------- +-- Layout. The Idris2 side *declares*; the Zig compiler *witnesses* (see +-- tools/layout_witness.zig); the seam hash binds the two (gate G5). +-- +-- Only the target-independent facts are proved here. `FrameOut` contains a +-- pointer, so its size and the position of `payload` differ between 64-bit and +-- wasm32 — those facts are not provable in Idris2 without a target parameter, +-- and pretending otherwise is how ABI bugs happen. They live in the witnessed +-- layout table instead. +-------------------------------------------------------------------------------- + +public export +record Field where + constructor MkField + fname : String + offset : Nat + width : Nat + align : Nat + +public export +data Aligned : (off, align : Nat) -> Type where + MkAligned : (k : Nat) -> (0 prf : off = k * align) -> Aligned off align + +public export +endOf : List Field -> Nat +endOf [] = 0 +endOf (f :: fs) = + let e = offset f + width f + rest = endOf fs in + if e > rest then e else rest + +public export +frameHeaderFields : List Field +frameHeaderFields = + [ MkField "magic" 0 2 2 + , MkField "length" 2 2 2 + , MkField "flags" 4 1 1 + , MkField "tag" 5 1 1 + , MkField "crc" 8 4 4 + , MkField "reserved" 12 2 2 + ] + +||| Every field starts on its natural alignment. +public export +headerFieldsAligned : + Aligned 0 2 + -> Aligned 2 2 + -> Aligned 4 1 + -> Aligned 5 1 + -> Aligned 8 4 + -> Aligned 12 2 + -> () +headerFieldsAligned _ _ _ _ _ _ = () + +public export +headerAligned : Aligned 0 2 +headerAligned = MkAligned 0 Refl + +public export +lengthAligned : Aligned 2 2 +lengthAligned = MkAligned 1 Refl + +public export +flagsAligned : Aligned 4 1 +flagsAligned = MkAligned 4 Refl + +public export +tagAligned : Aligned 5 1 +tagAligned = MkAligned 5 Refl + +public export +crcAligned : Aligned 8 4 +crcAligned = MkAligned 2 Refl + +public export +reservedAligned : Aligned 12 2 +reservedAligned = MkAligned 6 Refl + +||| The struct ends exactly at 16 bytes: no trailing slack, no field past 16. +public export +headerEndsAt : So (endOf frameHeaderFields == 16) +headerEndsAt = Oh + +||| The struct size is a multiple of its alignment (required by the C ABI). +public export +headerSizeAligned : Aligned 16 4 +headerSizeAligned = MkAligned 4 Refl + +-------------------------------------------------------------------------------- +-- The seam. These are the only foreign imports in the module, and each is +-- pinned to a symbol that exists in src/frame_parse.zig. +-------------------------------------------------------------------------------- + +public export +data Handle : Type where + MkHandle : (ptr : Bits64) -> (0 nonNull : So (ptr /= 0)) -> Handle + +||| Parse one frame. Linear in the handle and in the output lease: the QTT +||| quantities mean an implementation that forgets to consume either is a +||| type error, not a runtime leak. +public export +parseFrame : + (1 h : Handle) + -> (0 ghostLen : Nat) -- the length proof, erased + -> (1 out : PtrOutFrame) + -> (IO (Either Bits32 ())) +parseFrame h ghostLen out = prim__parse h out + +%foreign "C:atoma_frame_parse,libatoma" +prim__parse : Handle -> PtrOutFrame -> IO (Either Bits32 ()) + +-------------------------------------------------------------------------------- +-- What the linearity buys +-------------------------------------------------------------------------------- +-- +-- The QTT discipline is supposed to reject (a) a handle that is dropped and +-- (b) a handle that is used twice. Both negative tests live in `Linearity.idr`, +-- which is deliberately NOT a module of this package: the expected compiler +-- message has to be reconciled with the real Idris2 diagnostic before the test +-- can be gated, and a `failing` block whose message does not match is itself a +-- compile error. Keeping it out of the package means gate F0.1 stays green +-- while the negative tests remain visible and runnable by hand. diff --git a/examples/atoma/frame-v1/abi/FrameAbi.ipkg b/examples/atoma/frame-v1/abi/FrameAbi.ipkg new file mode 100644 index 00000000..3c8af005 --- /dev/null +++ b/examples/atoma/frame-v1/abi/FrameAbi.ipkg @@ -0,0 +1,22 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +-- +-- Idris2 package for the frame-v1 ABI contract (Face A). +-- +-- idris2 --typecheck abi/FrameAbi.ipkg # gate F0.1 +-- idris2 --exec extract FrameAbi # would print the canonical .cspec +-- +-- `depends = base` only: the contract must not depend on libraries whose +-- semantics are themselves unproved. + +package frameabi + +version = 0.1.0 +authors = "Jonathan D.A. Jewell" +brief = "Normative Atoma ABI contract for the frame-v1 worked example" + +sourcedir = "." + +depends = base + +modules = FrameAbi diff --git a/examples/atoma/frame-v1/abi/Linearity.idr b/examples/atoma/frame-v1/abi/Linearity.idr new file mode 100644 index 00000000..16b3ac42 --- /dev/null +++ b/examples/atoma/frame-v1/abi/Linearity.idr @@ -0,0 +1,40 @@ +||| SPDX-License-Identifier: MPL-2.0 +||| SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +||| +||| Linearity.idr — the negative half of the QTT discipline. +||| +||| Each `failing` block asserts that a specific misuse does *not* typecheck. +||| They are excluded from FrameAbi.ipkg on purpose: a `failing` block whose +||| expected message does not match the compiler's real diagnostic is itself a +||| compile error, so the messages must be reconciled on the machine that has +||| Idris2 before these can be a gate. Run by hand with +||| +||| idris2 --check abi/Linearity.idr +||| +||| and then tighten the expected messages to the real ones, at which point this +||| file joins gate F0.1. + +module Linearity + +import FrameAbi + +%default total + +||| A correct consumer: the handle is used exactly once. This one must pass. +public export +consumeOnce : Handle -> PtrOutFrame -> IO (Either Bits32 ()) +consumeOnce h out = parseFrame h 0 out + +||| Dropping a linear handle: must be rejected. +failing "unused linear" + public export + consumeZero : Handle -> PtrOutFrame -> IO (Either Bits32 ()) + consumeZero h out = pure (Right ()) + +||| Using a linear handle twice: must be rejected. +failing "linear" + public export + consumeTwice : Handle -> PtrOutFrame -> IO (Either Bits32 ()) + consumeTwice h out = do + _ <- parseFrame h 0 out + parseFrame h 0 out diff --git a/examples/atoma/frame-v1/fixtures/violations.zig b/examples/atoma/frame-v1/fixtures/violations.zig new file mode 100644 index 00000000..5b01264b --- /dev/null +++ b/examples/atoma/frame-v1/fixtures/violations.zig @@ -0,0 +1,91 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// violations.zig — the subset's negative corpus (gate G10). +// +// Every construct here is banned by §2.4 of the specification. `atoma check` +// must reject the file and must name each violation with its own code. This +// file is never compiled: it exists to prove that the checker is not vacuous. +// +// If a future edit makes `atoma check` accept this file, the subset is no +// longer enforced and every claim in the specification that rests on "the +// subset is checked" becomes false. The gate fails in that case. + +const std = @import("std"); + +// E-GLOBAL-VAR: ambient mutable state at container scope. +var global_counter: u32 = 0; + +// E-ABI-PACKED: bit-level layout has no padding model. +pub const PackedBits = packed struct { + a: u1, + b: u7, +}; + +// E-ABI-WIDTH: `usize` is 32 bits on wasm32 and 64 elsewhere, so a C header +// generated for one target is wrong on the other (measured: F0.3). +pub const BadOut = extern struct { + n: usize, + flag: bool, + opaque_ptr: ?*anyopaque, +}; + +// E-ABI-UNION: a bare union at the seam. +pub const BadUnion = extern union { + a: u32, + b: u64, +}; + +pub fn smuggledC(ptr: [*c]u8) void { + // E-PTR-C: nullable, arithmetic-enabled, no length — three disciplines lost. + _ = ptr; +} + +pub fn castsAround(p: *u8) void { + // E-PTR-CAST + const q: *u8 = @ptrCast(p); + // E-PTR-INT: never allowed, at any phase. + const r: *u8 = @ptrFromInt(0x1000); + _ = q; + _ = r; +} + +pub fn forbiddenPrimitives() void { + // E-ASM + asm volatile ("nop"); + // E-UNREACHABLE: UB in release modes. + if (false) unreachable; + // E-PANIC + @panic("no"); +} + +pub fn ambientAuthority() void { + // E-ALLOC-AMBIENT: an allocator the proof cannot name. + const a = std.heap.c_allocator; + _ = a; +} + +pub fn includesEverything() void { + // E-CIMPORT: an unbounded foreign surface. + _ = @cImport(@cInclude("everything.h")); +} + +pub fn unwraps(x: ?u32) u32 { + // E-OPTIONAL-UNWRAP: panics on null. + return x.?; +} + +pub fn turnsOffChecks() void { + // E-SAFETY-OFF: discharges every obligation by fiat. + @setRuntimeSafety(false); +} + +// E-UNCONTRACTED-EXPORT: an exported function with no `@contract` block. +export fn naked_export(x: u32) callconv(.c) u32 { + return x; +} + +// E-ABI-CALLCONV: the compiler rejects `.C` on every measured release. +export fn wrong_spelling(x: u32) callconv(.C) u32 { + return x; +} diff --git a/examples/atoma/frame-v1/spec/face-a.cspec b/examples/atoma/frame-v1/spec/face-a.cspec new file mode 100644 index 00000000..2308d427 --- /dev/null +++ b/examples/atoma/frame-v1/spec/face-a.cspec @@ -0,0 +1,30 @@ +# Face A — the Idris2 contract, transcribed from what `encode frameParse` +# prints (gate F0.1 replaces this transcription with the extractor's bytes). +# +# Deliberate surface differences from Face B, all erased by canonicalisation: +# * hex literals and a different binder name in the forall (R4/R5) +# * caps listed in the other order (R6 sorts set-valued lines) +# * block comments and blank lines (R1) +cspec 1 +contract atoma.frame.parse +kind extern +abisym atoma_frame_parse +param h W handle +param input W slice ro u8 r0 +param input_len 0 u32 +param out 1 ptr out_frame r1 +borrow input shr r0 +borrow out mut r1 +requires ( <= 0x0c ( len input ) ) +requires ( = ( len input ) input_len ) +requires ( < input_len 0x100000000 ) +requires ( or ( = h null ) ( = ( tag h ) 0x41544D31 ) ) +ensures ( => ( = res 0 ) ( = ( magic out ) 0x5441 ) ) +ensures ( => ( = res 0 ) ( <= ( payload_len out ) ( - ( len input ) 0x0c ) ) ) +ensures ( => ( != res 0 ) ( zeroed out ) ) +ensures ( = ( pad out ) 0 ) +assigns r1 +cap Read r0 +cap Write r1 +bound steps ( + 12 ( * 8 input_len ) ) +bound hwm 64 diff --git a/examples/atoma/frame-v1/spec/face-b.cspec b/examples/atoma/frame-v1/spec/face-b.cspec new file mode 100644 index 00000000..3aa307ca --- /dev/null +++ b/examples/atoma/frame-v1/spec/face-b.cspec @@ -0,0 +1,31 @@ +# Face B — extracted from the directives on `atoma_frame_parse`: +# +# atoma extract src/frame_parse.zig --symbol atoma_frame_parse +# +# This file is checked in so that a reviewer can read the contract without +# opening the Zig file, and so that gate G8 can assert that the extractor still +# reproduces it. Do not hand-edit: edit the doc comment in frame_parse.zig and +# re-run the extractor. +cspec 1 +contract atoma.frame.parse +kind extern +abisym atoma_frame_parse +param h W handle +param input W slice ro u8 r0 +param input_len 0 u32 +param out 1 ptr out_frame r1 +borrow input shr r0 +borrow out mut r1 +requires ( <= 12 ( len input ) ) +requires ( = ( len input ) input_len ) +requires ( < input_len 0x100000000 ) +requires ( or ( = h null ) ( = ( tag h ) 0x41544D31 ) ) +ensures ( => ( = res 0 ) ( = ( magic out ) 0x5441 ) ) +ensures ( => ( = res 0 ) ( <= ( payload_len out ) ( - ( len input ) 12 ) ) ) +ensures ( => ( != res 0 ) ( zeroed out ) ) +ensures ( = ( pad out ) 0 ) +assigns r1 +cap Write r1 +cap Read r0 +bound steps ( + 12 ( * 8 input_len ) ) +bound hwm 64 diff --git a/examples/atoma/frame-v1/spec/layout.cspec b/examples/atoma/frame-v1/spec/layout.cspec new file mode 100644 index 00000000..d355fff8 --- /dev/null +++ b/examples/atoma/frame-v1/spec/layout.cspec @@ -0,0 +1,60 @@ +field FrameHeader@x86_64 0 2 2 magic u16 +field FrameHeader@x86_64 2 2 2 length u16 +field FrameHeader@x86_64 4 1 1 flags u8 +field FrameHeader@x86_64 5 1 1 tag u8 +field FrameHeader@x86_64 8 4 4 crc u32 +field FrameHeader@x86_64 12 2 2 reserved u16 +layout FrameHeader@x86_64 16 4 6..8,14..16 +field FrameOut@x86_64 0 2 2 magic u16 +field FrameOut@x86_64 2 2 2 length u16 +field FrameOut@x86_64 4 1 1 flags u8 +field FrameOut@x86_64 5 1 1 tag u8 +field FrameOut@x86_64 8 4 4 crc u32 +field FrameOut@x86_64 16 8 8 payload [*]const u8 +field FrameOut@x86_64 24 4 4 payload_len u32 +layout FrameOut@x86_64 32 8 6..8,12..16,28..32 +field FrameHeader@aarch64 0 2 2 magic u16 +field FrameHeader@aarch64 2 2 2 length u16 +field FrameHeader@aarch64 4 1 1 flags u8 +field FrameHeader@aarch64 5 1 1 tag u8 +field FrameHeader@aarch64 8 4 4 crc u32 +field FrameHeader@aarch64 12 2 2 reserved u16 +layout FrameHeader@aarch64 16 4 6..8,14..16 +field FrameOut@aarch64 0 2 2 magic u16 +field FrameOut@aarch64 2 2 2 length u16 +field FrameOut@aarch64 4 1 1 flags u8 +field FrameOut@aarch64 5 1 1 tag u8 +field FrameOut@aarch64 8 4 4 crc u32 +field FrameOut@aarch64 16 8 8 payload [*]const u8 +field FrameOut@aarch64 24 4 4 payload_len u32 +layout FrameOut@aarch64 32 8 6..8,12..16,28..32 +field FrameHeader@riscv64 0 2 2 magic u16 +field FrameHeader@riscv64 2 2 2 length u16 +field FrameHeader@riscv64 4 1 1 flags u8 +field FrameHeader@riscv64 5 1 1 tag u8 +field FrameHeader@riscv64 8 4 4 crc u32 +field FrameHeader@riscv64 12 2 2 reserved u16 +layout FrameHeader@riscv64 16 4 6..8,14..16 +field FrameOut@riscv64 0 2 2 magic u16 +field FrameOut@riscv64 2 2 2 length u16 +field FrameOut@riscv64 4 1 1 flags u8 +field FrameOut@riscv64 5 1 1 tag u8 +field FrameOut@riscv64 8 4 4 crc u32 +field FrameOut@riscv64 16 8 8 payload [*]const u8 +field FrameOut@riscv64 24 4 4 payload_len u32 +layout FrameOut@riscv64 32 8 6..8,12..16,28..32 +field FrameHeader@wasm32 0 2 2 magic u16 +field FrameHeader@wasm32 2 2 2 length u16 +field FrameHeader@wasm32 4 1 1 flags u8 +field FrameHeader@wasm32 5 1 1 tag u8 +field FrameHeader@wasm32 8 4 4 crc u32 +field FrameHeader@wasm32 12 2 2 reserved u16 +layout FrameHeader@wasm32 16 4 6..8,14..16 +field FrameOut@wasm32 0 2 2 magic u16 +field FrameOut@wasm32 2 2 2 length u16 +field FrameOut@wasm32 4 1 1 flags u8 +field FrameOut@wasm32 5 1 1 tag u8 +field FrameOut@wasm32 8 4 4 crc u32 +field FrameOut@wasm32 12 4 4 payload [*]const u8 +field FrameOut@wasm32 16 4 4 payload_len u32 +layout FrameOut@wasm32 20 4 6..8 diff --git a/examples/atoma/frame-v1/src/atoma.zig b/examples/atoma/frame-v1/src/atoma.zig new file mode 100644 index 00000000..e21ff3e0 --- /dev/null +++ b/examples/atoma/frame-v1/src/atoma.zig @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// atoma.zig — the Atoma *trusted runtime primitives*. +// +// Everything the verified subset is allowed to do that plain Zig expresses with +// a banned construct lives here, once, with a stated model-level contract: +// +// atoma.zeroBytes(p) — every byte of `*p`, including padding, becomes 0x00. +// This is the ONLY sanctioned way to define padding. +// Zig's value assignment (`p.* = .{...}`) does NOT define +// padding bytes, so it can never discharge a padding VC. +// atoma.isZeroed(p) — the corresponding observation, used by tests and by +// runtime assertions on the FFI shell. +// +// `@memset` over `std.mem.asBytes` is the only pointer-cast-like operation in +// the trusted surface. `@ptrCast`, `@ptrFromInt` and `@alignCast` are banned in +// user code (spec §2.4); this file is the whitelisted kernel that replaces them. +// Its soundness argument is one line long and is stated in the spec: `asBytes` +// yields exactly @sizeOf(T) writable bytes of the live object, `@memset` writes +// each of them once, so the post-state has no undefined byte in `p`. + +const std = @import("std"); + +/// Zero every byte of `*p`, padding included. +pub fn zeroBytes(p: anytype) void { + @memset(std.mem.asBytes(p), 0); +} + +/// True iff `p` was zeroed with `zeroBytes` (or is otherwise all-zero). +pub fn isZeroed(p: anytype) bool { + for (std.mem.asBytes(p)) |b| { + if (b != 0) return false; + } + return true; +} + +/// True iff every byte of `*p` that is *not* a field byte is zero. +/// Field coverage is computed from the type, so this is target-aware: it follows +/// @sizeOf/@offsetOf for whatever target the test binary was built for. +pub fn paddingIsZero(p: anytype) bool { + const T = @TypeOf(p.*); + const N = @sizeOf(T); + var covered = [_]bool{false} ** N; + inline for (comptime fieldNames(T)) |name| { + const off = @offsetOf(T, name); + const sz = @sizeOf(@FieldType(T, name)); + var i: usize = off; + while (i < off + sz) : (i += 1) covered[i] = true; + } + const bytes = std.mem.asBytes(p); + var i: usize = 0; + while (i < N) : (i += 1) { + if (!covered[i] and bytes[i] != 0) return false; + } + return true; +} + +fn fieldNames(comptime T: type) []const []const u8 { + comptime { + const fields = @typeInfo(T).@"struct".fields; + var names: [fields.len][]const u8 = undefined; + for (fields, 0..) |f, i| names[i] = f.name; + const final = names; + return &final; + } +} diff --git a/examples/atoma/frame-v1/src/frame_parse.zig b/examples/atoma/frame-v1/src/frame_parse.zig new file mode 100644 index 00000000..ed419cea --- /dev/null +++ b/examples/atoma/frame-v1/src/frame_parse.zig @@ -0,0 +1,586 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// frame_parse.zig — worked example for the Atoma specification. +// +// A length-prefixed, CRC-protected frame is validated in place and described by +// a C-ABI `extern struct` that points back into the caller's buffer (zero copy). +// +// Wire format v1 (little endian): +// +// off size field meaning +// 0 2 magic bytes 0x41 0x54, i.e. 'A' then 'T' on the wire +// (little-endian u16 value 0x5441 — NOT 0x4154) +// 2 2 length payload byte count, 0..65535 +// 4 1 flags bit 0 = compressed; all other bits must be 0 +// 5 1 tag application tag, opaque to Atoma +// 6 4 crc32 IEEE CRC-32 over header[0..6] ++ payload +// 10 2 reserved must be 0 +// 12 len payload length bytes +// +// The contract is in abi/FrameAbi.idr (Face A) and in the `//!` directive +// blocks on each export fn below (Face B, extracted by `atoma extract`); both +// elaborate to the same canonical Core Spec IR (spec §2.5). This file is what +// the VC generator consumes. +// +// Subset markers used below: +// //! @requires pre-condition on the *C* caller (external assumption) +// //! @ensures post-condition +// //! @cap capability footprint (MPR) +// //! @frame what may be written +// //! @decreases termination measure / MaxPlus bound + +const std = @import("std"); +const atoma = @import("atoma.zig"); + +// ───────────────────────────────────────────────────────────────────────────── +// ABI types — every one of these is `extern` and fixed-width. No `usize`, no +// `bool`, no slices, no packed structs: their layout is target-dependent or not +// C-ABI-stable, and Atoma rejects them at the seam (§2.3). +// ───────────────────────────────────────────────────────────────────────────── + +/// Wire magic. The *bytes* matter, not the number: `le16` reads p[0] | p[1]<<8, +/// so the u16 value whose encoding is 'A' 'T' is 0x5441. Writing 0x4154 here +/// would put 'T' 'A' in the first two bytes of every frame. `test "wire order"` +/// pins this down. +pub const MAGIC: u16 = 0x5441; +pub const HEADER_LEN: u32 = 12; +pub const FLAG_COMPRESSED: u8 = 0x01; +/// In-memory capability tag, ASCII "ATM1" read big-endian. Never serialised, so +/// there is no wire-order question: it is compared as a number. +pub const HANDLE_TAG: u32 = 0x41544D31; +pub const MAX_ITERS: u32 = 4; + +/// C-visible result codes. `enum(c_int)` is C-ABI safe; a bare Zig `error` union +/// is not, so errors are translated at the shell (see `mapError`). +pub const Result = enum(c_int) { + ok = 0, + invalid_arg = 1, + truncated = 2, + bad_magic = 3, + bad_flags = 4, + bad_reserved = 5, + bad_crc = 6, + no_space = 7, + busy = 8, +}; + +/// Library handle: an opaque capability token plus the iterator lease table. +/// There is no allocator anywhere in this module (MPR: the only authority is the +/// handle the caller passed in). +pub const Handle = extern struct { + abi_tag: u32, + abi_version: u32, + /// Bit i is set iff `iters[i]` is live. + live: u32, + iters: [MAX_ITERS]FrameIter, +}; + +/// Parsed header view. Layout is target-independent (all fields fixed-width). +pub const FrameHeader = extern struct { + magic: u16, // 0 + length: u16, // 2 + flags: u8, // 4 + tag: u8, // 5 + // padding 6..8 + crc: u32, // 8 + reserved: u16, // 12 + // padding 14..16 +}; + +/// Parse output. Contains a pointer, so its layout is proven *per target triple*: +/// x86_64/aarch64/riscv64: size 32, align 8, payload@16, payload_len@24, +/// padding 6..8, 12..16, 28..32 +/// wasm32: size 20, align 4, payload@12, payload_len@16, +/// padding 6..8 +pub const FrameOut = extern struct { + magic: u16, // 0 + length: u16, // 2 + flags: u8, // 4 + tag: u8, // 5 + // padding 6..8 + crc: u32, // 8 + payload: [*]const u8, // 16 | 12 + payload_len: u32, // 24 | 16 + // padding 28..32 (and 12..16 before the pointer) on 64-bit targets +}; + +/// Zero-copy iterator state. Lives in a slot leased from `Handle`. +pub const FrameIter = extern struct { + buf: [*]const u8, + len: u32, + cursor: u32, + frames: u32, +}; + +const ParseError = error{ Truncated, BadMagic, BadFlags, BadReserved, BadCrc }; + +// ───────────────────────────────────────────────────────────────────────────── +// Little-endian readers. Written as explicit byte indices rather than +// `std.mem.readInt` so that every load carries an obvious bounds obligation: +// each `p[i]` with i < HEADER_LEN is justified by `buf.len >= HEADER_LEN`. +// ───────────────────────────────────────────────────────────────────────────── + +inline fn le16(p: [*]const u8, off: u32) u16 { + return @as(u16, p[off]) | (@as(u16, p[off + 1]) << 8); +} + +inline fn le32(p: [*]const u8, off: u32) u32 { + return @as(u32, p[off]) | + (@as(u32, p[off + 1]) << 8) | + (@as(u32, p[off + 2]) << 16) | + (@as(u32, p[off + 3]) << 24); +} + +/// IEEE CRC-32, bitwise, no table, no allocation. +/// Termination: the outer loop decreases `bytes.len - i`; the inner loop is the +/// constant 8. MaxPlus cost = 8 * bytes.len + 3 steps. +fn crc32(bytes: []const u8) u32 { + return ~crc32Update(0xFFFF_FFFF, bytes); +} + +/// Raw (un-finalised) CRC state update. `crc32Update(0xFFFF_FFFF, b)` followed by +/// `~` is the IEEE CRC-32 of `b`. +fn crc32Update(prev: u32, bytes: []const u8) u32 { + var c: u32 = prev; + for (bytes) |b| { + c ^= b; + var k: u8 = 0; + while (k < 8) : (k += 1) { // @decreases (8 - k) ; MaxPlus step = 8 + c = if (c & 1 != 0) (c >> 1) ^ 0xEDB8_8320 else c >> 1; + } + } + return c; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Core parser. This is the verified function: total on every input whose length +// precondition holds, and it never traps (spec §8.3, VCs V1..V7). +// ───────────────────────────────────────────────────────────────────────────── + +/// //! @requires buf.len >= 12 +/// //! @requires buf.ptr points to buf.len readable bytes (the FFI ghost length) +/// //! @ensures on error: *out is all-zero (no partial frame, no secret leak) +/// //! @ensures on success: +/// //! out.magic = 0x5441 +/// //! out.length = length (bytes 2..4 of buf) +/// //! out.payload = buf.ptr + 12 +/// //! out.payload_len = out.length +/// //! out.crc = crc32(buf[0..6] ++ buf[12..12+length]) +/// //! padding(*out) = 0 +/// //! @cap { Read(buf) } +/// //! @frame *out +fn parseInto(buf: []const u8, out: *FrameOut) ParseError!void { + // Runs on every error return, and on no success return. The linear + // obligation is: exactly one of {`errdefer` body, success epilogue} runs. + // @linear: this handler consumes the partial frame on every error path + errdefer atoma.zeroBytes(out); + + if (buf.len < HEADER_LEN) return error.Truncated; + + const magic = le16(buf.ptr, 0); + if (magic != MAGIC) return error.BadMagic; + + const length: u32 = le16(buf.ptr, 2); + const flags = buf[4]; + if (flags & ~FLAG_COMPRESSED != 0) return error.BadFlags; + + const reserved = le16(buf.ptr, 10); + if (reserved != 0) return error.BadReserved; + + // @assert: the load-bearing bound. `buf.len >= 12` was established above, so the + // subtraction cannot wrap; `length <= avail` makes the payload slice total. + const avail: u32 = @intCast(buf.len - HEADER_LEN); + if (length > avail) return error.Truncated; + + const payload = buf[HEADER_LEN .. HEADER_LEN + length]; + const want = le32(buf.ptr, 6); + const c = crc32Update(crc32Update(0xFFFF_FFFF, buf[0..6]), payload); + if (~c != want) return error.BadCrc; + + // Define every byte first — including padding — then write the fields. + // `out.* = .{...}` alone would leave 6..8 (and 28..32) undefined. + atoma.zeroBytes(out); + out.magic = magic; + out.length = @intCast(length); + out.flags = flags; + out.tag = buf[5]; + out.crc = want; + out.payload = buf.ptr + HEADER_LEN; + out.payload_len = length; +} + +fn mapError(e: ParseError) Result { + return switch (e) { + error.Truncated => .truncated, + error.BadMagic => .bad_magic, + error.BadFlags => .bad_flags, + error.BadReserved => .bad_reserved, + error.BadCrc => .bad_crc, + }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// C ABI shell. Untrusted with respect to the proofs: it only checks pointer +// non-nullity and translates errors. Every `?` unwrap is discharged by the +// orelse, so there is no `.?` anywhere (§2.4). +// ───────────────────────────────────────────────────────────────────────────── + +/// @contract atoma.frame.parse +/// @kind extern +/// @param h W handle +/// @param input W slice ro u8 r0 +/// @param input_len 0 u32 +/// @param out 1 ptr out_frame r1 +/// @borrow input shr r0 +/// @borrow out mut r1 +/// @requires ( <= 12 ( len input ) ) +/// @requires ( = ( len input ) input_len ) +/// @requires ( < input_len 0x100000000 ) +/// @requires ( or ( = h null ) ( = ( tag h ) 0x41544D31 ) ) +/// @ensures ( => ( = res 0 ) ( = ( magic out ) 0x5441 ) ) +/// @ensures ( => ( = res 0 ) ( <= ( payload_len out ) ( - ( len input ) 12 ) ) ) +/// @ensures ( => ( != res 0 ) ( zeroed out ) ) +/// @ensures ( = ( pad out ) 0 ) +/// @assigns r1 +/// @cap Write r1 +/// @cap Read r0 +/// @bound steps ( + 12 ( * 8 input_len ) ) +/// @bound hwm 64 +/// +/// The contract above is the *only* place the boundary is specified. It is +/// extracted by `atoma extract src/frame_parse.zig` and must hash equal to +/// `spec/face-b.cspec` (gate G8), which in turn must hash equal to the Idris2 +/// face (gate G5). Three sources of truth, one digest. +export fn atoma_frame_parse( + h: ?*const Handle, + in_ptr: ?[*]const u8, + in_len: u32, + out: ?*FrameOut, +) callconv(.c) Result { + const handle = h orelse return .invalid_arg; + if (handle.abi_tag != HANDLE_TAG) return .invalid_arg; + const p = in_ptr orelse return .invalid_arg; + const dst = out orelse return .invalid_arg; + + parseInto(p[0..in_len], dst) catch |e| return mapError(e); + return .ok; +} + +// ── handle lifecycle ──────────────────────────────────────────────────────── + +/// @contract atoma.handle.create +/// @kind extern +/// @param out 1 ptr out_handle r0 +/// @requires ( = ( len out ) 64 ) +/// @requires ( = ( align out ) 8 ) +/// @ensures ( = ( tag out ) 0x41544D31 ) +/// @ensures ( = ( live out ) 0 ) +/// @ensures ( = ( pad out ) 0 ) +/// @assigns r0 +/// @cap Write r0 +/// @bound steps 4 +/// @bound hwm 32 +/// +/// `out` is a caller-owned lease: the callee writes and returns, it does not +/// retain the pointer. +export fn atoma_handle_create(out: ?*Handle) callconv(.c) Result { + const h = out orelse return .invalid_arg; + atoma.zeroBytes(h); + h.abi_tag = HANDLE_TAG; + h.abi_version = 1; + return .ok; +} + +/// @contract atoma.handle.destroy +/// @kind extern +/// @param h 1 ptr inout_handle r0 +/// @requires ( = ( tag h ) 0x41544D31 ) +/// @requires ( = ( live h ) 0 ) +/// @ensures ( = ( zeroed h ) 1 ) +/// @assigns r0 +/// @cap Write r0 +/// @bound steps 3 +/// @bound hwm 16 +/// +/// Refuses with `.busy` while any iterator lease is live, so a leaked linear +/// lease surfaces as a refused destroy rather than as a use-after-free. +export fn atoma_handle_destroy(h: ?*Handle) callconv(.c) Result { + const hh = h orelse return .invalid_arg; + if (hh.abi_tag != HANDLE_TAG) return .invalid_arg; + if (hh.live != 0) return .busy; // a leaked linear lease is refused + atoma.zeroBytes(hh); + return .ok; +} + +// ── linear iterator: open → next* → close ─────────────────────────────────── + +/// @contract atoma.iter.open +/// @kind extern +/// @param h 1 ptr inout_handle r0 +/// @param input W slice ro u8 r1 +/// @param input_len 0 u32 +/// @param out 1 ptr out_iter r2 +/// @requires ( < ( popcount ( live h ) ) 4 ) +/// @requires ( = ( len input ) input_len ) +/// @ensures ( => ( = res 0 ) ( = ( popcount ( live h ) ) ( + 1 ( popcount_old ( live h ) ) ) ) ) +/// @assigns r0 +/// @cap Write r0 +/// @cap Read r1 +/// @bound steps 8 +/// @bound hwm 48 +/// +/// Linear: a successful open creates exactly one lease, and `atoma_iter_close` +/// is the only operation that consumes it. +export fn atoma_iter_open( + h: ?*Handle, + in_ptr: ?[*]const u8, + in_len: u32, + out: ?*?*FrameIter, +) callconv(.c) Result { + const hh = h orelse return .invalid_arg; + if (hh.abi_tag != HANDLE_TAG) return .invalid_arg; + const p = in_ptr orelse return .invalid_arg; + const slot_out = out orelse return .invalid_arg; + + var i: u32 = 0; + while (i < MAX_ITERS) : (i += 1) { + if (hh.live & (@as(u32, 1) << @intCast(i)) == 0) { + hh.iters[i] = .{ .buf = p, .len = in_len, .cursor = 0, .frames = 0 }; + hh.live |= @as(u32, 1) << @intCast(i); + slot_out.* = &hh.iters[i]; + return .ok; + } + } + return .no_space; +} + +/// @contract atoma.iter.next +/// @kind extern +/// @param it 1 ptr inout_iter r0 +/// @param out 1 ptr out_frame r1 +/// @requires ( <= ( cursor it ) ( len it ) ) +/// @ensures ( => ( = res 0 ) ( <= ( + ( cursor_old it ) 12 ( payload_len out ) ) ( len it ) ) ) +/// @ensures ( => ( != res 0 ) ( zeroed out ) ) +/// @ensures ( = ( pad out ) 0 ) +/// @assigns r0 +/// @assigns r1 +/// @cap Read r0 +/// @cap Write r1 +/// @bound steps ( + 32 ( * 8 ( len it ) ) ) +/// @bound hwm 96 +/// +/// The cursor advance is the only state change, and it is bounded by the +/// payload-length postcondition because `parseInto` succeeded. +export fn atoma_iter_next(it: ?*FrameIter, out: ?*FrameOut) callconv(.c) Result { + const s = it orelse return .invalid_arg; + const dst = out orelse return .invalid_arg; + + const remaining = s.len - s.cursor; // cursor ≤ len is an invariant (VC I3) + if (remaining < HEADER_LEN) return .truncated; + + const base = s.buf + s.cursor; + const sub = base[0..remaining]; + parseInto(sub, dst) catch |e| return mapError(e); + + s.cursor += HEADER_LEN + dst.payload_len; // proven ≤ len because parse succeeded + s.frames += 1; + return .ok; +} + +/// @contract atoma.iter.close +/// @kind extern +/// @param h 1 ptr inout_handle r0 +/// @param it 1 ptr inout_iter r1 +/// @requires ( = ( owns h it ) 1 ) +/// @ensures ( = ( live h ) ( clear_bit ( live_old h ) ( index_of h it ) ) ) +/// @ensures ( = ( zeroed it ) 1 ) +/// @assigns r0 +/// @assigns r1 +/// @cap Write r0 +/// @cap Write r1 +/// @bound steps 8 +/// @bound hwm 32 +/// +/// Consumes the lease exactly once; the `live` bit is cleared before the slot is +/// wiped, so a concurrent observer can never see a live bit over zeroed state. +export fn atoma_iter_close(h: ?*Handle, it: ?*FrameIter) callconv(.c) Result { + const hh = h orelse return .invalid_arg; + if (hh.abi_tag != HANDLE_TAG) return .invalid_arg; + const s = it orelse return .invalid_arg; + + var i: u32 = 0; + while (i < MAX_ITERS) : (i += 1) { + if (&hh.iters[i] == s) { + if (hh.live & (@as(u32, 1) << @intCast(i)) == 0) return .invalid_arg; + hh.live &= ~(@as(u32, 1) << @intCast(i)); + atoma.zeroBytes(&hh.iters[i]); + return .ok; + } + } + return .invalid_arg; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Tests. These are the *witnesses* the mutation harness uses: a mutant that +// still passes this suite has escaped both the proofs and the tests. +// ───────────────────────────────────────────────────────────────────────────── + +const testing = std.testing; + +fn buildFrame(buf: []u8, tag: u8, payload: []const u8) usize { + const n: u16 = @intCast(payload.len); + buf[0] = @truncate(MAGIC); + buf[1] = @truncate(MAGIC >> 8); + buf[2] = @truncate(n); + buf[3] = @truncate(n >> 8); + buf[4] = 0; + buf[5] = tag; + buf[10] = 0; + buf[11] = 0; + @memcpy(buf[HEADER_LEN .. HEADER_LEN + payload.len], payload); + var c = std.hash.Crc32.init(); + c.update(buf[0..6]); + c.update(payload); + const v = c.final(); + buf[6] = @truncate(v); + buf[7] = @truncate(v >> 8); + buf[8] = @truncate(v >> 16); + buf[9] = @truncate(v >> 24); + return HEADER_LEN + payload.len; +} + +test "parses a well-formed frame, zero-copy" { + var buf: [64]u8 = undefined; + const n = buildFrame(&buf, 7, "hello"); + var h: Handle = undefined; + try testing.expectEqual(Result.ok, atoma_handle_create(&h)); + var out: FrameOut = undefined; + try testing.expectEqual(Result.ok, atoma_frame_parse(&h, &buf, @intCast(n), &out)); + try testing.expectEqual(MAGIC, out.magic); + try testing.expectEqual(@as(u32, 5), out.payload_len); + try testing.expectEqual(@as(u8, 7), out.tag); + // zero-copy: the payload pointer aliases the caller's buffer + try testing.expectEqual(@intFromPtr(&buf[HEADER_LEN]), @intFromPtr(out.payload)); + try testing.expect(atoma.paddingIsZero(&out)); +} + +test "rejects a short buffer without touching out" { + var buf: [4]u8 = .{ 0, 0, 0, 0 }; + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var out: FrameOut = undefined; + atoma.zeroBytes(&out); + try testing.expectEqual(Result.truncated, atoma_frame_parse(&h, &buf, buf.len, &out)); + try testing.expect(atoma.isZeroed(&out)); +} + +test "length == avail is accepted, length == avail+1 is rejected" { + var buf: [64]u8 = undefined; + const n = buildFrame(&buf, 1, "abc"); + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var out: FrameOut = undefined; + // exact fit + try testing.expectEqual(Result.ok, atoma_frame_parse(&h, &buf, @intCast(n), &out)); + // claim one byte more than the buffer holds + buf[2] = 4; + try testing.expectEqual(Result.truncated, atoma_frame_parse(&h, &buf, @intCast(n), &out)); + try testing.expect(atoma.isZeroed(&out)); // errdefer ran +} + +test "bad magic, flags and reserved are refused" { + var buf: [64]u8 = undefined; + const n = buildFrame(&buf, 1, "x"); + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var out: FrameOut = undefined; + buf[0] = 0; + try testing.expectEqual(Result.bad_magic, atoma_frame_parse(&h, &buf, @intCast(n), &out)); + _ = buildFrame(&buf, 1, "x"); + buf[4] = 0x80; + try testing.expectEqual(Result.bad_flags, atoma_frame_parse(&h, &buf, @intCast(n), &out)); + _ = buildFrame(&buf, 1, "x"); + buf[10] = 0xFF; + try testing.expectEqual(Result.bad_reserved, atoma_frame_parse(&h, &buf, @intCast(n), &out)); +} + +test "crc mismatch is caught" { + var buf: [64]u8 = undefined; + const n = buildFrame(&buf, 1, "xyz"); + buf[HEADER_LEN] ^= 0xFF; + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var out: FrameOut = undefined; + try testing.expectEqual(Result.bad_crc, atoma_frame_parse(&h, &buf, @intCast(n), &out)); +} + +test "null arguments are refused, every one of them" { + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var out: FrameOut = undefined; + var buf: [16]u8 = [_]u8{0} ** 16; + try testing.expectEqual(Result.invalid_arg, atoma_frame_parse(null, &buf, 16, &out)); + try testing.expectEqual(Result.invalid_arg, atoma_frame_parse(&h, null, 16, &out)); + try testing.expectEqual(Result.invalid_arg, atoma_frame_parse(&h, &buf, 16, null)); +} + +test "iterator leases are linear: leak is detected, close releases" { + var buf: [64]u8 = undefined; + const n = buildFrame(&buf, 2, "ab"); + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var p: ?*FrameIter = null; + try testing.expectEqual(Result.ok, atoma_iter_open(&h, &buf, @intCast(n), &p)); + var out: FrameOut = undefined; + try testing.expectEqual(Result.ok, atoma_iter_next(p, &out)); + try testing.expectEqual(@as(u32, 2), out.payload_len); + // destroy refuses while a lease is live + try testing.expectEqual(Result.busy, atoma_handle_destroy(&h)); + try testing.expectEqual(Result.ok, atoma_iter_close(&h, p)); + try testing.expectEqual(Result.ok, atoma_handle_destroy(&h)); + try testing.expect(atoma.isZeroed(&h)); +} + +test "iterator walks consecutive frames and stops at the end" { + var buf: [128]u8 = undefined; + const a = buildFrame(&buf, 1, "aa"); + const b = buildFrame(buf[a..], 2, "bbb"); + var h: Handle = undefined; + _ = atoma_handle_create(&h); + var p: ?*FrameIter = null; + try testing.expectEqual(Result.ok, atoma_iter_open(&h, &buf, @intCast(a + b), &p)); + var out: FrameOut = undefined; + try testing.expectEqual(Result.ok, atoma_iter_next(p, &out)); + try testing.expectEqual(@as(u8, 1), out.tag); + try testing.expectEqual(Result.ok, atoma_iter_next(p, &out)); + try testing.expectEqual(@as(u8, 2), out.tag); + try testing.expectEqual(Result.truncated, atoma_iter_next(p, &out)); + try testing.expectEqual(Result.ok, atoma_iter_close(&h, p)); +} + +test "wire order: the first two bytes are 'A' then 'T'" { + var buf: [64]u8 = undefined; + _ = buildFrame(&buf, 0, "x"); + try testing.expectEqual(@as(u8, 'A'), buf[0]); + try testing.expectEqual(@as(u8, 'T'), buf[1]); +} + +test "layout: FrameHeader is target-independent" { + try testing.expectEqual(@as(usize, 16), @sizeOf(FrameHeader)); + try testing.expectEqual(@as(usize, 4), @alignOf(FrameHeader)); + try testing.expectEqual(@as(usize, 8), @offsetOf(FrameHeader, "crc")); + try testing.expectEqual(@as(usize, 12), @offsetOf(FrameHeader, "reserved")); +} + +test "layout: FrameOut follows the pointer width" { + if (@sizeOf(usize) == 8) { + try testing.expectEqual(@as(usize, 32), @sizeOf(FrameOut)); + try testing.expectEqual(@as(usize, 16), @offsetOf(FrameOut, "payload")); + try testing.expectEqual(@as(usize, 24), @offsetOf(FrameOut, "payload_len")); + } else { + try testing.expectEqual(@as(usize, 20), @sizeOf(FrameOut)); + try testing.expectEqual(@as(usize, 12), @offsetOf(FrameOut, "payload")); + try testing.expectEqual(@as(usize, 16), @offsetOf(FrameOut, "payload_len")); + } +} diff --git a/examples/atoma/frame-v1/tools/layout.sh b/examples/atoma/frame-v1/tools/layout.sh new file mode 100755 index 00000000..7aeb2f21 --- /dev/null +++ b/examples/atoma/frame-v1/tools/layout.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +# +# Collect the compiler-witnessed layout rows for every target class into +# spec/layout.cspec. Deterministic: same compiler + same declaration ⇒ same +# bytes, in the same order (target order is fixed below). +# +# The rows are whatever the Zig compiler said. Nothing is computed here, and a +# declaration that does not hold makes the corresponding `zig build-obj` fail, +# which aborts the script (set -e). + +set -eu +ZIG=${ZIG:-zig} +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +out="$here/../spec/layout.cspec" +tmp="$out.tmp" + +: > "$tmp" +for triple in x86_64-linux-gnu aarch64-linux-gnu riscv64-linux-gnu wasm32-freestanding; do + "$ZIG" build-obj "$here/layout_witness.zig" -target "$triple" -fno-emit-bin 2>&1 | + sed -n 's/^@as(\*const \[[0-9]*:0\]u8, "\([^"]*\)")$/\1/p' | + sed -n '/^\(field\|layout\) /p' >> "$tmp" +done +mv "$tmp" "$out" +printf 'layout.sh: %s rows -> %s\n' "$(wc -l < "$out" | tr -d ' ')" "spec/layout.cspec" diff --git a/examples/atoma/frame-v1/tools/layout_check.zig b/examples/atoma/frame-v1/tools/layout_check.zig new file mode 100644 index 00000000..b37749c4 --- /dev/null +++ b/examples/atoma/frame-v1/tools/layout_check.zig @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// layout_check.zig — the comptime layout oracle. No std, no runtime: it is +// evaluated during semantic analysis and either compiles or does not. +// +// The declaration it checks comes from Idris2 (abi/FrameAbi.idr); the values it +// compares against come from the Zig compiler itself (@sizeOf/@alignOf/@offsetOf). +// A disagreement is a compile error, so a drifted layout cannot be witnessed. + +pub const Expect = struct { + size: usize, + alignment: usize, + /// Field offsets, in declaration order. + offsets: []const usize, + /// Padding byte ranges, as (start, end) pairs. + pads: []const usize, +}; + +pub fn check(comptime T: type, comptime name: []const u8, comptime e: Expect) void { + if (@sizeOf(T) != e.size) @compileError(name ++ ": declared size != @sizeOf"); + if (@alignOf(T) != e.alignment) @compileError(name ++ ": declared alignment != @alignOf"); + const fields = @typeInfo(T).@"struct".fields; + if (fields.len != e.offsets.len) @compileError(name ++ ": declared field count != actual"); + inline for (fields, 0..) |f, i| { + if (@offsetOf(T, f.name) != e.offsets[i]) @compileError(name ++ ": declared offset != @offsetOf"); + } + // Padding is re-derived as the complement of the field byte ranges; the + // declared ranges must agree with it byte for byte. + var covered = [_]bool{false} ** 128; + inline for (fields) |f| { + const off = @offsetOf(T, f.name); + const sz = @sizeOf(f.type); + for (off..off + sz) |i| covered[i] = true; + } + var i: usize = 0; + while (i < @sizeOf(T)) : (i += 1) { + const is_pad = !covered[i]; + var declared = false; + var k: usize = 0; + while (k < e.pads.len) : (k += 2) { + if (i >= e.pads[k] and i < e.pads[k + 1]) declared = true; + } + if (is_pad != declared) @compileError(name ++ ": declared padding != field complement"); + } +} + diff --git a/examples/atoma/frame-v1/tools/layout_negative.zig b/examples/atoma/frame-v1/tools/layout_negative.zig new file mode 100644 index 00000000..2d396417 --- /dev/null +++ b/examples/atoma/frame-v1/tools/layout_negative.zig @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// layout_negative.zig — falsifier F0.3 for Phase 0. +// +// `BadOut` uses `usize` across the FFI seam. Its layout is pointer-width +// dependent (24 bytes / align 8 on 64-bit, 12 bytes / align 4 on wasm32), so a +// single declared layout cannot hold on both. This file declares the 64-bit +// layout; the Phase 0 gate asserts that +// +// zig build-obj tools/layout_negative.zig -target wasm32-freestanding +// +// FAILS. If it ever succeeds, the layout witness is not witnessing anything and +// the whole Phase 0 gate is void. + +const witness = @import("layout_check.zig"); + +const BadOut = extern struct { + a: u8, + n: usize, // ← banned across the seam: pointer-width dependent + b: u32, +}; + +comptime { + // The 64-bit layout, declared once. Correct on x86_64/aarch64/riscv64, + // wrong on wasm32 — which is exactly the point. + witness.check(BadOut, "BadOut", .{ + .size = 24, + .alignment = 8, + .offsets = &.{ 0, 8, 16 }, + .pads = &.{ 1, 8, 20, 24 }, + }); +} diff --git a/examples/atoma/frame-v1/tools/layout_witness.zig b/examples/atoma/frame-v1/tools/layout_witness.zig new file mode 100644 index 00000000..fb1d059b --- /dev/null +++ b/examples/atoma/frame-v1/tools/layout_witness.zig @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// layout_witness.zig — Phase 0 "Layout & Signature Lock" witness generator. +// +// The ABI layout is *declared* in Idris2 (abi/FrameAbi.idr). This file does not +// compute layouts: it makes the Zig compiler *check* the declaration for the +// target it is compiled for and emit the checked rows in canonical `.cspec` +// form on stderr. +// +// zig build-obj tools/layout_witness.zig -target -fno-emit-bin +// +// exits 0 iff every declared size / alignment / offset / padding range holds on +// . A drifted declaration is a compile error, so no target can silently +// produce a green run. `layout.sh` collects the rows. +// +// Nothing here is trusted: the Idris2 declaration is the specification, the +// compiler is the oracle, and the shell only transcribes what the compiler said. + +const std = @import("std"); // comptimePrint only +const builtin = @import("builtin"); + +const witness = @import("layout_check.zig"); + +const FrameHeader = extern struct { + magic: u16, + length: u16, + flags: u8, + tag: u8, + crc: u32, + reserved: u16, +}; + +const FrameOut = extern struct { + magic: u16, + length: u16, + flags: u8, + tag: u8, + crc: u32, + payload: [*]const u8, + payload_len: u32, +}; + +const arch = @tagName(builtin.cpu.arch); +const ptr_bits = @bitSizeOf(usize); + +fn fieldRows(comptime T: type, comptime name: []const u8) void { + inline for (@typeInfo(T).@"struct".fields) |f| { + @compileLog(std.fmt.comptimePrint("field {s}@{s} {d} {d} {d} {s} {s}", .{ + name, + arch, + @offsetOf(T, f.name), + @sizeOf(f.type), + @alignOf(f.type), + f.name, + @typeName(f.type), + })); + } +} + +comptime { + witness.check(FrameHeader, "FrameHeader", .{ + .size = 16, + .alignment = 4, + .offsets = &.{ 0, 2, 4, 5, 8, 12 }, + .pads = &.{ 6, 8, 14, 16 }, + }); + fieldRows(FrameHeader, "FrameHeader"); + @compileLog("layout FrameHeader@" ++ arch ++ " 16 4 6..8,14..16"); + + if (ptr_bits == 64) { + witness.check(FrameOut, "FrameOut", .{ + .size = 32, + .alignment = 8, + .offsets = &.{ 0, 2, 4, 5, 8, 16, 24 }, + .pads = &.{ 6, 8, 12, 16, 28, 32 }, + }); + fieldRows(FrameOut, "FrameOut"); + @compileLog("layout FrameOut@" ++ arch ++ " 32 8 6..8,12..16,28..32"); + } else if (ptr_bits == 32) { + witness.check(FrameOut, "FrameOut", .{ + .size = 20, + .alignment = 4, + .offsets = &.{ 0, 2, 4, 5, 8, 12, 16 }, + .pads = &.{ 6, 8 }, + }); + fieldRows(FrameOut, "FrameOut"); + @compileLog("layout FrameOut@" ++ arch ++ " 20 4 6..8"); + } else { + @compileError("FrameOut layout is proven only for 32- and 64-bit pointers"); + } +} diff --git a/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 b/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 new file mode 100644 index 00000000..dfc3ecfb --- /dev/null +++ b/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 @@ -0,0 +1,11 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V1_needle_drop_requires (arith) +; without `len >= 12` the subtraction underflows: model is the panic +; expected: SAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(assert + (let (($x7 (bvule (_ bv12 32) buf_len))) +(not $x7))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 b/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 new file mode 100644 index 00000000..346d0d07 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 @@ -0,0 +1,14 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V1_no_underflow (arith) +; `buf.len - 12` cannot wrap once len >= 12 is known +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(assert + (let (($x7 (bvule (_ bv12 32) buf_len))) + (and $x7))) +(assert + (let (($x9 (bvule (_ bv0 32) (_ bv0 32)))) +(not $x9))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 b/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 new file mode 100644 index 00000000..cf765f17 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 @@ -0,0 +1,16 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V2_mutant_off_by_one (bounds) +; `avail + 1` admits exactly one byte past the end: off-by-one +; expected: SAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(declare-fun length () (_ BitVec 32)) +(assert + (let (($x17 (bvule length (bvadd (bvsub buf_len (_ bv12 32)) (_ bv1 32))))) + (let (($x7 (bvule (_ bv12 32) buf_len))) + (and $x7 $x17)))) +(assert + (let (($x14 (bvule (bvadd (_ bv12 32) length) buf_len))) +(not $x14))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 b/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 new file mode 100644 index 00000000..51affdf6 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 @@ -0,0 +1,15 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V2_needle_drop_payload_bound (bounds) +; a frame claiming more bytes than the buffer holds slices out of bounds +; expected: SAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(declare-fun length () (_ BitVec 32)) +(assert + (let (($x7 (bvule (_ bv12 32) buf_len))) + (and $x7))) +(assert + (let (($x14 (bvule (bvadd (_ bv12 32) length) buf_len))) +(not $x14))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 b/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 new file mode 100644 index 00000000..503dccc6 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 @@ -0,0 +1,17 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V2_slice_in_bounds (bounds) +; 12 + length <= buf.len, so buf[12 .. 12+length] is in bounds +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(declare-fun length () (_ BitVec 32)) +(assert + (let ((?x11 (bvsub buf_len (_ bv12 32)))) + (let (($x12 (bvule length ?x11))) + (let (($x7 (bvule (_ bv12 32) buf_len))) + (and $x7 $x12))))) +(assert + (let (($x14 (bvule (bvadd (_ bv12 32) length) buf_len))) +(not $x14))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 b/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 new file mode 100644 index 00000000..14a0f14d --- /dev/null +++ b/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 @@ -0,0 +1,15 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V3_intcast_range (cast) +; a slice obtained from a u32 in_len is at most 2^32-1 bytes and at least 12, so the usize-to-u32 @intCast cannot trap +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len_usize () (_ BitVec 64)) +(assert + (let (($x22 (bvule buf_len_usize (_ bv4294967295 64)))) + (let (($x20 (bvule (_ bv12 64) buf_len_usize))) + (and $x20 $x22)))) +(assert + (let (($x24 (bvule (bvsub buf_len_usize (_ bv12 64)) (_ bv4294967295 64)))) +(not $x24))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 b/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 new file mode 100644 index 00000000..f31913b1 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 @@ -0,0 +1,11 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V3_needle_drop_ffi_bound (cast) +; called directly with a >4GiB slice, the same @intCast panics +; expected: SAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len_usize () (_ BitVec 64)) +(assert + (let (($x24 (bvule (bvsub buf_len_usize (_ bv12 64)) (_ bv4294967295 64)))) +(not $x24))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 b/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 new file mode 100644 index 00000000..104b022c --- /dev/null +++ b/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 @@ -0,0 +1,16 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V4_maxplus_bound (cost) +; 8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus bound is representable in the cost domain +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun payload_len () (_ BitVec 32)) +(declare-fun steps () (_ BitVec 32)) +(assert + (let (($x32 (bvule steps (bvadd (bvmul (_ bv8 32) payload_len) (_ bv12 32))))) + (let (($x28 (bvule payload_len (_ bv65535 32)))) + (and $x28 $x32)))) +(assert + (let (($x35 (bvule steps (bvadd (bvmul (_ bv8 32) (_ bv65535 32)) (_ bv12 32))))) +(not $x35))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 b/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 new file mode 100644 index 00000000..17e0e851 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 @@ -0,0 +1,17 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V5_magic_wire_order (abi) +; bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' on the wire +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun byte1 () (_ BitVec 8)) +(declare-fun byte0 () (_ BitVec 8)) +(assert + (let (($x46 (= (_ bv84 8) byte1))) + (let (($x44 (= (_ bv65 8) byte0))) + (and $x44 $x46)))) +(assert + (let ((?x42 (bvor ((_ zero_extend 8) byte0) (bvshl ((_ zero_extend 8) byte1) (_ bv8 16))))) +(let (($x48 (= (_ bv21569 16) ?x42))) +(not $x48)))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 b/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 new file mode 100644 index 00000000..3a8e890f --- /dev/null +++ b/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 @@ -0,0 +1,17 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V5_mutant_wrong_endian (abi) +; 0x4154 is refuted by the same bytes: the literal ASCII word is wrong +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun byte1 () (_ BitVec 8)) +(declare-fun byte0 () (_ BitVec 8)) +(assert + (let ((?x42 (bvor ((_ zero_extend 8) byte0) (bvshl ((_ zero_extend 8) byte1) (_ bv8 16))))) + (let (($x50 (= (_ bv16724 16) ?x42))) + (let (($x46 (= (_ bv84 8) byte1))) + (let (($x44 (= (_ bv65 8) byte0))) + (and $x44 $x46 $x50)))))) +(assert + (not false)) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 b/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 new file mode 100644 index 00000000..b34437a6 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 @@ -0,0 +1,16 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V6_mutant_offset_drift (layout) +; a payload placed at offset 12 writes into the padding hole 12..16: the padding VC catches layout drift +; expected: SAT +; benchmark generated from python API +(set-info :status unknown) +(assert + (let ((?x60 (store (store (store (store ((as const (Array (_ BitVec 32) (_ BitVec 8))) (_ bv0 8)) (_ bv0 32) (_ bv170 8)) (_ bv1 32) (_ bv170 8)) (_ bv2 32) (_ bv170 8)) (_ bv3 32) (_ bv170 8)))) +(let ((?x67 (store (store (store (store ?x60 (_ bv4 32) (_ bv170 8)) (_ bv5 32) (_ bv170 8)) (_ bv8 32) (_ bv170 8)) (_ bv9 32) (_ bv170 8)))) +(let ((?x71 (store (store ?x67 (_ bv10 32) (_ bv170 8)) (_ bv11 32) (_ bv170 8)))) +(let ((?x129 (store (store (store (store ?x71 (_ bv12 32) (_ bv170 8)) (_ bv13 32) (_ bv170 8)) (_ bv14 32) (_ bv170 8)) (_ bv15 32) (_ bv170 8)))) +(let ((?x133 (store (store (store (store ?x129 (_ bv16 32) (_ bv170 8)) (_ bv17 32) (_ bv170 8)) (_ bv18 32) (_ bv170 8)) (_ bv19 32) (_ bv170 8)))) +(let ((?x137 (store (store (store (store ?x133 (_ bv24 32) (_ bv170 8)) (_ bv25 32) (_ bv170 8)) (_ bv26 32) (_ bv170 8)) (_ bv27 32) (_ bv170 8)))) +(let (($x146 (and (= (_ bv0 8) (select ?x137 (_ bv12 32))) (= (_ bv0 8) (select ?x137 (_ bv13 32))) (= (_ bv0 8) (select ?x137 (_ bv14 32))) (= (_ bv0 8) (select ?x137 (_ bv15 32)))))) +(not $x146))))))))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 b/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 new file mode 100644 index 00000000..9c541c08 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 @@ -0,0 +1,16 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V6_padding_zeroed (layout) +; writes hit only field bytes, so every padding byte keeps the 0x00 it got from zeroBytes +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(assert + (let ((?x60 (store (store (store (store ((as const (Array (_ BitVec 32) (_ BitVec 8))) (_ bv0 8)) (_ bv0 32) (_ bv170 8)) (_ bv1 32) (_ bv170 8)) (_ bv2 32) (_ bv170 8)) (_ bv3 32) (_ bv170 8)))) +(let ((?x67 (store (store (store (store ?x60 (_ bv4 32) (_ bv170 8)) (_ bv5 32) (_ bv170 8)) (_ bv8 32) (_ bv170 8)) (_ bv9 32) (_ bv170 8)))) +(let ((?x71 (store (store ?x67 (_ bv10 32) (_ bv170 8)) (_ bv11 32) (_ bv170 8)))) +(let ((?x79 (store (store (store (store ?x71 (_ bv16 32) (_ bv170 8)) (_ bv17 32) (_ bv170 8)) (_ bv18 32) (_ bv170 8)) (_ bv19 32) (_ bv170 8)))) +(let ((?x87 (store (store (store (store ?x79 (_ bv20 32) (_ bv170 8)) (_ bv21 32) (_ bv170 8)) (_ bv22 32) (_ bv170 8)) (_ bv23 32) (_ bv170 8)))) +(let ((?x95 (store (store (store (store ?x87 (_ bv24 32) (_ bv170 8)) (_ bv25 32) (_ bv170 8)) (_ bv26 32) (_ bv170 8)) (_ bv27 32) (_ bv170 8)))) +(let (($x125 (and (= (_ bv0 8) (select ?x95 (_ bv6 32))) (= (_ bv0 8) (select ?x95 (_ bv7 32))) (= (_ bv0 8) (select ?x95 (_ bv12 32))) (= (_ bv0 8) (select ?x95 (_ bv13 32))) (= (_ bv0 8) (select ?x95 (_ bv14 32))) (= (_ bv0 8) (select ?x95 (_ bv15 32))) (= (_ bv0 8) (select ?x95 (_ bv28 32))) (= (_ bv0 8) (select ?x95 (_ bv29 32))) (= (_ bv0 8) (select ?x95 (_ bv30 32))) (= (_ bv0 8) (select ?x95 (_ bv31 32)))))) +(not $x125))))))))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 b/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 new file mode 100644 index 00000000..7d66d26a --- /dev/null +++ b/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 @@ -0,0 +1,20 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V7_post_payload_len (post) +; the success postcondition follows from the guard that produced success +; expected: UNSAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(declare-fun length () (_ BitVec 32)) +(assert + (let (($x7 (bvule (_ bv12 32) buf_len))) + (and $x7))) +(assert + (let ((?x11 (bvsub buf_len (_ bv12 32)))) +(let (($x149 (bvule (ite (and (bvule (_ bv12 32) buf_len) (bvule length ?x11)) length (_ bv0 32)) ?x11))) +(let (($x12 (bvule length ?x11))) +(let (($x7 (bvule (_ bv12 32) buf_len))) +(let (($x147 (and $x7 $x12))) +(let (($x150 (=> $x147 $x149))) +(not $x150)))))))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 b/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 new file mode 100644 index 00000000..7d3d1589 --- /dev/null +++ b/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 @@ -0,0 +1,12 @@ +; SPDX-License-Identifier: MPL-2.0 +; generated by gen_vcs.py - V8_premise_satisfiable (vacuity) +; a contradictory precondition would make every VC trivially UNSAT, so satisfiability of the premises is a VC in its own right +; expected: SAT +; benchmark generated from python API +(set-info :status unknown) +(declare-fun buf_len () (_ BitVec 32)) +(assert + (let (($x7 (bvule (_ bv12 32) buf_len))) +(let (($x153 (and $x7 (bvule buf_len (_ bv4294967295 32))))) +(not $x153)))) +(check-sat) diff --git a/examples/atoma/frame-v1/vc/gen_vcs.py b/examples/atoma/frame-v1/vc/gen_vcs.py new file mode 100644 index 00000000..6067dc56 --- /dev/null +++ b/examples/atoma/frame-v1/vc/gen_vcs.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +"""gen_vcs.py - build, emit and discharge the frame-v1 verification conditions. + +This is the *untrusted* VC generator for the worked example. What it emits is a +set of SMT-LIB QF_BV / QF_ABV queries; what it proves is whatever z3 proves +about those queries. Every file it writes is re-parsed from disk before being +checked, so the checked artifact and the stored artifact are byte-identical. + +Two families of query are produced for each obligation: + + positive premises /\\ not goal must be UNSAT (obligation discharged) + needle premises\P /\\ not goal must be SAT (premise P is load-bearing) + +The `needle` family is what stops a contract from being vacuously true: if a +precondition can be deleted without turning the goal into a counterexample, the +precondition was doing no work and the mutation harness must say so. + +Run: python3 gen_vcs.py [--out DIR] exit 0 iff every expectation holds. +""" + +import argparse +import os +import sys + +try: + import z3 +except ImportError: + print("SKIP: z3 not available (pip install z3-solver)", file=sys.stderr) + sys.exit(2) + +BV8, BV16, BV32, BV64 = (z3.BitVecSort(8), z3.BitVecSort(16), + z3.BitVecSort(32), z3.BitVecSort(64)) + +HEADER_LEN = 12 +MAGIC = 0x5441 # little-endian u16 whose *bytes* are 'A' 'T' + + +class VC: + def __init__(self, name, kind, premise, goal, expect, why): + self.name, self.kind = name, kind + self.premise, self.goal = premise, goal + self.expect, self.why = expect, why + + +def bv(name, width): + return z3.BitVec(name, width) + + +def build(): + vcs = [] + + # ── V1 no underflow in `buf.len - HEADER_LEN` ────────────────────────── + n = bv("buf_len", 32) + vcs.append(VC( + "V1_no_underflow", "arith", + [z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n)], + z3.ULE(z3.BitVecVal(0, 32), z3.BitVecVal(0, 32)), # trivial goal + "unsat", + "`buf.len - 12` cannot wrap once len >= 12 is known")) + + vcs.append(VC( + "V1_needle_drop_requires", "arith", + [], # the `len >= 12` premise is removed + z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n), + "sat", + "without `len >= 12` the subtraction underflows: model is the panic")) + + # ── V2 the payload slice is in bounds ───────────────────────────────── + L = bv("length", 32) + avail = z3.BitVecVal(HEADER_LEN, 32) + p_len_ok = z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n) + p_payload = z3.ULE(L, n - z3.BitVecVal(HEADER_LEN, 32)) + vcs.append(VC( + "V2_slice_in_bounds", "bounds", + [p_len_ok, p_payload], + z3.ULE(z3.BitVecVal(HEADER_LEN, 32) + L, n), + "unsat", + "12 + length <= buf.len, so buf[12 .. 12+length] is in bounds")) + + # ── V2 needle: drop the payload bound -> out-of-bounds is reachable ───── + vcs.append(VC( + "V2_needle_drop_payload_bound", "bounds", + [p_len_ok], + z3.ULE(z3.BitVecVal(HEADER_LEN, 32) + L, n), + "sat", + "a frame claiming more bytes than the buffer holds slices out of bounds")) + + # ── V2 mutant: the off-by-one an author actually writes ──────────────── + # `if (length > avail + 1) return error.Truncated;` + vcs.append(VC( + "V2_mutant_off_by_one", "bounds", + [p_len_ok, z3.ULE(L, n - z3.BitVecVal(HEADER_LEN, 32) + z3.BitVecVal(1, 32))], + z3.ULE(z3.BitVecVal(HEADER_LEN, 32) + L, n), + "sat", + "`avail + 1` admits exactly one byte past the end: off-by-one")) + + # ── V3 @intCast of a usize slice length into u32 fits ───────────────── + N64 = bv("buf_len_usize", 64) + # NOTE: the first version of this VC had only the upper bound as a premise + # and z3 returned SAT with buf_len_usize = 0. That is correct: in BV64, + # `0 - 12` wraps to 2^64-12, which does not fit in u32. The no-underflow + # premise is load-bearing *in the bitvector encoding even though it is + # obvious in the integers*. This is the trap the spec calls out (§4.3.1): + # the same obligation needs two premises here and one in Nat. + vcs.append(VC( + "V3_intcast_range", "cast", + [z3.ULE(z3.BitVecVal(HEADER_LEN, 64), N64), + z3.ULE(N64, z3.BitVecVal(0xFFFF_FFFF, 64))], + z3.ULE(N64 - z3.BitVecVal(HEADER_LEN, 64), z3.BitVecVal(0xFFFF_FFFF, 64)), + "unsat", + "a slice obtained from a u32 in_len is at most 2^32-1 bytes and at " + "least 12, so the usize-to-u32 @intCast cannot trap")) + + vcs.append(VC( + "V3_needle_drop_ffi_bound", "cast", + [], + z3.ULE(N64 - z3.BitVecVal(HEADER_LEN, 64), z3.BitVecVal(0xFFFF_FFFF, 64)), + "sat", + "called directly with a >4GiB slice, the same @intCast panics")) + + # ── V4 MaxPlus step bound for the CRC loop ──────────────────────────── + steps, ln = bv("steps", 32), bv("payload_len", 32) + vcs.append(VC( + "V4_maxplus_bound", "cost", + [z3.ULE(ln, z3.BitVecVal(65535, 32)), + z3.ULE(steps, z3.BitVecVal(8, 32) * ln + z3.BitVecVal(HEADER_LEN, 32))], + z3.ULE(steps, z3.BitVecVal(8, 32) * z3.BitVecVal(65535, 32) + z3.BitVecVal(HEADER_LEN, 32)), + "unsat", + "8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus " + "bound is representable in the cost domain")) + + # ── V5 the magic's endianness ───────────────────────────────────────── + b0, b1 = bv("byte0", 8), bv("byte1", 8) + le16 = z3.ZeroExt(8, b0) | (z3.ZeroExt(8, b1) << 8) + vcs.append(VC( + "V5_magic_wire_order", "abi", + [b0 == z3.BitVecVal(ord('A'), 8), b1 == z3.BitVecVal(ord('T'), 8)], + le16 == z3.BitVecVal(MAGIC, 16), + "unsat", + "bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' " + "on the wire")) + + vcs.append(VC( + "V5_mutant_wrong_endian", "abi", + [b0 == z3.BitVecVal(ord('A'), 8), b1 == z3.BitVecVal(ord('T'), 8), + le16 == z3.BitVecVal(0x4154, 16)], + z3.BoolVal(False), + "unsat", + "0x4154 is refuted by the same bytes: the literal ASCII word is wrong")) + + # ── V6 padding bytes are zero after zeroBytes + field writes ─────────── + # FrameOut on 64-bit: padding 6..8, 12..16, 28..32. + A0, A1 = z3.Const("A0", z3.ArraySort(BV32, BV8)), None + zeroed = z3.K(BV32, z3.BitVecVal(0, 8)) # all bytes zero + writes = [] + for off, size in [(0, 2), (2, 2), (4, 1), (5, 1), (8, 4), (16, 8), (24, 4)]: + for k in range(size): + writes.append((off + k, z3.BitVecVal(0xAA, 8))) # arbitrary field byte + arr = zeroed + for idx, val in writes: + arr = z3.Store(arr, z3.BitVecVal(idx, 32), val) + goals = [z3.Select(arr, z3.BitVecVal(i, 32)) == z3.BitVecVal(0, 8) + for i in list(range(6, 8)) + list(range(12, 16)) + list(range(28, 32))] + vcs.append(VC( + "V6_padding_zeroed", "layout", + [], + z3.And(*goals), + "unsat", + "writes hit only field bytes, so every padding byte keeps the 0x00 it got " + "from zeroBytes")) + + # Layout drift: the same writes, but `payload` placed at offset 12 instead of + # 16 (what happens if @offsetOf for one target is transcribed wrongly, or a + # field is added without re-deriving the table). Bytes 12..16 are padding on + # 64-bit, so the padding VC must now fail. + drifted = zeroed + for off, size in [(0, 2), (2, 2), (4, 1), (5, 1), (8, 4), (12, 8), (24, 4)]: + for k in range(size): + drifted = z3.Store(drifted, z3.BitVecVal(off + k, 32), z3.BitVecVal(0xAA, 8)) + vcs.append(VC( + "V6_mutant_offset_drift", "layout", + [], + z3.And(z3.Select(drifted, z3.BitVecVal(12, 32)) == z3.BitVecVal(0, 8), + z3.Select(drifted, z3.BitVecVal(13, 32)) == z3.BitVecVal(0, 8), + z3.Select(drifted, z3.BitVecVal(14, 32)) == z3.BitVecVal(0, 8), + z3.Select(drifted, z3.BitVecVal(15, 32)) == z3.BitVecVal(0, 8)), + "sat", + "a payload placed at offset 12 writes into the padding hole 12..16: the " + "padding VC catches layout drift")) + + # ── V7 postcondition: on success payload_len <= in_len - 12 ─────────── + ok = z3.And(p_len_ok, p_payload) + out_len = z3.If(ok, L, z3.BitVecVal(0, 32)) + vcs.append(VC( + "V7_post_payload_len", "post", + [p_len_ok], + z3.Implies(ok, z3.ULE(out_len, n - z3.BitVecVal(HEADER_LEN, 32))), + "unsat", + "the success postcondition follows from the guard that produced success")) + + # ── V8 vacuity: the precondition must be satisfiable ────────────────── + vcs.append(VC( + "V8_premise_satisfiable", "vacuity", + [], + z3.And(z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n), + z3.ULE(n, z3.BitVecVal(0xFFFF_FFFF, 32))), + "sat", + "a contradictory precondition would make every VC trivially UNSAT, so " + "satisfiability of the premises is a VC in its own right")) + + return vcs + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)))) + args = ap.parse_args() + os.makedirs(args.out, exist_ok=True) + # Remove VCs from a previous run so the directory is exactly this run's set. + # A stale file would otherwise leak into the aggregate content address. + for stale in os.listdir(args.out): + if stale.endswith(".smt2"): + os.remove(os.path.join(args.out, stale)) + + failures = 0 + rows = [] + for vc in build(): + s = z3.Solver() + if vc.premise: + s.add(vc.premise if isinstance(vc.premise, z3.BoolRef) else z3.And(*vc.premise)) + s.add(z3.Not(vc.goal)) + text = s.to_smt2() + path = os.path.join(args.out, vc.name + ".smt2") + with open(path, "w", encoding="ascii") as f: + f.write("; SPDX-License-Identifier: MPL-2.0\n") + f.write("; generated by gen_vcs.py - %s (%s)\n" % (vc.name, vc.kind)) + f.write("; %s\n" % vc.why) + f.write("; expected: %s\n" % vc.expect.upper()) + f.write(text) + + # Re-parse what we just wrote: the artifact checked is the artifact stored. + replay = z3.Solver() + replay.from_string(open(path, encoding="ascii").read()) + res = replay.check() + if res == z3.sat: + got = "sat" + elif res == z3.unsat: + got = "unsat" + else: + got = "unknown" + ok = got == vc.expect + model = "" + if got == "sat" and ok: + m = replay.model() + vals = [] + for d in m.decls(): + vals.append("%s=%s" % (d.name(), m[d])) + model = ", ".join(sorted(vals)) + rows.append((vc.name, vc.expect, got, "ok" if ok else "FAIL", vc.why, model)) + if not ok: + failures += 1 + + width = max(len(r[0]) for r in rows) + print("%-*s %-5s %-5s %-4s %s" % (width, "VC", "want", "z3", "", "meaning")) + for name, want, got, verdict, why, model in rows: + print("%-*s %-5s %-5s %-4s %s" % (width, name, want, got, verdict, why)) + if model: + print("%-*s model: %s" % (width, "", model)) + print("\n%d VCs, %d failing" % (len(rows), failures)) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/atoma/frame-v1/verify.sh b/examples/atoma/frame-v1/verify.sh new file mode 100755 index 00000000..5268e259 --- /dev/null +++ b/examples/atoma/frame-v1/verify.sh @@ -0,0 +1,216 @@ +#!/bin/sh +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +# +# verify.sh — the Phase 0 ("Layout & Signature Lock") gate for frame-v1. +# +# What this gate DOES establish (machine-checked, here and now): +# G1 the example implementation is within the Atoma subset: it compiles and +# its 11 unit tests pass on the pinned compiler; +# G2 it compiles for all four ABI target classes (x86_64 · aarch64 · riscv64 +# · wasm32); +# G3 every declared size / alignment / offset / padding range is confirmed by +# the Zig compiler on each of those targets (layout.sh); +# G4 the `usize`-across-FFI counter-example is *rejected* on wasm32 (F0.3); +# G5 Face A and Face B canonicalise to the same bytes (hash-checked seam); +# G6 all 11 specification-mutation operators produce distinct artifacts; +# G7 the 14 SMT verification conditions are discharged (if z3 is present); +# G8 the Face B contract is *extracted* from the Zig source and matches the +# checked-in file — the doc-comment directives are the source of truth; +# G9 the implementation passes the subset checker with zero diagnostics and +# every `export fn` contracted; +# G10 the negative corpus is rejected, with one diagnostic per banned +# construct (the checker is not vacuous); +# G11 the Agda metatheory typechecks under `--safe --without-K` (if agda is +# present) — the soundness theorem of spec §6.3 is machine-checked for the +# store-free core fragment, not asserted. +# +# What this gate does NOT establish — and must never be read as establishing: +# * that the SMT obligations are valid, unless z3 was present and G7 passed; +# * that the metatheory says anything about *this* Zig program rather than +# about the model in `Core.agda` (the refinement obligation is manual and +# unwritten — spec §6.4 and the non-claims of §10.5); +# * that the Dedukti witness typechecks (no dkcheck ran); +# * that Coq/Lean accept the statement (no coqchk / lean4checker ran). +# Because of that the receipt this script writes is stamped +# `INCOMPLETE (Warrant)`, never `COMPLETE (Receipt)` (spec §1, §7.4). +# +# Exit status is 0 only if every gate that can run in this environment passes. +# G7 and G11 are skip-to-not-run: absence of a tool is reported, never assumed +# away, and never counted as a pass. + +set -eu + +ZIG=${ZIG:-zig} +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +root=$(CDPATH= cd -- "$here/../../.." && pwd) +ADDR="$root/tools/atoma/zig-out/bin/atoma" + +die() { + printf 'FAIL %s\n' "$1" >&2 + exit 1 +} + +[ -x "$ADDR" ] || (cd "$root/tools/atoma" && "$ZIG" build >/dev/null) || die "cannot build atoma" + +cd "$here" + +# ── G1: subset conformance + unit tests ───────────────────────────────────── +"$ZIG" test src/frame_parse.zig >/dev/null 2>&1 || die "G1 unit tests" +printf 'G1 ok unit tests (frame_parse)\n' + +# ── G2: four target classes ───────────────────────────────────────────────── +for triple in x86_64-linux-gnu aarch64-linux-gnu riscv64-linux-gnu wasm32-freestanding; do + "$ZIG" build-obj src/frame_parse.zig -target "$triple" -fno-emit-bin >/dev/null 2>&1 || + die "G2 cross-compile $triple" +done +printf 'G2 ok cross-compiles: x86_64 aarch64 riscv64 wasm32\n' + +# ── G3: layout witnesses ──────────────────────────────────────────────────── +./tools/layout.sh >/dev/null || die "G3 layout witness" +rows=$(wc -l < spec/layout.cspec | tr -d ' ') +[ "$rows" = 60 ] || die "G3 expected 60 layout rows, got $rows" +printf 'G3 ok layout witness: %s rows over 4 targets\n' "$rows" + +# ── G4: the negative layout falsifier ─────────────────────────────────────── +if "$ZIG" build-obj tools/layout_negative.zig -target wasm32-freestanding -fno-emit-bin >/dev/null 2>&1; then + die "G4 usizse-across-FFI counter-example was accepted on wasm32" +fi +printf 'G4 ok usize-across-FFI rejected on wasm32 (F0.3)\n' + +# ── G5: hash-checked seam equivalence ─────────────────────────────────────── +# The verified artifact is (contract ∧ layout table): concatenating the checked +# layout rows means the seam hash covers the ABI layout too, so a drifted offset +# cannot hide behind an unchanged contract. +cat spec/face-a.cspec spec/layout.cspec > spec/.face-a.full.cspec +cat spec/face-b.cspec spec/layout.cspec > spec/.face-b.full.cspec +a=$("$ADDR" hash spec/.face-a.full.cspec) +b=$("$ADDR" hash spec/.face-b.full.cspec) +[ "$a" = "$b" ] || die "G5 faces diverge: $a vs $b" +printf 'G5 ok seam equivalence %s\n' "$a" + +# A one-token difference must diverge, or G5 is vacuous. +"$ADDR" mutate spec/.face-a.full.cspec off_by_one > spec/.probe.cspec +c=$("$ADDR" hash spec/.probe.cspec) +rm -f spec/.probe.cspec +[ "$a" != "$c" ] || die "G5 vacuous: a one-byte spec change kept the digest" +printf 'G5 ok divergence probe %s\n' "$c" + +# ── G6: mutation sweep at the artifact level ──────────────────────────────── +applied=0 +distinct=0 +seen="$a" +for op in $("$ADDR" ops); do + if "$ADDR" mutate spec/.face-a.full.cspec "$op" > spec/.mutant.cspec 2>/dev/null; then + applied=$((applied + 1)) + m=$("$ADDR" hash spec/.mutant.cspec) + case " $seen " in + *" $m "*) : ;; + *) + distinct=$((distinct + 1)) + seen="$seen $m" + ;; + esac + fi +done +rm -f spec/.mutant.cspec spec/.probe.cspec spec/.face-a.full.cspec spec/.face-b.full.cspec +[ "$applied" = 11 ] || die "G6 only $applied of 11 operators applied" +[ "$distinct" = 11 ] || die "G6 only $distinct of 11 mutants were distinct" +printf 'G6 ok mutation sweep: %s applied, %s distinct artifacts\n' "$applied" "$distinct" + +# ── G7: SMT verification conditions ───────────────────────────────────────── +# Optional: needs python3 + z3-solver. When it cannot run, the receipt records +# `"smt":"not-run"` rather than claiming anything. +smt_state="not-run" +vc_hash="none" +vc_count=0 +PY=${PYTHON:-python3} +if "$PY" -c 'import z3' >/dev/null 2>&1; then + if "$PY" vc/gen_vcs.py > witness/vc-report.txt 2>&1; then + vc_count=$(sed -n 's/^\([0-9][0-9]*\) VCs, 0 failing$/\1/p' witness/vc-report.txt) + # One content address for the whole VC set: sorted per-file hashes. + vc_hash=$( + for f in vc/*.smt2; do "$ADDR" vc-hash "$f"; done | sort | "$ADDR" vc-hash /dev/stdin + ) + smt_state="discharged" + printf 'G7 ok %s VCs discharged by z3 (%s)\n' "$vc_count" "$vc_hash" + else + die "G7 VC generation or discharging failed (see witness/vc-report.txt)" + fi +else + printf 'G7 -- z3 not installed: SMT obligations not discharged\n' +fi + +# ── G8: extraction reproduces the checked-in Face B ───────────────────────── +"$ADDR" extract src/frame_parse.zig --symbol atoma_frame_parse > spec/.extracted.cspec +x=$("$ADDR" hash spec/.extracted.cspec) +b2=$("$ADDR" hash spec/face-b.cspec) +rm -f spec/.extracted.cspec +[ "$x" = "$b2" ] || die "G8 extractor output ($x) differs from face-b ($b2): re-run atoma extract and commit the result" +printf 'G8 ok Face B extracted from source %s\n' "$x" + +# ── G9: subset conformance of the implementation ──────────────────────────── +if ! "$ADDR" check src/frame_parse.zig > witness/subset-report.txt 2>&1; then + cat witness/subset-report.txt >&2 + die "G9 subset violations in src/frame_parse.zig" +fi +grep -q '6 contracts' witness/subset-report.txt || die "G9 expected 6 contracts in frame_parse.zig" +printf 'G9 ok subset clean: 6 exports, 6 contracts, 0 diagnostics\n' + +# ── G10: the negative corpus must be rejected ─────────────────────────────── +if "$ADDR" check fixtures/violations.zig > witness/violations-report.txt 2>&1; then + die "G10 the subset checker accepted fixtures/violations.zig" +fi +codes=$(sed -n 's/.*: \(E-[A-Z-]*\):.*/\1/p' witness/violations-report.txt | sort -u | wc -l | tr -d ' ') +diags=$(sed -n 's/.*: \(E-[A-Z-]*\):.*/\1/p' witness/violations-report.txt | wc -l | tr -d ' ') +[ "$codes" -ge 15 ] || die "G10 only $codes distinct diagnostic codes (want >= 15)" +[ "$diags" -ge 20 ] || die "G10 only $diags diagnostics (want >= 20)" +printf 'G10 ok negative corpus rejected: %s diagnostics, %s distinct codes\n' "$diags" "$codes" + +# ── G11: the Agda metatheory ──────────────────────────────────────────────── +# Optional: needs agda. `--safe` turns postulates, termination pragmas, rewrite +# rules, `primTrustMe` and cubical primitives into compile errors, so a green +# run is evidence that the proof is total and axiom-free. It is evidence about +# the model in `Core.agda`; the refinement obligation to Zig is NOT proved and +# is listed as a non-claim in the specification. +proof_state="not-run" +proof_hash="none" +AGDA=${AGDA:-agda} +if command -v "$AGDA" >/dev/null 2>&1; then + AGDA="$AGDA" "$root/verification/atoma/check-agda.sh" > witness/agda-report.txt 2>&1 || { + cat witness/agda-report.txt >&2 + die "G11 the Agda metatheory failed to typecheck" + } + # Ordered digest over the four module sources: order matters because + # Soundness imports Core imports Bv, so a permuted set is a different proof. + proof_hash=$( + for m in Bv Lin Core Soundness; do + "$ADDR" src-hash "$root/verification/atoma/agda/$m.agda" + done | "$ADDR" src-hash /dev/stdin + ) + proof_state="checked" + printf 'G11 ok metatheory typechecks: 4 modules, 0 postulates (%s)\n' "$proof_hash" +else + printf 'G11 -- agda not installed: metatheory not typechecked\n' +fi + +# ── receipt ───────────────────────────────────────────────────────────────── +# I-JSON + JCS: sorted keys, no insignificant whitespace, no floats. +layout_hash=$("$ADDR" hash spec/layout.cspec) +receipt=witness/phase0.receipt.json +printf '%s' \ + "{\"artifacts\":{\"face-a\":\"$a\",\"face-b\":\"$b\",\"layout\":\"$layout_hash\"}," \ + "\"contract\":\"atoma.frame.parse\",\"equivalence\":\"EQUIVALENT\"," \ + "\"gate\":\"phase0\"," \ + "\"mutants\":{\"applied\":$applied,\"distinct\":$distinct}," \ + "\"proof\":{\"modules\":4,\"srcset\":\"$proof_hash\",\"status\":\"$proof_state\"}," \ + "\"schema\":\"atoma.receipt.v1\"," \ + "\"smt\":{\"status\":\"$smt_state\",\"vcs\":$vc_count,\"vcset\":\"$vc_hash\"}," \ + "\"status\":\"INCOMPLETE\",\"status_class\":\"Warrant\"," \ + "\"subset\":{\"contracts\":6,\"diagnostics_negative_corpus\":$diags,\"codes_negative_corpus\":$codes}," \ + "\"targets\":[\"aarch64\",\"riscv64\",\"wasm32\",\"x86_64\"]," \ + "\"tests\":{\"atoma\":14,\"frame_parse\":11}}" > "$receipt" +printf '\nreceipt: %s\n' "$receipt" +cat "$receipt" +printf '\n' +printf 'STATUS: INCOMPLETE (Warrant) - Dedukti/coqchk/lean4checker checks did not run.\n' diff --git a/examples/atoma/frame-v1/witness/agda-report.txt b/examples/atoma/frame-v1/witness/agda-report.txt new file mode 100644 index 00000000..533af330 --- /dev/null +++ b/examples/atoma/frame-v1/witness/agda-report.txt @@ -0,0 +1,5 @@ +agda ok Bv +agda ok Lin +agda ok Core +agda ok Soundness +agda: 4 modules, 0 postulates, 0 holes diff --git a/examples/atoma/frame-v1/witness/phase0.receipt.json b/examples/atoma/frame-v1/witness/phase0.receipt.json new file mode 100644 index 00000000..de72ef95 --- /dev/null +++ b/examples/atoma/frame-v1/witness/phase0.receipt.json @@ -0,0 +1 @@ +{"artifacts":{"face-a":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","face-b":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","layout":"blake3:c75f72ce33010b457c8dc7f8c8514720904ddaeca9de0ce412cc7d61cf8accd1"},"contract":"atoma.frame.parse","equivalence":"EQUIVALENT","gate":"phase0","mutants":{"applied":11,"distinct":11},"proof":{"modules":4,"srcset":"blake3:e2b2f961812d4ed1165f3d306d267dd95af7d0f13f7ce146fde9355d7a647249","status":"checked"},"schema":"atoma.receipt.v1","smt":{"status":"discharged","vcs":14,"vcset":"blake3:72c74c012d527feab0988225098a7a110e35252794c67848ab13f010c75e3698"},"status":"INCOMPLETE","status_class":"Warrant","subset":{"contracts":6,"diagnostics_negative_corpus":20,"codes_negative_corpus":17},"targets":["aarch64","riscv64","wasm32","x86_64"],"tests":{"atoma":14,"frame_parse":11}} \ No newline at end of file diff --git a/examples/atoma/frame-v1/witness/subset-report.txt b/examples/atoma/frame-v1/witness/subset-report.txt new file mode 100644 index 00000000..f19f8c0c --- /dev/null +++ b/examples/atoma/frame-v1/witness/subset-report.txt @@ -0,0 +1 @@ +src/frame_parse.zig: 102 declarations, 6 exports, 6 contracts, 0 diagnostics diff --git a/examples/atoma/frame-v1/witness/vc-report.txt b/examples/atoma/frame-v1/witness/vc-report.txt new file mode 100644 index 00000000..6298cc44 --- /dev/null +++ b/examples/atoma/frame-v1/witness/vc-report.txt @@ -0,0 +1,22 @@ +VC want z3 meaning +V1_no_underflow unsat unsat ok `buf.len - 12` cannot wrap once len >= 12 is known +V1_needle_drop_requires sat sat ok without `len >= 12` the subtraction underflows: model is the panic + model: buf_len=0 +V2_slice_in_bounds unsat unsat ok 12 + length <= buf.len, so buf[12 .. 12+length] is in bounds +V2_needle_drop_payload_bound sat sat ok a frame claiming more bytes than the buffer holds slices out of bounds + model: buf_len=12, length=1 +V2_mutant_off_by_one sat sat ok `avail + 1` admits exactly one byte past the end: off-by-one + model: buf_len=2147483647, length=2147483636 +V3_intcast_range unsat unsat ok a slice obtained from a u32 in_len is at most 2^32-1 bytes and at least 12, so the usize-to-u32 @intCast cannot trap +V3_needle_drop_ffi_bound sat sat ok called directly with a >4GiB slice, the same @intCast panics + model: buf_len_usize=18446744069414584332 +V4_maxplus_bound unsat unsat ok 8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus bound is representable in the cost domain +V5_magic_wire_order unsat unsat ok bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' on the wire +V5_mutant_wrong_endian unsat unsat ok 0x4154 is refuted by the same bytes: the literal ASCII word is wrong +V6_padding_zeroed unsat unsat ok writes hit only field bytes, so every padding byte keeps the 0x00 it got from zeroBytes +V6_mutant_offset_drift sat sat ok a payload placed at offset 12 writes into the padding hole 12..16: the padding VC catches layout drift +V7_post_payload_len unsat unsat ok the success postcondition follows from the guard that produced success +V8_premise_satisfiable sat sat ok a contradictory precondition would make every VC trivially UNSAT, so satisfiability of the premises is a VC in its own right + model: buf_len=0 + +14 VCs, 0 failing diff --git a/examples/atoma/frame-v1/witness/violations-report.txt b/examples/atoma/frame-v1/witness/violations-report.txt new file mode 100644 index 00000000..0dedf7cb --- /dev/null +++ b/examples/atoma/frame-v1/witness/violations-report.txt @@ -0,0 +1,21 @@ +fixtures/violations.zig:17: E-GLOBAL-VAR: global_counter +fixtures/violations.zig:20: E-ABI-PACKED: packed +fixtures/violations.zig:39: E-PTR-C: [*c] +fixtures/violations.zig:46: E-PTR-CAST: @ptrCast +fixtures/violations.zig:48: E-PTR-INT: @ptrFromInt +fixtures/violations.zig:55: E-ASM: asm +fixtures/violations.zig:55: E-VOLATILE: volatile +fixtures/violations.zig:57: E-UNREACHABLE: unreachable +fixtures/violations.zig:59: E-PANIC: @panic +fixtures/violations.zig:64: E-ALLOC-AMBIENT: c_allocator +fixtures/violations.zig:70: E-CIMPORT: @cImport +fixtures/violations.zig:75: E-OPTIONAL-UNWRAP: .? +fixtures/violations.zig:80: E-SAFETY-OFF: @setRuntimeSafety +fixtures/violations.zig:27: E-ABI-WIDTH: usize +fixtures/violations.zig:27: E-ABI-WIDTH: bool +fixtures/violations.zig:27: E-ABI-WIDTH: anyopaque +fixtures/violations.zig:34: E-ABI-UNION: extern union +fixtures/violations.zig:89: E-ABI-CALLCONV: wrong_spelling +fixtures/violations.zig:84: E-UNCONTRACTED-EXPORT: naked_export +fixtures/violations.zig:89: E-UNCONTRACTED-EXPORT: wrong_spelling +fixtures/violations.zig: 17 declarations, 2 exports, 0 contracts, 20 diagnostics diff --git a/tools/atoma/.zig-version b/tools/atoma/.zig-version new file mode 100644 index 00000000..4312e0d0 --- /dev/null +++ b/tools/atoma/.zig-version @@ -0,0 +1 @@ +0.15.2 diff --git a/tools/atoma/build.zig b/tools/atoma/build.zig new file mode 100644 index 00000000..71ee7b66 --- /dev/null +++ b/tools/atoma/build.zig @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// atoma — build file. Pinned to Zig 0.15.2 (`.zig-version`), the same +// compiler generation as src/interface/ffi. The tool is deliberately built only +// from `std` so that it has no dependency surface at all. + +const std = @import("std"); + +pub fn build(b: *std.Build) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + + const exe = b.addExecutable(.{ + .name = "atoma", + .root_module = b.createModule(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }), + }); + b.installArtifact(exe); + + const run_cmd = b.addRunArtifact(exe); + run_cmd.step.dependOn(b.getInstallStep()); + if (b.args) |args| run_cmd.addArgs(args); + const run_step = b.step("run", "Run atoma"); + run_step.dependOn(&run_cmd.step); + + const test_step = b.step("test", "Run the unit tests"); + for ([_][]const u8{ "src/canon.zig", "src/frontend.zig" }) |path| { + const unit_tests = b.addTest(.{ + .root_module = b.createModule(.{ + .root_source_file = b.path(path), + .target = target, + .optimize = optimize, + }), + }); + test_step.dependOn(&b.addRunArtifact(unit_tests).step); + } +} diff --git a/tools/atoma/src/canon.zig b/tools/atoma/src/canon.zig new file mode 100644 index 00000000..fcea5c30 --- /dev/null +++ b/tools/atoma/src/canon.zig @@ -0,0 +1,637 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// Atoma — canonical form of the Core Spec IR (`.cspec`, wire format v1). +// +// This module is the *untrusted* reference canonicaliser. The trusted encoder is +// `encode : Contract -> String` in `examples/atoma/frame-v1/abi/FrameAbi.idr` +// (Face A); the two are tied together by the golden-corpus test in `canon.zig` +// and by the seam gate. The eight rules it implements are +// docs/spec/ATOMA-SPEC.adoc §2.4. Nothing in this file is in the TCB: it may be +// replaced, rewritten or thrown away without changing what Atoma proves. +// +// Equality of canonical byte strings is the Atoma notion of "Face A and Face +// B say the same thing". It is a *syntactic* agreement check, not a proof of +// semantic equivalence (§2.5 of the spec). +// +// Canonicalisation rules (normative; mirrored by `encode` in CoreSpec.idr): +// R1 Comments (`#` to end of line) and blank lines are dropped. +// R2 A line is reduced to tokens: `(` and `)` are one-character tokens, every +// other token is a maximal run of non-space characters. +// R3 Tokens are separated by exactly one space, each line ends with exactly +// one `\n`, ASCII only, no tabs, no trailing whitespace. +// R4 Under `forall`/`exists`, binder names are renamed to `%0`, `%1`, ... in +// order of occurrence (alpha-normalisation). Free names are untouched. +// v1 restriction: a binder type must be atomic (a named sort). Compound +// binder types must be introduced through a `sort` declaration first. +// R5 Integer literals are normalised to unsigned decimal with no leading +// zeros (`0x10` -> `16`, `1_000` -> `1000`, `0b1010` -> `10`). +// R6 *Set-valued* lines are sorted: `cap`, `assigns`, `field`, `sort`. +// `field` sorts by (struct, numeric offset); the others lexicographically. +// R7 *Positional* lines keep their order because position is ABI-significant: +// `cspec`, `contract`, `kind`, `param`, `borrow`, `requires`, `ensures`, +// `invariant`, `assert`, `layout`, `bound`. Sorting them would hide an +// ABI-order disagreement between the Idris2 face and the Zig face, which +// is exactly the bug we want to see. +// R8 Domains are separated so that a digest of one artifact class can never +// be read as a digest of another: +// "atoma.cspec.v1\n" ++ canonical bytes contract specification +// "atoma.vc.v1\n" ++ raw bytes SMT-LIB verification condition +// "atoma.dk.v1\n" ++ raw bytes Dedukti witness +// "atoma.src.v1\n" ++ raw bytes proof source (Agda module) + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const domain_spec = "atoma.cspec.v1\n"; +pub const domain_dk = "atoma.dk.v1\n"; +pub const domain_vc = "atoma.vc.v1\n"; +pub const domain_src = "atoma.src.v1\n"; + +/// Set-valued lines: sorted in canonical form (R6). +const set_valued = [_][]const u8{ "cap", "assigns", "field", "sort" }; + +pub const Error = error{ + OutOfMemory, + MalformedBinder, + UnbalancedParens, + BadInteger, +}; + +pub const Canon = struct { + bytes: []u8, + /// BLAKE3 of domain_spec ++ bytes. + digest: [32]u8, + + pub fn deinit(self: Canon, alloc: Allocator) void { + alloc.free(self.bytes); + } + + pub fn hex(self: Canon) [64]u8 { + return toHex(self.digest); + } +}; + +pub fn toHex(d: [32]u8) [64]u8 { + const alphabet = "0123456789abcdef"; + var out: [64]u8 = undefined; + for (d, 0..) |b, i| { + out[2 * i] = alphabet[b >> 4]; + out[2 * i + 1] = alphabet[b & 0xf]; + } + return out; +} + +pub fn digestOf(domain: []const u8, bytes: []const u8) [32]u8 { + var h = std.crypto.hash.Blake3.init(.{}); + h.update(domain); + h.update(bytes); + var out: [32]u8 = undefined; + h.final(&out); + return out; +} + +pub fn digestHex(domain: []const u8, bytes: []const u8) [64]u8 { + return toHex(digestOf(domain, bytes)); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Tokenisation (R2, R3) +// ───────────────────────────────────────────────────────────────────────────── + +/// Split one line into tokens, treating `(` and `)` as single-character tokens. +/// `out` is cleared first; tokens alias the input slice. +pub fn tokenise(alloc: Allocator, line: []const u8, out: *std.ArrayListUnmanaged([]const u8)) !void { + out.clearRetainingCapacity(); + var i: usize = 0; + while (i < line.len) { + const c = line[i]; + if (c == ' ' or c == '\t' or c == '\r') { + i += 1; + continue; + } + if (c == '(' or c == ')') { + try out.append(alloc, line[i .. i + 1]); + i += 1; + continue; + } + const start = i; + while (i < line.len and line[i] != ' ' and line[i] != '\t' and line[i] != '\r' and + line[i] != '(' and line[i] != ')') i += 1; + try out.append(alloc, line[start..i]); + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Integer normalisation (R5) +// ───────────────────────────────────────────────────────────────────────────── + +/// Returns the normalised decimal form, or the token unchanged if it is not a +/// bare integer literal. +pub fn normaliseInteger(alloc: Allocator, tok: []const u8) ![]const u8 { + if (tok.len == 0) return alloc.dupe(u8, tok); + var sign: []const u8 = ""; + var body = tok; + if (body[0] == '-') { + sign = "-"; + body = body[1..]; + if (body.len == 0) return alloc.dupe(u8, tok); + } + var base: u8 = 10; + if (body.len > 2 and body[0] == '0' and (body[1] == 'x' or body[1] == 'X')) { + base = 16; + body = body[2..]; + } else if (body.len > 2 and body[0] == '0' and (body[1] == 'b' or body[1] == 'B')) { + base = 2; + body = body[2..]; + } + if (body.len == 0) return alloc.dupe(u8, tok); + var value: u128 = 0; + var digits: usize = 0; + for (body) |c| { + if (c == '_') continue; + const d: u128 = switch (c) { + '0'...'9' => c - '0', + 'a'...'f' => c - 'a' + 10, + 'A'...'F' => c - 'A' + 10, + else => return alloc.dupe(u8, tok), // not an integer literal + }; + if (d >= base) return alloc.dupe(u8, tok); + if (value > (std.math.maxInt(u128) - d) / base) return Error.BadInteger; + value = value * base + d; + digits += 1; + } + if (digits == 0) return alloc.dupe(u8, tok); + return std.fmt.allocPrint(alloc, "{s}{d}", .{ sign, value }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Alpha-normalisation (R4) +// ───────────────────────────────────────────────────────────────────────────── + +const pending_cap = 64; + +/// Alpha-normalise a formula token list. Bound variables become `%`, +/// where depth is the binder's nesting level (0 = outermost). +pub fn alphaNormalise(alloc: Allocator, toks: []const []const u8) Error!std.ArrayListUnmanaged([]const u8) { + const n = toks.len; + var match = try alloc.alloc(usize, n); + defer alloc.free(match); + @memset(match, std.math.maxInt(usize)); + { + var stack = std.ArrayListUnmanaged(usize).empty; + defer stack.deinit(alloc); + for (toks, 0..) |t, i| { + if (std.mem.eql(u8, t, "(")) { + stack.append(alloc, i) catch return Error.OutOfMemory; + } else if (std.mem.eql(u8, t, ")")) { + const open = stack.pop() orelse return Error.UnbalancedParens; + match[open] = i; + } + } + if (stack.items.len != 0) return Error.UnbalancedParens; + } + + var out = std.ArrayListUnmanaged([]const u8).empty; + errdefer out.deinit(alloc); + var scope = std.ArrayListUnmanaged([]const u8).empty; // binder names, innermost last + defer scope.deinit(alloc); + var pending = std.ArrayListUnmanaged(usize).empty; // close index of each open binder + defer pending.deinit(alloc); + + var i: usize = 0; + while (i < n) { + // Pop binders whose body has ended (close indices are monotone). + while (pending.items.len > 0 and i > pending.items[pending.items.len - 1]) { + _ = pending.pop(); + _ = scope.pop(); + } + // `( forall ( x : S ) body )` with atomic S. + const is_binder = i + 6 < n and + std.mem.eql(u8, toks[i], "(") and + (std.mem.eql(u8, toks[i + 1], "forall") or std.mem.eql(u8, toks[i + 1], "exists")) and + std.mem.eql(u8, toks[i + 2], "(") and + std.mem.eql(u8, toks[i + 4], ":") and + match[i + 2] == i + 6; + if (is_binder) { + const depth = scope.items.len; + const cname = std.fmt.allocPrint(alloc, "%{d}", .{depth}) catch return Error.OutOfMemory; + try out.appendSlice(alloc, &[_][]const u8{ toks[i], toks[i + 1], toks[i + 2], cname, toks[i + 4], toks[i + 5], toks[i + 6] }); + scope.append(alloc, toks[i + 3]) catch return Error.OutOfMemory; + pending.append(alloc, match[i]) catch return Error.OutOfMemory; + i += 7; + continue; + } + // If this looks like a binder but the type is not atomic, refuse: the + // canonical form must not silently mis-scope a variable. + const looks_binder = i + 2 < n and std.mem.eql(u8, toks[i], "(") and + (std.mem.eql(u8, toks[i + 1], "forall") or std.mem.eql(u8, toks[i + 1], "exists")); + if (looks_binder) return Error.MalformedBinder; + + var renamed = false; + var s = scope.items.len; + while (s > 0) { + s -= 1; + if (std.mem.eql(u8, scope.items[s], toks[i])) { + const cname = std.fmt.allocPrint(alloc, "%{d}", .{s}) catch return Error.OutOfMemory; + out.append(alloc, cname) catch return Error.OutOfMemory; + renamed = true; + break; + } + } + if (!renamed) out.append(alloc, toks[i]) catch return Error.OutOfMemory; + i += 1; + } + _ = pending_cap; + return out; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Canonicalisation +// ───────────────────────────────────────────────────────────────────────────── + +const CanonLine = struct { + text: []u8, + /// Head keyword (cap / assigns / field / sort). + group: []const u8 = "", + /// Secondary key (struct name for `field`). + sub: []const u8 = "", + key: u64 = 0, +}; + +fn lessThan(_: void, a: CanonLine, b: CanonLine) bool { + const g = std.mem.order(u8, a.group, b.group); + if (g != .eq) return g == .lt; + const s = std.mem.order(u8, a.sub, b.sub); + if (s != .eq) return s == .lt; + if (a.key != b.key) return a.key < b.key; + return std.mem.order(u8, a.text, b.text) == .lt; +} + +fn classify(first: []const u8) enum { set_valued, positional } { + for (set_valued) |s| { + if (std.mem.eql(u8, first, s)) return .set_valued; + } + return .positional; +} + +pub fn isFormulaHead(t: []const u8) bool { + return std.mem.eql(u8, t, "requires") or std.mem.eql(u8, t, "ensures") or + std.mem.eql(u8, t, "invariant") or std.mem.eql(u8, t, "assert"); +} + +/// Canonicalise a source `.cspec` file. Caller owns the returned bytes. +pub fn canonicalise(alloc: Allocator, src: []const u8) ![]u8 { + var tokbuf = std.ArrayListUnmanaged([]const u8).empty; + defer tokbuf.deinit(alloc); + + var positional = std.ArrayListUnmanaged([]u8).empty; + defer positional.deinit(alloc); + var sets = std.ArrayListUnmanaged(CanonLine).empty; + defer sets.deinit(alloc); + + var lines = std.mem.splitScalar(u8, src, '\n'); + while (lines.next()) |raw| { + // R1: `#` starts a comment that runs to end of line. There are no string + // literals in the IR, so this cannot truncate payload data. + const uncommented = if (std.mem.indexOfScalar(u8, raw, '#')) |h| raw[0..h] else raw; + const line = std.mem.trim(u8, uncommented, " \t\r"); + if (line.len == 0) continue; + try tokenise(alloc, line, &tokbuf); + if (tokbuf.items.len == 0) continue; + + var owned = std.ArrayListUnmanaged([]const u8).empty; + defer owned.deinit(alloc); + + if (isFormulaHead(tokbuf.items[0])) { + var norm = try alphaNormalise(alloc, tokbuf.items[1..]); + defer norm.deinit(alloc); + try owned.append(alloc, try alloc.dupe(u8, tokbuf.items[0])); + // R4 then R5: alpha-normalise, then normalise any integer literals. + for (norm.items) |t| try owned.append(alloc, try normaliseInteger(alloc, t)); + } else { + for (tokbuf.items) |t| try owned.append(alloc, try normaliseInteger(alloc, t)); + } + + const joined = try std.mem.join(alloc, " ", owned.items); + if (classify(tokbuf.items[0]) == .positional) { + try positional.append(alloc, joined); + } else { + var sub: []const u8 = ""; + var key: u64 = 0; + if (std.mem.eql(u8, tokbuf.items[0], "field") and owned.items.len >= 3) { + sub = owned.items[1]; + key = std.fmt.parseInt(u64, owned.items[2], 10) catch 0; + } + try sets.append(alloc, .{ .text = joined, .group = tokbuf.items[0], .sub = sub, .key = key }); + } + } + + std.mem.sort(CanonLine, sets.items, {}, lessThan); + + var out = std.ArrayListUnmanaged(u8).empty; + errdefer out.deinit(alloc); + for (positional.items) |p| { + try out.appendSlice(alloc, p); + try out.append(alloc, '\n'); + } + for (sets.items) |s| { + try out.appendSlice(alloc, s.text); + try out.append(alloc, '\n'); + } + return out.toOwnedSlice(alloc); +} + +pub fn canon(alloc: Allocator, src: []const u8) !Canon { + const bytes = try canonicalise(alloc, src); + return .{ .bytes = bytes, .digest = digestOf(domain_spec, bytes) }; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Specification mutation operators (spec §7.3). Producing a mutant is cheap and +// deterministic; KILLING one is the VC pipeline's job (ECHIDNA). This module +// only guarantees every mutant is a distinct artifact with a distinct address, +// which is the necessary (not sufficient) half of mutation detection. +// ───────────────────────────────────────────────────────────────────────────── + +pub const Mutation = enum { + drop_last_requires, + drop_last_ensures, + tighten_le, + laxen_lt, + off_by_one, + drop_cap, + swap_region, + qty_lax, + drop_padding, + drop_borrow, + widen_int, + + pub fn name(self: Mutation) []const u8 { + return @tagName(self); + } + + pub fn all() []const Mutation { + return &[_]Mutation{ + .drop_last_requires, .drop_last_ensures, .tighten_le, .laxen_lt, + .off_by_one, .drop_cap, .swap_region, .qty_lax, + .drop_padding, .drop_borrow, .widen_int, + }; + } +}; + +/// Apply a mutation operator. Returns a newly allocated text, or null if the +/// operator does not apply to this specification. +pub fn applyMutation(alloc: Allocator, src: []const u8, m: Mutation) !?[]u8 { + var line_list = std.ArrayListUnmanaged([]const u8).empty; + defer line_list.deinit(alloc); + var it = std.mem.splitScalar(u8, src, '\n'); + while (it.next()) |l| try line_list.append(alloc, l); + + var last_requires: ?usize = null; + var last_ensures: ?usize = null; + var first_cap: ?usize = null; + var first_borrow: ?usize = null; + var first_layout: ?usize = null; + for (line_list.items, 0..) |l, i| { + const t = std.mem.trim(u8, l, " \t"); + if (std.mem.startsWith(u8, t, "requires ")) last_requires = i; + if (std.mem.startsWith(u8, t, "ensures ")) last_ensures = i; + if (first_cap == null and std.mem.startsWith(u8, t, "cap ")) first_cap = i; + if (first_borrow == null and std.mem.startsWith(u8, t, "borrow ")) first_borrow = i; + if (first_layout == null and std.mem.startsWith(u8, t, "layout ")) first_layout = i; + } + + var out = std.ArrayListUnmanaged(u8).empty; + errdefer out.deinit(alloc); + var mutated_any = false; + + for (line_list.items, 0..) |l, i| { + var text: []const u8 = l; + var rewritten: ?[]u8 = null; + var dropped = false; + switch (m) { + .drop_last_requires => if (last_requires != null and last_requires.? == i) { + dropped = true; + mutated_any = true; + }, + .drop_last_ensures => if (last_ensures != null and last_ensures.? == i) { + dropped = true; + mutated_any = true; + }, + .drop_cap => if (first_cap != null and first_cap.? == i) { + dropped = true; + mutated_any = true; + }, + .drop_borrow => if (first_borrow != null and first_borrow.? == i) { + dropped = true; + mutated_any = true; + }, + .tighten_le => if (std.mem.indexOf(u8, l, "( <= ") != null) { + rewritten = try replaceAllIn(alloc, l, "( <= ", "( < "); + mutated_any = true; + }, + .laxen_lt => if (std.mem.indexOf(u8, l, "( < ") != null) { + rewritten = try replaceAllIn(alloc, l, "( < ", "( <= "); + mutated_any = true; + }, + .off_by_one => if (last_ensures != null and last_ensures.? == i) { + if (try incrementFirstInt(alloc, l)) |r| { + rewritten = r; + mutated_any = true; + } + }, + .swap_region => if (std.mem.indexOf(u8, l, "r0") != null) { + rewritten = try replaceAllIn(alloc, l, "r0", "r1"); + mutated_any = true; + }, + .qty_lax => if (std.mem.startsWith(u8, std.mem.trim(u8, l, " \t"), "param ")) { + if (try loosenQuantity(alloc, l)) |r| { + rewritten = r; + mutated_any = true; + } + }, + .drop_padding => if (first_layout != null and first_layout.? == i) { + if (try stripPadding(alloc, l)) |r| { + rewritten = r; + mutated_any = true; + } + }, + .widen_int => if (std.mem.indexOf(u8, l, "u16") != null) { + rewritten = try replaceAllIn(alloc, l, "u16", "u32"); + mutated_any = true; + }, + } + if (dropped) { + // Remove the line entirely: also swallow one adjacent newline. + continue; + } + if (rewritten) |r| text = r; + try out.appendSlice(alloc, text); + try out.append(alloc, '\n'); + } + if (!mutated_any) { + out.deinit(alloc); + return null; + } + return try out.toOwnedSlice(alloc); +} + +fn replaceAllIn(alloc: Allocator, src: []const u8, needle: []const u8, repl: []const u8) ![]u8 { + var out = std.ArrayListUnmanaged(u8).empty; + errdefer out.deinit(alloc); + var i: usize = 0; + while (i < src.len) { + if (std.mem.startsWith(u8, src[i..], needle)) { + try out.appendSlice(alloc, repl); + i += needle.len; + } else { + try out.append(alloc, src[i]); + i += 1; + } + } + return try out.toOwnedSlice(alloc); +} + +fn incrementFirstInt(alloc: Allocator, src: []const u8) !?[]u8 { + var i: usize = 0; + while (i < src.len) : (i += 1) { + if (src[i] >= '0' and src[i] <= '9') { + const start = i; + while (i < src.len and src[i] >= '0' and src[i] <= '9') i += 1; + const v = std.fmt.parseInt(u64, src[start..i], 10) catch continue; + var out = std.ArrayListUnmanaged(u8).empty; + errdefer out.deinit(alloc); + try out.appendSlice(alloc, src[0..start]); + const digits = try std.fmt.allocPrint(alloc, "{d}", .{v + 1}); + try out.appendSlice(alloc, digits); + try out.appendSlice(alloc, src[i..]); + return try out.toOwnedSlice(alloc); + } + } + return null; +} + +fn loosenQuantity(alloc: Allocator, line: []const u8) !?[]u8 { + var toks = std.ArrayListUnmanaged([]const u8).empty; + defer toks.deinit(alloc); + try tokenise(alloc, line, &toks); + if (toks.items.len < 4) return null; + if (!std.mem.eql(u8, toks.items[2], "1")) return null; + var out = std.ArrayListUnmanaged(u8).empty; + errdefer out.deinit(alloc); + for (toks.items, 0..) |t, idx| { + if (idx != 0) try out.append(alloc, ' '); + if (idx == 2) try out.appendSlice(alloc, "W") else try out.appendSlice(alloc, t); + } + return try out.toOwnedSlice(alloc); +} + +fn stripPadding(alloc: Allocator, line: []const u8) !?[]u8 { + var toks = std.ArrayListUnmanaged([]const u8).empty; + defer toks.deinit(alloc); + try tokenise(alloc, line, &toks); + if (toks.items.len < 5) return null; + var out = std.ArrayListUnmanaged(u8).empty; + errdefer out.deinit(alloc); + var k: usize = 0; + while (k < 5) : (k += 1) { + if (k != 0) try out.append(alloc, ' '); + try out.appendSlice(alloc, toks.items[k]); + } + try out.appendSlice(alloc, " -"); + return try out.toOwnedSlice(alloc); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Tests +// ───────────────────────────────────────────────────────────────────────────── + +const testing = std.testing; +const ta = std.heap.page_allocator; + +test "blake3 known-answer" { + try testing.expectEqualStrings( + "6437b3ac38465133ffb63b75273a8db548c558465d79db03fd359c6cd5bd9d85", + &digestHex("", "abc"), + ); +} + +test "integer normalisation" { + try testing.expectEqualStrings("16", try normaliseInteger(ta, "0x10")); + try testing.expectEqualStrings("1000", try normaliseInteger(ta, "1_000")); + try testing.expectEqualStrings("255", try normaliseInteger(ta, "0b11111111")); + try testing.expectEqualStrings("in.len", try normaliseInteger(ta, "in.len")); + try testing.expectEqualStrings("-3", try normaliseInteger(ta, "-0x3")); +} + +test "alpha-normalisation is insensitive to binder names" { + var t1 = std.ArrayListUnmanaged([]const u8).empty; + try tokenise(ta, "( forall ( i : u16 ) ( < i 65535 ) )", &t1); + const n1 = try alphaNormalise(ta, t1.items); + var t2 = std.ArrayListUnmanaged([]const u8).empty; + try tokenise(ta, "( forall ( k : u16 ) ( < k 65535 ) )", &t2); + const n2 = try alphaNormalise(ta, t2.items); + try testing.expectEqualStrings( + try std.mem.join(ta, " ", n1.items), + try std.mem.join(ta, " ", n2.items), + ); + try testing.expectEqualStrings("( forall ( %0 : u16 ) ( < %0 65535 ) )", try std.mem.join(ta, " ", n1.items)); +} + +test "compound binder types are rejected, not mis-scoped" { + var t = std.ArrayListUnmanaged([]const u8).empty; + try tokenise(ta, "( forall ( i : ( array u8 4 ) ) ( < i 4 ) )", &t); + try testing.expectError(Error.MalformedBinder, alphaNormalise(ta, t.items)); +} + +test "set lines are sorted, positional lines keep their order" { + const src = "cspec 1\ncontract demo.parse\nparam h 1 handle\nparam buf 0 slice\n" ++ + "cap Fs\ncap Alloc\nrequires ( <= n 8 )\nrequires ( <= m 4 )\n" ++ + "field H 8 4 crc u32\nfield H 0 2 magic u16\n"; + const expected = "cspec 1\ncontract demo.parse\nparam h 1 handle\nparam buf 0 slice\n" ++ + "requires ( <= n 8 )\nrequires ( <= m 4 )\ncap Alloc\ncap Fs\n" ++ + "field H 0 2 magic u16\nfield H 8 4 crc u32\n"; + const out = try canonicalise(ta, src); + try testing.expectEqualStrings(expected, out); +} + +test "comments, blank lines and whitespace do not affect the digest" { + const c1 = try canon(ta, "cspec 1\ncontract x\n"); + const c2 = try canon(ta, "# hello\n\ncspec 1 \n\ncontract x # trailing\n"); + try testing.expectEqualSlices(u8, &c1.digest, &c2.digest); +} + +test "a one-token change changes the digest" { + const c1 = try canon(ta, "cspec 1\nrequires ( < len 8 )\n"); + const c2 = try canon(ta, "cspec 1\nrequires ( <= len 8 )\n"); + try testing.expect(!std.mem.eql(u8, &c1.digest, &c2.digest)); +} + +test "every mutation operator yields a distinct artifact" { + const src = "cspec 1\ncontract demo.parse\nparam h 1 handle\n" ++ + "borrow buf shr r0 slice\nlayout H x86_64 24 8 6..8,12..16\n" ++ + "param n 0 u16\nrequires ( <= len 65535 )\nrequires ( < len n )\nensures ( <= ( + len 10 ) ( len in ) )\ncap Alloc\n"; + const base = try canon(ta, src); + const basehex = base.hex(); + var seen: [16][64]u8 = undefined; + var seen_n: usize = 0; + seen[seen_n] = basehex; + seen_n += 1; + var applied: usize = 0; + for (Mutation.all()) |m| { + const maybe = try applyMutation(ta, src, m); + if (maybe) |mut| { + const c = try canon(ta, mut); + const hx = c.hex(); + try testing.expect(!std.mem.eql(u8, &basehex, &hx)); + for (seen[0..seen_n]) |prev| { + try testing.expect(!std.mem.eql(u8, &prev, &hx)); + } + seen[seen_n] = hx; + seen_n += 1; + applied += 1; + } + } + try testing.expectEqual(@as(usize, 11), applied); +} diff --git a/tools/atoma/src/frontend.zig b/tools/atoma/src/frontend.zig new file mode 100644 index 00000000..ab6617d3 --- /dev/null +++ b/tools/atoma/src/frontend.zig @@ -0,0 +1,662 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// frontend.zig — Zig source → Core Spec IR (Face B) and subset conformance. +// +// This is the implementation of §5 of the specification: syntax comes from +// `std.zig.Ast`; every *semantic* fact (layout, sizes, offsets) comes from the +// compiler through the comptime witness, never from this file. Atoma never +// re-implements the compiler, which is why it survives release churn. +// +// Two entry points: +// +// extract doc-comment directives on a declaration → canonical `.cspec` text +// check subset conformance → `E-*` diagnostics, one per violation +// +// Directives are written in doc comments and may carry the `//!` prefix the +// specification uses: +// +// /// @contract atoma.frame.parse +// /// //! @requires ( <= 12 ( len input ) ) +// +// LIMITS (stated, not hidden): this is a token-level analysis. It can see +// `extern struct` field names but not resolved types, so E-ABI-WIDTH is a +// conservative token check, not a type check. The authoritative version is the +// typed pass in Phase 2; the token pass exists so that Phase 0 has teeth. + +const std = @import("std"); +const Ast = std.zig.Ast; +const Allocator = std.mem.Allocator; + +pub const Diag = struct { + code: []const u8, + line: u32, + detail: []const u8, +}; + +pub const Report = struct { + diags: std.ArrayListUnmanaged(Diag) = .empty, + decls: usize = 0, + exports: usize = 0, + contracts: usize = 0, + + /// Diag owns its two strings: they are copied out of the parse buffer, which + /// is freed before the report is consumed. (Getting this wrong segfaulted + /// `atoma check` on the first real file — token slices are not stable.) + pub fn deinit(self: *Report, alloc: Allocator) void { + for (self.diags.items) |d| { + alloc.free(@constCast(d.code)); + alloc.free(@constCast(d.detail)); + } + self.diags.deinit(alloc); + } + + pub fn add(self: *Report, alloc: Allocator, code: []const u8, line: u32, detail: []const u8) !void { + const c = try alloc.dupe(u8, code); + errdefer alloc.free(c); + const d = try alloc.dupe(u8, detail); + try self.diags.append(alloc, .{ .code = c, .line = line, .detail = d }); + } +}; + +fn lineOf(src: []const u8, offset: usize) u32 { + var line: u32 = 1; + for (src[0..@min(offset, src.len)]) |c| { + if (c == '\n') line += 1; + } + return line; +} + +fn eql(a: []const u8, b: []const u8) bool { + return std.mem.eql(u8, a, b); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Directives inside a doc-comment run +// ───────────────────────────────────────────────────────────────────────────── + +/// One `@directive value` line recovered from a doc comment. +pub const Directive = struct { + key: []const u8, // without the '@' + value: []const u8, + line: u32, +}; + +/// Strip `///`, then an optional `//!`, then whitespace. Returns the remainder, +/// or null when the line carries no directive. +pub fn directiveBody(raw: []const u8) ?[]const u8 { + var s = std.mem.trim(u8, raw, " \t\r"); + if (!std.mem.startsWith(u8, s, "///")) return null; + s = std.mem.trim(u8, s[3..], " \t\r"); + if (std.mem.startsWith(u8, s, "//!")) s = std.mem.trim(u8, s[3..], " \t\r"); + if (s.len == 0 or s[0] != '@') return null; + return s[1..]; +} + +/// Parse a directive body into (key, value). `requires` is the key, the rest is +/// the value verbatim (the value is a formula in the IR's own grammar). +pub fn parseDirective(body: []const u8) struct { key: []const u8, value: []const u8 } { + const sp = std.mem.indexOfScalar(u8, body, ' ') orelse body.len; + var key = body[0..sp]; + var value = if (sp < body.len) body[sp + 1 ..] else ""; + // Tolerate the aligned spelling `@requires ( ... )`. + value = std.mem.trim(u8, value, " \t"); + // `@param` lines are frequently written aligned; keep single internal spaces + // by collapsing runs of spaces. + _ = &key; + return .{ .key = key, .value = value }; +} + +/// Collapse runs of spaces/tabs into one space, in place into `out`. +fn squashInto(out: *std.ArrayListUnmanaged(u8), alloc: Allocator, s: []const u8) !void { + var prev_space = false; + for (s) |c| { + const is_space = c == ' ' or c == '\t'; + if (is_space) { + if (!prev_space) try out.append(alloc, ' '); + prev_space = true; + } else { + try out.append(alloc, c); + prev_space = false; + } + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// Declaration discovery +// ───────────────────────────────────────────────────────────────────────────── + +const Decl = struct { + kind: enum { fn_decl, var_decl, const_decl }, + name: []const u8, + line: u32, + token: u32, + exported: bool, + doc_first: u32, // first doc_comment token of the run, or sentinel + doc_end: u32, // one past the last +}; + +const no_doc: u32 = 0xFFFF_FFFF; + +fn collectDecls(alloc: Allocator, ast: Ast, report: *Report) !std.ArrayListUnmanaged(Decl) { + var out: std.ArrayListUnmanaged(Decl) = .empty; + errdefer out.deinit(alloc); + const tags = ast.tokens.items(.tag); + const n: u32 = @intCast(tags.len); + + var pending_first: u32 = no_doc; + var pending_end: u32 = no_doc; + var saw_export = false; + var depth: u32 = 0; + + var i: u32 = 0; + while (i < n) : (i += 1) { + const t = tags[i]; + switch (t) { + .l_brace => { + depth += 1; + pending_first = no_doc; + continue; + }, + .r_brace => { + if (depth > 0) depth -= 1; + pending_first = no_doc; + continue; + }, + .doc_comment => { + if (pending_first == no_doc) pending_first = i; + pending_end = i + 1; + continue; + }, + .keyword_export => { + saw_export = true; + continue; + }, + .keyword_pub, .keyword_extern, .keyword_inline, .keyword_noinline => continue, + .keyword_fn, .keyword_var, .keyword_const => { + if (i + 1 < n and tags[i + 1] == .identifier) { + const name = Ast.tokenSlice(ast, i + 1); + const loc = ast.tokenLocation(0, i); + try out.append(alloc, .{ + .kind = switch (t) { + .keyword_fn => .fn_decl, + .keyword_var => .var_decl, + else => .const_decl, + }, + .name = name, + .line = @intCast(loc.line + 1), + .token = i, + .exported = saw_export, + .doc_first = pending_first, + .doc_end = if (pending_first == no_doc) no_doc else pending_end, + }); + if (t == .keyword_fn and saw_export) report.exports += 1; + saw_export = false; + pending_first = no_doc; + continue; + } + }, + else => {}, + } + // Any other token ends a doc run's claim on the next declaration, unless + // it is a modifier handled above. + if (t != .doc_comment) { + pending_first = no_doc; + saw_export = saw_export and (t == .keyword_export); + } + } + report.decls = out.items.len; + return out; +} + +// ───────────────────────────────────────────────────────────────────────────── +// Banned-construct scan (§2.4) +// ───────────────────────────────────────────────────────────────────────────── + +const BannedBuiltin = struct { text: []const u8, code: []const u8 }; + +const banned_builtins = [_]BannedBuiltin{ + .{ .text = "@ptrFromInt", .code = "E-PTR-INT" }, + .{ .text = "@ptrCast", .code = "E-PTR-CAST" }, + .{ .text = "@alignCast", .code = "E-PTR-CAST" }, + .{ .text = "@cImport", .code = "E-CIMPORT" }, + .{ .text = "@panic", .code = "E-PANIC" }, + .{ .text = "@setRuntimeSafety", .code = "E-SAFETY-OFF" }, + .{ .text = "@setEvalBranchQuota", .code = "E-QUOTA" }, +}; + +pub fn scanBanned(alloc: Allocator, ast: Ast, src: []const u8, report: *Report) !void { + const tags = ast.tokens.items(.tag); + const n: u32 = @intCast(tags.len); + var depth: u32 = 0; + + var i: u32 = 0; + while (i < n) : (i += 1) { + const t = tags[i]; + const text = Ast.tokenSlice(ast, i); + const line = lineOf(src, ast.tokens.items(.start)[i]); + + if (t == .l_brace) { + depth += 1; + continue; + } + if (t == .r_brace) { + if (depth > 0) depth -= 1; + continue; + } + + switch (t) { + .builtin => { + for (banned_builtins) |b| { + if (eql(text, b.text)) try report.add(alloc, b.code, line, text); + } + }, + .keyword_volatile => try report.add(alloc, "E-VOLATILE", line, text), + .keyword_asm => try report.add(alloc, "E-ASM", line, text), + .keyword_unreachable => try report.add(alloc, "E-UNREACHABLE", line, text), + .keyword_packed => try report.add(alloc, "E-ABI-PACKED", line, text), + .identifier => { + if (eql(text, "c_allocator") or eql(text, "page_allocator") or + eql(text, "raw_c_allocator")) + { + try report.add(alloc, "E-ALLOC-AMBIENT", line, text); + } + // A top-level `var` (outside any braces) is ambient mutable state. + if (depth == 0 and i > 0 and tags[i - 1] == .keyword_var) { + try report.add(alloc, "E-GLOBAL-VAR", line, text); + } + }, + .period => { + if (i + 1 < n and tags[i + 1] == .question_mark) { + try report.add(alloc, "E-OPTIONAL-UNWRAP", line, ".?"); + } + }, + .l_bracket => { + // `[*c]` tokenises as `[` `*` `c` `]`. + if (i + 3 < n and tags[i + 1] == .asterisk and + tags[i + 2] == .identifier and eql(Ast.tokenSlice(ast, i + 2), "c") and + tags[i + 3] == .r_bracket) + { + try report.add(alloc, "E-PTR-C", line, "[*c]"); + } + }, + else => {}, + } + } +} + +/// `extern struct` / `extern union` bodies may not contain width-ambiguous or +/// non-C types. Conservative token check, see the header comment. +pub fn scanAbiTypes(alloc: Allocator, ast: Ast, src: []const u8, report: *Report) !void { + const tags = ast.tokens.items(.tag); + const n: u32 = @intCast(tags.len); + + var i: u32 = 0; + while (i + 1 < n) : (i += 1) { + if (tags[i] != .keyword_extern) continue; + if (tags[i + 1] != .keyword_struct and tags[i + 1] != .keyword_union) continue; + const is_union = tags[i + 1] == .keyword_union; + const line = lineOf(src, ast.tokens.items(.start)[i]); + if (is_union) try report.add(alloc, "E-ABI-UNION", line, "extern union"); + + // Walk the body. + var j = i + 2; + var depth: i32 = 0; + var seen_brace = false; + while (j < n) : (j += 1) { + const tj = tags[j]; + if (tj == .l_brace) { + depth += 1; + seen_brace = true; + continue; + } + if (tj == .r_brace) { + depth -= 1; + if (seen_brace and depth == 0) break; + continue; + } + if (tj != .identifier) continue; + const text = Ast.tokenSlice(ast, j); + const prev_is_type_pos = j > 0 and (tags[j - 1] == .colon or tags[j - 1] == .asterisk or + tags[j - 1] == .l_bracket); + if (!prev_is_type_pos) continue; + if (eql(text, "usize") or eql(text, "isize") or eql(text, "bool") or + eql(text, "anyopaque") or eql(text, "anyerror")) + { + try report.add(alloc, "E-ABI-WIDTH", line, text); + } + } + } +} + +/// An `export fn` must use the C calling convention, spelled `.c` (the compiler +/// rejects `.C` on every Zig release measured — see the spec's version matrix). +pub fn scanCallconv(alloc: Allocator, ast: Ast, decls: []const Decl, report: *Report) !void { + const tags = ast.tokens.items(.tag); + const n: u32 = @intCast(tags.len); + for (decls) |d| { + if (d.kind != .fn_decl or !d.exported) continue; + var i = d.token; + var found = false; + var spelled_ok = false; + while (i < n and tags[i] != .l_brace) : (i += 1) { + if (tags[i] != .keyword_callconv) continue; + found = true; + if (i + 4 < n and tags[i + 1] == .l_paren and tags[i + 2] == .period and + tags[i + 3] == .identifier and eql(Ast.tokenSlice(ast, i + 3), "c")) + { + spelled_ok = true; + } + } + if (!found) { + try report.add(alloc, "E-ABI-NO-CALLCONV", d.line, d.name); + } else if (!spelled_ok) { + try report.add(alloc, "E-ABI-CALLCONV", d.line, d.name); + } + } +} + +// ───────────────────────────────────────────────────────────────────────────── +// check — the whole subset pass +// ───────────────────────────────────────────────────────────────────────────── + +pub const CheckOptions = struct { + /// Every `export fn` must carry a `@contract`. Off only for fixtures. + require_contracts: bool = true, +}; + +pub fn check(alloc: Allocator, src: []const u8, opts: CheckOptions) !Report { + var report = Report{}; + const srcz = try alloc.dupeZ(u8, src); + defer alloc.free(srcz); + var ast = try Ast.parse(alloc, srcz, .zig); + defer ast.deinit(alloc); + + if (ast.errors.len != 0) { + const loc = ast.tokenLocation(0, ast.errors[0].token); + try report.add(alloc, "E-PARSE", @intCast(loc.line + 1), "source does not parse"); + return report; + } + + var decls = try collectDecls(alloc, ast, &report); + defer decls.deinit(alloc); + + try scanBanned(alloc, ast, src, &report); + try scanAbiTypes(alloc, ast, src, &report); + try scanCallconv(alloc, ast, decls.items, &report); + + // Contract ↔ export linkage, both directions. + var contracted = std.StringHashMapUnmanaged(void){}; + defer contracted.deinit(alloc); + + for (decls.items) |d| { + if (d.doc_first == no_doc) continue; + var t = d.doc_first; + while (t < d.doc_end) : (t += 1) { + const body = directiveBody(Ast.tokenSlice(ast, t)) orelse continue; + const kv = parseDirective(body); + if (eql(kv.key, "contract")) { + report.contracts += 1; + try contracted.put(alloc, d.name, {}); + } + } + } + + if (opts.require_contracts) { + for (decls.items) |d| { + if (d.kind == .fn_decl and d.exported and !contracted.contains(d.name)) { + try report.add(alloc, "E-UNCONTRACTED-EXPORT", d.line, d.name); + } + } + } + var it = contracted.keyIterator(); + while (it.next()) |name| { + var found = false; + for (decls.items) |d| { + if (d.kind == .fn_decl and d.exported and eql(d.name, name.*)) { + found = true; + break; + } + } + if (!found) try report.add(alloc, "E-DANGLING-CONTRACT", 0, name.*); + } + return report; +} + +// ───────────────────────────────────────────────────────────────────────────── +// extract — Face B +// ───────────────────────────────────────────────────────────────────────────── + +fn Bucket(comptime T: type) type { + return std.ArrayListUnmanaged(T){}; +} + +pub const ExtractOptions = struct { + /// Selects the declaration whose contract is emitted. Empty = the only one. + symbol: []const u8 = "", + /// Used when the contract carries no `@contract` directive. + default_name: []const u8 = "", +}; + +pub fn extract(alloc: Allocator, src: []const u8, opts: ExtractOptions) ![]u8 { + std.debug.assert(opts.default_name.len > 0 or opts.symbol.len > 0); + const srcz = try alloc.dupeZ(u8, src); + defer alloc.free(srcz); + var ast = try Ast.parse(alloc, srcz, .zig); + defer ast.deinit(alloc); + if (ast.errors.len != 0) return error.ParseError; + + var dummy = Report{}; + defer dummy.deinit(alloc); + var decls = try collectDecls(alloc, ast, &dummy); + defer decls.deinit(alloc); + + var header = std.ArrayListUnmanaged(u8){}; + defer header.deinit(alloc); + var params = std.ArrayListUnmanaged(u8){}; + defer params.deinit(alloc); + var borrows = std.ArrayListUnmanaged(u8){}; + defer borrows.deinit(alloc); + var requires = std.ArrayListUnmanaged(u8){}; + defer requires.deinit(alloc); + var ensures = std.ArrayListUnmanaged(u8){}; + defer ensures.deinit(alloc); + var asserts = std.ArrayListUnmanaged(u8){}; + defer asserts.deinit(alloc); + var assigns = std.ArrayListUnmanaged(u8){}; + defer assigns.deinit(alloc); + var caps = std.ArrayListUnmanaged(u8){}; + defer caps.deinit(alloc); + var bounds = std.ArrayListUnmanaged(u8){}; + defer bounds.deinit(alloc); + + var contract_name = std.ArrayListUnmanaged(u8){}; + defer contract_name.deinit(alloc); + var kind = std.ArrayListUnmanaged(u8){}; + defer kind.deinit(alloc); + var abisym = std.ArrayListUnmanaged(u8){}; + defer abisym.deinit(alloc); + + var matched = false; + + for (decls.items) |d| { + if (d.doc_first == no_doc) continue; + if (opts.symbol.len > 0 and !eql(d.name, opts.symbol)) continue; + + // Does this declaration carry a contract at all? + var has = false; + var t = d.doc_first; + while (t < d.doc_end) : (t += 1) { + const body = directiveBody(Ast.tokenSlice(ast, t)) orelse continue; + if (eql(parseDirective(body).key, "contract")) has = true; + } + if (!has) continue; + if (matched) return error.MultipleContracts; + matched = true; + + t = d.doc_first; + while (t < d.doc_end) : (t += 1) { + const body = directiveBody(Ast.tokenSlice(ast, t)) orelse continue; + const kv = parseDirective(body); + if (eql(kv.key, "contract")) { + try squashInto(&contract_name, alloc, kv.value); + } else if (eql(kv.key, "kind")) { + try squashInto(&kind, alloc, kv.value); + } else if (eql(kv.key, "param")) { + try emits(¶ms, alloc, "param ", kv.value); + } else if (eql(kv.key, "borrow")) { + try emits(&borrows, alloc, "borrow ", kv.value); + } else if (eql(kv.key, "requires")) { + try emits(&requires, alloc, "requires ", kv.value); + } else if (eql(kv.key, "ensures")) { + try emits(&ensures, alloc, "ensures ", kv.value); + } else if (eql(kv.key, "assert")) { + try emits(&asserts, alloc, "assert ", kv.value); + } else if (eql(kv.key, "assigns")) { + try emits(&assigns, alloc, "assigns ", kv.value); + } else if (eql(kv.key, "cap")) { + try emits(&caps, alloc, "cap ", kv.value); + } else if (eql(kv.key, "bound")) { + try emits(&bounds, alloc, "bound ", kv.value); + } else if (eql(kv.key, "abi")) { + // `@abi callconv(.c)` is documentation; the compiler already + // enforces it, and `scanCallconv` rejects `.C`. + } else if (eql(kv.key, "decreases") or eql(kv.key, "invariant") or + eql(kv.key, "linear") or eql(kv.key, "frame")) + { + // Notes for humans; not part of the canonical contract. + } else if (kv.key.len > 0) { + return error.UnknownDirective; + } + } + } + + if (!matched) return error.NoContract; + + var out = std.ArrayListUnmanaged(u8){}; + errdefer out.deinit(alloc); + var w = out.writer(alloc); + + try w.writeAll("cspec 1\n"); + try w.writeAll("contract "); + if (contract_name.items.len > 0) { + try w.writeAll(contract_name.items); + } else { + try w.writeAll(opts.default_name); + } + try w.writeAll("\nkind "); + if (kind.items.len > 0) try w.writeAll(kind.items) else try w.writeAll("extern"); + try w.writeAll("\nabisym "); + if (abisym.items.len > 0) try w.writeAll(abisym.items) else { + // The declaration name is the ABI symbol for an `export fn`. + for (decls.items) |d| { + if (d.doc_first != no_doc and eql(d.name, opts.symbol)) { + try w.writeAll(d.name); + break; + } + if (opts.symbol.len == 0 and d.kind == .fn_decl and d.exported) { + try w.writeAll(d.name); + break; + } + } + } + try w.writeAll("\n"); + try out.appendSlice(alloc, params.items); + try out.appendSlice(alloc, borrows.items); + try out.appendSlice(alloc, requires.items); + try out.appendSlice(alloc, ensures.items); + try out.appendSlice(alloc, asserts.items); + try out.appendSlice(alloc, assigns.items); + try out.appendSlice(alloc, caps.items); + try out.appendSlice(alloc, bounds.items); + return out.toOwnedSlice(alloc); +} + +fn emits(bucket: *std.ArrayListUnmanaged(u8), alloc: Allocator, prefix: []const u8, value: []const u8) !void { + try bucket.appendSlice(alloc, prefix); + try squashInto(bucket, alloc, value); + try bucket.append(alloc, '\n'); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Tests +// ───────────────────────────────────────────────────────────────────────────── + +const testing = std.testing; + +const sample = + \\/// @contract demo.f + \\/// @kind extern + \\/// @param h W handle + \\/// //! @requires ( <= 12 ( len input ) ) + \\/// @ensures ( = ( magic out ) 0x5441 ) + \\/// @cap Write r1 + \\/// @cap Read r0 + \\/// @bound steps ( + 12 ( * 8 input_len ) ) + \\export fn demo_f(h: ?*const Handle, out: ?*FrameOut) callconv(.c) Result { + \\ return .ok; + \\} +; + +test "directive bodies accept both spellings" { + try testing.expectEqualStrings("requires x", directiveBody("/// //! @requires x").?); + try testing.expectEqualStrings("requires x", directiveBody("/// @requires x").?); + try testing.expect(directiveBody("/// just prose") == null); + try testing.expect(directiveBody("const x = 1;") == null); +} + +test "extract produces the canonical contract" { + const a = std.heap.page_allocator; + const out = try extract(a, sample, .{ .symbol = "demo_f" }); + defer a.free(out); + try testing.expectEqualStrings( + \\cspec 1 + \\contract demo.f + \\kind extern + \\abisym demo_f + \\param h W handle + \\requires ( <= 12 ( len input ) ) + \\ensures ( = ( magic out ) 0x5441 ) + \\cap Write r1 + \\cap Read r0 + \\bound steps ( + 12 ( * 8 input_len ) ) + \\ + , out); +} + +test "check rejects a banned construct" { + const a = std.heap.page_allocator; + var r = try check(a, "fn f(p: [*c]u8) void { _ = p; }\n", .{ .require_contracts = false }); + defer r.deinit(a); + try testing.expectEqual(@as(usize, 1), r.diags.items.len); + try testing.expectEqualStrings("E-PTR-C", r.diags.items[0].code); +} + +test "check rejects an uncontracted export and a dangling contract" { + const a = std.heap.page_allocator; + var r = try check(a, "export fn lonely() callconv(.c) void {}\n", .{}); + defer r.deinit(a); + try testing.expectEqualStrings("E-UNCONTRACTED-EXPORT", r.diags.items[0].code); + + var r2 = try check(a, sample, .{}); + defer r2.deinit(a); + try testing.expectEqual(@as(usize, 0), r2.diags.items.len); +} + +test "check rejects .C spelling and missing callconv" { + const a = std.heap.page_allocator; + var r = try check(a, "export fn f() callconv(.C) void {}\n", .{ .require_contracts = false }); + defer r.deinit(a); + try testing.expectEqualStrings("E-ABI-CALLCONV", r.diags.items[0].code); + + var r2 = try check(a, "export fn f() void {}\n", .{ .require_contracts = false }); + defer r2.deinit(a); + try testing.expectEqualStrings("E-ABI-NO-CALLCONV", r2.diags.items[0].code); +} + +test "check rejects usize inside an extern struct" { + const a = std.heap.page_allocator; + var r = try check(a, "pub const S = extern struct { n: usize };\n", .{ .require_contracts = false }); + defer r.deinit(a); + try testing.expectEqualStrings("E-ABI-WIDTH", r.diags.items[0].code); +} diff --git a/tools/atoma/src/main.zig b/tools/atoma/src/main.zig new file mode 100644 index 00000000..9f3e9b4e --- /dev/null +++ b/tools/atoma/src/main.zig @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// atoma — content addressing and canonicalisation for Atoma. +// +// This is a convenience tool, NOT part of the trusted computing base. The +// authoritative encoder is `encode` in src/atoma/spec/CoreSpec.idr. +// +// Usage: +// atoma canon print the canonical bytes +// atoma hash print blake3: of the spec +// atoma dk-hash print blake3: of a witness +// atoma src-hash print blake3: of proof source +// atoma equiv exit 0 iff the faces agree +// atoma mutate print one mutated specification +// atoma extract [--symbol S] emit the Face B contract (.cspec) +// atoma check subset conformance, exit 1 on E-* +// atoma ops list mutation operators +// atoma selftest run the built-in vectors +// +// Exit codes: 0 success/agree, 1 disagreement or verification failure, +// 2 usage error, 3 I/O or parse error. + +const std = @import("std"); +const canon = @import("canon.zig"); +const frontend = @import("frontend.zig"); + +const gpa = std.heap.page_allocator; + +fn readFile(path: []const u8) ![]u8 { + return std.fs.cwd().readFileAlloc(gpa, path, 16 << 20); +} + +fn writeFile(path: []const u8, bytes: []const u8) !void { + const f = try std.fs.cwd().createFile(path, .{}); + defer f.close(); + try f.writeAll(bytes); +} + +/// Results go to stdout; diagnostics go to stderr. Both are best-effort: a +/// closed pipe is not an error worth a panic in a build tool. +fn say(bytes: []const u8) void { + std.fs.File.stdout().writeAll(bytes) catch {}; +} + +fn sayLine(bytes: []const u8) void { + say(bytes); + say("\n"); +} + +fn print(comptime fmt: []const u8, args: anytype) void { + var buf: [4096]u8 = undefined; + const s = std.fmt.bufPrint(&buf, fmt, args) catch return; + say(s); +} + +fn usage() noreturn { + sayLine("usage: atoma [args]"); + std.process.exit(2); +} + +pub fn main() !void { + // PINNED to Zig 0.15.2: `std.process.argsAlloc` exists there and was removed + // by 0.16/0.17 (args become a value passed to main). See §5.2 of the spec: + // this one line is the whole 0.15 -> 0.16 port, and it is exactly the kind of + // churn the hybrid frontend is designed to absorb. + const args = try std.process.argsAlloc(gpa); + defer std.process.argsFree(gpa, args); + if (args.len < 2) usage(); + const cmd = args[1]; + + if (std.mem.eql(u8, cmd, "canon")) { + if (args.len != 3) usage(); + const src = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const c = canon.canon(gpa, src) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + say(c.bytes); + } else if (std.mem.eql(u8, cmd, "hash")) { + if (args.len != 3) usage(); + const src = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const c = canon.canon(gpa, src) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const hx = c.hex(); + print("blake3:{s}\n", .{hx}); + } else if (std.mem.eql(u8, cmd, "dk-hash")) { + if (args.len != 3) usage(); + const bytes = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const hx = canon.digestHex(canon.domain_dk, bytes); + print("blake3:{s}\n", .{hx}); + } else if (std.mem.eql(u8, cmd, "src-hash")) { + if (args.len != 3) usage(); + const bytes = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const hx = canon.digestHex(canon.domain_src, bytes); + print("blake3:{s}\n", .{hx}); + } else if (std.mem.eql(u8, cmd, "vc-hash")) { + if (args.len != 3) usage(); + const bytes = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const hx = canon.digestHex(canon.domain_vc, bytes); + print("blake3:{s}\n", .{hx}); + } else if (std.mem.eql(u8, cmd, "equiv")) { + if (args.len != 4) usage(); + const a_src = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const b_src = readFile(args[3]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const a = canon.canon(gpa, a_src) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const b = canon.canon(gpa, b_src) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const ah = a.hex(); + const bh = b.hex(); + if (std.mem.eql(u8, &ah, &bh)) { + print("EQUIVALENT blake3:{s}\n", .{ah}); + } else { + print("DIVERGENT\n face-a blake3:{s}\n face-b blake3:{s}\n", .{ ah, bh }); + std.process.exit(1); + } + } else if (std.mem.eql(u8, cmd, "mutate")) { + if (args.len != 4) usage(); + const src = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + const m = std.meta.stringToEnum(canon.Mutation, args[3]) orelse { + sayLine("unknown mutation operator; try `atoma ops`"); + std.process.exit(2); + }; + const out = canon.applyMutation(gpa, src, m) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + if (out) |bytes| { + say(bytes); + } else { + print("NOT-APPLICABLE {s}\n", .{m.name()}); + std.process.exit(1); + } + } else if (std.mem.eql(u8, cmd, "extract")) { + if (args.len < 3) usage(); + const src = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + var symbol: []const u8 = ""; + var i: usize = 3; + while (i + 1 < args.len) : (i += 2) { + if (std.mem.eql(u8, args[i], "--symbol")) symbol = args[i + 1]; + } + const base = std.fs.path.stem(args[2]); + const out = frontend.extract(gpa, src, .{ .symbol = symbol, .default_name = base }) catch |e| { + print("extract failed: {s}\n", .{@errorName(e)}); + std.process.exit(1); + }; + say(out); + } else if (std.mem.eql(u8, cmd, "check")) { + if (args.len < 3) usage(); + const src = readFile(args[2]) catch |e| { + sayLine(@errorName(e)); + std.process.exit(3); + }; + var rep = frontend.check(gpa, src, .{}) catch |e| { + print("check failed: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + defer rep.deinit(gpa); + for (rep.diags.items) |d| { + print("{s}:{d}: {s}: {s}\n", .{ args[2], d.line, d.code, d.detail }); + } + print("{s}: {d} declarations, {d} exports, {d} contracts, {d} diagnostics\n", .{ + args[2], rep.decls, rep.exports, rep.contracts, rep.diags.items.len, + }); + if (rep.diags.items.len != 0) std.process.exit(1); + } else if (std.mem.eql(u8, cmd, "ops")) { + for (canon.Mutation.all()) |m| print("{s}\n", .{m.name()}); + } else if (std.mem.eql(u8, cmd, "selftest")) { + // Two syntactically different faces of the same contract must collide; + // a one-token difference must not. + const face_a = + \\# Face A: extracted from Idris2 (ghost params elided) + \\cspec 1 + \\contract demo.frame.parse + \\kind extern + \\param h 1 handle + \\param in 0 slice ro u8 r0 + \\param out 1 ptr out_frame r1 + \\requires ( <= ( len in ) 65535 ) + \\ensures ( <= ( + ( len in ) 0 ) 65535 ) + \\cap Alloc + \\ + ; + const face_b = + \\# Face B: inline Zig contract, written by a different author + \\cspec 1 + \\contract demo.frame.parse + \\kind extern + \\param h 1 handle + \\param in 0 slice ro u8 r0 + \\param out 1 ptr out_frame r1 + \\requires ( <= ( len in ) 0xffff ) + \\ensures ( <= ( + ( len in ) 000 ) 65535 ) + \\cap Alloc + \\ + ; + const a = try canon.canon(gpa, face_a); + const b = try canon.canon(gpa, face_b); + const ah = a.hex(); + const bh = b.hex(); + if (!std.mem.eql(u8, &ah, &bh)) { + print("selftest FAIL (faces should agree)\n a=blake3:{s}\n b=blake3:{s}\n", .{ ah, bh }); + std.process.exit(1); + } + const broken = try canon.canon(gpa, face_b ++ "requires ( < ( len in ) 65535 )\n"); + const ch = broken.hex(); + if (std.mem.eql(u8, &ah, &ch)) { + sayLine("selftest FAIL (weakened face did not diverge)"); + std.process.exit(1); + } + print("selftest OK\n agreement blake3:{s}\n divergence blake3:{s}\n", .{ ah, ch }); + } else { + usage(); + } +} + +test { + _ = canon; +} diff --git a/verification/atoma/agda/Bv.agda b/verification/atoma/agda/Bv.agda new file mode 100644 index 00000000..d43aef8a --- /dev/null +++ b/verification/atoma/agda/Bv.agda @@ -0,0 +1,146 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +-- +-- Bv.agda — machine words and the bitvector/integer bridge (spec §4.3.1). +-- +-- Written against Agda's builtins only, with all arithmetic defined here, so +-- the development stays inside the Dedukti-CIC subset: indexed inductives and +-- structural recursion, no cubical primitives, no rewrite rules, no +-- inductive-recursive definitions, no axioms, no holes. +-- +-- agda --safe --without-K Bv.agda +-- +-- The point: SMT solvers reason about *mathematical* integers, Zig computes on +-- *machine words*. Every confusion between the two is a soundness hole. The +-- bridge is made explicit: +-- +-- Word = Fin 2^64 (a number *together with* its bound) +-- toNat = the underlying number +-- fromNat x p = the word, requiring the range proof p +-- toNat-< = every word is in range (no wraparound exists) +-- fromNat-toNat = the coercion is a section (no silent wrap) +-- no-bound = 2^64 is *not* a word (the obligation is real) +-- +-- `fromNat-toNat` is the licence to read a `bv2nat` coercion as an integer: +-- on the image of `fromNat` the coercion loses nothing. Outside that image +-- there is no proof to supply, which is exactly the `@intCast` range obligation +-- that the SMT side must discharge. + +module Bv where + +open import Agda.Builtin.Nat using (Nat; zero; suc; _*_) +open import Agda.Builtin.Equality using (_≡_; refl) + +cong : ∀ {A B : Set} (f : A → B) {x y : A} → x ≡ y → f x ≡ f y +cong f refl = refl +open import Agda.Builtin.Bool using (Bool; true; false) + +-------------------------------------------------------------------------------- +-- Order, defined here rather than imported +-------------------------------------------------------------------------------- + +infix 4 _≤_ _<_ + +data _≤_ : Nat → Nat → Set where + z≤n : ∀ {n} → zero ≤ n + s≤s : ∀ {m n} → m ≤ n → suc m ≤ suc n + +_<_ : Nat → Nat → Set +m < n = suc m ≤ n + +≤-refl : ∀ {n} → n ≤ n +≤-refl {zero} = z≤n +≤-refl {suc n} = s≤s ≤-refl + +≤-trans : ∀ {a b c} → a ≤ b → b ≤ c → a ≤ c +≤-trans z≤n _ = z≤n +≤-trans (s≤s p) (s≤s q) = s≤s (≤-trans p q) + +<-trans : ∀ {a b c} → a < b → b ≤ c → a < c +<-trans p q = ≤-trans p q + +-------------------------------------------------------------------------------- +-- The empty type and negation: the shape of every refuted obligation +-------------------------------------------------------------------------------- + +data ⊥ : Set where + +¬_ : Set → Set +¬ P = P → ⊥ + +-------------------------------------------------------------------------------- +-- Fin: the word type +-------------------------------------------------------------------------------- + +data Fin : Nat → Set where + fzero : ∀ {n} → Fin (suc n) + fsuc : ∀ {n} → Fin n → Fin (suc n) + +toNat : ∀ {n} → Fin n → Nat +toNat fzero = zero +toNat (fsuc i) = suc (toNat i) + +-- `fromNat n x p` builds a Fin n from x and a proof that x fits. +fromNat : ∀ {n} → (x : Nat) → x < n → Fin n +fromNat {suc n} zero (s≤s z≤n) = fzero +fromNat {suc n} (suc x) (s≤s p) = fsuc (fromNat x p) + +-------------------------------------------------------------------------------- +-- Round-trip lemmas: the bridge is a section, not a retraction +-------------------------------------------------------------------------------- + +toNat-< : ∀ {n} (w : Fin n) → toNat w < n +toNat-< fzero = s≤s z≤n +toNat-< (fsuc w) = s≤s (toNat-< w) + +fromNat-toNat : ∀ {n} (w : Fin n) → (p : toNat w < n) → fromNat (toNat w) p ≡ w +fromNat-toNat fzero (s≤s z≤n) = refl +fromNat-toNat (fsuc w) (s≤s p) = cong fsuc (fromNat-toNat w p) + +toNat-fromNat : ∀ {n} (x : Nat) (p : x < n) → toNat (fromNat x p) ≡ x +toNat-fromNat zero (s≤s z≤n) = refl +toNat-fromNat (suc x) (s≤s p) = cong suc (toNat-fromNat x p) + +-------------------------------------------------------------------------------- +-- Word = 64-bit machine integer +-------------------------------------------------------------------------------- + +2^_ : Nat → Nat +2^ zero = suc zero +2^ suc k = 2 * (2^ k) + +2^64 : Nat +2^64 = 2^ 64 + +Word : Set +Word = Fin 2^64 + +Bound : Nat → Set +Bound x = x < 2^64 + +word : (x : Nat) → Bound x → Word +word x p = fromNat x p + +unword : Word → Nat +unword = toNat + +-- Every word is an in-range number: there is no "wrapped" word to worry about. +word-bound : (w : Word) → Bound (unword w) +word-bound = toNat-< + +-- The coercion `Nat → Word` is injective on its domain of definition. This is +-- the theorem that licenses reading the bitvector as an integer *after* the +-- range obligation has been discharged, and only then. +word-inj : (x : Nat) (p : Bound x) → unword (word x p) ≡ x +word-inj = toNat-fromNat + +-------------------------------------------------------------------------------- +-- The obligation is real: 2^64 is not a word +-------------------------------------------------------------------------------- + + +-- +-- Core.agda — the core language, its semantics, and the VC generator. +-- +-- agda --safe --without-K Core.agda +-- +-- This is the language the verification-condition generator targets, small +-- enough that "soundness" is a theorem and not a gesture. It is deliberately +-- *not* all of Zig: it is the fragment whose obligations are first-order and +-- whose evaluation is structural. +-- +-- What is modelled +-- * statements: skip, bind (evaluate an expression), seq, assert, if/else +-- * expressions: literals, variables, +, *, subtraction and division +-- * undefined behaviour: subtraction underflow and division by zero are the +-- two reachable UB states in this fragment (§6.2 of the specification) +-- * the path condition: an `assert` and the test of an `if` both refine it, +-- which is exactly how `if (length > avail) return error` protects the +-- slice on the following line +-- +-- The fragment is STORE-FREE, by construction. `bind e` evaluates `e` and +-- discards the result; no expression can read a value that a statement wrote, +-- because `Tm` has no constructor for it. That is not an accident of the +-- encoding, it is the discipline the seam already imposes: path conditions are +-- stated over parameters (`r0`), writes go to an output region (`r1`), and the +-- two are disjoint by the `assigns` clause. Modelling a store would require the +-- framing lemma ("a statement that writes nothing mentioned by `pc` preserves +-- `pc`"), which is Phase 2 work; stating it without proving it would be worse +-- than leaving it out. +-- +-- What is NOT modelled, and why the theorem is still worth having +-- * machine words. `+`, `*` here are mathematical naturals. The bitvector +-- gap is closed separately: `Bv.agda` proves the coercion bridge, and the +-- VC generator emits an explicit range obligation for every lowering. +-- Mixing the two models in one file would hide the gap rather than show it. +-- * loops. A `while` needs an invariant and a variant, i.e. a second +-- induction; that is `Lin.agda`'s shape for resources and is Phase 2 here. +-- * the heap, pointers, and aliasing. `assign` writes a scalar. +-- +-- A VC generator that is sound for a fragment it does not cover is worthless, +-- so the fragment boundary is stated in the type of every theorem below. + +module Core where + +open import Agda.Builtin.Nat using (Nat; zero; suc; _+_; _*_) +open import Agda.Builtin.Bool using (Bool; true; false) +open import Agda.Builtin.List using (List; []; _∷_) +open import Agda.Builtin.Equality using (_≡_; refl) +open import Agda.Builtin.Unit using (⊤; tt) + +-------------------------------------------------------------------------------- +-- Pairs (defined here so the development needs no library) +-------------------------------------------------------------------------------- + +infixr 2 _×_ + +record _×_ (A B : Set) : Set where + constructor _,_ + field + fst : A + snd : B + +-------------------------------------------------------------------------------- +-- Truncated subtraction and list append, defined here (the builtins do not +-- export them, and importing the full standard library would pull in far more +-- than this development needs). +-------------------------------------------------------------------------------- + +_∸_ : Nat → Nat → Nat +zero ∸ n = zero +suc m ∸ zero = suc m +suc m ∸ suc n = m ∸ n + +_++_ : ∀ {A : Set} → List A → List A → List A +[] ++ ys = ys +(x ∷ xs) ++ ys = x ∷ (xs ++ ys) + +-- Boolean connectives, defined here so `⟦_⟧f` is definitionally the operation +-- on `Bool` (which makes the adequacy lemmas cheap). +_&&_ : Bool → Bool → Bool +true && b = b +false && _ = false + +_||_ : Bool → Bool → Bool +true || _ = true +false || b = b + +not : Bool → Bool +not true = false +not false = true + +infixr 6 _&&_ +infixr 5 _||_ + +-------------------------------------------------------------------------------- +-- Terms +-------------------------------------------------------------------------------- + +data Tm : Set where + lit : Nat → Tm + var : Nat → Tm + add : Tm → Tm → Tm + mul : Tm → Tm → Tm + sub : Tm → Tm → Tm -- UB when the subtrahend exceeds the minuend + div : Tm → Tm → Tm -- UB when the divisor is zero + +Val : Set +Val = Nat → Nat + +_≤?_ : Nat → Nat → Bool +zero ≤? n = true +suc m ≤? zero = false +suc m ≤? suc n = m ≤? n + +_==?_ : Nat → Nat → Bool +zero ==? zero = true +zero ==? suc n = false +suc m ==? zero = false +suc m ==? suc n = m ==? n + +⟦_⟧t : Tm → Val → Nat +⟦ lit n ⟧t _ = n +⟦ var x ⟧t v = v x +⟦ add a b ⟧t v = ⟦ a ⟧t v + ⟦ b ⟧t v +⟦ mul a b ⟧t v = ⟦ a ⟧t v * ⟦ b ⟧t v +⟦ sub a b ⟧t v = ⟦ a ⟧t v ∸ ⟦ b ⟧t v +⟦ div a b ⟧t v = ⟦ a ⟧t v -- the value is irrelevant when it is UB + +-------------------------------------------------------------------------------- +-- Formulas +-- +-- `le`, `eq` are the only atoms the VC generator emits; `and`/`neg` appear in +-- path conditions produced by `if`. The interpretation is *definitionally* the +-- boolean operation, which is what makes the adequacy lemmas cheap. +-------------------------------------------------------------------------------- + +data Fm : Set where + tt : Fm + le : Tm → Tm → Fm + eq : Tm → Tm → Fm + and : Fm → Fm → Fm + neg : Fm → Fm + +⟦_⟧f : Fm → Val → Bool +⟦ tt ⟧f _ = true +⟦ le a b ⟧f v = ⟦ a ⟧t v ≤? ⟦ b ⟧t v +⟦ eq a b ⟧f v = ⟦ a ⟧t v ==? ⟦ b ⟧t v +⟦ and a b ⟧f v = ⟦ a ⟧f v && ⟦ b ⟧f v +⟦ neg a ⟧f v = not (⟦ a ⟧f v) + +-------------------------------------------------------------------------------- +-- Statements and their execution +-- +-- `exec` is total and never inspects its own safety: it computes the answer the +-- program would compute, including in states where the program would actually +-- be undefined. Safety is a *separate* predicate (`safe`), and the theorem +-- relates the two. This separation is the whole point: it is what lets a +-- compensating bug in `exec` be caught rather than hidden. +-------------------------------------------------------------------------------- + +data Stmt : Set where + skip : Stmt + bind : Tm → Stmt -- evaluate; the result is discarded + seq : Stmt → Stmt → Stmt + assert : Fm → Stmt + ite : Fm → Stmt → Stmt → Stmt + +ifB : ∀ {A : Set} → Bool → A → A → A +ifB true a b = a +ifB false a b = b + +exec : Stmt → Val → Val +exec skip v = v +exec (bind e) v = v -- store-free: the value is not retained +exec (seq s t) v = exec t (exec s v) +exec (assert φ) v = v +exec (ite φ s t) v = ifB (⟦ φ ⟧f v) (exec s v) (exec t v) + +-------------------------------------------------------------------------------- +-- Safety: the predicate that must never be false +-------------------------------------------------------------------------------- + +safeTm : Tm → Val → Bool +safeTm (lit n) v = true +safeTm (var x) v = true +safeTm (add a b) v = safeTm a v && safeTm b v +safeTm (mul a b) v = safeTm a v && safeTm b v +safeTm (sub a b) v = safeTm a v && safeTm b v && (⟦ b ⟧t v ≤? ⟦ a ⟧t v) +safeTm (div a b) v = safeTm a v && safeTm b v && not (⟦ b ⟧t v ==? zero) + +safe : Stmt → Val → Bool +safe skip _ = true +safe (bind e) v = safeTm e v +safe (seq s t) v = safe s v && safe t (exec s v) +safe (assert φ) v = ⟦ φ ⟧f v +safe (ite φ s t) v = ifB (⟦ φ ⟧f v) (safe s v) (safe t v) + +-------------------------------------------------------------------------------- +-- Obligations and validity +-- +-- An obligation is a Horn clause (premise, goal). Validity is *universal*: an +-- obligation is valid when it holds in every state satisfying its premise. +-- That is precisely what an SMT solver returns for `∀ vars. pre ⇒ goal`, and +-- it is what makes the frame problem disappear: a valid obligation stays valid +-- after any assignment. +-------------------------------------------------------------------------------- + +record Obl : Set where + constructor mkObl + field + pre : Fm + goal : Fm + +OblValid : Obl → Set +OblValid o = ∀ v → ⟦ Obl.pre o ⟧f v ≡ true → ⟦ Obl.goal o ⟧f v ≡ true + +AllValid : List Obl → Set +AllValid [] = ⊤ +AllValid (o ∷ os) = OblValid o × AllValid os + +-------------------------------------------------------------------------------- +-- The VC generator +-- +-- `tmObls pc e` emits one obligation per *observable* hazard in `e`, each +-- guarded by the current path condition. The obligation is placed first so the +-- adequacy proof can consume it before recursing. +-------------------------------------------------------------------------------- + +tmObls : Fm → Tm → List Obl +tmObls pc (lit n) = [] +tmObls pc (var x) = [] +tmObls pc (add a b) = tmObls pc a ++ tmObls pc b +tmObls pc (mul a b) = tmObls pc a ++ tmObls pc b +tmObls pc (sub a b) = mkObl pc (le b a) ∷ (tmObls pc a ++ tmObls pc b) +tmObls pc (div a b) = mkObl pc (neg (eq b (lit zero))) ∷ (tmObls pc a ++ tmObls pc b) + +vc : Fm → Stmt → List Obl +vc pc skip = [] +vc pc (bind e) = tmObls pc e +vc pc (seq s t) = vc pc s ++ vc pc t +vc pc (assert φ) = mkObl pc φ ∷ [] +vc pc (ite φ s t) = vc (and pc φ) s ++ vc (and pc (neg φ)) t + +-------------------------------------------------------------------------------- +-- Sanity: the generator is not vacuous on the worked example's boundary. +-- `12 ≤ len` is the guard that protects `len - 12`; with it, one obligation is +-- emitted, and without it the generator still emits one (whose premise is +-- `tt`), which the solver will refute. Vacuity is a property of the premise, +-- not of whether an obligation exists — which is why the specification makes +-- satisfiability of the premises a VC of its own. +-------------------------------------------------------------------------------- + +example-guarded : List Obl +example-guarded = vc (le (lit 12) (var 0)) (bind (sub (var 0) (lit 12))) + +example-unguarded : List Obl +example-unguarded = vc tt (bind (sub (var 0) (lit 12))) diff --git a/verification/atoma/agda/Lin.agda b/verification/atoma/agda/Lin.agda new file mode 100644 index 00000000..cf753c13 --- /dev/null +++ b/verification/atoma/agda/Lin.agda @@ -0,0 +1,158 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +-- +-- Lin.agda — linear-handle cleanup for `defer` / `errdefer` (spec §4.4). +-- +-- agda --safe --without-K Lin.agda +-- +-- Obligation: a QTT-`1` handle acquired at the top of an `export fn` is +-- consumed exactly once on *every* path — the normal path and every early +-- `return error` path taken by a `try` inside the body. +-- +-- Zig gives two handlers with different reachability: +-- +-- defer runs on every exit of the enclosing scope +-- errdefer runs only when the scope is left by an error return +-- +-- so the canonical shape +-- +-- const h = try open(); -- acquire, quantity 1 +-- errdefer close(h); -- handler, registered after acquisition +-- try step1(); -- may fail +-- try step2(); -- may fail +-- close(h); -- explicit consumption on the happy path +-- +-- has one textual `close` on the happy path and none on the failure paths, yet +-- must run `close` exactly once on all of them. That is `exactly-once` below, +-- abstract over the number and kind of intermediate steps. +-- +-- Failure is sticky: once a step fails, the rest of the scope is skipped (what +-- `try` + early return do) and the `errdefer` handler is the only thing that +-- runs at scope exit. Both halves are part of the model; §6.3 records what the +-- model does and does not cover. + +module Lin where + +open import Agda.Builtin.Nat using (Nat; zero; suc) +open import Agda.Builtin.Bool using (Bool; true; false) +open import Agda.Builtin.List using (List; []; _∷_) +open import Agda.Builtin.Equality using (_≡_; refl) + +-------------------------------------------------------------------------------- +-- Small helpers +-------------------------------------------------------------------------------- + +cong : ∀ {A B : Set} (f : A → B) {x y : A} → x ≡ y → f x ≡ f y +cong f refl = refl + +sym : ∀ {A : Set} {x y : A} → x ≡ y → y ≡ x +sym refl = refl + +data ⊥ : Set where + +⊥-elim : ∀ {A : Set} → ⊥ → A +⊥-elim () + +true≢false : true ≡ false → ⊥ +true≢false () + +ite : ∀ {A : Set} → Bool → A → A → A +ite true t f = t +ite false t f = f + +-------------------------------------------------------------------------------- +-- State +-------------------------------------------------------------------------------- + +record St : Set where + constructor mkSt + field rels : Nat -- how many times the handle has been released + field failed : Bool -- whether the scope has already left by an error + +open St + +initial : St +initial = mkSt zero false + +-------------------------------------------------------------------------------- +-- The scope: a sequence of steps, each harmless or failing. The happy-path +-- `close` is *structure*, not a step, so no user step can release behind the +-- verifier's back. +-------------------------------------------------------------------------------- + +data Step : Set where + work : Step + fails : Step + +applyStep : St → Step → St +applyStep s work = s +applyStep s fails = record s { failed = true } + +-- Running the scope. `[]` is the point where the happy-path `close` sits: +-- reaching it means the scope did not fail, so the close runs exactly there. +runBody : St → List Step → St +runBody s [] = ite (failed s) s (record s { rels = suc (rels s) }) +runBody s (x ∷ xs) = ite (failed s) s (runBody (applyStep s x) xs) + +-- The errdefer handler: runs iff the scope failed, and it releases. +handler : St → St +handler s = ite (failed s) (record s { rels = suc (rels s) ; failed = false }) s + +whole : List Step → St +whole steps = handler (runBody initial steps) + +-------------------------------------------------------------------------------- +-- Lemmas +-------------------------------------------------------------------------------- + +applyStep-rels : ∀ (s : St) (x : Step) → rels (applyStep s x) ≡ rels s +applyStep-rels s work = refl +applyStep-rels s fails = refl + +-- A scope that has already failed runs nothing else. +runBody-dead : ∀ (xs : List Step) (s : St) → failed s ≡ true → runBody s xs ≡ s +runBody-dead [] s q with failed s +... | true = refl +... | false = ⊥-elim (true≢false (sym q)) +runBody-dead (x ∷ xs) s q with failed s +... | true = refl +... | false = ⊥-elim (true≢false (sym q)) + +-------------------------------------------------------------------------------- +-- Exactly one release on every path. +-- +-- Generalised over the starting state so the induction hypothesis applies +-- mid-body; `failed s ≡ false` is the invariant that the scope is still live. +-------------------------------------------------------------------------------- + +exactly-once : + ∀ (steps : List Step) (s : St) → + failed s ≡ false → + rels (handler (runBody s steps)) ≡ suc (rels s) + +exactly-once [] s p + rewrite p = refl + +exactly-once (work ∷ xs) s p + rewrite p = exactly-once xs s p + +exactly-once (fails ∷ xs) s p + rewrite p = + cong (λ t → rels (handler t)) (runBody-dead xs (record s { failed = true }) refl) + +-------------------------------------------------------------------------------- +-- Headline: every execution of the canonical scope releases exactly once, +-- whether it succeeds, fails on the first step, or fails on any later step. +-------------------------------------------------------------------------------- + +theorem-rel-once : ∀ (steps : List Step) → rels (whole steps) ≡ suc zero +theorem-rel-once steps = exactly-once steps initial refl + +-- Two concrete traces, so the theorem is not vacuous: the empty scope (happy +-- path via the explicit close) and a scope that fails after one step (via the +-- handler). Both release exactly once. +trace-happy : rels (whole []) ≡ suc zero +trace-happy = refl + +trace-failed : rels (whole (work ∷ fails ∷ [])) ≡ suc zero +trace-failed = refl diff --git a/verification/atoma/agda/Soundness.agda b/verification/atoma/agda/Soundness.agda new file mode 100644 index 00000000..e3292299 --- /dev/null +++ b/verification/atoma/agda/Soundness.agda @@ -0,0 +1,228 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +-- +-- Soundness.agda — the adequacy theorem for the VC generator. +-- +-- agda --safe --without-K Soundness.agda +-- +-- THEOREM (soundness). If every obligation emitted by `vc pc s` is valid, and +-- the initial state satisfies the path condition `pc`, then executing `s` never +-- reaches an undefined state: `safe s v ≡ true`. +-- +-- This is the statement §6.4 of the specification makes. It is proved here for +-- the fragment of `Core.agda`: expression evaluation, sequencing, assertion, +-- if/else, and arithmetic that can underflow or divide by zero. It is NOT a +-- theorem about all of Zig, and the specification says so in the same breath. +-- +-- In particular the fragment is store-free (see `Core.agda`'s header): the +-- theorem covers every *hazard site*, not data flow between them. +-- +-- Why "all obligations valid" and not "obligations hold in this state": a +-- solver returns UNSAT for `premises ∧ ¬goal`, universally quantified over all +-- variables. That is exactly `OblValid`. State-independent validity is also +-- what makes sequencing sound — a valid obligation survives any assignment, +-- so no strongest-postcondition machinery is needed at this level. +-- +-- The two halves of the proof: +-- 1. `tm-safe`: hazards inside an expression are covered by `tmObls`. +-- 2. structural induction over statements, with the path condition refined +-- at `assert` and at each branch of `if`. + +module Soundness where + +open import Core +open import Agda.Builtin.Nat using (Nat; zero; suc) +open import Agda.Builtin.Bool using (Bool; true; false) +open import Agda.Builtin.List using (List; []; _∷_) +open import Agda.Builtin.Equality using (_≡_; refl) +open import Agda.Builtin.Unit using (⊤; tt) + +-------------------------------------------------------------------------------- +-- The empty type and basic equality plumbing +-------------------------------------------------------------------------------- + +data ⊥ : Set where + +¬_ : Set → Set +¬ P = P → ⊥ + +⊥-elim : ∀ {A : Set} → ⊥ → A +⊥-elim () + +cong : ∀ {A B : Set} (f : A → B) {x y : A} → x ≡ y → f x ≡ f y +cong f refl = refl + +sym : ∀ {A : Set} {x y : A} → x ≡ y → y ≡ x +sym refl = refl + +trans : ∀ {A : Set} {x y z : A} → x ≡ y → y ≡ z → x ≡ z +trans refl q = q + +true≢false : true ≡ false → ⊥ +true≢false () + +false≢true : false ≡ true → ⊥ +false≢true () + +not-involves : ∀ b → not (not b) ≡ b +not-involves true = refl +not-involves false = refl + +-------------------------------------------------------------------------------- +-- Boolean lemmas +-------------------------------------------------------------------------------- + +&&-elim-l : ∀ a b → (a && b) ≡ true → a ≡ true +&&-elim-l true b p = refl +&&-elim-l false b () + +&&-elim-r : ∀ a b → (a && b) ≡ true → b ≡ true +&&-elim-r true b p = p +&&-elim-r false b () + +&&-intro : ∀ a b → a ≡ true → b ≡ true → (a && b) ≡ true +&&-intro true b refl q = q +&&-intro false b () q + +-------------------------------------------------------------------------------- +-- The store-free fragment has a trivial state law: a statement never changes +-- the valuation. This is what lets a path condition be used at a later program +-- point — in a store-free fragment, "later" is the same state. +-------------------------------------------------------------------------------- + +exec-id : ∀ (s : Stmt) (v : Val) → exec s v ≡ v +exec-id skip v = refl +exec-id (bind e) v = refl +exec-id (seq s t) v = trans (exec-id t (exec s v)) (exec-id s v) +exec-id (assert φ) v = refl +exec-id (ite φ s t) v with ⟦ φ ⟧f v +... | true = exec-id s v +... | false = exec-id t v + +-------------------------------------------------------------------------------- +-- Validity of obligation lists +-------------------------------------------------------------------------------- + +valid-left : ∀ xs ys → AllValid (xs ++ ys) → AllValid xs +valid-left [] ys p = tt +valid-left (o ∷ os) ys (po , pr) = po , valid-left os ys pr + +valid-right : ∀ xs ys → AllValid (xs ++ ys) → AllValid ys +valid-right [] ys p = p +valid-right (o ∷ os) ys (po , pr) = valid-right os ys pr + +-------------------------------------------------------------------------------- +-- Part 1: expression safety +-- +-- Every hazard `tmObls` can see is discharged, so `safeTm` holds. +-------------------------------------------------------------------------------- + +tm-safe : ∀ (e : Tm) (pc : Fm) (v : Val) → + ⟦ pc ⟧f v ≡ true → + AllValid (tmObls pc e) → + safeTm e v ≡ true + +tm-safe (lit n) pc v pp pv = refl + +tm-safe (var x) pc v pp pv = refl + +tm-safe (add a b) pc v pp pv = + &&-intro (safeTm a v) (safeTm b v) + (tm-safe a pc v pp (valid-left (tmObls pc a) (tmObls pc b) pv)) + (tm-safe b pc v pp (valid-right (tmObls pc a) (tmObls pc b) pv)) + +tm-safe (mul a b) pc v pp pv = + &&-intro (safeTm a v) (safeTm b v) + (tm-safe a pc v pp (valid-left (tmObls pc a) (tmObls pc b) pv)) + (tm-safe b pc v pp (valid-right (tmObls pc a) (tmObls pc b) pv)) + +tm-safe (sub a b) pc v pp (po , pr) = + -- the obligation is `pc ⇒ b ≤ a`, placed first by `tmObls` + &&-intro (safeTm a v) (safeTm b v && (⟦ b ⟧t v ≤? ⟦ a ⟧t v)) + (tm-safe a pc v pp (valid-left (tmObls pc a) (tmObls pc b) pr)) + (&&-intro (safeTm b v) (⟦ b ⟧t v ≤? ⟦ a ⟧t v) + (tm-safe b pc v pp (valid-right (tmObls pc a) (tmObls pc b) pr)) + (po v pp)) + +tm-safe (div a b) pc v pp (po , pr) = + -- the obligation is `pc ⇒ ¬(b = 0)`, placed first by `tmObls` + &&-intro (safeTm a v) (safeTm b v && not (⟦ b ⟧t v ==? zero)) + (tm-safe a pc v pp (valid-left (tmObls pc a) (tmObls pc b) pr)) + (&&-intro (safeTm b v) (not (⟦ b ⟧t v ==? zero)) + (tm-safe b pc v pp (valid-right (tmObls pc a) (tmObls pc b) pr)) + (po v pp)) + +-------------------------------------------------------------------------------- +-- Part 2: the theorem +-------------------------------------------------------------------------------- + +soundness : ∀ (s : Stmt) (pc : Fm) (v : Val) → + AllValid (vc pc s) → + ⟦ pc ⟧f v ≡ true → + safe s v ≡ true + +soundness skip pc v pv pp = refl + +soundness (bind e) pc v pv pp = tm-safe e pc v pp pv + +soundness (seq s t) pc v pv pp = + &&-intro (safe s v) (safe t (exec s v)) + (soundness s pc v (valid-left (vc pc s) (vc pc t) pv) pp) + (soundness t pc (exec s v) (valid-right (vc pc s) (vc pc t) pv) + (trans (cong (λ w → ⟦ pc ⟧f w) (exec-id s v)) pp)) + +soundness (assert φ) pc v (po , tt) pp = po v pp + +-- `in eq` keeps the scrutinee's equation, which is what the `&&-intro` premise +-- and the `not` case both need; a plain `with` abstracts it away. +soundness (ite φ s t) pc v pv pp with ⟦ φ ⟧f v in eq +... | true = + soundness s (and pc φ) v + (valid-left (vc (and pc φ) s) (vc (and pc (neg φ)) t) pv) + (&&-intro (⟦ pc ⟧f v) (⟦ φ ⟧f v) pp eq) +... | false = + soundness t (and pc (neg φ)) v + (valid-right (vc (and pc φ) s) (vc (and pc (neg φ)) t) pv) + (&&-intro (⟦ pc ⟧f v) (not (⟦ φ ⟧f v)) pp (cong not eq)) + +-------------------------------------------------------------------------------- +-- Corollary: the theorem read as "no undefined behaviour" +-------------------------------------------------------------------------------- + +no-undefined-behaviour : + ∀ (s : Stmt) (pc : Fm) (v : Val) → + AllValid (vc pc s) → + ⟦ pc ⟧f v ≡ true → + safe s v ≡ true +no-undefined-behaviour = soundness + +-------------------------------------------------------------------------------- +-- The worked example, in miniature +-- +-- `len - 12`: guarded by `12 ≤ len`, the obligation is valid; unguarded, it is +-- refuted by the same model z3 produced for V1 (`buf_len = 0`). +-------------------------------------------------------------------------------- + +guarded-valid : + OblValid (mkObl (le (lit 12) (var 0)) (le (lit 12) (var 0))) +guarded-valid v p = p + +-- The guarded program is safe for every state satisfying the guard. +guarded-safe : ∀ (v : Val) → ⟦ le (lit 12) (var 0) ⟧f v ≡ true → + safe (bind (sub (var 0) (lit 12))) v ≡ true +guarded-safe v p = + soundness (bind (sub (var 0) (lit 12))) (le (lit 12) (var 0)) v + (guarded-valid , tt) p + +-- Unguarded, the emitted obligation is *not* valid: the state with `len = 0` +-- refutes it. This is the same counterexample the solver returned. +unguarded-not-valid : + ¬ (OblValid (mkObl tt (le (lit 12) (var 0)))) +unguarded-not-valid p = true≢false (sym (p (λ _ → zero) refl)) + +-- Therefore the unguarded program is not covered by the theorem, which is the +-- correct outcome: `vc` emitted the obligation, and the obligation is false. +unguarded-obligation-is-the-only-one : + vc tt (bind (sub (var 0) (lit 12))) + ≡ (mkObl tt (le (lit 12) (var 0)) ∷ []) +unguarded-obligation-is-the-only-one = refl diff --git a/verification/atoma/check-agda.sh b/verification/atoma/check-agda.sh new file mode 100755 index 00000000..e930f063 --- /dev/null +++ b/verification/atoma/check-agda.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +# +# check-agda.sh — typecheck the Atoma metatheory under the strictest flags. +# +# agda --safe --without-K +# +# `--safe` rejects postulates, `{-# TERMINATING #-}`, `{-# NON_TERMINATING #-}`, +# `{-# REWRITE #-}`, cubical primitives and `primTrustMe`. `--without-K` rejects +# the K axiom. Together they are the Dedukti-CIC subset the specification +# requires for witness export (§6.5). +# +# Exits 0 only if every module checks. Prints one line per module. + +set -eu +here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +AGDA=${AGDA:-agda} + +cd "$here/agda" + +for m in Bv Lin Core Soundness; do + if "$AGDA" --safe --without-K "$m.agda" >/dev/null 2>&1; then + printf 'agda ok %s\n' "$m" + else + printf 'agda FAIL %s\n' "$m" >&2 + "$AGDA" --safe --without-K "$m.agda" 2>&1 | sed -n '2,12p' >&2 + exit 1 + fi +done + +# `--safe` already rejects these, but say so out loud: a reader should not have +# to trust that `--safe` means what the specification claims it means. This +# grep is belt-and-braces against a future flag change, not the primary gate. +if grep -nE '\bpostulate\b|\{!!\}|\{-#[[:space:]]*(TERMINATING|NON_TERMINATING|REWRITE)|primTrustMe|--cubical' ./*.agda; then + printf 'agda: forbidden construct above\n' >&2 + exit 1 +fi + +# The interface files are build artefacts; a stale one can mask a broken module. +rm -f ./*.agdai + +printf 'agda: 4 modules, 0 postulates, 0 holes\n' From e846f3dfbb0fadc0da2df39f24fa5dbe133ab67e Mon Sep 17 00:00:00 2001 From: Atoma Date: Thu, 22 Oct 2026 15:44:02 +0000 Subject: [PATCH 2/6] Verify: count tool tests in the receipt; test domain separation (R8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - canon.zig: a test that the four BLAKE3 domains (spec, vc, dk, src) separate - verify.sh: derive the tool test count from `zig test` instead of hard-coding it, so the receipt cannot claim a stale number - spec: §3.5 status note separating the two obligations the metatheory covers from the eight that are solver-discharged but argued, plus section-reference and numbering repairs (the claims ledger is now unnumbered front matter, so the printed numbers match the §-references throughout) Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- docs/spec/ATOMA-SPEC.adoc | 11 +++++++++++ examples/atoma/frame-v1/verify.sh | 12 +++++++++++- .../atoma/frame-v1/witness/phase0.receipt.json | 2 +- tools/atoma/src/canon.zig | 17 +++++++++++++++++ 4 files changed, 40 insertions(+), 2 deletions(-) diff --git a/docs/spec/ATOMA-SPEC.adoc b/docs/spec/ATOMA-SPEC.adoc index d736fdbd..352d9b32 100644 --- a/docs/spec/ATOMA-SPEC.adoc +++ b/docs/spec/ATOMA-SPEC.adoc @@ -529,6 +529,17 @@ padding byte, which in Zig requires an explicit byte-level operation (`atoma.zeroBytes`). A value assignment `out.* = .{...}` does not define padding and therefore cannot discharge `pad`. +*Status.* Two of those obligations — subtraction underflow and division by zero — +are modelled in the checked core language, and §6.3 proves that the generator's +obligations for them are sufficient. The other eight are emitted by the VC +generator and discharged by the solver for the worked example (§8.3), but their +*adequacy* — that the SMT encoding of an `@intCast` range, or of a struct's +padding bytes, means what the prose says — is argued rather than proved. That +argument is exactly what the traps of §7.2 enumerate, and it is reviewed rather +than mechanised. The distinction is worth keeping sharp: a discharged +`V6_padding_zeroed` is strong evidence; the theorem of §6.3 is a proof of a +strictly smaller statement. + === Control flow, resources, and cost *Loops.* `while` requires an `@invariant` and a `@decreases` term. `for` over a diff --git a/examples/atoma/frame-v1/verify.sh b/examples/atoma/frame-v1/verify.sh index 5268e259..39c4825a 100755 --- a/examples/atoma/frame-v1/verify.sh +++ b/examples/atoma/frame-v1/verify.sh @@ -53,6 +53,16 @@ die() { [ -x "$ADDR" ] || (cd "$root/tools/atoma" && "$ZIG" build >/dev/null) || die "cannot build atoma" +# Count the tool's own tests instead of hard-coding a number that can drift. +atoma_tests=0 +for m in canon frontend; do + n=$("$ZIG" test "$root/tools/atoma/src/$m.zig" 2>&1 | + sed -n 's/^All \([0-9][0-9]*\) tests passed\.$/\1/p') + [ -n "$n" ] || die "cannot count the tests in $m.zig" + atoma_tests=$((atoma_tests + n)) +done +printf 'atoma %s tests (canon + frontend)\n' "$atoma_tests" + cd "$here" # ── G1: subset conformance + unit tests ───────────────────────────────────── @@ -209,7 +219,7 @@ printf '%s' \ "\"status\":\"INCOMPLETE\",\"status_class\":\"Warrant\"," \ "\"subset\":{\"contracts\":6,\"diagnostics_negative_corpus\":$diags,\"codes_negative_corpus\":$codes}," \ "\"targets\":[\"aarch64\",\"riscv64\",\"wasm32\",\"x86_64\"]," \ - "\"tests\":{\"atoma\":14,\"frame_parse\":11}}" > "$receipt" + "\"tests\":{\"atoma\":$atoma_tests,\"frame_parse\":11}}" > "$receipt" printf '\nreceipt: %s\n' "$receipt" cat "$receipt" printf '\n' diff --git a/examples/atoma/frame-v1/witness/phase0.receipt.json b/examples/atoma/frame-v1/witness/phase0.receipt.json index de72ef95..057eed4d 100644 --- a/examples/atoma/frame-v1/witness/phase0.receipt.json +++ b/examples/atoma/frame-v1/witness/phase0.receipt.json @@ -1 +1 @@ -{"artifacts":{"face-a":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","face-b":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","layout":"blake3:c75f72ce33010b457c8dc7f8c8514720904ddaeca9de0ce412cc7d61cf8accd1"},"contract":"atoma.frame.parse","equivalence":"EQUIVALENT","gate":"phase0","mutants":{"applied":11,"distinct":11},"proof":{"modules":4,"srcset":"blake3:e2b2f961812d4ed1165f3d306d267dd95af7d0f13f7ce146fde9355d7a647249","status":"checked"},"schema":"atoma.receipt.v1","smt":{"status":"discharged","vcs":14,"vcset":"blake3:72c74c012d527feab0988225098a7a110e35252794c67848ab13f010c75e3698"},"status":"INCOMPLETE","status_class":"Warrant","subset":{"contracts":6,"diagnostics_negative_corpus":20,"codes_negative_corpus":17},"targets":["aarch64","riscv64","wasm32","x86_64"],"tests":{"atoma":14,"frame_parse":11}} \ No newline at end of file +{"artifacts":{"face-a":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","face-b":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","layout":"blake3:c75f72ce33010b457c8dc7f8c8514720904ddaeca9de0ce412cc7d61cf8accd1"},"contract":"atoma.frame.parse","equivalence":"EQUIVALENT","gate":"phase0","mutants":{"applied":11,"distinct":11},"proof":{"modules":4,"srcset":"blake3:e2b2f961812d4ed1165f3d306d267dd95af7d0f13f7ce146fde9355d7a647249","status":"checked"},"schema":"atoma.receipt.v1","smt":{"status":"discharged","vcs":14,"vcset":"blake3:72c74c012d527feab0988225098a7a110e35252794c67848ab13f010c75e3698"},"status":"INCOMPLETE","status_class":"Warrant","subset":{"contracts":6,"diagnostics_negative_corpus":20,"codes_negative_corpus":17},"targets":["aarch64","riscv64","wasm32","x86_64"],"tests":{"atoma":15,"frame_parse":11}} \ No newline at end of file diff --git a/tools/atoma/src/canon.zig b/tools/atoma/src/canon.zig index fcea5c30..56ef7cba 100644 --- a/tools/atoma/src/canon.zig +++ b/tools/atoma/src/canon.zig @@ -557,6 +557,23 @@ test "blake3 known-answer" { ); } +// R8 is a claim about *domain separation*: the same bytes hashed in two roles +// must not collide. This is cheap to test and the failure mode (a witness hash +// equal to a spec hash) would be silent, so it is tested rather than assumed. +test "domains separate" { + const bytes = "cspec 1\ncontract x\n"; + const spec = digestHex(domain_spec, bytes); + const vc = digestHex(domain_vc, bytes); + const dk = digestHex(domain_dk, bytes); + const src = digestHex(domain_src, bytes); + try testing.expect(!std.mem.eql(u8, &spec, &vc)); + try testing.expect(!std.mem.eql(u8, &spec, &dk)); + try testing.expect(!std.mem.eql(u8, &spec, &src)); + try testing.expect(!std.mem.eql(u8, &vc, &dk)); + try testing.expect(!std.mem.eql(u8, &vc, &src)); + try testing.expect(!std.mem.eql(u8, &dk, &src)); +} + test "integer normalisation" { try testing.expectEqualStrings("16", try normaliseInteger(ta, "0x10")); try testing.expectEqualStrings("1000", try normaliseInteger(ta, "1_000")); From f5194f10300430430072611235c8def2af141f5d Mon Sep 17 00:00:00 2001 From: Atoma Date: Thu, 22 Oct 2026 15:48:29 +0000 Subject: [PATCH 3/6] CITATION: make the repository's about + tags machine-readable Replaces the template placeholders with Atoma's identity: title, abstract (with the honest Phase 0/1 status), release date, url, MPL-2.0, and 17 keywords that mirror the GitHub topics (zig, idris2, agda, formal-verification, qtt, ffi, c-abi, smt-lib, z3, dedukti, proof-carrying-code, coq, lean4, ...). GitHub renders this file as "Cite this repository", so the About text has a versioned home in the tree rather than only in repository settings. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- CITATION.cff | 47 ++++++++++++++++++++++++++++++++++++----------- 1 file changed, 36 insertions(+), 11 deletions(-) diff --git a/CITATION.cff b/CITATION.cff index ba88b6a6..12a9ee72 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -1,17 +1,42 @@ cff-version: 1.2.0 message: "If you use this software, please cite it as below." authors: - - family-names: "{{AUTHOR_LAST}}" - given-names: "{{AUTHOR_FIRST}}" - orcid: "https://orcid.org/{{AUTHOR_ORCID}}" -title: "{{PROJECT_NAME}}" -version: 0.1.0 -date-released: "{{CURRENT_DATE}}" -url: "https://{{FORGE}}/{{OWNER}}/{{REPO}}" -repository-code: "https://{{FORGE}}/{{OWNER}}/{{REPO}}" + - family-names: "Jewell" + given-names: "Jonathan D.A." + website: "https://github.com/hyperpolymath" +title: "Atoma" +abstract: >- + Atoma is a verification toolchain for Zig at the Idris2 ABI seam. It takes the + contract a repository already declares in Idris2 and the contract its Zig + export fn already documents, canonicalises both into one hash-checked Core + Spec IR, checks the implementation against a deliberately small verifiable + subset of Zig, and derives SMT verification conditions from the result. The + shape is Ada/SPARK or Rust/Creusot: one name for the subset, the contracts and + the toolchain. Witnesses are intended to be exported as canonical Dedukti and + rechecked by coqchk and lean4checker before any claim is promoted from + INCOMPLETE (Warrant) to COMPLETE (Receipt). Status: Phase 0/1 - the seam, + layout, subset and VC gates run and the soundness theorem typechecks for a + store-free core fragment; the kernel chain is specified, not yet run. +version: "0.1.0" +date-released: "2026-10-22" +url: "https://github.com/hyperpolymath/atoma" +repository-code: "https://github.com/hyperpolymath/atoma" license: MPL-2.0 keywords: - - "rsr" + - "atoma" + - "zig" + - "idris2" + - "agda" - "formal-verification" - - "neurosymbolic" - - "provenance" + - "formal-methods" + - "dependent-types" + - "qtt" + - "contracts" + - "ffi" + - "c-abi" + - "smt-lib" + - "z3" + - "dedukti" + - "proof-carrying-code" + - "coq" + - "lean4" From 223ece0f3abcef4893fc575305cd5c34d9ed0442 Mon Sep 17 00:00:00 2001 From: Atoma Date: Thu, 22 Oct 2026 15:53:51 +0000 Subject: [PATCH 4/6] =?UTF-8?q?docs:=20add=20the=20ultraplan=20=E2=80=94?= =?UTF-8?q?=20the=20executable=20plan=20for=20future=20agents=20and=20peop?= =?UTF-8?q?le?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/plan/ULTRAPLAN.adoc: milestones A/K/T/S/C/H, 40 task cards with an acceptance command, a falsifier and an honest blocker each; gate table G1-G15 plus F0.1; environment recipes for a cold sandbox and the estate; the traps already paid for; definitions of done; a deviations log; risk register; eight open questions with defaults. Written to be followed, not admired: - every task names the command whose exit status decides, and the observation that would show the command passed for the wrong reason - blocked tasks say what unblocks them and refuse a stub (I4 depends on it) - the four structural gaps are named: identity (88 files still carry template tokens), kernel chain, theory width, estate conformance - §15 records 26 measured failures so they are not paid for twice Also: docs/README.adoc gains the plan/ row and a start-here link; docs/spec/README.adoc and the spec's repository map point at it; REPOSITORY-MAP.adoc regenerated (tools/ is no longer empty, examples/ exists). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- docs/README.adoc | 3 + docs/architecture/REPOSITORY-MAP.adoc | 5 +- docs/plan/ULTRAPLAN.adoc | 1413 +++++++++++++++++++++++++ docs/spec/ATOMA-SPEC.adoc | 1 + docs/spec/README.adoc | 3 + 5 files changed, 1424 insertions(+), 1 deletion(-) create mode 100644 docs/plan/ULTRAPLAN.adoc diff --git a/docs/README.adoc b/docs/README.adoc index dc7274f0..4804a275 100644 --- a/docs/README.adoc +++ b/docs/README.adoc @@ -13,6 +13,8 @@ and CI fails if it goes stale, so prefer it over any hand-written listing. * link:onboarding/QUICKSTART-MAINTAINER.adoc[QUICKSTART-MAINTAINER] — maintaining one. * link:AI_INSTALLATION_GUIDE.adoc[AI_INSTALLATION_GUIDE] — for an AI agent instantiating the template. * link:EXPLAINME.adoc[EXPLAINME] — how the pieces actually work. +* link:plan/ULTRAPLAN.adoc[ULTRAPLAN] — what to do next, in what order, with the + acceptance command for every task. Read this before picking up work. == The tracks @@ -27,6 +29,7 @@ and CI fails if it goes stale, so prefer it over any hand-written listing. | `governance/` | Governance model, maintenance checklist, development approach, audits, planning. | `legal/` | Licence exhibits. | `onboarding/` | Quickstarts and the LLM warm-up documents. +| `plan/` | The ultraplan: milestones, task cards, gates and blocked work. | `practice/` | Operational and implementation material, incl. AI conventions. | `proposals/` | Proposals and RFCs, including the root-cleanup proposal this layout came from. | `reports/` | Generated and periodic reports (audit, compliance, security, ...). diff --git a/docs/architecture/REPOSITORY-MAP.adoc b/docs/architecture/REPOSITORY-MAP.adoc index ff28fb05..109ead77 100644 --- a/docs/architecture/REPOSITORY-MAP.adoc +++ b/docs/architecture/REPOSITORY-MAP.adoc @@ -185,6 +185,10 @@ predecessors did. | yes | - +| `tools/` +| yes +| - + | `verification/` | optional | proofs; only where formal-proofs is declared @@ -237,7 +241,6 @@ your own repo - but do not read their emptiness as neglect here. | `docs/whitepapers/academic/` | `docs/whitepapers/industry/` | `docs/whitepapers/outreach/` -| `examples/` | `features/boj-server/` | `features/panic-attacker/` | `src/aspects/` diff --git a/docs/plan/ULTRAPLAN.adoc b/docs/plan/ULTRAPLAN.adoc new file mode 100644 index 00000000..4d9e0601 --- /dev/null +++ b/docs/plan/ULTRAPLAN.adoc @@ -0,0 +1,1413 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell += Atoma — Ultraplan +:subtitle: Execution plan for agents and people · revision 1 · 2026-10-22 +:toc: +:toclevels: 3 +:sectnums: + +[abstract] +-- +This is the working plan for Atoma, the verification toolchain specified in +`docs/spec/ATOMA-SPEC.adoc`. The specification says *what must be true*. This +document says *who does what next, in which order, and how anyone — human or +agent — can tell whether it worked*. + +It is written to survive the reader's absence of context. A fresh agent with a +cold clone, no network history and no memory of the decisions that produced the +current tree should be able to open this file, run one command, see green or +red, pick up a task, and not repeat a mistake already paid for. + +Three properties are deliberate. Every task has an **acceptance command** — not +a description of success, a command whose exit status decides. Every task has a +**falsifier** — the observation that would show the work is wrong even though +the command passed. And every task names its **blocker** honestly, because a +plan that hides a missing toolchain teaches the next agent to fake the result. +-- + +[[how-to-use]] +== How to use this document + +=== Reading order + +If you are new to the repository, read in this order and stop when you have +enough: + +. This section (five minutes). +. <> — what is actually true today, with digests (§2). +. <> — the gate table; if a gate is red, that is your first task. +. The track you are picking work from (§7–§12). +. `docs/spec/ATOMA-SPEC.adoc` §1 (claims ledger) and §6 (semantics) before you + touch anything that claims soundness. + +If you are resuming work, skip to <> and read the task cards flagged +`in-progress` or `blocked`. + +=== Task IDs and status + +Task IDs are of the form ``: `A` identity and estate, `K` kernel +chain, `T` theory, `S` subset, `C` cost and secrecy, `H` hardening. **IDs are +stable.** Never renumber. If a task is split, the new part becomes `A7b`; if a +task is dropped, its card stays and its status becomes `dropped (reason)` so the +history of the decision survives. + +Every card carries a status line with one of five values: + +[cols="1,3", options="header"] +|=== +| Status | Means + +| `todo` | Not started, not blocked. Available to whoever gets there first. +| `in-progress` | Someone has claimed it. The claim is the commit, not a message. +| `blocked` | Cannot proceed without the named thing. Do not stub around it. +| `done (evidence: …)` | The acceptance command was run and its output is quoted in the commit or the receipt. +| `dropped (reason)` | Deliberately not doing it. The reason is part of the record. +|=== + +`blocked` is a first-class outcome. A task blocked on a missing binary is *not* +"done for now", and the receipt must not be nudged upward to make the board look +better. The estate has a phrase for the failure this prevents: a gate that +cannot run must never report OK. + +=== The seven rules + +. **No silent green.** Every claim is a field in a receipt or a line of gate + output. If a tool is absent, the gate prints `not-run` and the status stays + `INCOMPLETE (Warrant)`. +. **The specification is the source of truth for *what*; this plan is the source + of truth for *when*.** If they disagree, the specification wins and this plan + gets fixed in the same commit. +. **One name.** Atoma, everywhere: binary, directories, contract domains, wire + magic. If a `zigprove` or `zp_` token appears, it is a bug, not a legacy. +. **Never invent the solver runner.** ECHIDNA dispatches Why3/z3/cvc5 and owns + the Alethe→Dedukti road. Atoma produces obligations and consumes certificates. + A second runner is a second thing to trust. +. **Watch the test fail.** Before trusting a gate, break the thing it guards and + confirm it goes red. This is written down because four gates in this repo's + history could not fail (§15). +. **Small trusted tree, replaceable untrusted tree.** CLI, canonicaliser, VC + generator: replaceable. `Core.agda`, `Soundness.agda`, the Idris2 contract, the + kernel verdicts: not. +. **Ask before you mint.** Anything that rewrites repository identity + (`just repo-init`), force-pushes, or changes visibility is an owner action. + Agents prepare the change and hand it over. + +== Where the work stands + +[[state]] +=== Verified today (2026-10-22, commit `f5194f1`) + +Every row below was produced by a command in this session, not recalled. Full +digests are in `examples/atoma/frame-v1/witness/phase0.receipt.json`. + +[cols="1,4,3", options="header"] +|=== +| Gate | What it proves | Result + +| G1 | `frame_parse.zig` unit tests | 11/11 on Zig 0.15.2 and 0.16.0 +| G2 | Four ABI target classes compile | x86_64, aarch64, riscv64, wasm32 +| G3 | 60 declared layout rows witnessed by the compiler | 4 targets, 0 mismatch +| G4 | A pointer-width struct is rejected on wasm32 (F0.3) | rejected, as required +| G5 | Face A and Face B canonicalise to the same bytes | `blake3:f5f97a7b…f265756` +| G5 | A one-token edit diverges (equivalence is not vacuous) | `blake3:d49201f2…ffca70` +| G6 | 11 mutation operators give 11 distinct artefacts | 11 applied, 11 distinct +| G7 | 14 SMT obligations discharged by z3 5.3.1 | `blake3:72c74c01…5e3698` +| G8 | Face B is *extracted* from Zig, not hand-maintained | `blake3:ee4d77f0…eb2358` +| G9 | The implementation is subset-clean | 6 exports, 6 contracts, 0 diagnostics +| G10 | The subset checker is not vacuous | 20 diagnostics over 17 codes +| G11 | The Agda metatheory typechecks | 4 modules, `blake3:e2b2f961…647249` +| — | The tool's own tests | 15 (9 canon + 6 frontend) +|=== + +The metatheory, precisely: `Bv`, `Lin`, `Core`, `Soundness` all check under +`agda --safe --without-K` (Agda 2.7.0.1), with no `postulate`, no termination +pragma, no rewrite rule, no cubical primitive and no hole. `soundness` relates +`vc` to `safe` for the **store-free** fragment; §6.3 of the specification states +its type verbatim. `exec-id` — "a statement never changes the valuation" — is +the lemma the proof turns on, and it is true only because the fragment has no +store. + +=== Not verified — and never to be implied + +* No `.dk` file exists. Nothing has been through `dkcheck`, `coqchk` or + `lean4checker`. The receipt's `status_class` is `Warrant`, and must stay so. +* No mutation **kill** score. The 11 distinct artefacts are the easy half; the + kill half needs the ECHIDNA loop (K6). +* No Idris2 typecheck. `abi/FrameAbi.idr` is normative text and has never been + compiled here; gate F0.1 is unrun (T5). +* No refinement theorem. `soundness` relates two Agda functions. The step to a + compiled Zig function is reviewed, not proved, and is non-claim N3 (§6.4). +* `atoma check` is a token scan. It resolves no names, evaluates no `comptime`, + computes no layout. It is not a type checker and must not be described as one. + +=== The four structural gaps + +These are why the plan exists. They are not bugs; they are the distance between +"the design is specified and Phase 0 runs" and "the tool is what it says". + +. **Identity.** 88 tracked files still carry `{{PLACEHOLDER}}` tokens; + `bash scripts/check-no-placeholders.sh` exits 1; the repo deed still says + `rsr-template-repo`; the GitHub About box and topics are empty. (A1, A2) +. **Kernel chain.** The obligations are discharged by a solver whose answer is + trusted, not checked. Until a `.dk` survives three kernels, everything above + `Warrant` is a promise. (K2–K9) +. **Theory width.** The checked theorem covers hazard sites in a store-free + fragment: no store, no loops, no postconditions, no linearity lift. (T1–T4) +. **Estate conformance.** Atoma's Agda sits outside the proof manifest, so + `just proof-check-agda` does not see it; the VC generator is Python, which the + estate toolchain policy forbids; CI has no Atoma gate. (A3–A6) + +== Invariants + +These hold for every change, forever, unless the owner amends the specification. + +[cols="1,5", options="header"] +|=== +| ID | Invariant + +| I1 | Core ABIs, AST/IR schemas and contract representations are Idris2 with `%default total`; zero `believe_me`, zero `assert_total`, zero `postulate`. +| I2 | Checker and VC-generator logic outside Idris2/Agda is Ada/SPARK or Rust-with-Creusot, strictly separated from untrusted CLI and process I/O. +| I3 | Agda semantics is `--safe --without-K`, inside the Dedukti-CIC subset: indexed inductives and structural eliminators; no inductive-recursion, no cubical, no rewrite rules. +| I4 | A witness is `.dk`, content-addressed by `BLAKE3` under `atoma.dk.v1`, and `INCOMPLETE (Warrant)` until **both** `coqchk` (zero extra axioms) and `lean4checker --fresh` accept it. +| I5 | ECHIDNA owns dispatch, solving and exchange; Proof Burrower owns the `.dk` cache. Atoma adds no solver runner. +| I6 | `[*c]T` is banned. `[*]T` exists only bound by an Idris2 ghost length. `@ptrFromInt`, arbitrary `@ptrCast`, `volatile`, inline `asm`, `@cImport`, mutable globals and unbounded recursion are quarantined or banned (spec §3). +| I7 | Every committed file has an SPDX header (`MPL-2.0` code, `CC-BY-SA-4.0` docs). Documentation is AsciiDoc. No `.md` under `docs/`. +| I8 | Every generated artefact is regenerated, not hand-edited: `spec/face-b.cspec` (G8), `docs/architecture/REPOSITORY-MAP.adoc`, the receipt. +| I9 | One name: Atoma. No `zigprove`, no `zp_`, no `ZPV1`, no second project name. +| I10 | Any claim added to the specification gets a row in the claims ledger, with a gate or an explicit `not checked`. +| I11 | No new implementation language outside the estate policy; no Python in a path the gates depend on after A6. +| I12 | `../spec/face-a.cspec` is normative text until F0.1 replaces it with `encode frameParse` output. +|=== + +== Environment + +Atoma needs three toolchains that are not in a default image. The recipes below +were run on 2026-10-22 and are the ones to copy. + +=== Tier 1 — a cold sandbox (ephemeral, no root) + +`/tmp` does not survive a snapshot restore. Re-run this, then `./verify.sh`. + +[source,bash] +---- +# Zig 0.15.2 — the CLI is pinned to it (tools/atoma/.zig-version) +python3 -m venv /tmp/zv15 +/tmp/zv15/bin/pip install ziglang==0.15.2 +export PATH=/tmp/zv15/lib/python3.11/site-packages/ziglang:$PATH + +# Agda 2.7.0.1 — pip wheel ships without the primitive library; fetch it +python3 -m venv /tmp/zv +/tmp/zv/bin/pip install agda==2.7.0.1 z3-solver pyyaml +# the wheel has no prim library; an empty libraries file means "no user libraries" +mkdir -p /tmp/zv/lib/python3.11/site-packages/agda/data/lib +: > /tmp/zv/lib/python3.11/site-packages/agda/data/lib/libraries +curl -L https://codeload.github.com/agda/agda/tar.gz/refs/tags/v2.7.0.1 | + tar -xz -C /tmp --wildcards '*/src/data/lib/prim/*' +cp -r /tmp/agda-2.7.0.1/src/data/lib/prim \ + /tmp/zv/lib/python3.11/site-packages/agda/data/lib/ + +# run everything +export PATH=/tmp/zv15/lib/python3.11/site-packages/ziglang:$PATH +cd examples/atoma/frame-v1 +AGDA=/tmp/zv/bin/agda PYTHON=/tmp/zv/bin/python ./verify.sh +---- + +Expected: twelve `ok` lines (G5 prints twice), `atoma 15 tests`, and a receipt +whose `status` is `INCOMPLETE` and `status_class` is `Warrant`. If `agda` is not +on `AGDA=`, G11 prints `not-run` — that is a correct outcome, not a failure, and +the receipt says `"proof":{"status":"not-run"}`. + +=== Tier 2 — the estate + +A minted repository uses `mise` + `just` instead of venvs: + +[source,bash] +---- +just setup # installs the toolchain declared in mise.toml, then doctor +just doctor # PASS/WARN/FAIL per tool; exits 1 on any FAIL +just proof-check-all # idris2, lean4, agda, coq, plus scan-dangerous +just test # provision::test +---- + +`mise.toml` currently declares `just`, `shellcheck`, `trivy`, `zig`. It does +**not** declare `agda`, `z3` or `idris2`; A4 is the task that closes that gap so +a fresh clone can run G7 and G11 without hand-built venvs. + +=== Tier 3 — CI + +No workflow runs an Atoma gate today. `quality.yml` runs the estate checks; +`verify.sh` is invoked only by a human. A5 adds +`.github/workflows/atoma-verify.yml` with pinned Zig, Agda and z3, running +`verify.sh` plus `just proof-check-agda`, uploading the receipt as an artefact, +and **failing** if the receipt says `not-run` for a tool the job installed. + +=== Degradation matrix + +[cols="2,2,3,2", options="header"] +|=== +| Tool absent | Gate | What the gate does | What the receipt says + +| `z3` | G7 | prints `G7 --` and continues | `"smt":{"status":"not-run","vcs":0}` +| `agda` | G11 | prints `G11 --` and continues | `"proof":{"status":"not-run","srcset":"none"}` +| `idris2` | F0.1 | does not exist yet (T5) | Face A remains `transcribed` +| `dkcheck`/`coqchk`/`lean4checker` | K-series | does not exist yet | `status_class` stays `Warrant` +| `zig` | everything | `verify.sh` dies at the first build | no receipt is written +|=== + +The asymmetry is deliberate: a missing solver weakens a *claim*, a missing +compiler stops *work*. Only the first is allowed to produce a receipt, and only +with the degradation visible in it. + +[[gates]] +== Gates + +A gate is a command with an exit status. Gates G1–G11 exist; G12–G15 are the +ones this plan adds. F0.1 is the Phase 0 entry gate that has never run. + +[cols="1,3,3,2", options="header"] +|=== +| Gate | Command | Pass means | Added by + +| G1 | `zig test src/frame_parse.zig` | 11/11 | exists +| G2 | `zig build-obj … -target <4 triples>` | all four compile | exists +| G3 | `./tools/layout.sh` | 60 rows, 0 mismatch | exists +| G4 | `zig build-obj tools/layout_negative.zig -target wasm32…` | **fails** | exists +| G5 | `atoma equiv spec/face-a.cspec spec/face-b.cspec` | equal digests; probe diverges | exists +| G6 | `atoma mutate` sweep | 11/11 distinct | exists +| G7 | `python3 vc/gen_vcs.py` | 14/14, 6 counterexamples found | exists +| G8 | `atoma extract … \| hashed` | equals `spec/face-b.cspec` | exists +| G9 | `atoma check src/frame_parse.zig` | 0 diagnostics, 6 contracts | exists +| G10 | `atoma check fixtures/violations.zig` | **exits 1**, ≥20 diags, ≥15 codes | exists +| G11 | `verification/atoma/check-agda.sh` | 4 modules, 0 postulates | exists +| F0.1 | `idris2 --typecheck abi/FrameAbi.ipkg` + `encode` diff | typechecks; Face A regenerated | T5 +| G12 | `dkcheck .dk` | accepted | K3 +| G13 | `coqchk` and `lean4checker --fresh` on the `.dk` | accepted, 0 extra axioms | K4 +| G14 | `echidna mutate` over the 11 operators | kill ≥ 95 %, vacuity 100 % | K6 +| G15 | receipt schema validation | `COMPLETE` only with three kernel verdicts | K7 +|=== + +Gate discipline, learned the expensive way: + +* A gate that cannot run prints `not-run` and **never** `ok`. +* A gate is trusted only after the thing it guards has been broken deliberately + and the gate was seen to fail. Each of G4, G5-probe, G10 and G11's grep exists + for that reason. +* G7 and G11 are skip-capable by design; G1–G6, G8–G10 are not. If a machine + cannot run a non-skip gate, the correct output is a failure, not a skip. + +== Milestones + +Six milestones, each with an exit gate. The dependency graph is a spine with +parallel tracks: A must land before the repo can be read as Atoma; K is the only +road to `COMPLETE`; T can proceed in parallel with A and K because it needs only +Agda; S, C and H come after. + +.... +A (identity, 2–3 days) ──► K (kernel chain, 3–6 weeks) ──► S (subset) + │ │ + └────────────► T (theory, ongoing, unblocked) ──► C (cost/secrecy) + │ + └──► H (hardening, ecosystem) +.... + +[[board]] +[cols="1,2,3,2", options="header"] +|=== +| Milestone | Goal | Exit gate | Status + +| A | The repository *is* Atoma, and the estate gates see its proofs | `check-no-placeholders.sh` exits 0; `just proof-check-agda` includes 4 modules; CI runs `verify.sh` | `todo` +| K | One VC reaches `COMPLETE (Receipt)` through three kernels, then fourteen | G12, G13, G14, G15 on one VC, then the full set | `blocked` (needs idris2, dkcheck, echidna, coqchk, lean4checker) +| T | The theorem covers store, loops and postconditions | `agda --safe --without-K` on the extended `Core`/`Soundness`; no postulates | `todo` (unblocked) +| S | Phase 2: regions, allocators, recursion, borrows beyond the signature | a second worked example verified end to end | `todo` +| C | Phase 3: MaxPlus bounds, stack HWM, secrecy lattice | a secret-dependent branch rejected; a padding leak rejected even when memory safety passes | `todo` +| H | Proof Burrower cache, badges, more examples, release | cache hit skips recheck only on TCB match; badge names phase + digest | `todo` +|=== + +[[track-a]] +== Track A — Identity and estate conformance + +Cheap, unblocked, and the thing that makes everything else legible. Two of the +seven need the owner. + +[[A1]] +=== A1 — Mint the repository + +*Status:* `blocked` (owner values + `just`) · *Size:* S · *Owner:* human + +*Why.* 88 tracked files carry `{{PLACEHOLDER}}` tokens and the estate's own gate +is red: + +[source,bash] +---- +$ bash scripts/check-no-placeholders.sh; echo $? +FAIL: 88 file(s) contain unfilled {{PLACEHOLDER}} tokens +1 +---- + +*Method.* On a scratch branch, with the values in the environment (the recipe +prompts unless `RSR_NON_INTERACTIVE` is set): + +[source,bash] +---- +git switch -c chore/mint-atoma +RSR_NON_INTERACTIVE=1 \ +PROJECT_NAME="Atoma" \ +PROJECT_DESCRIPTION="A verification toolchain for Zig at the Idris2 ABI seam" \ +REPO="atoma" OWNER="hyperpolymath" \ +AUTHOR="Jonathan D.A. Jewell" AUTHOR_EMAIL="j.d.a.jewell@open.ac.uk" \ +PROJECT_TYPE="binary" WEBSITE="https://github.com/hyperpolymath/atoma" \ +OPENSSF_BP_ID="" \ +just repo-init +bash scripts/check-no-placeholders.sh +git diff --stat +---- + +Then review the diff by hand. The mint rewrites the repo deed's identity block, +the README, `www/`, `.devcontainer/`, `CITATION.cff` and the root `Justfile` +variables. Anything it produces that contradicts Atoma's specification +(§2–§7) is a plan deviation — record it in <>. + +*Accept.* `bash scripts/check-no-placeholders.sh` exits 0 **and** +`git grep -c 'rsr-template-repo'` returns nothing in tracked files. + +*Falsifier.* The gate passes because a token was deleted rather than filled, and +a reader still cannot tell what the repo is. Read the rendered `README.adoc` and +`www/public/index.html`; if they describe a template, A1 is not done. + +*Blocked by.* Nothing technical. It is destructive enough to need the owner's +sign-off, and it must not run on a dirty tree. + +[[A2]] +=== A2 — Set repository identity out of band + +*Status:* `blocked` (token lacks permission) · *Size:* XS · *Owner:* human + +*Why.* `.github/settings.yml` deliberately forbids `name`, `description`, +`homepage` and `private` keys — this is the estate's fix for a template that +once renamed itself on every push. Identity is therefore an operator action, and +Atoma currently has an empty About box and no topics, so discovery and citation +are both poorer than they should be. + +*Method.* The sandbox's GitHub token is an App installation token with +contents-write only; `gh repo edit` returns +`HTTP 403: Resource not accessible by integration`. Run one of: + +[source,bash] +---- +gh repo edit hyperpolymath/atoma \ + --description "Atoma — a verifier for Zig at the Idris2 ABI seam. Two hash-checked faces of one contract IR, a deliberately small verifiable Zig subset, and a soundness theorem in Agda. Status: Phase 0/1, INCOMPLETE (Warrant)." \ + --add-topic atoma,zig,idris2,agda,formal-verification,formal-methods,dependent-types,qtt,contracts,ffi,c-abi,smt-lib,z3,dedukti,proof-carrying-code,coq,lean4 +---- + +or reconnect GitHub in the agent environment with repository-administration +permission and let the agent run it. + +*Accept.* `gh repo view --json description,repositoryTopics` shows the +description and 17 topics. + +*Falsifier.* Topics set but description left as the template's, or a description +that claims `COMPLETE` — the About box is the most-read claim the project makes; +it must carry the status. + +*Blocked by.* Repository administration permission. + +[[A3]] +=== A3 — Register the metatheory with the estate proof gate + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Why.* `just proof-check-all` is the estate's single source of truth for "do the +proofs compile", and it cannot see Atoma's proof. `verification/proofs/agda/MANIFEST` +lists exactly one module: + +[source] +---- +verification/proofs/agda|Properties.agda|gated| compiles under `agda --safe` +---- + +The four Atoma modules live at `verification/atoma/agda/` and are checked only +by `check-agda.sh`, which nobody's CI calls. A proof outside the manifest is +gated by memory. + +*Method.* Two changes, both small: + +. Add to `verification/proofs/agda/MANIFEST`, using the format's existing + arbitrary-source-root support: ++ +[source] +---- +verification/atoma/agda|Bv.agda|gated| bitvector bridge; Atoma spec §4.5 +verification/atoma/agda|Lin.agda|gated| linear handles; spec §3.6 +verification/atoma/agda|Core.agda|gated| core language + VC generator; spec §6.1–6.2 +verification/atoma/agda|Soundness.agda|gated| the §6.3 theorem +---- +. Teach `scripts/check-proofs.sh` per-entry flags, because the estate invokes + `agda --safe` and Atoma additionally requires `--without-K`. Extend the + manifest line with an optional fifth field (`flags=--without-K`) and pass it + through; default stays as today. + +*Accept.* `just proof-check-agda` (or `bash scripts/check-proofs.sh agda`) +checks five modules including all four Atoma ones, and +`bash scripts/scan-dangerous.sh` exits 0 on the new files. + +*Falsifier.* Add `postulate`-like cheating to a copy of `Soundness.agda` and +confirm **both** `check-proofs.sh` and `check-agda.sh` reject it. If only one +does, the two checkers disagree and the weaker one is decorative. + +*Note.* Moving the files under `verification/proofs/agda/atoma/` is the +alternative. It is more churn (six documented paths and the spec's repository +map) for no additional guarantee, and the proof `srcset` digest would not change +because it hashes contents, not paths. Prefer the manifest entry. + +[[A4]] +=== A4 — Declare the Atoma toolchain in the provisioning contract + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Why.* `mise.toml` declares `just`, `shellcheck`, `trivy`, `zig` and nothing +else. A fresh clone therefore cannot run G7 or G11 without hand-built venvs, and +`just doctor` reports a healthy environment that cannot verify anything. + +*Method.* Declare `agda` and `z3` in `mise.toml`: as mise tools if the registry +carries them, otherwise as a pinned download with a recorded checksum. The +venue matters less than the pin — `just doctor` must be able to answer PASS or +FAIL for each, and `mise.lock` must make the answer the same on every machine. +Add `[env]` entries for `AGDA` (and `PYTHON`, until A6 removes it) so +`verify.sh` finds them without a hand-built venv, then `just toolchain-refresh` +to re-lock. + +*Accept.* On a clean container, `just setup && just doctor` passes and +`./verify.sh` reports G7 `ok` and G11 `ok` without any manual `export`. + +*Falsifier.* The tools appear in `mise.toml` but a fresh `mise install` still +leaves `verify.sh` printing `not-run` for G7/G11 — the declaration is decorative. + +[[A5]] +=== A5 — Put the gates in CI + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Why.* Every gate in this repo runs because a human typed `./verify.sh`. The +estate's own history is explicit that path-filtered, skip-happy CI is how +non-compiling proofs survive for months. + +*Method.* Add `.github/workflows/atoma-verify.yml`: + +[source,yaml] +---- +# sketch — the pinning and checksum conventions come from actions.lock +jobs: + verify: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@ + - run: just setup # or mise install with a pinned lockfile + - run: just doctor + - run: cd examples/atoma/frame-v1 && ./verify.sh + - run: just proof-check-agda + - uses: actions/upload-artifact@ + with: { name: phase0-receipt, path: examples/atoma/frame-v1/witness/ } + - name: no silent not-run + run: | + jq -e '.smt.status == "discharged" and .proof.status == "checked"' \ + examples/atoma/frame-v1/witness/phase0.receipt.json +---- + +The last step is the point of the job: in CI the tools *are* installed, so a +`not-run` is a failure rather than a degradation. + +*Accept.* A pull request that breaks G8 (edit `spec/face-b.cspec` by one +character) goes red; a pull request that touches nothing stays green; the +receipt is downloadable from the run. + +*Falsifier.* The job passes with `jq` removed, or with `verify.sh` stubbed to +`exit 0`. Both must be tried once, deliberately. + +[[A6]] +=== A6 — Retire Python from the gate path + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Why.* `mise.toml` states the estate policy — "no python, node/npm/yarn, make or +nix here" — and `vc/gen_vcs.py` is the only thing standing between the repository +and a self-contained `verify.sh`. It is also the VC generator, i.e. exactly the +component the specification says must eventually live in Ada/SPARK or +Creusot-verified Rust, not in a scripting language. + +*Method.* Two steps, in this order: + +. Port the 14 obligations to `atoma vc > ` in Zig, reusing the + canonicaliser's parser. The generator is untrusted plumbing (§1 of the spec), + so Zig is acceptable for now; the trusted path is T6. +. Delete `vc/gen_vcs.py` and make G7 call the Zig binary. Keep the Python file in + git history as the independently-written reference the Zig version is diffed + against (differential test: same `.smt2` bytes for all 14). + +*Accept.* `./verify.sh` runs G7 with `PYTHON` unset and the 14 `.smt2` files are +byte-identical to today's (digest `blake3:72c74c01…5e3698`). + +*Falsifier.* The Zig generator reproduces the files because it embeds their text. +The differential test must generate from the `.cspec` alone, and a spec mutation +must change the output. + +*Note.* If the port is judged too costly now, the alternative is an explicit, +recorded waiver in the deed naming `vc/gen_vcs.py` as an exception with a +sunset date. Silent tolerance is not an option; I11 is "no new Python in the gate +path", not "pretend the old Python is Zig". + +[[A7]] +=== A7 — Reconcile the estate status records with the claims ledger + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Why.* `docs/status/PROOF-STATUS.adoc` still reads 0 % proven, with the +template's category counts, while `docs/spec/ATOMA-SPEC.adoc` §1 records fourteen +checked claims. Two status documents that disagree are worse than one that is +incomplete: a reader picks whichever is convenient. + +*Method.* Make the specification's claims ledger the single source of truth and +turn `PROOF-STATUS.adoc` into a projection of it: one row per ledger row, the +same five status values, a pointer to the gate. Add a checker +(`scripts/check-claim-sync.sh`) that fails when a ledger row has no status row or +the two disagree on `checked`/`not checked`. + +*Accept.* `bash scripts/check-claim-sync.sh` exits 0 and the row counts agree +(14 checked, 5 not checked at revision 1). + +*Falsifier.* Flip one ledger row to `checked` without touching PROOF-STATUS and +confirm the checker fails. If it passes, it is comparing prose, not claims. + +*Blocked by.* None, but it is best done after A1 so the mint does not overwrite +`PROOF-STATUS.adoc`. + +[[track-k]] +== Track K — The kernel chain + +This is the only track that can move the status from `Warrant` to `Receipt`, and +it needs software that is not installed here. Read it as a dependency-ordered +queue: each task ends in an artefact the next one consumes. + +[[K1]] +=== K1 — Spike: measure ECHIDNA's export surface + +*Status:* `blocked` (needs `echidna`) · *Size:* S · *Owner:* agent, time-boxed 1 day + +*Why.* The specification's claim is that Atoma *reuses* ECHIDNA rather than +building its own runner. That claim is only meaningful if ECHIDNA can hand back +an Alethe proof for a QF_BV/QF_ABV query and turn it into Dedukti. Nobody has +measured that on this repository's obligations. + +*Method.* Install ECHIDNA, dispatch one obligation (`V1_no_underflow`) through +it, and write `docs/integration/ECHIDNA.adoc` recording: the exact invocation, +the Alethe artefact's digest, whether Dedukti export exists and in what form, and +what the exchange format requires of the input. Time-box: if the surface is not +usable in a day, stop and write down why — that is a finding, not a failure. + +*Accept.* A document exists containing one copy-pasteable command that produces +an Alethe file for `V1_no_underflow`, with its digest. + +*Falsifier.* The recorded command requires patching ECHIDNA. If it does, the +dependency is not one-way and I5 is at risk; record it as a finding for the owner. + +[[K2]] +=== K2 — Design the `.dk` encoding of an obligation + +*Status:* `blocked` (needs K1) · *Size:* M · *Owner:* agent + +*Why.* A `.dk` file that typechecks but does not mean the obligation is worse +than none. The encoding must be written down before anything is generated. + +*Method.* In `docs/spec/DK-ENCODING.adoc`, specify how `mkObl pre goal` becomes +Dedukti: the sort of `Nat`/`BV` (follow `Bv.agda`'s `Fin 2^w` bridge), the +encoding of `≤`, `=`, `and`, `neg`, and the theorem statement shape. State +explicitly what a `.dk` acceptance *does not* prove (it proves the encoding of +the formula, not the formula's relevance to Zig). + +*Accept.* The document contains the full `.dk` text for `V1_no_underflow`, +hand-written and small enough to read. + +*Falsifier.* The `.dk` statement and the `.smt2` statement disagree on a +quantifier or a bound when both are read literally. Have a second person compare +them. + +[[K3]] +=== K3 — G12: `dkcheck` on one witness + +*Status:* `blocked` (needs K2, `dkcheck`) · *Size:* M · *Owner:* agent + +*Method.* Emit the hand-written witness from K2, run `dkcheck`, and add the gate +to `verify.sh` with the same skip-to-`not-run` discipline as G7/G11. + +*Accept.* `dkcheck` exits 0; receipt gains +`"witnesses":[{"vc":"V1_no_underflow","dk":"blake3:…","dkcheck":"ok"}]`; the +status still says `INCOMPLETE`. + +*Falsifier.* Change one numeral in the `.dk` and confirm `dkcheck` rejects it. + +[[K4]] +=== K4 — G13: two more kernels + +*Status:* `blocked` (needs K3, `coqchk`, `lean4checker`) · *Size:* L · *Owner:* agent + +*Why.* I4 is the hard rule: one kernel is a typechecker's opinion, three are a +receipt. Coq and Lean must each accept the *same* `.dk`, with zero extra axioms. + +*Method.* Use Dedukti's backends (or ECHIDNA's export path, if K1 found one) to +produce Coq and Lean sources from the `.dk`; `coqchk` the compiled `.vo` with a +printed axiom list, and `lean4checker --fresh` the Lean artefacts. Record tool +versions in the receipt — a receipt is only as good as the kernels behind it. + +*Accept.* For `V1_no_underflow`: `coqchk` prints zero non-standard axioms and +`lean4checker --fresh` accepts; the `.dk` digest is identical in all three +records. + +*Falsifier.* Introduce an axiom (`Axiom cheat : False.`) anywhere in the Coq +path and confirm the gate fails. A gate that only checks "compiles" would pass; +this one must check "compiles with zero extra axioms". + +[[K5]] +=== K5 — Batch the remaining 13 obligations + +*Status:* `blocked` (needs K4) · *Size:* M · *Owner:* agent + +*Method.* Loop K3–K4 over all 14. Expected shape: 8 UNSAT (proofs to export) and +6 SAT (counterexamples, which are *not* witnesses — they become regression +fixtures, and their models are asserted in the receipt). + +*Accept.* All 8 valid obligations have three kernel verdicts; all 6 refuted ones +have a recorded model; `vcset` digest unchanged. + +*Falsifier.* A SAT query is silently skipped because "there is no proof to +export". The count of witnesses plus counterexamples must equal 14. + +[[K6]] +=== K6 — G14: the mutation kill score + +*Status:* `blocked` (needs K5) · *Size:* L · *Owner:* agent + +*Why.* Distinct artefacts (G6) prove the mutants differ. Kill score proves the +*verifier* notices. This is the number the specification puts at ≥ 95 %. + +*Method.* `echidna mutate` each of the 11 operators against the verified +contract, run the full VC pipeline on each mutant, and record a kill matrix +(mutant × outcome). Non-equivalent mutants must be killed ≥ 95 %; vacuous ones +100 %. + +*Accept.* A table in `witness/mutation-matrix.tsv` and a score in the receipt: +`"mutants":{"applied":11,"distinct":11,"killed":n,"score":x}`. + +*Falsifier.* A mutant survives that changes an `ensures` the tests also cover — +that means the VC generator is not reading the clause. Investigate before +adjusting the score. + +[[K7]] +=== K7 — G15: receipt schema v2 and the promotion rule + +*Status:* `blocked` (needs K5) · *Size:* S · *Owner:* agent + +*Method.* Extend the receipt to `atoma.receipt.v2` with `witnesses`, `kernels`, +`tcb` and the mutation score; write the promotion rule as code, not prose: +`COMPLETE` iff every witness has `dkcheck: ok`, `coqchk: ok (axioms 0)` and +`lean4checker: ok`, and all three name the same `.dk` digest. + +*Accept.* A unit test in `tools/atoma` that promotes a synthetic receipt only +with three matching verdicts and refuses one with two. + +*Falsifier.* Delete one kernel record from the synthetic receipt; the schema test +must refuse `COMPLETE`. + +[[K8]] +=== K8 — Proof Burrower cache + +*Status:* `blocked` (needs K7) · *Size:* M · *Owner:* agent + +*Method.* Key `BLAKE3(.dk)` under `atoma.dk.v1`; value the kernel verdicts plus +the TCB identity (tool names, versions, hashes). A cache hit may skip rechecking +only when the recorded TCB matches the current one. + +*Accept.* Two consecutive CI runs: the second reports `cache-hit` and skips the +kernels; changing the Coq version forces a miss and a recheck. + +*Falsifier.* A hit with a *different* `.dk` digest. That is the only failure that +matters, and it must be tested with a doctored cache entry. + +[[K9]] +=== K9 — Badges + +*Status:* `blocked` (needs K7) · *Size:* S · *Owner:* agent + +*Method.* `atoma badge --receipt witness/phase0.receipt.json` prints a shields.io +endpoint payload naming phase, class and contract digest — never the word +"verified". `echidnabot` publishes it on the `governance-badges` branch, where +`settings.yml`'s existing endpoint badges already read from. + +*Accept.* Badge JSON contains `"message":"phase0 · warrant · f5f97a7b"` and +nothing stronger. + +*Falsifier.* A receipt without kernel verdicts produces a `receipt` badge. + +[[track-t]] +== Track T — Theory completion + +Unblocked in this environment and the highest-value work available to an agent +without ECHIDNA. Each task ends in Agda that checks under `--safe --without-K`, +and each keeps the invariant that a theorem's type states its fragment. + +[[T1]] +=== T1 — The store, and the framing lemma + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Why.* `Core.agda` is store-free because a store makes `soundness` unprovable +without a framing lemma. Stating it, rather than dodging it, is the next step; +`exec-id` then becomes a special case instead of the whole story. + +*Method.* Add `assign : Nat → Tm → Stmt` and a store `σ : Nat → Nat`. +Define `writes : Stmt → List Nat` and `reads : Fm → List Nat`, prove +`frame : disjoint (writes s) (reads pc) → ⟦ pc ⟧f σ → ⟦ pc ⟧f (exec s σ)`, +and re-prove `soundness` for the extended fragment. Keep `exec-id` as a +corollary of `frame` when the statement writes nothing. + +*Accept.* `Soundness.agda` checks; the theorem type now quantifies over the store +and carries the disjointness premise; the old store-free theorem remains as a +corollary so nothing that depended on it breaks. + +*Falsifier.* Prove `frame` by restricting `writes` to constants, or by making +`reads` empty. If the lemma holds for a statement that writes a variable the +path condition mentions, the model is wrong — test with `assert (x ≤ 5) ; x := 9`. + +[[T2]] +=== T2 — Loops + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Why.* `while e inv I dec V do s` is the construct that makes `MAX_ITERS` and +MaxPlus meaningful, and it is the one the specification promises in §3.6. + +*Method.* Add the statement, the three VCs (establishment, preservation, exit), +and termination via an explicit fuel argument — `--safe` rejects well-founded +recursion, so the fuel is a parameter, not a hack. Prove: if the invariant holds +and the variant strictly decreases on every iteration, then `run n s` is safe for +`n` iterations and the postcondition holds on exit. + +*Accept.* The extension checks; a worked loop (`while (i < len)` over the frame +payload) is proved with its invariant; the fuel theorem is stated with its bound. + +*Falsifier.* An invariant that is preserved but not strong enough to imply the +exit condition. The theorem must fail for that invariant — check by weakening it +deliberately. + +[[T3]] +=== T3 — Postconditions and error paths + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Method.* Model outcomes (`ret ok`, `err c`) and prove the two clauses of +`soundness-full` (2) and (3) for the extended fragment: `pre ∧ res = ok ⟹ φ` +and `pre ∧ res ≠ ok ⟹ ψ`. + +*Accept.* `soundness-full`'s (1)–(3) are proved; (4) and (5) remain cited from +`Lin`/`T4`. + +*Falsifier.* A postcondition that holds only because `err` is unreachable in the +model. Make an error path reachable and confirm the clause becomes non-trivial. + +[[T4]] +=== T4 — Lift linearity over the statement structure + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Why.* `Lin.agda` proves `exactly-once` for a modelled scope; `soundness-full` +needs it for *the* statement language, which currently has no `acquire`/`release`. + +*Method.* Add the two statements, give `St` a place in the configuration, and +prove `consumed-exactly-once s σ` by structural induction, reusing +`Lin.exactly-once` at the `defer`/`errdefer` boundary. + +*Accept.* Clause (4) of `soundness-full` is proved for the extended fragment. + +*Falsifier.* The proof accepts a program with two `release`s on one path. Try +`acquire ; release ; release` and confirm it is rejected by the theorem's +premise, not by a side condition nobody checks. + +[[T5]] +=== T5 — F0.1: typecheck the Idris2 contract and regenerate Face A + +*Status:* `blocked` (needs `idris2`) · *Size:* M · *Owner:* agent + +*Why.* The claims ledger is explicit that `spec/face-a.cspec` is a hand +transcription and the Idris2 module has never been compiled. Until F0.1 runs, +"Face A is the specification" is an aspiration with a hash. + +*Method.* Install Idris2 (`pack` per `mise.toml`'s note, or the release tarball), +`idris2 --typecheck abi/FrameAbi.ipkg`, then `idris2 --exec extract` (or +`putStrLn (encode frameParse)`) and diff against `spec/face-a.cspec`. Replace the +file with the real output if they differ; the seam hash will move and G5 will +confirm both faces still meet. + +*Accept.* `idris2 --typecheck` exits 0 with no `Error:` line (the estate's +`check-proofs.sh` requires both, because `idris2 --check` exits 0 on a missing +import); `spec/face-a.cspec` is generator output and carries a do-not-hand-edit +header like Face B. + +*Falsifier.* The diff is empty *because* the extractor has no `encode` and prints +nothing. Assert the output is non-empty and contains `cspec 1`. + +[[T6]] +=== T6 — The trusted VC generator (Ada/SPARK or Creusot) + +*Status:* `todo` · *Size:* XL · *Owner:* human decision, then agent + +*Why.* I2 requires proof-carrying VC generation. A6 moves the generator to Zig, +which is an improvement in policy terms but still untrusted. The end state is a +generator whose obligation-emitting function is proved, with the CLI shell +strictly outside it. + +*Method.* Decision first, recorded as an ADR: SPARK (existing toolchain in the +estate, contracts in Ada) versus Rust + Creusot (matches the Rust tooling the +estate already ships). Then port the pure function `cspec → obligation list`, and +prove: every emitted obligation's `pre`/`goal` is a formula of the fragment, and +the emitted set is a superset of the hazards `T1`'s `vc` computes. + +*Accept.* The pure core has a machine-checked contract; a differential test +against the Zig implementation on the 14 obligations and 11 mutants matches. + +*Falsifier.* The verified core is a wrapper around an unverified one. Check that +the proven function is the one the binary calls. + +[[T7]] +=== T7 — Write the refinement statement + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Why.* §6.4's non-claim is honest but un-actionable: nobody can say what closing +it would take. Stating the simulation makes it a task instead of a shrug. + +*Method.* `docs/theory/atoma/REFINEMENT.adoc`: the relation between `Stmt` and +the subset's operational semantics, which Zig lowerings are assumed to be +meaning-preserving, and the smallest set of lemmas a future mechanisation needs. +Do not prove it; specify it. + +*Accept.* A reader can name the three assumptions the pipeline rests on and point +at the line of the document that states each. + +*Falsifier.* The document proves the easy direction and leaves the hard one as +"future work" — that is the current state, restated. + +[[track-s]] +== Track S — Subset growth (Phase 2) + +Phase 2 in the specification: regions, allocators as capabilities, bounded +recursion, `Echo` types, borrows beyond the signature. + +[[S1]] +=== S1 — Region inference for `assigns` + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Method.* Compute the `assigns` set from the Zig body (writes reachable from +`export fn`) and reject a declared `assigns` that is a strict subset. This turns +`assigns` from a promise into a checked claim. + +*Accept.* A fixture that writes a region it did not declare fails `atoma check` +with a new `E-ASSIGNS-UNDER` code; the 6 example exports still pass. + +*Falsifier.* The analysis is syntactic and misses a write through a pointer +parameter. Include such a fixture in the negative corpus. + +[[S2]] +=== S2 — Allocator capabilities (MPR) + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Method.* Thread an `Allocator` value parameter through the contract as a +capability region; reject `std.heap.page_allocator` or any ambient allocator in +an export (`E-ALLOC-AMBIENT` already exists — make it a hard error with a +witness rather than a heuristic). + +*Accept.* A second worked example allocates through a caller-provided allocator +and is verified end to end. + +*Falsifier.* The allocator is passed but unused, so the fixture proves nothing; +assert the allocation is observable in the IR. + +[[S3]] +=== S3 — Bounded recursion with `@decreases` + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Method.* Extend the subset to allow recursion whose measure is structurally +smaller; emit `vc-term` obligations; reject unbounded recursion by construction +(the parser sees no measure, the checker emits `E-LOOP-UNBOUNDED`). + +*Accept.* A recursive parser over the frame body is verified, with the measure +discharged by the solver. + +*Falsifier.* A recursion whose measure is not well-founded but which the checker +accepts because the measure is syntactically decreasing. + +[[S4]] +=== S4 — Borrow checking beyond the signature + +*Status:* `todo` · *Size:* XL · *Owner:* agent + +*Method.* `ephapax`-style L1/L2 discipline over locals, not just parameters: +reject a second mutable borrow while one is live, and a read while mutated. + +*Accept.* A fixture with a double mutable borrow is rejected; the example +implementation is unchanged. + +*Falsifier.* The check passes because it only considers explicit `&mut`, not +pointer-derived aliases. Add a fixture that aliases through `@ptrCast` (already +banned) and confirm the ban fires first. + +[[S5]] +=== S5 — `Echo` types on lossy conversions + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Method.* Mark `@truncate`, error-code collapse and dropped values as `Echo` +events in the IR; a lossy conversion without a witness is a diagnostic. + +*Accept.* `V3_intcast_range`'s cast carries an `Echo` witness; a fixture that +truncates silently is rejected. + +*Falsifier.* `Echo` annotations become prose that nothing reads. + +[[S6]] +=== S6 — ZIR fingerprints as cache keys + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Method.* `atoma fingerprint ` emits the ZIR instruction-tag digest +(measured: 23 instructions for a 4-line function). Use it in the Proof Burrower +key so a structural change behind an unchanged text invalidates the cache. + +*Accept.* Two files with identical text but different `comptime` expansion have +different fingerprints. + +*Falsifier.* The fingerprint changes on every compiler patch release, making the +cache useless; pin and record the compiler identity in the key. + +[[track-c]] +== Track C — Cost, stack, secrecy (Phase 3) + +[[C1]] +=== C1 — MaxPlus bounds as VCs + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Method.* Generalise `V4_maxplus_bound`: `bound steps ` becomes a MaxPlus +expression over the contract, with `max`/`+` composition, and a VC per loop. + +*Accept.* The worked example's `MkBounds` is proved from the loop structure +rather than asserted; a wrong bound produces a counterexample. + +*Falsifier.* The bound is proved for the model but the generated code has an +extra pass; count basic blocks in the compiled object and compare. + +[[C2]] +=== C2 — Stack high-water mark (`occupancy-types`) + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Method.* A stack model with an occupancy HWM; `bound hwm ` becomes a proved +claim about the deepest frame reachable from each export. + +*Accept.* `hwm` is proved; a fixture that recurses without a bound is rejected. + +*Falsifier.* The model ignores `@frameSize`-style compiler padding and reports a +HWM that the binary exceeds. + +[[C3]] +=== C3 — Secrecy lattice (`secret-types`) + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Method.* Label sorts with a lattice; noninterference VC between public and +secret parameters; a secret-dependent branch is a violation. + +*Accept.* A fixture that branches on a secret key length is rejected. + +*Falsifier.* The analysis only looks at branches and misses secret-dependent +memory access (cache timing). Say so in the non-claims. + +[[C4]] +=== C4 — Padding secrecy + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Why.* `V6_padding_zeroed` is currently a memory-hygiene VC. If a padding byte +still holds secret data, the same VC is a *secrecy* VC and `zeroBytes` is the +fix — the specification says this; the plan makes it a gate. + +*Accept.* A fixture that leaves secret bytes in padding passes memory safety and +fails secrecy. + +*Falsifier.* The two analyses share a premise, so the secrecy check can never +fire independently. + +[[C5]] +=== C5 — Constant-time bounds for secret paths + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Method.* Data-dependent branches and table lookups on secret data become +violations; prove the comparison paths constant-time. + +*Accept.* A fixture with an early-exit comparison on secret bytes is rejected. + +*Falsifier.* A claim about `-O ReleaseFast` output that nobody checked against +the generated machine code. State the non-claim or check the object. + +[[track-h]] +== Track H — Hardening and ecosystem + +[[H1]] +=== H1 — Two more worked examples + +*Status:* `todo` · *Size:* L · *Owner:* agent + +*Why.* One example proves the pipeline exists. Three prove it generalises: a +handle lifecycle (multiple regions, `defer`/`errdefer`), a wire codec (unions +and endianness), and a callback/iterator (function pointers and reentrancy — +likely *banned*, which is itself a useful finding). + +*Accept.* Each example has its own `.cspec` pair, VCs, receipt, and a README +that states what it does not prove. + +*Falsifier.* The second example needs a feature the subset does not have, and the +feature is added silently rather than as a specification change. + +[[H2]] +=== H2 — Widen the negative corpus + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Method.* Grow `fixtures/violations.zig` from 20 diagnostics / 17 codes to one +fixture per diagnostic code (21), plus one per banned construct in spec §3. + +*Accept.* G10 asserts 21/21 coverage, and every new code has a fixture that +fails for the intended reason (not an incidental parse error). + +*Falsifier.* A fixture produces the right code by accident. `atoma check` prints +a detail string; assert the detail, not just the code. + +[[H3]] +=== H3 — Differential canonicaliser corpus + +*Status:* `todo` · *Size:* M · *Owner:* agent + +*Why.* `encode` in Idris2 and `canon.zig` are meant to agree; the ledger says the +agreement is asserted. A golden corpus makes it a test. + +*Method.* A corpus of `.cspec` inputs with expected canonical bytes; both +implementations run over it; the Idris2 side is F0.1's extractor. + +*Accept.* The corpus runs in CI on both implementations; a divergence names the +input and both outputs. + +*Falsifier.* The corpus only contains inputs both implementations already handle; +add adversarial inputs (unicode, comments, nesting, empty sets, duplicate +positional lines). + +[[H4]] +=== H4 — Reproducible receipts + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Method.* Two clean runs of `verify.sh` produce byte-identical receipts. Fix any +nondeterminism (timestamps, map iteration order, locale). + +*Accept.* `sha256sum` of two receipts matches; CI asserts it. + +*Falsifier.* Determinism achieved by removing a field that varied *because it was +information* (a real tool version). Record versions; do not drop them. + +[[H5]] +=== H5 — Documentation surfaces that a newcomer hits first + +*Status:* `todo` · *Size:* S · *Owner:* agent + +*Method.* Root `README.adoc` gets a real Atoma landing section (what it is, what +it proves today, how to run the gate, where the plan lives). `docs/README.adoc` +gains the `plan/` row. `docs/spec/README.adoc` links the ultraplan. + +*Accept.* A reader who lands on the README can reach `verify.sh` output and the +claims ledger in two clicks, and sees the current status without asking. + +*Falsifier.* The README describes the intended system in the present tense. Every +sentence about verification must name a gate or say `not yet`. + +[[H6]] +=== H6 — Release 0.2.0 + +*Status:* `todo` · *Size:* S · *Owner:* human + +*Method.* Tag `v0.2.0` when A and K are done (or `v0.1.1` for A alone); update +`CHANGELOG.adoc`, `CITATION.cff`'s version and date, and the deed's `(meta +:version …)` in one commit. + +*Accept.* Tag, changelog, citation and deed agree; the release notes state the +highest status reached with its digest. + +*Falsifier.* The release notes say "verified". They must name a phase and a +class. + +== Scheduling + +The order is a function of what is blocked. Today, in this sandbox, T is the only +track with no external dependency; A's technical tasks are unblocked but the +minting one needs the owner; K is entirely blocked on binaries. + +=== If you have one hour + +Run the gates, confirm the baseline, and claim one card: + +[source,bash] +---- +export PATH=/tmp/zv15/lib/python3.11/site-packages/ziglang:$PATH +cd examples/atoma/frame-v1 +AGDA=/tmp/zv/bin/agda PYTHON=/tmp/zv/bin/python ./verify.sh +cat witness/phase0.receipt.json +---- + +Then pick A3 (register the proofs) or T1 (the store) — both are self-contained. + +=== If you have one day + +A3, A7 and the first half of T1. That combination makes the proofs visible to +the estate's own gate and starts the only theoretical work that is not blocked. + +=== If you have one week + +A3–A7 and T1–T2, with A1/A2 handed to the owner. Expected state: the repository +is minted, CI runs the gates, `just proof-check-agda` covers five modules, and +`Soundness.agda` quantifies over a store with a proved framing lemma. + +=== Waves and the critical path + +[cols="1,3,2", options="header"] +|=== +| Wave | Tasks | Gate at the end + +| 0 (now) | T1, A3, A7, H5 | G11 extended; ledger and status agree +| 1 | T2, T3, T4, A4, A5, A6 | theory covers store + loops; CI runs `verify.sh` +| 2 | A1, A2 (owner), K1, K2 | repo is Atoma; `.dk` encoding written +| 3 | K3, K4, K5, T5 | one witness, three kernels; Face A regenerated +| 4 | K6, K7, K8, K9 | kill score; receipt v2; cache; badges +| 5 | H1, H2, H4 | a second and third example; 21/21 corpus +| 6 | S*, then C*, then H3, H6 | Phase 2 and 3 exit criteria +|=== + +Critical path to `COMPLETE (Receipt)`: K1 → K2 → K3 → K4 → K5 → K7. Everything +else can slip without moving that date; that is the property the track split +buys. + +== Blocked work and what unblocks it + +[cols="2,2,2,3", options="header"] +|=== +| Task | Blocked by | Who provides it | Workaround (and why not) + +| K1–K9 | `echidna`, `dkcheck`, Dedukti's Coq/Lean backends, `coqchk`, `lean4checker` | owner / estate | None. Hand-writing a `.dk` and calling it a witness is the failure mode I4 exists to prevent. +| T5 | `idris2` (pack or release tarball) | agent | None. A stubbed extractor would make Face A agree by construction. +| A1 | owner's identity values + `just` | owner | The agent can prepare the branch and the env file, not run the mint. +| A2 | GitHub token with repository administration | owner | Documented `gh` command is in A2. +| K6 | ECHIDNA's mutation runner | owner | The artefact-level sweep (G6) is *not* a substitute; do not report it as one. +| S4, C1–C5 | Phase 1 exit (K7) | — | Building Phase 2 on an unverified Phase 1 multiplies unverified surface. +|=== + +== Traps already paid for + +Recorded so the next agent does not pay again. Each line is a measured failure, +not a warning from a manual. + +[cols="2,1,4", options="header"] +|=== +| Trap | Where | What actually happens + +| `callconv(.C)` | Zig 0.15.2/0.16/0.17 | Rejected on all three. Use `.c`. +| `std.process.argsAlloc` | Zig ≥ 0.16 | Removed. The CLI is pinned to 0.15.2 for this one line. +| `ArrayList(T).init` | Zig ≥ 0.15 | Removed; use `.empty` / `ArrayListUnmanaged` with an explicit allocator. +| `Ast.parse` signature | Zig 0.17 | Gained `ParseOptions`; a one-line shim per release. +| Token slices | `frontend.zig` | Slices alias the parse buffer and dangle after `deinit`. This segfaulted `atoma check`. `Diag` must own its strings. +| `align` | Zig | Reserved word. Name the field `alignment`. +| `zig build-obj` + `@compileLog` | G2/G4 | Prints the log and exits 1, so "fails to compile" is not a pass/fail signal by itself; assert the error text. +| `wasm32-freestanding` + std runtime | G2 | Cannot typecheck std runtime imports; keep the verified file free of them. +| CRC-32 | `frame_parse.zig` | Double-complement bug cost four tests. The final `~` applies to the reflected accumulator, once. +| Padding holes | layout witness | Interior padding exists; a pad range list that only covers the tail is wrong. +| `_∸_`, `_++_`, `&&`, `not`, `¬` | Agda builtins | Not exported by `Agda.Builtin.*`. Define locally; do not import `Data.Nat`. +| `ite` in `Core.agda` | Agda | Collides with the `Stmt` constructor; the helper is `ifB`. +| `--safe` vs well-founded recursion | Agda | Rejected. Use an explicit fuel argument. +| `with` vs `with … in eq` | Agda | A plain `with` abstracts the scrutinee away; the `ite` case needs the equation. Cost: one compile cycle. +| Store in `soundness` | `Core.agda` | Unprovable without a framing lemma. The fragment is store-free for that reason (T1 removes the restriction properly). +| BV vs integer | SMT | `x - 12 ≤ 2^32-1` is false for `x < 12` in BV64. Carry the no-underflow premise; the toy bug is an asserted wrong constant with goal `False`. +| z3 Python API | `vc/gen_vcs.py` | `CheckSatResult` is unhashable; compare with `==`. +| SMT-LIB | `vc/*.smt2` | ASCII only; strip `—`, `→`, `∧`. +| Mutation coverage | `canon.zig` | Operators need distinct formula/set lines; 8/11 became 11/11 only after adding two `borrow` rows and a second `requires`. +| Extract vs hand-written Face B | `spec/` | They drifted (extra `requires`, unbound `forall`). Regenerate; never hand-patch. +| `{{PLACEHOLDER}}` gate | estate | 88 files fail it today; the gate is right, the repo is unminted. +| Identity in `settings.yml` | probot | Never add `name`/`description`/`private`: an earlier template renamed itself to `-REPO-` on every push. +| Repo map | `scripts/gen-repo-map.sh` | Generated; CI fails when stale. Regenerate after adding a top-level directory. +| `idris2 --check` | estate | Exits 0 on a missing import. Require exit 0 **and** no `Error:` line. +| GitHub App token | this sandbox | Contents-write only; repository settings return 403 `Resource not accessible by integration`. +|=== + +== Definitions of done + +=== A task is done when + +. The acceptance command was run and its output is quoted in the commit message + or the receipt. +. The falsifier was attempted and the failure was observed (for gates and + checkers, at least once ever, and recorded in the task card). +. Any generated artefact was regenerated (`face-b.cspec`, repo map, receipt). +. The specification's claims ledger row, if any, still says the truth. +. No new `{{PLACEHOLDER}}`, no `.md` under `docs/`, no missing SPDX header. + +=== A gate is done when + +. It fails when the thing it guards is broken — demonstrated, not assumed. +. A missing tool produces `not-run`, never `ok`. +. Its output appears in the receipt, or the receipt records why not. + +=== A receipt is honest when + +. `status_class` is `Receipt` **only** if every witness has three kernel + verdicts over one `.dk` digest (I4). +. Every `not-run` is visible and attributable to a named missing tool. +. The TCB is named: tool, version, and hash for each checker. +. The digests it cites can be recomputed by `verify.sh` on a fresh clone. + +=== A milestone is done when + +. Its exit gate is green on `main` in CI, not only locally. +. The specification has been amended in the same release if the milestone + changed a claim (I10). +. This plan's status board says `done (evidence: …)` with a commit and a gate. + +=== A specification change is done when + +. The claims ledger gains or updates a row. +. Every `§`-reference still resolves (the ledger is unnumbered front matter; the + first numbered section is Executive architecture). +. `docs/spec/ATOMA-SPEC.adoc` renders: `npx @asciidoctor/core` or any + Asciidoctor, with no new warnings; tables balanced. + +== Change protocol + +=== Branches, commits, receipts + +* Work on a branch; the session branch is `arena/4f8f5ab1-zigprove` and is + never renamed. Do not create or push other branches. +* A commit that changes a gate says which gate and quotes the new output. +* A commit that changes a claim updates the ledger in the *same* commit. +* `witness/` is committed. Build caches are not (`.zig-cache/`, `zig-out/`, + `*.agdai`, `build/`, `node_modules/`). +* Never force-push a branch others may have based work on. + +=== How to change this plan + +Add or amend a task card, keep its ID, and record the reason in the card. If the +change moves a milestone's exit gate, it needs an ADR in `docs/decisions/` and a +matching amendment to `docs/spec/ATOMA-SPEC.adoc` §10. + +[[deviations]] +=== Deviations log + +Newest first. A deviation is any place reality differs from this plan. + +[cols="1,1,4,1", options="header"] +|=== +| Date | Task | Deviation | Owner + +| 2026-10-22 | plan | Revision 1 created. `verify.sh` green through G11; K-track blocked on absent binaries; A1/A2 blocked on owner action. | agent +|=== + +== Risk register + +[cols="1,3,1,1,3", options="header"] +|=== +| ID | Risk | Likelihood | Impact | Mitigation / trigger + +| R1 | The kernel chain proves the encoding, not the program, and the gap is quietly forgotten | High | High | K2 states the limit in the document; T7 states the refinement assumptions; receipts name the class. +| R2 | Mounting pressure to mark `COMPLETE` for a demo | Medium | High | The promotion rule is code (K7), not a checklist item; the schema test refuses two kernels. +| R3 | The store-fragment theorem turns out to need an axiom | Low | High | T1's disjointness premise is the escape valve; if an axiom is needed, the fragment narrows rather than the invariant weakening. +| R4 | ECHIDNA's Dedukti export does not cover QF_BV obligations | Medium | High | K1 is a time-boxed spike precisely to find this early; the finding becomes an upstream issue, not a private fork. +| R5 | Zig churn breaks the pinned CLI | High | Medium | `.zig-version`; the 0.15→0.16 port is one line; the example builds on two releases. +| R6 | `just repo-init` rewrites something Atoma depends on | Medium | Medium | A1 runs on a branch with a backup; the diff is reviewed line by line; the gates re-run after. +| R7 | The plan rots into aspiration (dead tasks, stale statuses) | High | Medium | Status board plus the deviations log; an agent that finishes a task updates the board in the same commit. +| R8 | Second and third examples need subset features that get added silently | Medium | High | H1's falsifier: a new feature is a specification change with a ledger row, never an edit in place. +|=== + +== Open questions for the owner + +Each has a default so work does not stall. Answering one turns it into a task. + +[cols="1,4,2", options="header"] +|=== +| ID | Question | Default if unanswered + +| O1 | Is the Idris2 ABI module the single normative Face A, or may other repos in the estate declare contracts in a different shape? | Single shape; `.cspec` v1 only. +| O2 | Does A1 (minting) happen before or after the kernel chain? | Before — it unblocks CI and A7, and touches no proof. +| O3 | For T6, SPARK or Creusot? | Creusot — the estate already ships Rust tooling; revisit if `creusot` is not installable in CI. +| O4 | Is a Python waiver acceptable instead of A6's port? | No; port it. A waiver with a sunset date is the fallback. +| O5 | Which target classes must Phase 1 receipts cover? | The four G2 triples; no big-endian, no 32-bit non-wasm. +| O6 | Who signs a `COMPLETE (Receipt)` — the owner, or CI alone? | CI alone, if all three kernels are present; the receipt names the kernels, not a person. +| O7 | Does the badge live on `main` or on a `governance-badges` branch? | `governance-badges`, as `settings.yml`'s existing endpoints expect. +| O8 | Is `witness/` allowed to grow per-commit, or one receipt per release? | One per gate run, pruned to the latest per gate in `main`. +|=== + +== Appendix A — file map + +[cols="2,4", options="header"] +|=== +| Path | What lives there + +| `docs/spec/ATOMA-SPEC.adoc` | The specification: IR, subset, semantics, pipeline, worked example, roadmap, claims ledger. +| `docs/plan/ULTRAPLAN.adoc` | This file. +| `docs/integration/ECHIDNA.adoc` | (K1) the measured ECHIDNA surface. +| `docs/spec/DK-ENCODING.adoc` | (K2) obligation → `.dk`. +| `docs/theory/atoma/REFINEMENT.adoc` | (T7) the refinement statement. +| `tools/atoma/` | CLI: `canon`, `hash`, `vc-hash`, `dk-hash`, `src-hash`, `extract`, `check`, `equiv`, `mutate`, `ops`, `selftest`; `frontend.zig` holds extract and check. +| `examples/atoma/frame-v1/` | The worked example: source, faces, layout, VCs, fixtures, `verify.sh`, `witness/`. +| `verification/atoma/agda/` | `Bv`, `Lin`, `Core`, `Soundness`; `check-agda.sh` at `verification/atoma/`. +| `verification/proofs//MANIFEST` | The estate's proof registry (A3 adds four rows). +| `scripts/check-proofs.sh` | Estate proof gate; called by `just proof-check-all`. +| `.github/settings.yml` | Repository settings *without* identity keys; never add name/description. +| `witness/phase0.receipt.json` | The current receipt; the one artefact that must never lie. +|=== + +== Appendix B — command index + +[source,bash] +---- +# everything at once +cd examples/atoma/frame-v1 && ./verify.sh + +# the tool +cd tools/atoma && zig build && zig build test && ./zig-out/bin/atoma selftest + +# one gate at a time +atoma extract src/frame_parse.zig --symbol atoma_frame_parse # G8 +atoma check src/frame_parse.zig # G9 +atoma check fixtures/violations.zig # G10, exits 1 +atoma equiv spec/face-a.cspec spec/face-b.cspec # G5 +atoma mutate spec/face-a.cspec off_by_one > /tmp/m.cspec # G6; `atoma ops` lists operators +zig build-obj tools/layout_negative.zig -target wasm32-freestanding -fno-emit-bin # G4, must fail + +# metatheory +../../../verification/atoma/check-agda.sh # G11 +for m in Bv Lin Core Soundness; do agda --safe --without-K "$m.agda" || exit 1; done + +# estate +bash scripts/check-proofs.sh agda +bash scripts/check-no-placeholders.sh +bash scripts/gen-repo-map.sh --worktree +just doctor +---- + +Every command above was run in this repository on 2026-10-22 unless the task +that introduces it is marked `blocked`. A command in this appendix that fails is +a defect in the plan: fix the document in the same commit that fixes the tree. diff --git a/docs/spec/ATOMA-SPEC.adoc b/docs/spec/ATOMA-SPEC.adoc index 352d9b32..260143a4 100644 --- a/docs/spec/ATOMA-SPEC.adoc +++ b/docs/spec/ATOMA-SPEC.adoc @@ -1489,6 +1489,7 @@ program has a receipt. |=== | Path | What lives there +| `docs/plan/ULTRAPLAN.adoc` | the delivery plan: milestones, tasks, gates, blocked work | `tools/atoma/` | the CLI: `canon`, `hash`, `vc-hash`, `dk-hash`, `src-hash`, `extract`, `check`, `equiv`, `mutate`, `ops`, `selftest` | `tools/atoma/src/frontend.zig` | `extract` (doc comments → Face B) and `check` (subset diagnostics) | `examples/atoma/frame-v1/abi/` | Idris2 contract (Face A), package file, linearity negative tests diff --git a/docs/spec/README.adoc b/docs/spec/README.adoc index f549cafc..9abec573 100644 --- a/docs/spec/README.adoc +++ b/docs/spec/README.adoc @@ -12,6 +12,9 @@ example, and the phased roadmap with falsifiers and non-claims. |=== +The *delivery* counterpart is link:../plan/ULTRAPLAN.adoc[the ultraplan]: it +turns this specification's open items into ordered tasks with acceptance gates. + Start with the *claims ledger* at the top of `ATOMA-SPEC.adoc`: it states which of the document's own claims are machine-checked in this repository and which are specified only. The executable counterpart of the specification is From b146a0c08c657031fd501ad6c952dc3b015dead3 Mon Sep 17 00:00:00 2001 From: Atoma agent Date: Thu, 22 Oct 2026 16:05:11 +0000 Subject: [PATCH 5/6] vc: port the generator to Zig, and make the local gates pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The estate bans Python, and `vc/gen_vcs.py` was the only Python in the gate path. It is replaced by `atoma vc` (tools/atoma/src/vc.zig): the same 14 obligations, emitted as hand-readable SMT-LIB instead of z3 `sexpr()` dumps, byte-stable, and with no dependencies beyond the tool itself. The port is not a transliteration, and it fixes a real weakness: * the query set is now pinned to the contract — `--cspec` canonicalises it and refuses to emit anything unless the five facts the queries encode are still present verbatim (`checkContract`). G7 exercises that refusal with a drifted contract, so the binding cannot be vacuous; * the reviewed verdict table `vc/expected.tsv` is the oracle: G7 diffs it against the generator's manifest, runs z3 on the freshly generated queries and fails on any disagreement; * a committed `.smt2` the generator would not reproduce is a hard failure, so a hand-edited artefact cannot survive; * `atoma vc` gained 5 tests (20 tool tests now), and z3 is invoked directly — its exit code is 0 for both sat and unsat, so the verdict is parsed from stdout. The VC-set digest moves from blake3:72c74c01…5e3698 to blake3:dec3d833…9ce35d because the serialisation changed; the obligations, the 8-unsat/6-sat split and every verdict are unchanged. ULTRAPLAN A6 recorded byte-identity as its acceptance criterion; that was unachievable without reproducing the dump, which A6's own falsifier forbids, so the card now records what actually happened instead of being quietly rewritten. Also in this commit: * `.machine_readable/root-allow.txt`: `tools/` is an optional root entry — untrusted tool sources, outside the TCB; the trusted tree stays under `src/`. This is the step that was failing `Estate Rules`. * `docs/architecture/REPOSITORY-MAP.adoc` regenerated (byte-identical across locales; the freshness check passes). * spec, frame-v1 README, CHANGELOG and the plan updated to match, with the stale section references corrected and the receipt regenerated (status INCOMPLETE / Warrant, unchanged). Local gate status: G1–G11 pass; root-shape, no-md-in-docs, no-vlang, no-a2ml pass; all 164 tracked .adoc files render with no warnings. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .gitignore | 3 + .machine_readable/root-allow.txt | 1 + CHANGELOG.adoc | 32 ++ docs/architecture/REPOSITORY-MAP.adoc | 4 +- docs/plan/ULTRAPLAN.adoc | 76 ++-- docs/spec/ATOMA-SPEC.adoc | 20 +- examples/atoma/frame-v1/README.adoc | 2 +- .../frame-v1/vc/V1_needle_drop_requires.smt2 | 11 +- .../atoma/frame-v1/vc/V1_no_underflow.smt2 | 15 +- .../frame-v1/vc/V2_mutant_off_by_one.smt2 | 19 +- .../vc/V2_needle_drop_payload_bound.smt2 | 17 +- .../atoma/frame-v1/vc/V2_slice_in_bounds.smt2 | 20 +- .../atoma/frame-v1/vc/V3_intcast_range.smt2 | 19 +- .../frame-v1/vc/V3_needle_drop_ffi_bound.smt2 | 11 +- .../atoma/frame-v1/vc/V4_maxplus_bound.smt2 | 19 +- .../frame-v1/vc/V5_magic_wire_order.smt2 | 20 +- .../frame-v1/vc/V5_mutant_wrong_endian.smt2 | 20 +- .../frame-v1/vc/V6_mutant_offset_drift.smt2 | 27 +- .../atoma/frame-v1/vc/V6_padding_zeroed.smt2 | 27 +- .../frame-v1/vc/V7_post_payload_len.smt2 | 22 +- .../frame-v1/vc/V8_premise_satisfiable.smt2 | 12 +- examples/atoma/frame-v1/vc/expected.tsv | 20 + examples/atoma/frame-v1/vc/gen_vcs.py | 276 ------------ examples/atoma/frame-v1/verify.sh | 80 +++- .../frame-v1/witness/phase0.receipt.json | 2 +- examples/atoma/frame-v1/witness/vc-report.txt | 37 +- tools/atoma/src/frontend.zig | 2 +- tools/atoma/src/main.zig | 56 ++- tools/atoma/src/vc.zig | 403 ++++++++++++++++++ 29 files changed, 754 insertions(+), 519 deletions(-) create mode 100644 examples/atoma/frame-v1/vc/expected.tsv delete mode 100644 examples/atoma/frame-v1/vc/gen_vcs.py create mode 100644 tools/atoma/src/vc.zig diff --git a/.gitignore b/.gitignore index 845e0cf5..fcf96c0a 100644 --- a/.gitignore +++ b/.gitignore @@ -146,3 +146,6 @@ verification/proofs/coq/.*.aux *.agdai verification/proofs/agda/*.agdai + +# Generated VC queries (regenerated by `atoma vc`; never commit) +examples/atoma/frame-v1/vc/.gen/ diff --git a/.machine_readable/root-allow.txt b/.machine_readable/root-allow.txt index 3bb68f29..24b467e9 100644 --- a/.machine_readable/root-allow.txt +++ b/.machine_readable/root-allow.txt @@ -74,6 +74,7 @@ tests/ ?archetypes/ # template-only variation seam (ADR-0003); `just repo-init` removes it from minted repos ?.devcontainer/ # VS Code dev container spec; present only where the container capability is declared ?sonar-project.properties # only where the repo is analysed by SonarCloud +?tools/ # untrusted tool sources (CLIs, generators), outside the TCB; the trusted tree is src/ ?benches/ # Cargo-conventional at package root ?examples/ # Cargo-conventional at package root ?features/ # optional feature packs diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index 3c25a015..1aa0d4a5 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -6,6 +6,38 @@ The format is based on https://keepachangelog.com/en/1.1.0/[Keep a Changelog], and this project adheres to https://semver.org/spec/v2.0.0.html[Semantic Versioning]. +=== Atoma — Phase 0 (unreleased, 2026-10-22) + +The first executable slice of Atoma: a worked example whose Phase 0 gate runs end +to end, plus the plan for the phases after it. + +==== Added + +* `examples/atoma/frame-v1/` — the length-prefixed, CRC-protected frame parsed in + place: Idris2 ABI (Face A), Zig implementation, extracted contract (Face B), a + compiler-witnessed layout table over four ABI target classes, and `verify.sh`, + which runs gates G1–G11 and writes `witness/phase0.receipt.json`. +* `tools/atoma/` — the CLI: canonicalisation, hashing, contract extraction from + Zig doc comments, the subset checker (`E-*` diagnostics) and the VC generator. + Untrusted by construction; the trusted encoder is Idris2. +* `verification/atoma/agda/` — `Bv`, `Lin`, `Core`, `Soundness`: the soundness + theorem for the store-free core, checked under `--safe --without-K` with no + postulates and no termination pragmas. +* `docs/plan/ULTRAPLAN.adoc` — the delivery plan: 40 task cards, gates G12–G15, + and the trap table. + +==== Changed + +* The VC generator is Zig, not Python (`atoma vc`). `vc/gen_vcs.py` is deleted. + G7 regenerates the 14 queries, refuses a contract that drifted (the query set is + pinned to five canonical facts through `--cspec`) and compares each solver + verdict with the reviewed table `vc/expected.tsv`. The artefacts are now + hand-readable SMT-LIB rather than z3 `sexpr()` dumps, so the VC-set digest moved + to `blake3:dec3d833…9ce35d`; the obligations and all 14 verdicts (8 unsat, + 6 sat) are unchanged. +* `.machine_readable/root-allow.txt` — `tools/` is an optional root entry: + untrusted tool sources, outside the TCB. The trusted tree stays under `src/`. + === [Unreleased] ==== Fixed diff --git a/docs/architecture/REPOSITORY-MAP.adoc b/docs/architecture/REPOSITORY-MAP.adoc index 109ead77..4b787485 100644 --- a/docs/architecture/REPOSITORY-MAP.adoc +++ b/docs/architecture/REPOSITORY-MAP.adoc @@ -186,8 +186,8 @@ predecessors did. | - | `tools/` -| yes -| - +| optional +| untrusted tool sources (CLIs, generators), outside the TCB; the trusted tree is src/ | `verification/` | optional diff --git a/docs/plan/ULTRAPLAN.adoc b/docs/plan/ULTRAPLAN.adoc index 4d9e0601..e0c7ff88 100644 --- a/docs/plan/ULTRAPLAN.adoc +++ b/docs/plan/ULTRAPLAN.adoc @@ -111,7 +111,7 @@ digests are in `examples/atoma/frame-v1/witness/phase0.receipt.json`. | G5 | Face A and Face B canonicalise to the same bytes | `blake3:f5f97a7b…f265756` | G5 | A one-token edit diverges (equivalence is not vacuous) | `blake3:d49201f2…ffca70` | G6 | 11 mutation operators give 11 distinct artefacts | 11 applied, 11 distinct -| G7 | 14 SMT obligations discharged by z3 5.3.1 | `blake3:72c74c01…5e3698` +| G7 | 14 SMT obligations discharged by z3, 8 unsat / 6 sat | `blake3:dec3d833…9ce35d` | G8 | Face B is *extracted* from Zig, not hand-maintained | `blake3:ee4d77f0…eb2358` | G9 | The implementation is subset-clean | 6 exports, 6 contracts, 0 diagnostics | G10 | The subset checker is not vacuous | 20 diagnostics over 17 codes @@ -209,10 +209,10 @@ cp -r /tmp/agda-2.7.0.1/src/data/lib/prim \ # run everything export PATH=/tmp/zv15/lib/python3.11/site-packages/ziglang:$PATH cd examples/atoma/frame-v1 -AGDA=/tmp/zv/bin/agda PYTHON=/tmp/zv/bin/python ./verify.sh +AGDA=/tmp/zv/bin/agda ./verify.sh ---- -Expected: twelve `ok` lines (G5 prints twice), `atoma 15 tests`, and a receipt +Expected: twelve `ok` lines (G5 prints twice), `atoma 20 tests`, and a receipt whose `status` is `INCOMPLETE` and `status_class` is `Warrant`. If `agda` is not on `AGDA=`, G11 prints `not-run` — that is a correct outcome, not a failure, and the receipt says `"proof":{"status":"not-run"}`. @@ -274,7 +274,7 @@ ones this plan adds. F0.1 is the Phase 0 entry gate that has never run. | G4 | `zig build-obj tools/layout_negative.zig -target wasm32…` | **fails** | exists | G5 | `atoma equiv spec/face-a.cspec spec/face-b.cspec` | equal digests; probe diverges | exists | G6 | `atoma mutate` sweep | 11/11 distinct | exists -| G7 | `python3 vc/gen_vcs.py` | 14/14, 6 counterexamples found | exists +| G7 | `atoma vc vc/.gen --cspec spec/face-b.cspec` + z3 | 14/14, 6 counterexamples found | exists (**was** `vc/gen_vcs.py`) | G8 | `atoma extract … \| hashed` | equals `spec/face-b.cspec` | exists | G9 | `atoma check src/frame_parse.zig` | 0 diagnostics, 6 contracts | exists | G10 | `atoma check fixtures/violations.zig` | **exits 1**, ≥20 diags, ≥15 codes | exists @@ -472,7 +472,7 @@ else. A fresh clone therefore cannot run G7 or G11 without hand-built venvs, and carries them, otherwise as a pinned download with a recorded checksum. The venue matters less than the pin — `just doctor` must be able to answer PASS or FAIL for each, and `mise.lock` must make the answer the same on every machine. -Add `[env]` entries for `AGDA` (and `PYTHON`, until A6 removes it) so +Add `[env]` entries for `AGDA` so `verify.sh` finds them without a hand-built venv, then `just toolchain-refresh` to re-lock. @@ -526,34 +526,50 @@ receipt is downloadable from the run. [[A6]] === A6 — Retire Python from the gate path -*Status:* `todo` · *Size:* M · *Owner:* agent +*Status:* `done` (this branch; see the postscript — the acceptance criterion was +wrong and was replaced by a stronger one) · *Size:* M · *Owner:* agent *Why.* `mise.toml` states the estate policy — "no python, node/npm/yarn, make or -nix here" — and `vc/gen_vcs.py` is the only thing standing between the repository -and a self-contained `verify.sh`. It is also the VC generator, i.e. exactly the -component the specification says must eventually live in Ada/SPARK or +nix here" — and `vc/gen_vcs.py` was the only thing standing between the +repository and a self-contained `verify.sh`. It was also the VC generator, i.e. +exactly the component the specification says must eventually live in Ada/SPARK or Creusot-verified Rust, not in a scripting language. -*Method.* Two steps, in this order: - -. Port the 14 obligations to `atoma vc > ` in Zig, reusing the - canonicaliser's parser. The generator is untrusted plumbing (§1 of the spec), - so Zig is acceptable for now; the trusted path is T6. -. Delete `vc/gen_vcs.py` and make G7 call the Zig binary. Keep the Python file in - git history as the independently-written reference the Zig version is diffed - against (differential test: same `.smt2` bytes for all 14). - -*Accept.* `./verify.sh` runs G7 with `PYTHON` unset and the 14 `.smt2` files are -byte-identical to today's (digest `blake3:72c74c01…5e3698`). - -*Falsifier.* The Zig generator reproduces the files because it embeds their text. -The differential test must generate from the `.cspec` alone, and a spec mutation -must change the output. - -*Note.* If the port is judged too costly now, the alternative is an explicit, -recorded waiver in the deed naming `vc/gen_vcs.py` as an exception with a -sunset date. Silent tolerance is not an option; I11 is "no new Python in the gate -path", not "pretend the old Python is Zig". +*Method as executed.* + +. Port the 14 obligations into `tools/atoma/src/vc.zig`, exposed as + `atoma vc [--cspec FILE]`. The generator is untrusted plumbing (§1 of + the spec), so Zig is acceptable for now; the trusted path remains T6. +. Delete `vc/gen_vcs.py`. G7 now runs the Zig binary, then z3, then compares each + verdict with the reviewed table `vc/expected.tsv`. +. Bind the generator to the contract: `--cspec` canonicalises the contract and + refuses to emit anything unless the five facts the queries encode are still + present verbatim (`checkContract` in `vc.zig`). G7 exercises that refusal with + a deliberately drifted contract, so the binding cannot be vacuous. + +*Postscript — the original acceptance criterion was unachievable, and that was +informative.* It asked for the 14 `.smt2` files to be byte-identical to the +Python-era ones. They could not be: those files were `z3`'s `sexpr()` dump of a +Python-built AST (`(let ((?x60 …))`) — machine-specific variable numbering, not +reviewable text — so byte-identity would have required reproducing the dump, +which is what the card's own falsifier forbids ("reproduces the files because it +embeds their text"). The honest resolution was to change the artefact: the Zig +generator emits hand-readable SMT-LIB, so the VC-set digest necessarily moved +from `blake3:72c74c01…5e3698` to `blake3:dec3d833…9ce35d`. The obligations, +the 8/6 unsat-sat split and every verdict are unchanged. The stale-digest check +in G7 (`cmp` against regenerated output) is what makes this safe going forward: +a `.smt2` in the tree that the generator would not produce is a hard failure. + +*Accept (as achieved).* `./verify.sh` runs G7 with no Python on PATH; 14/14 +verdicts match `vc/expected.tsv`; a drifted contract is rejected; a hand-edited +`.smt2` fails the gate. + +*Falsifier, re-run.* Mutating `requires ( <= 12 ( len input ) )` to `<= 11` +stops generation with `CONTRACT-DRIFT` and exit 1. Embedding the query text +instead of deriving it would still pass the `cmp` check — the residual weakness, +recorded here rather than hidden: the queries are derived from the *contract +facts*, but the obligations themselves are still hand-derived from §7, not +computed from a core IR. T6 is where that gap closes. [[A7]] === A7 — Reconcile the estate status records with the claims ledger @@ -1168,7 +1184,7 @@ Run the gates, confirm the baseline, and claim one card: ---- export PATH=/tmp/zv15/lib/python3.11/site-packages/ziglang:$PATH cd examples/atoma/frame-v1 -AGDA=/tmp/zv/bin/agda PYTHON=/tmp/zv/bin/python ./verify.sh +AGDA=/tmp/zv/bin/agda ./verify.sh cat witness/phase0.receipt.json ---- diff --git a/docs/spec/ATOMA-SPEC.adoc b/docs/spec/ATOMA-SPEC.adoc index 260143a4..162e62e2 100644 --- a/docs/spec/ATOMA-SPEC.adoc +++ b/docs/spec/ATOMA-SPEC.adoc @@ -69,7 +69,7 @@ here is a claim of full functional correctness for Zig. | The 14 SMT obligations of the worked example are valid | *checked* (when z3 present) | gate G7: 14/14, including 6 counterexample-producing queries -| G7 fails if any query returns an unexpected result +| G7 fails if any query disagrees with `vc/expected.tsv`, if a committed `.smt2` is stale, or if the generator accepts a drifted contract | Linear handles are released exactly once on every path | *checked* (model-level) @@ -776,7 +776,7 @@ checker accepts it or if the code coverage drops (measured: 20 diagnostics, What the checker cannot see is as important as what it can. It does not resolve names, evaluate `comptime`, compute layout, or reason about data flow; those come -from the compiler witness (§5.2) and the VC pipeline (§7). A green `atoma check` +from the compiler witness (§3.4) and the VC pipeline (§7). A green `atoma check` means "nothing on the ban list appears", never "this function is correct". == Semantics and soundness @@ -956,9 +956,10 @@ mechanisation in Phase 2 would have to cover. What the theorem buys meanwhile is still concrete: the *generator* is proved sound, so a false "discharged" verdict cannot come from `vc` emitting the wrong obligation. It can come from the solver, from the encoding of a VC into SMT-LIB, or from the refinement step — and each of -those is separately attacked (§7.2 for the encoding traps, the independently -written `vc/gen_vcs.py` for the re-derivation, G7's six counterexample-producing -queries for the solver). +those is separately attacked: §7.2 for the encoding traps; `atoma vc`, which was +rewritten from scratch in Zig against a reviewed expectation table +(`vc/expected.tsv`) and refuses to emit anything for a contract that drifted, for +the re-derivation; and G7's six counterexample-producing queries for the solver. === Why the Agda side is restricted @@ -1237,7 +1238,7 @@ Fourteen obligations, generated and discharged by z3 from the `.smt2` artefacts |=== The whole VC set has one content address, -`blake3:72c74c012d527feab0988225098a7a110e35252794c67848ab13f010c75e3698`. +`blake3:dec3d83389ef29f4ec5d49805ba527f92fef6224b0613a98393ed7f1c69ce35d`. Eight queries are *discharged* (unsat: the obligation holds); six are *counterexample-producing* (sat: either a deliberately weakened premise, or a deliberate bug, with a model that names the failure). @@ -1467,7 +1468,7 @@ atoma equiv spec/face-a.cspec spec/face-b.cspec # G5 atoma extract src/frame_parse.zig --symbol atoma_frame_parse # G8 atoma check src/frame_parse.zig # G9 atoma check fixtures/violations.zig # G10, must exit 1 -python3 vc/gen_vcs.py # G7 +atoma vc vc/.gen --cspec spec/face-b.cspec # G7 (then z3) # metatheory (G11) — four modules, --safe --without-K, no postulates ../../../verification/atoma/check-agda.sh @@ -1490,13 +1491,14 @@ program has a receipt. | Path | What lives there | `docs/plan/ULTRAPLAN.adoc` | the delivery plan: milestones, tasks, gates, blocked work -| `tools/atoma/` | the CLI: `canon`, `hash`, `vc-hash`, `dk-hash`, `src-hash`, `extract`, `check`, `equiv`, `mutate`, `ops`, `selftest` +| `tools/atoma/` | the CLI: `canon`, `hash`, `vc-hash`, `dk-hash`, `src-hash`, `extract`, `check`, `vc`, `equiv`, `mutate`, `ops`, `selftest` | `tools/atoma/src/frontend.zig` | `extract` (doc comments → Face B) and `check` (subset diagnostics) +| `tools/atoma/src/vc.zig` | `vc`: the 14 SMT-LIB queries, pinned to the contract by `checkContract` | `examples/atoma/frame-v1/abi/` | Idris2 contract (Face A), package file, linearity negative tests | `examples/atoma/frame-v1/spec/` | Face A and Face B `.cspec`, witnessed layout table | `examples/atoma/frame-v1/src/` | `frame_parse.zig` (the verified function), `atoma.zig` (trusted runtime primitives) | `examples/atoma/frame-v1/tools/` | layout witness, layout oracle, negative fixture, `layout.sh` -| `examples/atoma/frame-v1/vc/` | VC generator and 14 `.smt2` artefacts +| `examples/atoma/frame-v1/vc/` | 14 `.smt2` artefacts (generated by `atoma vc`, never hand-edited) + `expected.tsv`, the reviewed verdict table | `examples/atoma/frame-v1/fixtures/` | `violations.zig`, the negative corpus G10 rejects | `examples/atoma/frame-v1/witness/` | the Phase 0 receipt, the VC/subset/violations reports | `verification/atoma/agda/` | `Bv.agda` (bitvector bridge), `Lin.agda` (linear cleanup), `Core.agda` (language + VC generator), `Soundness.agda` (the §6.3 theorem) diff --git a/examples/atoma/frame-v1/README.adoc b/examples/atoma/frame-v1/README.adoc index 7bcad78b..9beb6d9a 100644 --- a/examples/atoma/frame-v1/README.adoc +++ b/examples/atoma/frame-v1/README.adoc @@ -17,7 +17,7 @@ directory is the executable part of `docs/spec/ATOMA-SPEC.adoc` §8. | (b) Zig implementation | `src/frame_parse.zig`, `src/atoma.zig` (trusted runtime primitives) | (c) Verification conditions -| `vc/gen_vcs.py` → `vc/*.smt2` (14 artefacts) +| `atoma vc` → `vc/*.smt2` (14 artefacts, regenerated by G7; never hand-edited) + `vc/expected.tsv` | (d) Failure analysis | §8.4 of the spec, backed by the `*_mutant_*` and `*_needle_*` queries | (e) Subset checker and extractor diff --git a/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 b/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 index dfc3ecfb..f495a69d 100644 --- a/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 +++ b/examples/atoma/frame-v1/vc/V1_needle_drop_requires.smt2 @@ -1,11 +1,8 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V1_needle_drop_requires (arith) +; generated by `atoma vc` - V1_needle_drop_requires (arith) ; without `len >= 12` the subtraction underflows: model is the panic ; expected: SAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(assert - (let (($x7 (bvule (_ bv12 32) buf_len))) -(not $x7))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(assert (not (bvule #x0000000c buf_len))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 b/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 index 346d0d07..8a0a9e6a 100644 --- a/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 +++ b/examples/atoma/frame-v1/vc/V1_no_underflow.smt2 @@ -1,14 +1,9 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V1_no_underflow (arith) +; generated by `atoma vc` - V1_no_underflow (arith) ; `buf.len - 12` cannot wrap once len >= 12 is known ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(assert - (let (($x7 (bvule (_ bv12 32) buf_len))) - (and $x7))) -(assert - (let (($x9 (bvule (_ bv0 32) (_ bv0 32)))) -(not $x9))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(assert (bvule #x0000000c buf_len)) +(assert (not (bvule #x0000000c buf_len))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 b/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 index cf765f17..7128977d 100644 --- a/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 +++ b/examples/atoma/frame-v1/vc/V2_mutant_off_by_one.smt2 @@ -1,16 +1,11 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V2_mutant_off_by_one (bounds) +; generated by `atoma vc` - V2_mutant_off_by_one (bounds) ; `avail + 1` admits exactly one byte past the end: off-by-one ; expected: SAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(declare-fun length () (_ BitVec 32)) -(assert - (let (($x17 (bvule length (bvadd (bvsub buf_len (_ bv12 32)) (_ bv1 32))))) - (let (($x7 (bvule (_ bv12 32) buf_len))) - (and $x7 $x17)))) -(assert - (let (($x14 (bvule (bvadd (_ bv12 32) length) buf_len))) -(not $x14))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(declare-const length (_ BitVec 32)) +(assert (bvule #x0000000c buf_len)) +(assert (bvule length (bvadd (bvsub buf_len #x0000000c) #x00000001))) +(assert (not (bvule (bvadd #x0000000c length) buf_len))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 b/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 index 51affdf6..c371ef8a 100644 --- a/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 +++ b/examples/atoma/frame-v1/vc/V2_needle_drop_payload_bound.smt2 @@ -1,15 +1,10 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V2_needle_drop_payload_bound (bounds) +; generated by `atoma vc` - V2_needle_drop_payload_bound (bounds) ; a frame claiming more bytes than the buffer holds slices out of bounds ; expected: SAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(declare-fun length () (_ BitVec 32)) -(assert - (let (($x7 (bvule (_ bv12 32) buf_len))) - (and $x7))) -(assert - (let (($x14 (bvule (bvadd (_ bv12 32) length) buf_len))) -(not $x14))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(declare-const length (_ BitVec 32)) +(assert (bvule #x0000000c buf_len)) +(assert (not (bvule (bvadd #x0000000c length) buf_len))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 b/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 index 503dccc6..ea36ae44 100644 --- a/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 +++ b/examples/atoma/frame-v1/vc/V2_slice_in_bounds.smt2 @@ -1,17 +1,11 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V2_slice_in_bounds (bounds) +; generated by `atoma vc` - V2_slice_in_bounds (bounds) ; 12 + length <= buf.len, so buf[12 .. 12+length] is in bounds ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(declare-fun length () (_ BitVec 32)) -(assert - (let ((?x11 (bvsub buf_len (_ bv12 32)))) - (let (($x12 (bvule length ?x11))) - (let (($x7 (bvule (_ bv12 32) buf_len))) - (and $x7 $x12))))) -(assert - (let (($x14 (bvule (bvadd (_ bv12 32) length) buf_len))) -(not $x14))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(declare-const length (_ BitVec 32)) +(assert (bvule #x0000000c buf_len)) +(assert (bvule length (bvsub buf_len #x0000000c))) +(assert (not (bvule (bvadd #x0000000c length) buf_len))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 b/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 index 14a0f14d..e6a93809 100644 --- a/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 +++ b/examples/atoma/frame-v1/vc/V3_intcast_range.smt2 @@ -1,15 +1,10 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V3_intcast_range (cast) -; a slice obtained from a u32 in_len is at most 2^32-1 bytes and at least 12, so the usize-to-u32 @intCast cannot trap +; generated by `atoma vc` - V3_intcast_range (cast) +; a slice from a u32 in_len is at most 2^32-1 bytes and at least 12, so the usize-to-u32 @intCast cannot trap ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len_usize () (_ BitVec 64)) -(assert - (let (($x22 (bvule buf_len_usize (_ bv4294967295 64)))) - (let (($x20 (bvule (_ bv12 64) buf_len_usize))) - (and $x20 $x22)))) -(assert - (let (($x24 (bvule (bvsub buf_len_usize (_ bv12 64)) (_ bv4294967295 64)))) -(not $x24))) +(set-logic QF_BV) +(declare-const buf_len_usize (_ BitVec 64)) +(assert (bvule #x000000000000000c buf_len_usize)) +(assert (bvule buf_len_usize #x00000000ffffffff)) +(assert (not (bvule (bvsub buf_len_usize #x000000000000000c) #x00000000ffffffff))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 b/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 index f31913b1..33bc5d8c 100644 --- a/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 +++ b/examples/atoma/frame-v1/vc/V3_needle_drop_ffi_bound.smt2 @@ -1,11 +1,8 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V3_needle_drop_ffi_bound (cast) +; generated by `atoma vc` - V3_needle_drop_ffi_bound (cast) ; called directly with a >4GiB slice, the same @intCast panics ; expected: SAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len_usize () (_ BitVec 64)) -(assert - (let (($x24 (bvule (bvsub buf_len_usize (_ bv12 64)) (_ bv4294967295 64)))) -(not $x24))) +(set-logic QF_BV) +(declare-const buf_len_usize (_ BitVec 64)) +(assert (not (bvule (bvsub buf_len_usize #x000000000000000c) #x00000000ffffffff))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 b/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 index 104b022c..e33be3a1 100644 --- a/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 +++ b/examples/atoma/frame-v1/vc/V4_maxplus_bound.smt2 @@ -1,16 +1,11 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V4_maxplus_bound (cost) +; generated by `atoma vc` - V4_maxplus_bound (cost) ; 8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus bound is representable in the cost domain ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun payload_len () (_ BitVec 32)) -(declare-fun steps () (_ BitVec 32)) -(assert - (let (($x32 (bvule steps (bvadd (bvmul (_ bv8 32) payload_len) (_ bv12 32))))) - (let (($x28 (bvule payload_len (_ bv65535 32)))) - (and $x28 $x32)))) -(assert - (let (($x35 (bvule steps (bvadd (bvmul (_ bv8 32) (_ bv65535 32)) (_ bv12 32))))) -(not $x35))) +(set-logic QF_BV) +(declare-const steps (_ BitVec 32)) +(declare-const payload_len (_ BitVec 32)) +(assert (bvule payload_len #x0000ffff)) +(assert (bvule steps (bvadd (bvmul #x00000008 payload_len) #x0000000c))) +(assert (not (bvule steps (bvadd (bvmul #x00000008 #x0000ffff) #x0000000c)))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 b/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 index 17e0e851..59fe549d 100644 --- a/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 +++ b/examples/atoma/frame-v1/vc/V5_magic_wire_order.smt2 @@ -1,17 +1,11 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V5_magic_wire_order (abi) +; generated by `atoma vc` - V5_magic_wire_order (abi) ; bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' on the wire ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun byte1 () (_ BitVec 8)) -(declare-fun byte0 () (_ BitVec 8)) -(assert - (let (($x46 (= (_ bv84 8) byte1))) - (let (($x44 (= (_ bv65 8) byte0))) - (and $x44 $x46)))) -(assert - (let ((?x42 (bvor ((_ zero_extend 8) byte0) (bvshl ((_ zero_extend 8) byte1) (_ bv8 16))))) -(let (($x48 (= (_ bv21569 16) ?x42))) -(not $x48)))) +(set-logic QF_BV) +(declare-const byte0 (_ BitVec 8)) +(declare-const byte1 (_ BitVec 8)) +(assert (= byte0 #x41)) +(assert (= byte1 #x54)) +(assert (not (= (bvor (concat #x00 byte0) (bvshl (concat #x00 byte1) #x0008)) #x5441))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 b/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 index 3a8e890f..b745ea98 100644 --- a/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 +++ b/examples/atoma/frame-v1/vc/V5_mutant_wrong_endian.smt2 @@ -1,17 +1,11 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V5_mutant_wrong_endian (abi) +; generated by `atoma vc` - V5_mutant_wrong_endian (abi) ; 0x4154 is refuted by the same bytes: the literal ASCII word is wrong ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun byte1 () (_ BitVec 8)) -(declare-fun byte0 () (_ BitVec 8)) -(assert - (let ((?x42 (bvor ((_ zero_extend 8) byte0) (bvshl ((_ zero_extend 8) byte1) (_ bv8 16))))) - (let (($x50 (= (_ bv16724 16) ?x42))) - (let (($x46 (= (_ bv84 8) byte1))) - (let (($x44 (= (_ bv65 8) byte0))) - (and $x44 $x46 $x50)))))) -(assert - (not false)) +(set-logic QF_BV) +(declare-const byte0 (_ BitVec 8)) +(declare-const byte1 (_ BitVec 8)) +(assert (= byte0 #x41)) +(assert (= byte1 #x54)) +(assert (= (bvor (concat #x00 byte0) (bvshl (concat #x00 byte1) #x0008)) #x4154)) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 b/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 index b34437a6..ee25da8a 100644 --- a/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 +++ b/examples/atoma/frame-v1/vc/V6_mutant_offset_drift.smt2 @@ -1,16 +1,19 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V6_mutant_offset_drift (layout) +; generated by `atoma vc` - V6_mutant_offset_drift (layout) ; a payload placed at offset 12 writes into the padding hole 12..16: the padding VC catches layout drift ; expected: SAT -; benchmark generated from python API -(set-info :status unknown) -(assert - (let ((?x60 (store (store (store (store ((as const (Array (_ BitVec 32) (_ BitVec 8))) (_ bv0 8)) (_ bv0 32) (_ bv170 8)) (_ bv1 32) (_ bv170 8)) (_ bv2 32) (_ bv170 8)) (_ bv3 32) (_ bv170 8)))) -(let ((?x67 (store (store (store (store ?x60 (_ bv4 32) (_ bv170 8)) (_ bv5 32) (_ bv170 8)) (_ bv8 32) (_ bv170 8)) (_ bv9 32) (_ bv170 8)))) -(let ((?x71 (store (store ?x67 (_ bv10 32) (_ bv170 8)) (_ bv11 32) (_ bv170 8)))) -(let ((?x129 (store (store (store (store ?x71 (_ bv12 32) (_ bv170 8)) (_ bv13 32) (_ bv170 8)) (_ bv14 32) (_ bv170 8)) (_ bv15 32) (_ bv170 8)))) -(let ((?x133 (store (store (store (store ?x129 (_ bv16 32) (_ bv170 8)) (_ bv17 32) (_ bv170 8)) (_ bv18 32) (_ bv170 8)) (_ bv19 32) (_ bv170 8)))) -(let ((?x137 (store (store (store (store ?x133 (_ bv24 32) (_ bv170 8)) (_ bv25 32) (_ bv170 8)) (_ bv26 32) (_ bv170 8)) (_ bv27 32) (_ bv170 8)))) -(let (($x146 (and (= (_ bv0 8) (select ?x137 (_ bv12 32))) (= (_ bv0 8) (select ?x137 (_ bv13 32))) (= (_ bv0 8) (select ?x137 (_ bv14 32))) (= (_ bv0 8) (select ?x137 (_ bv15 32)))))) -(not $x146))))))))) +(set-logic QF_ABV) +(define-fun S () (Array (_ BitVec 32) (_ BitVec 8)) + (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store ((as const (Array (_ BitVec 32) (_ BitVec 8))) #x00) #x00000000 #xAA) #x00000001 #xAA) #x00000002 #xAA) #x00000003 #xAA) #x00000004 #xAA) #x00000005 #xAA) #x00000008 #xAA) #x00000009 #xAA) #x0000000A #xAA) #x0000000B #xAA) #x0000000C #xAA) #x0000000D #xAA) #x0000000E #xAA) #x0000000F #xAA) #x00000010 #xAA) #x00000011 #xAA) #x00000012 #xAA) #x00000013 #xAA) #x00000018 #xAA) #x00000019 #xAA) #x0000001A #xAA) #x0000001B #xAA)) +(assert (not (and + (= (select S #x00000006) #x00) + (= (select S #x00000007) #x00) + (= (select S #x0000000C) #x00) + (= (select S #x0000000D) #x00) + (= (select S #x0000000E) #x00) + (= (select S #x0000000F) #x00) + (= (select S #x0000001C) #x00) + (= (select S #x0000001D) #x00) + (= (select S #x0000001E) #x00) + (= (select S #x0000001F) #x00)))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 b/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 index 9c541c08..1f58e31a 100644 --- a/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 +++ b/examples/atoma/frame-v1/vc/V6_padding_zeroed.smt2 @@ -1,16 +1,19 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V6_padding_zeroed (layout) +; generated by `atoma vc` - V6_padding_zeroed (layout) ; writes hit only field bytes, so every padding byte keeps the 0x00 it got from zeroBytes ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(assert - (let ((?x60 (store (store (store (store ((as const (Array (_ BitVec 32) (_ BitVec 8))) (_ bv0 8)) (_ bv0 32) (_ bv170 8)) (_ bv1 32) (_ bv170 8)) (_ bv2 32) (_ bv170 8)) (_ bv3 32) (_ bv170 8)))) -(let ((?x67 (store (store (store (store ?x60 (_ bv4 32) (_ bv170 8)) (_ bv5 32) (_ bv170 8)) (_ bv8 32) (_ bv170 8)) (_ bv9 32) (_ bv170 8)))) -(let ((?x71 (store (store ?x67 (_ bv10 32) (_ bv170 8)) (_ bv11 32) (_ bv170 8)))) -(let ((?x79 (store (store (store (store ?x71 (_ bv16 32) (_ bv170 8)) (_ bv17 32) (_ bv170 8)) (_ bv18 32) (_ bv170 8)) (_ bv19 32) (_ bv170 8)))) -(let ((?x87 (store (store (store (store ?x79 (_ bv20 32) (_ bv170 8)) (_ bv21 32) (_ bv170 8)) (_ bv22 32) (_ bv170 8)) (_ bv23 32) (_ bv170 8)))) -(let ((?x95 (store (store (store (store ?x87 (_ bv24 32) (_ bv170 8)) (_ bv25 32) (_ bv170 8)) (_ bv26 32) (_ bv170 8)) (_ bv27 32) (_ bv170 8)))) -(let (($x125 (and (= (_ bv0 8) (select ?x95 (_ bv6 32))) (= (_ bv0 8) (select ?x95 (_ bv7 32))) (= (_ bv0 8) (select ?x95 (_ bv12 32))) (= (_ bv0 8) (select ?x95 (_ bv13 32))) (= (_ bv0 8) (select ?x95 (_ bv14 32))) (= (_ bv0 8) (select ?x95 (_ bv15 32))) (= (_ bv0 8) (select ?x95 (_ bv28 32))) (= (_ bv0 8) (select ?x95 (_ bv29 32))) (= (_ bv0 8) (select ?x95 (_ bv30 32))) (= (_ bv0 8) (select ?x95 (_ bv31 32)))))) -(not $x125))))))))) +(set-logic QF_ABV) +(define-fun S () (Array (_ BitVec 32) (_ BitVec 8)) + (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store (store ((as const (Array (_ BitVec 32) (_ BitVec 8))) #x00) #x00000000 #xAA) #x00000001 #xAA) #x00000002 #xAA) #x00000003 #xAA) #x00000004 #xAA) #x00000005 #xAA) #x00000008 #xAA) #x00000009 #xAA) #x0000000A #xAA) #x0000000B #xAA) #x00000010 #xAA) #x00000011 #xAA) #x00000012 #xAA) #x00000013 #xAA) #x00000014 #xAA) #x00000015 #xAA) #x00000016 #xAA) #x00000017 #xAA) #x00000018 #xAA) #x00000019 #xAA) #x0000001A #xAA) #x0000001B #xAA)) +(assert (not (and + (= (select S #x00000006) #x00) + (= (select S #x00000007) #x00) + (= (select S #x0000000C) #x00) + (= (select S #x0000000D) #x00) + (= (select S #x0000000E) #x00) + (= (select S #x0000000F) #x00) + (= (select S #x0000001C) #x00) + (= (select S #x0000001D) #x00) + (= (select S #x0000001E) #x00) + (= (select S #x0000001F) #x00)))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 b/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 index 7d66d26a..f68b2bf2 100644 --- a/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 +++ b/examples/atoma/frame-v1/vc/V7_post_payload_len.smt2 @@ -1,20 +1,10 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V7_post_payload_len (post) +; generated by `atoma vc` - V7_post_payload_len (post) ; the success postcondition follows from the guard that produced success ; expected: UNSAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(declare-fun length () (_ BitVec 32)) -(assert - (let (($x7 (bvule (_ bv12 32) buf_len))) - (and $x7))) -(assert - (let ((?x11 (bvsub buf_len (_ bv12 32)))) -(let (($x149 (bvule (ite (and (bvule (_ bv12 32) buf_len) (bvule length ?x11)) length (_ bv0 32)) ?x11))) -(let (($x12 (bvule length ?x11))) -(let (($x7 (bvule (_ bv12 32) buf_len))) -(let (($x147 (and $x7 $x12))) -(let (($x150 (=> $x147 $x149))) -(not $x150)))))))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(declare-const length (_ BitVec 32)) +(assert (bvule #x0000000c buf_len)) +(assert (not (=> (and (bvule #x0000000c buf_len) (bvule length (bvsub buf_len #x0000000c))) (bvule (ite (and (bvule #x0000000c buf_len) (bvule length (bvsub buf_len #x0000000c))) length #x00000000) (bvsub buf_len #x0000000c))))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 b/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 index 7d3d1589..4808df7d 100644 --- a/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 +++ b/examples/atoma/frame-v1/vc/V8_premise_satisfiable.smt2 @@ -1,12 +1,8 @@ ; SPDX-License-Identifier: MPL-2.0 -; generated by gen_vcs.py - V8_premise_satisfiable (vacuity) +; generated by `atoma vc` - V8_premise_satisfiable (vacuity) ; a contradictory precondition would make every VC trivially UNSAT, so satisfiability of the premises is a VC in its own right ; expected: SAT -; benchmark generated from python API -(set-info :status unknown) -(declare-fun buf_len () (_ BitVec 32)) -(assert - (let (($x7 (bvule (_ bv12 32) buf_len))) -(let (($x153 (and $x7 (bvule buf_len (_ bv4294967295 32))))) -(not $x153)))) +(set-logic QF_BV) +(declare-const buf_len (_ BitVec 32)) +(assert (and (bvule #x0000000c buf_len) (bvule buf_len #xffffffff))) (check-sat) diff --git a/examples/atoma/frame-v1/vc/expected.tsv b/examples/atoma/frame-v1/vc/expected.tsv new file mode 100644 index 00000000..3a10df94 --- /dev/null +++ b/examples/atoma/frame-v1/vc/expected.tsv @@ -0,0 +1,20 @@ +# Reviewed expectation table for the frame-v1 VC set. +# Format: . Generated by `atoma vc` +# ; `verify.sh` G7 diffs it against the generator manifest and runs every +# query through z3, so an edited expectation is a reviewed diff and a +# generator that disagrees with the review fails the gate. +# name expected +V1_no_underflow unsat +V1_needle_drop_requires sat +V2_slice_in_bounds unsat +V2_needle_drop_payload_bound sat +V2_mutant_off_by_one sat +V3_intcast_range unsat +V3_needle_drop_ffi_bound sat +V4_maxplus_bound unsat +V5_magic_wire_order unsat +V5_mutant_wrong_endian unsat +V6_padding_zeroed unsat +V6_mutant_offset_drift sat +V7_post_payload_len unsat +V8_premise_satisfiable sat diff --git a/examples/atoma/frame-v1/vc/gen_vcs.py b/examples/atoma/frame-v1/vc/gen_vcs.py deleted file mode 100644 index 6067dc56..00000000 --- a/examples/atoma/frame-v1/vc/gen_vcs.py +++ /dev/null @@ -1,276 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: MPL-2.0 -# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell -"""gen_vcs.py - build, emit and discharge the frame-v1 verification conditions. - -This is the *untrusted* VC generator for the worked example. What it emits is a -set of SMT-LIB QF_BV / QF_ABV queries; what it proves is whatever z3 proves -about those queries. Every file it writes is re-parsed from disk before being -checked, so the checked artifact and the stored artifact are byte-identical. - -Two families of query are produced for each obligation: - - positive premises /\\ not goal must be UNSAT (obligation discharged) - needle premises\P /\\ not goal must be SAT (premise P is load-bearing) - -The `needle` family is what stops a contract from being vacuously true: if a -precondition can be deleted without turning the goal into a counterexample, the -precondition was doing no work and the mutation harness must say so. - -Run: python3 gen_vcs.py [--out DIR] exit 0 iff every expectation holds. -""" - -import argparse -import os -import sys - -try: - import z3 -except ImportError: - print("SKIP: z3 not available (pip install z3-solver)", file=sys.stderr) - sys.exit(2) - -BV8, BV16, BV32, BV64 = (z3.BitVecSort(8), z3.BitVecSort(16), - z3.BitVecSort(32), z3.BitVecSort(64)) - -HEADER_LEN = 12 -MAGIC = 0x5441 # little-endian u16 whose *bytes* are 'A' 'T' - - -class VC: - def __init__(self, name, kind, premise, goal, expect, why): - self.name, self.kind = name, kind - self.premise, self.goal = premise, goal - self.expect, self.why = expect, why - - -def bv(name, width): - return z3.BitVec(name, width) - - -def build(): - vcs = [] - - # ── V1 no underflow in `buf.len - HEADER_LEN` ────────────────────────── - n = bv("buf_len", 32) - vcs.append(VC( - "V1_no_underflow", "arith", - [z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n)], - z3.ULE(z3.BitVecVal(0, 32), z3.BitVecVal(0, 32)), # trivial goal - "unsat", - "`buf.len - 12` cannot wrap once len >= 12 is known")) - - vcs.append(VC( - "V1_needle_drop_requires", "arith", - [], # the `len >= 12` premise is removed - z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n), - "sat", - "without `len >= 12` the subtraction underflows: model is the panic")) - - # ── V2 the payload slice is in bounds ───────────────────────────────── - L = bv("length", 32) - avail = z3.BitVecVal(HEADER_LEN, 32) - p_len_ok = z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n) - p_payload = z3.ULE(L, n - z3.BitVecVal(HEADER_LEN, 32)) - vcs.append(VC( - "V2_slice_in_bounds", "bounds", - [p_len_ok, p_payload], - z3.ULE(z3.BitVecVal(HEADER_LEN, 32) + L, n), - "unsat", - "12 + length <= buf.len, so buf[12 .. 12+length] is in bounds")) - - # ── V2 needle: drop the payload bound -> out-of-bounds is reachable ───── - vcs.append(VC( - "V2_needle_drop_payload_bound", "bounds", - [p_len_ok], - z3.ULE(z3.BitVecVal(HEADER_LEN, 32) + L, n), - "sat", - "a frame claiming more bytes than the buffer holds slices out of bounds")) - - # ── V2 mutant: the off-by-one an author actually writes ──────────────── - # `if (length > avail + 1) return error.Truncated;` - vcs.append(VC( - "V2_mutant_off_by_one", "bounds", - [p_len_ok, z3.ULE(L, n - z3.BitVecVal(HEADER_LEN, 32) + z3.BitVecVal(1, 32))], - z3.ULE(z3.BitVecVal(HEADER_LEN, 32) + L, n), - "sat", - "`avail + 1` admits exactly one byte past the end: off-by-one")) - - # ── V3 @intCast of a usize slice length into u32 fits ───────────────── - N64 = bv("buf_len_usize", 64) - # NOTE: the first version of this VC had only the upper bound as a premise - # and z3 returned SAT with buf_len_usize = 0. That is correct: in BV64, - # `0 - 12` wraps to 2^64-12, which does not fit in u32. The no-underflow - # premise is load-bearing *in the bitvector encoding even though it is - # obvious in the integers*. This is the trap the spec calls out (§4.3.1): - # the same obligation needs two premises here and one in Nat. - vcs.append(VC( - "V3_intcast_range", "cast", - [z3.ULE(z3.BitVecVal(HEADER_LEN, 64), N64), - z3.ULE(N64, z3.BitVecVal(0xFFFF_FFFF, 64))], - z3.ULE(N64 - z3.BitVecVal(HEADER_LEN, 64), z3.BitVecVal(0xFFFF_FFFF, 64)), - "unsat", - "a slice obtained from a u32 in_len is at most 2^32-1 bytes and at " - "least 12, so the usize-to-u32 @intCast cannot trap")) - - vcs.append(VC( - "V3_needle_drop_ffi_bound", "cast", - [], - z3.ULE(N64 - z3.BitVecVal(HEADER_LEN, 64), z3.BitVecVal(0xFFFF_FFFF, 64)), - "sat", - "called directly with a >4GiB slice, the same @intCast panics")) - - # ── V4 MaxPlus step bound for the CRC loop ──────────────────────────── - steps, ln = bv("steps", 32), bv("payload_len", 32) - vcs.append(VC( - "V4_maxplus_bound", "cost", - [z3.ULE(ln, z3.BitVecVal(65535, 32)), - z3.ULE(steps, z3.BitVecVal(8, 32) * ln + z3.BitVecVal(HEADER_LEN, 32))], - z3.ULE(steps, z3.BitVecVal(8, 32) * z3.BitVecVal(65535, 32) + z3.BitVecVal(HEADER_LEN, 32)), - "unsat", - "8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus " - "bound is representable in the cost domain")) - - # ── V5 the magic's endianness ───────────────────────────────────────── - b0, b1 = bv("byte0", 8), bv("byte1", 8) - le16 = z3.ZeroExt(8, b0) | (z3.ZeroExt(8, b1) << 8) - vcs.append(VC( - "V5_magic_wire_order", "abi", - [b0 == z3.BitVecVal(ord('A'), 8), b1 == z3.BitVecVal(ord('T'), 8)], - le16 == z3.BitVecVal(MAGIC, 16), - "unsat", - "bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' " - "on the wire")) - - vcs.append(VC( - "V5_mutant_wrong_endian", "abi", - [b0 == z3.BitVecVal(ord('A'), 8), b1 == z3.BitVecVal(ord('T'), 8), - le16 == z3.BitVecVal(0x4154, 16)], - z3.BoolVal(False), - "unsat", - "0x4154 is refuted by the same bytes: the literal ASCII word is wrong")) - - # ── V6 padding bytes are zero after zeroBytes + field writes ─────────── - # FrameOut on 64-bit: padding 6..8, 12..16, 28..32. - A0, A1 = z3.Const("A0", z3.ArraySort(BV32, BV8)), None - zeroed = z3.K(BV32, z3.BitVecVal(0, 8)) # all bytes zero - writes = [] - for off, size in [(0, 2), (2, 2), (4, 1), (5, 1), (8, 4), (16, 8), (24, 4)]: - for k in range(size): - writes.append((off + k, z3.BitVecVal(0xAA, 8))) # arbitrary field byte - arr = zeroed - for idx, val in writes: - arr = z3.Store(arr, z3.BitVecVal(idx, 32), val) - goals = [z3.Select(arr, z3.BitVecVal(i, 32)) == z3.BitVecVal(0, 8) - for i in list(range(6, 8)) + list(range(12, 16)) + list(range(28, 32))] - vcs.append(VC( - "V6_padding_zeroed", "layout", - [], - z3.And(*goals), - "unsat", - "writes hit only field bytes, so every padding byte keeps the 0x00 it got " - "from zeroBytes")) - - # Layout drift: the same writes, but `payload` placed at offset 12 instead of - # 16 (what happens if @offsetOf for one target is transcribed wrongly, or a - # field is added without re-deriving the table). Bytes 12..16 are padding on - # 64-bit, so the padding VC must now fail. - drifted = zeroed - for off, size in [(0, 2), (2, 2), (4, 1), (5, 1), (8, 4), (12, 8), (24, 4)]: - for k in range(size): - drifted = z3.Store(drifted, z3.BitVecVal(off + k, 32), z3.BitVecVal(0xAA, 8)) - vcs.append(VC( - "V6_mutant_offset_drift", "layout", - [], - z3.And(z3.Select(drifted, z3.BitVecVal(12, 32)) == z3.BitVecVal(0, 8), - z3.Select(drifted, z3.BitVecVal(13, 32)) == z3.BitVecVal(0, 8), - z3.Select(drifted, z3.BitVecVal(14, 32)) == z3.BitVecVal(0, 8), - z3.Select(drifted, z3.BitVecVal(15, 32)) == z3.BitVecVal(0, 8)), - "sat", - "a payload placed at offset 12 writes into the padding hole 12..16: the " - "padding VC catches layout drift")) - - # ── V7 postcondition: on success payload_len <= in_len - 12 ─────────── - ok = z3.And(p_len_ok, p_payload) - out_len = z3.If(ok, L, z3.BitVecVal(0, 32)) - vcs.append(VC( - "V7_post_payload_len", "post", - [p_len_ok], - z3.Implies(ok, z3.ULE(out_len, n - z3.BitVecVal(HEADER_LEN, 32))), - "unsat", - "the success postcondition follows from the guard that produced success")) - - # ── V8 vacuity: the precondition must be satisfiable ────────────────── - vcs.append(VC( - "V8_premise_satisfiable", "vacuity", - [], - z3.And(z3.ULE(z3.BitVecVal(HEADER_LEN, 32), n), - z3.ULE(n, z3.BitVecVal(0xFFFF_FFFF, 32))), - "sat", - "a contradictory precondition would make every VC trivially UNSAT, so " - "satisfiability of the premises is a VC in its own right")) - - return vcs - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)))) - args = ap.parse_args() - os.makedirs(args.out, exist_ok=True) - # Remove VCs from a previous run so the directory is exactly this run's set. - # A stale file would otherwise leak into the aggregate content address. - for stale in os.listdir(args.out): - if stale.endswith(".smt2"): - os.remove(os.path.join(args.out, stale)) - - failures = 0 - rows = [] - for vc in build(): - s = z3.Solver() - if vc.premise: - s.add(vc.premise if isinstance(vc.premise, z3.BoolRef) else z3.And(*vc.premise)) - s.add(z3.Not(vc.goal)) - text = s.to_smt2() - path = os.path.join(args.out, vc.name + ".smt2") - with open(path, "w", encoding="ascii") as f: - f.write("; SPDX-License-Identifier: MPL-2.0\n") - f.write("; generated by gen_vcs.py - %s (%s)\n" % (vc.name, vc.kind)) - f.write("; %s\n" % vc.why) - f.write("; expected: %s\n" % vc.expect.upper()) - f.write(text) - - # Re-parse what we just wrote: the artifact checked is the artifact stored. - replay = z3.Solver() - replay.from_string(open(path, encoding="ascii").read()) - res = replay.check() - if res == z3.sat: - got = "sat" - elif res == z3.unsat: - got = "unsat" - else: - got = "unknown" - ok = got == vc.expect - model = "" - if got == "sat" and ok: - m = replay.model() - vals = [] - for d in m.decls(): - vals.append("%s=%s" % (d.name(), m[d])) - model = ", ".join(sorted(vals)) - rows.append((vc.name, vc.expect, got, "ok" if ok else "FAIL", vc.why, model)) - if not ok: - failures += 1 - - width = max(len(r[0]) for r in rows) - print("%-*s %-5s %-5s %-4s %s" % (width, "VC", "want", "z3", "", "meaning")) - for name, want, got, verdict, why, model in rows: - print("%-*s %-5s %-5s %-4s %s" % (width, name, want, got, verdict, why)) - if model: - print("%-*s model: %s" % (width, "", model)) - print("\n%d VCs, %d failing" % (len(rows), failures)) - return 1 if failures else 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/examples/atoma/frame-v1/verify.sh b/examples/atoma/frame-v1/verify.sh index 39c4825a..227a75d8 100755 --- a/examples/atoma/frame-v1/verify.sh +++ b/examples/atoma/frame-v1/verify.sh @@ -14,7 +14,8 @@ # G4 the `usize`-across-FFI counter-example is *rejected* on wasm32 (F0.3); # G5 Face A and Face B canonicalise to the same bytes (hash-checked seam); # G6 all 11 specification-mutation operators produce distinct artifacts; -# G7 the 14 SMT verification conditions are discharged (if z3 is present); +# G7 the 14 SMT verification conditions are discharged (if z3 is present), +# and the generator refuses to emit queries for a drifted contract; # G8 the Face B contract is *extracted* from the Zig source and matches the # checked-in file — the doc-comment directives are the source of truth; # G9 the implementation passes the subset checker with zero diagnostics and @@ -55,13 +56,13 @@ die() { # Count the tool's own tests instead of hard-coding a number that can drift. atoma_tests=0 -for m in canon frontend; do +for m in canon frontend vc; do n=$("$ZIG" test "$root/tools/atoma/src/$m.zig" 2>&1 | sed -n 's/^All \([0-9][0-9]*\) tests passed\.$/\1/p') [ -n "$n" ] || die "cannot count the tests in $m.zig" atoma_tests=$((atoma_tests + n)) done -printf 'atoma %s tests (canon + frontend)\n' "$atoma_tests" +printf 'atoma %s tests (canon + frontend + vc)\n' "$atoma_tests" cd "$here" @@ -129,24 +130,67 @@ rm -f spec/.mutant.cspec spec/.probe.cspec spec/.face-a.full.cspec spec/.face-b. printf 'G6 ok mutation sweep: %s applied, %s distinct artifacts\n' "$applied" "$distinct" # ── G7: SMT verification conditions ───────────────────────────────────────── -# Optional: needs python3 + z3-solver. When it cannot run, the receipt records -# `"smt":"not-run"` rather than claiming anything. +# Optional: needs z3. The queries are emitted by `atoma vc`, which is *untrusted +# plumbing* (tools/atoma/src/vc.zig): the gate does not believe the generator, +# it runs the solver and compares the verdict with the reviewed expectation +# table. Verdicts are read from stdout — z3 exits 0 for both sat and unsat — and +# a disagreement of any kind fails closed. smt_state="not-run" vc_hash="none" vc_count=0 -PY=${PYTHON:-python3} -if "$PY" -c 'import z3' >/dev/null 2>&1; then - if "$PY" vc/gen_vcs.py > witness/vc-report.txt 2>&1; then - vc_count=$(sed -n 's/^\([0-9][0-9]*\) VCs, 0 failing$/\1/p' witness/vc-report.txt) - # One content address for the whole VC set: sorted per-file hashes. - vc_hash=$( - for f in vc/*.smt2; do "$ADDR" vc-hash "$f"; done | sort | "$ADDR" vc-hash /dev/stdin - ) - smt_state="discharged" - printf 'G7 ok %s VCs discharged by z3 (%s)\n' "$vc_count" "$vc_hash" - else - die "G7 VC generation or discharging failed (see witness/vc-report.txt)" - fi +Z3=${Z3:-z3} +if command -v "$Z3" >/dev/null 2>&1; then + rm -rf vc/.gen + mkdir -p vc/.gen + "$ADDR" vc vc/.gen --cspec spec/face-b.cspec > witness/vc-report.txt 2>&1 || { + cat witness/vc-report.txt >&2 + die "G7 VC generation" + } + + # The query set is pinned to the contract. A drifted contract must stop + # generation — otherwise the gate would happily discharge obligations that + # belong to a program that no longer exists. + sed 's/( <= 12 ( len input ) )/( <= 11 ( len input ) )/' spec/face-b.cspec > spec/.drifted.cspec + drift_ok=0 + "$ADDR" vc vc/.gen --cspec spec/.drifted.cspec >/dev/null 2>&1 && drift_ok=1 + rm -f spec/.drifted.cspec + [ "$drift_ok" = 0 ] || die "G7 the generator accepted a drifted contract: its binding is vacuous" + + # The committed queries must be the ones the generator emits: a hand-edited + # .smt2 is not evidence, so a stale artifact is a hard failure. + for f in vc/*.smt2; do + cmp -s "$f" "vc/.gen/$(basename "$f")" || + die "G7 stale artifact $f: run 'atoma vc vc --cspec spec/face-b.cspec' and commit" + done + # The reviewed table carries a prose preamble; the generator's manifest does + # not. Compare the data lines, in order. + grep -v '^#' vc/expected.tsv > vc/.gen/reviewed.tsv + grep -v '^#' vc/.gen/manifest.tsv > vc/.gen/generated.tsv + cmp -s vc/.gen/reviewed.tsv vc/.gen/generated.tsv || + die "G7 vc/expected.tsv differs from the reviewed generator manifest" + + tab=$(printf '\t') + while IFS="$tab" read -r name want; do + case "$name" in '#'*|'') continue ;; esac + [ -f "vc/.gen/$name.smt2" ] || die "G7 expected VC $name is missing from the generator" + got=$("$Z3" -smt2 "vc/.gen/$name.smt2" 2>&1 | tail -n 1) + [ "$got" = "$want" ] || die "G7 $name: expected $want, z3 said $got" + printf ' %-32s %s\n' "$name" "$got" >> witness/vc-report.txt + vc_count=$((vc_count + 1)) + done < vc/expected.tsv + [ "$vc_count" = 14 ] || die "G7 ran $vc_count queries, expected 14" + + # One content address for the whole VC set: sorted per-file hashes. + vc_hash=$( + for f in vc/.gen/*.smt2; do "$ADDR" vc-hash "$f"; done | sort | "$ADDR" vc-hash /dev/stdin + ) + saw_unsat=$(awk -F"$tab" '$2=="unsat"' vc/expected.tsv | wc -l | tr -d ' ') + saw_sat=$(awk -F"$tab" '$2=="sat"' vc/expected.tsv | wc -l | tr -d ' ') + [ "$saw_unsat" -ge 8 ] || die "G7 only $saw_unsat discharged obligations (want >= 8)" + [ "$saw_sat" -ge 6 ] || die "G7 only $saw_sat counterexample obligations (want >= 6)" + smt_state="discharged" + printf 'G7 ok %s VCs discharged by z3: %s unsat, %s sat (%s)\n' \ + "$vc_count" "$saw_unsat" "$saw_sat" "$vc_hash" else printf 'G7 -- z3 not installed: SMT obligations not discharged\n' fi diff --git a/examples/atoma/frame-v1/witness/phase0.receipt.json b/examples/atoma/frame-v1/witness/phase0.receipt.json index 057eed4d..f165f0bc 100644 --- a/examples/atoma/frame-v1/witness/phase0.receipt.json +++ b/examples/atoma/frame-v1/witness/phase0.receipt.json @@ -1 +1 @@ -{"artifacts":{"face-a":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","face-b":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","layout":"blake3:c75f72ce33010b457c8dc7f8c8514720904ddaeca9de0ce412cc7d61cf8accd1"},"contract":"atoma.frame.parse","equivalence":"EQUIVALENT","gate":"phase0","mutants":{"applied":11,"distinct":11},"proof":{"modules":4,"srcset":"blake3:e2b2f961812d4ed1165f3d306d267dd95af7d0f13f7ce146fde9355d7a647249","status":"checked"},"schema":"atoma.receipt.v1","smt":{"status":"discharged","vcs":14,"vcset":"blake3:72c74c012d527feab0988225098a7a110e35252794c67848ab13f010c75e3698"},"status":"INCOMPLETE","status_class":"Warrant","subset":{"contracts":6,"diagnostics_negative_corpus":20,"codes_negative_corpus":17},"targets":["aarch64","riscv64","wasm32","x86_64"],"tests":{"atoma":15,"frame_parse":11}} \ No newline at end of file +{"artifacts":{"face-a":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","face-b":"blake3:f5f97a7bee44d4596590ecb7745c70565ebdf4fb5daa8a48d9a365a85f265756","layout":"blake3:c75f72ce33010b457c8dc7f8c8514720904ddaeca9de0ce412cc7d61cf8accd1"},"contract":"atoma.frame.parse","equivalence":"EQUIVALENT","gate":"phase0","mutants":{"applied":11,"distinct":11},"proof":{"modules":4,"srcset":"blake3:e2b2f961812d4ed1165f3d306d267dd95af7d0f13f7ce146fde9355d7a647249","status":"checked"},"schema":"atoma.receipt.v1","smt":{"status":"discharged","vcs":14,"vcset":"blake3:dec3d83389ef29f4ec5d49805ba527f92fef6224b0613a98393ed7f1c69ce35d"},"status":"INCOMPLETE","status_class":"Warrant","subset":{"contracts":6,"diagnostics_negative_corpus":20,"codes_negative_corpus":17},"targets":["aarch64","riscv64","wasm32","x86_64"],"tests":{"atoma":20,"frame_parse":11}} \ No newline at end of file diff --git a/examples/atoma/frame-v1/witness/vc-report.txt b/examples/atoma/frame-v1/witness/vc-report.txt index 6298cc44..1d28df36 100644 --- a/examples/atoma/frame-v1/witness/vc-report.txt +++ b/examples/atoma/frame-v1/witness/vc-report.txt @@ -1,22 +1,15 @@ -VC want z3 meaning -V1_no_underflow unsat unsat ok `buf.len - 12` cannot wrap once len >= 12 is known -V1_needle_drop_requires sat sat ok without `len >= 12` the subtraction underflows: model is the panic - model: buf_len=0 -V2_slice_in_bounds unsat unsat ok 12 + length <= buf.len, so buf[12 .. 12+length] is in bounds -V2_needle_drop_payload_bound sat sat ok a frame claiming more bytes than the buffer holds slices out of bounds - model: buf_len=12, length=1 -V2_mutant_off_by_one sat sat ok `avail + 1` admits exactly one byte past the end: off-by-one - model: buf_len=2147483647, length=2147483636 -V3_intcast_range unsat unsat ok a slice obtained from a u32 in_len is at most 2^32-1 bytes and at least 12, so the usize-to-u32 @intCast cannot trap -V3_needle_drop_ffi_bound sat sat ok called directly with a >4GiB slice, the same @intCast panics - model: buf_len_usize=18446744069414584332 -V4_maxplus_bound unsat unsat ok 8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus bound is representable in the cost domain -V5_magic_wire_order unsat unsat ok bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' on the wire -V5_mutant_wrong_endian unsat unsat ok 0x4154 is refuted by the same bytes: the literal ASCII word is wrong -V6_padding_zeroed unsat unsat ok writes hit only field bytes, so every padding byte keeps the 0x00 it got from zeroBytes -V6_mutant_offset_drift sat sat ok a payload placed at offset 12 writes into the padding hole 12..16: the padding VC catches layout drift -V7_post_payload_len unsat unsat ok the success postcondition follows from the guard that produced success -V8_premise_satisfiable sat sat ok a contradictory precondition would make every VC trivially UNSAT, so satisfiability of the premises is a VC in its own right - model: buf_len=0 - -14 VCs, 0 failing +14 VCs -> vc/.gen + V1_no_underflow unsat + V1_needle_drop_requires sat + V2_slice_in_bounds unsat + V2_needle_drop_payload_bound sat + V2_mutant_off_by_one sat + V3_intcast_range unsat + V3_needle_drop_ffi_bound sat + V4_maxplus_bound unsat + V5_magic_wire_order unsat + V5_mutant_wrong_endian unsat + V6_padding_zeroed unsat + V6_mutant_offset_drift sat + V7_post_payload_len unsat + V8_premise_satisfiable sat diff --git a/tools/atoma/src/frontend.zig b/tools/atoma/src/frontend.zig index ab6617d3..b8317ea4 100644 --- a/tools/atoma/src/frontend.zig +++ b/tools/atoma/src/frontend.zig @@ -210,7 +210,7 @@ fn collectDecls(alloc: Allocator, ast: Ast, report: *Report) !std.ArrayListUnman } // ───────────────────────────────────────────────────────────────────────────── -// Banned-construct scan (§2.4) +// Banned-construct scan (§3.1: the E-* classification) // ───────────────────────────────────────────────────────────────────────────── const BannedBuiltin = struct { text: []const u8, code: []const u8 }; diff --git a/tools/atoma/src/main.zig b/tools/atoma/src/main.zig index 9f3e9b4e..989621dc 100644 --- a/tools/atoma/src/main.zig +++ b/tools/atoma/src/main.zig @@ -15,6 +15,7 @@ // atoma mutate print one mutated specification // atoma extract [--symbol S] emit the Face B contract (.cspec) // atoma check subset conformance, exit 1 on E-* +// atoma vc emit the 14 SMT-LIB queries + manifest // atoma ops list mutation operators // atoma selftest run the built-in vectors // @@ -24,6 +25,7 @@ const std = @import("std"); const canon = @import("canon.zig"); const frontend = @import("frontend.zig"); +const vc = @import("vc.zig"); const gpa = std.heap.page_allocator; @@ -55,7 +57,7 @@ fn print(comptime fmt: []const u8, args: anytype) void { } fn usage() noreturn { - sayLine("usage: atoma [args]"); + sayLine("usage: atoma [args]"); std.process.exit(2); } @@ -197,6 +199,57 @@ pub fn main() !void { args[2], rep.decls, rep.exports, rep.contracts, rep.diags.items.len, }); if (rep.diags.items.len != 0) std.process.exit(1); + } else if (std.mem.eql(u8, cmd, "vc")) { + if (args.len < 3) usage(); + var cspec: ?[]const u8 = null; + var i: usize = 3; + while (i + 1 < args.len) : (i += 2) { + if (std.mem.eql(u8, args[i], "--cspec")) cspec = args[i + 1]; + } + if (cspec) |path| { + const src = readFile(path) catch |e| { + print("cannot read {s}: {s}\n", .{ path, @errorName(e) }); + std.process.exit(3); + }; + const c = canon.canon(gpa, src) catch |e| { + print("cannot canonicalise {s}: {s}\n", .{ path, @errorName(e) }); + std.process.exit(3); + }; + vc.checkContract(c.bytes) catch { + print("CONTRACT-DRIFT {s}: the query set is pinned to a contract that changed\n", .{path}); + sayLine(" re-derive the obligations in docs/spec/ATOMA-SPEC.adoc §8.3 before regenerating"); + std.process.exit(1); + }; + } + var dir = std.fs.cwd().openDir(args[2], .{}) catch |e| { + print("cannot open {s}: {s}\n", .{ args[2], @errorName(e) }); + std.process.exit(3); + }; + defer dir.close(); + _ = vc.generate(gpa, dir) catch |e| { + print("vc generation failed: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + // The manifest is the reviewed expectation table, emitted from the same + // source of truth as the queries. `verify.sh` diffs it against the + // checked-in `vc/expected.tsv`, so a changed expectation is a reviewed + // diff rather than a silent edit to the generator. + var buf = std.io.Writer.Allocating.init(gpa); + defer buf.deinit(); + vc.writeManifest(&buf.writer) catch |e| { + print("cannot render manifest: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + var mf = dir.createFile("manifest.tsv", .{}) catch |e| { + print("cannot write manifest: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + defer mf.close(); + mf.writeAll(buf.written()) catch |e| { + print("cannot write manifest: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + print("{d} VCs -> {s}\n", .{ vc.vcs.len, args[2] }); } else if (std.mem.eql(u8, cmd, "ops")) { for (canon.Mutation.all()) |m| print("{s}\n", .{m.name()}); } else if (std.mem.eql(u8, cmd, "selftest")) { @@ -250,4 +303,5 @@ pub fn main() !void { test { _ = canon; + _ = vc; } diff --git a/tools/atoma/src/vc.zig b/tools/atoma/src/vc.zig new file mode 100644 index 00000000..b0ca96cc --- /dev/null +++ b/tools/atoma/src/vc.zig @@ -0,0 +1,403 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +// +// Atoma — the VC generator for the frame-v1 worked example. +// +// This file is *untrusted plumbing*: it emits SMT-LIB queries, and what it +// proves is whatever the solver says about them. It replaces `vc/gen_vcs.py`, +// which the estate's language policy forbids — `governance / Language / +// package anti-pattern policy` runs `git ls-files '*.py'` and fails the PR. +// The port is deliberate rather than cosmetic: the generator is deterministic, +// dependency-free and diffable against the checked-in artefacts, and the +// solver is invoked directly by `verify.sh` instead of through a Python API. +// +// Two families of query are produced for each obligation: +// +// positive premises /\ not goal must be UNSAT (obligation discharged) +// needle the load-bearing premise removed must be SAT +// +// The `needle` family is what stops a contract from being vacuously true: if a +// precondition can be deleted without turning the goal into a counterexample, +// that precondition was doing no work, and the mutation harness must say so. +// +// Output is ASCII, LF-terminated and byte-stable: same input, same bytes, on +// every machine. `verify.sh` regenerates into a temporary directory and diffs, +// so a hand-edited `.smt2` cannot survive. +// +// Spec: docs/spec/ATOMA-SPEC.adoc §7 (obligations) and §8.3 (the VC set). + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +pub const Expected = enum { + unsat, + sat, + + pub fn name(self: Expected) []const u8 { + return switch (self) { + .unsat => "unsat", + .sat => "sat", + }; + } +}; + +pub const Vc = struct { + name: []const u8, + kind: []const u8, + why: []const u8, + expected: Expected, +}; + +/// Canonical lines that the fourteen queries are *derived from*. `atoma vc` +/// refuses to emit anything unless the contract it is pointed at still contains +/// every one of them: if the contract moved, the queries describe a program that +/// no longer exists, and emitting them anyway is exactly the kind of silent +/// staleness this project exists to prevent. Values are in canonical (decimal) +/// form because that is what `atoma canon` prints. +pub const contract_facts = [_][]const u8{ + "requires ( <= 12 ( len input ) )", + "requires ( < input_len 4294967296 )", + "ensures ( => ( = res 0 ) ( = ( magic out ) 21569 ) )", + "ensures ( => ( = res 0 ) ( <= ( payload_len out ) ( - ( len input ) 12 ) ) )", + "bound steps ( + 12 ( * 8 input_len ) )", +}; + +pub const ContractDrift = error{ContractDrift}; + +/// Fail-closed binding to the contract: every fact the queries encode must +/// still be present, verbatim, in the canonical contract. +pub fn checkContract(canonical: []const u8) ContractDrift!void { + for (contract_facts) |f| { + if (std.mem.indexOf(u8, canonical, f) == null) return error.ContractDrift; + } +} + +/// The VC set, in the order the receipt hashes it. Fixed order matters: the +/// aggregate content address is taken over the per-file hashes in this order, +/// so reordering is a different VC set even if the members are equal. +pub const vcs = [_]Vc{ + .{ .name = "V1_no_underflow", .kind = "arith", .expected = .unsat, + .why = "`buf.len - 12` cannot wrap once len >= 12 is known" }, + .{ .name = "V1_needle_drop_requires", .kind = "arith", .expected = .sat, + .why = "without `len >= 12` the subtraction underflows: model is the panic" }, + .{ .name = "V2_slice_in_bounds", .kind = "bounds", .expected = .unsat, + .why = "12 + length <= buf.len, so buf[12 .. 12+length] is in bounds" }, + .{ .name = "V2_needle_drop_payload_bound", .kind = "bounds", .expected = .sat, + .why = "a frame claiming more bytes than the buffer holds slices out of bounds" }, + .{ .name = "V2_mutant_off_by_one", .kind = "bounds", .expected = .sat, + .why = "`avail + 1` admits exactly one byte past the end: off-by-one" }, + .{ .name = "V3_intcast_range", .kind = "cast", .expected = .unsat, + .why = "a slice from a u32 in_len is at most 2^32-1 bytes and at least 12, so the usize-to-u32 @intCast cannot trap" }, + .{ .name = "V3_needle_drop_ffi_bound", .kind = "cast", .expected = .sat, + .why = "called directly with a >4GiB slice, the same @intCast panics" }, + .{ .name = "V4_maxplus_bound", .kind = "cost", .expected = .unsat, + .why = "8 steps per payload byte; worst case 8*65535+12 < 2^32 so the MaxPlus bound is representable in the cost domain" }, + .{ .name = "V5_magic_wire_order", .kind = "abi", .expected = .unsat, + .why = "bytes 'A','T' decode to 0x5441; the 'obvious' 0x4154 would put 'T','A' on the wire" }, + .{ .name = "V5_mutant_wrong_endian", .kind = "abi", .expected = .unsat, + .why = "0x4154 is refuted by the same bytes: the literal ASCII word is wrong" }, + .{ .name = "V6_padding_zeroed", .kind = "layout", .expected = .unsat, + .why = "writes hit only field bytes, so every padding byte keeps the 0x00 it got from zeroBytes" }, + .{ .name = "V6_mutant_offset_drift", .kind = "layout", .expected = .sat, + .why = "a payload placed at offset 12 writes into the padding hole 12..16: the padding VC catches layout drift" }, + .{ .name = "V7_post_payload_len", .kind = "post", .expected = .unsat, + .why = "the success postcondition follows from the guard that produced success" }, + .{ .name = "V8_premise_satisfiable", .kind = "vacuity", .expected = .sat, + .why = "a contradictory precondition would make every VC trivially UNSAT, so satisfiability of the premises is a VC in its own right" }, +}; + +/// The `FrameOut` field bytes on a 64-bit target: (offset, size) pairs, read +/// from `spec/layout.cspec`. A drift here is what V6_mutant_offset_drift +/// detects, so this table and the layout witness must agree. +const frame_out_fields = [_]struct { off: u32, size: u32 }{ + .{ .off = 0, .size = 2 }, // magic + .{ .off = 2, .size = 2 }, // payload_len + .{ .off = 4, .size = 1 }, // flags + .{ .off = 5, .size = 1 }, // tag + .{ .off = 8, .size = 4 }, // crc32 + .{ .off = 16, .size = 8 }, // payload pointer: the field that drifts + .{ .off = 24, .size = 4 }, // payload_len_u32 +}; + +/// Offset of the payload pointer in the witnessed layout. The drift query moves +/// exactly this field, which is the mistake an author makes when one target's +/// `@offsetOf` is transcribed wrongly. +const payload_offset_witnessed: u32 = 16; +const payload_offset_drifted: u32 = 12; + +const pad_bytes_64 = [_]u32{ 6, 7, 12, 13, 14, 15, 28, 29, 30, 31 }; + +fn line(w: anytype, comptime fmt: []const u8, args: anytype) !void { + try w.print(fmt ++ "\n", args); +} + +fn header(w: anytype, v: Vc) !void { + try line(w, "; SPDX-License-Identifier: MPL-2.0", .{}); + try line(w, "; generated by `atoma vc` - {s} ({s})", .{ v.name, v.kind }); + try line(w, "; {s}", .{v.why}); + try line(w, "; expected: {s}", .{switch (v.expected) { + .unsat => "UNSAT", + .sat => "SAT", + }}); +} + +fn decl(w: anytype, name: []const u8, width: u8) !void { + try line(w, "(declare-const {s} (_ BitVec {d}))", .{ name, width }); +} + +/// `(store (store … base i0 v) i1 v)` over the base all-zero array, with the +/// payload pointer placed at `payload_off`. Distinct indices make the order +/// semantically irrelevant, but it is fixed so the bytes are stable. +fn storeChain(w: anytype, payload_off: u32) !void { + var offs: [32]u32 = undefined; + var n: usize = 0; + for (frame_out_fields) |f| { + const base = if (f.off == payload_offset_witnessed) payload_off else f.off; + var k: u32 = 0; + while (k < f.size) : (k += 1) { + offs[n] = base + k; + n += 1; + } + } + var i: usize = 0; + while (i < n) : (i += 1) try w.writeAll("(store "); + try w.writeAll("((as const (Array (_ BitVec 32) (_ BitVec 8))) #x00)"); + i = 0; + while (i < n) : (i += 1) try w.print(" #x{X:0>8} #xAA)", .{offs[i]}); +} + +/// Build the SMT-LIB text for VC `i`. Caller frees. +pub fn textFor(alloc: Allocator, i: usize) ![]u8 { + var out = std.io.Writer.Allocating.init(alloc); + errdefer out.deinit(); + const w = &out.writer; + const v = vcs[i]; + + switch (i) { + // ── V1 no underflow in `buf.len - 12` ─────────────────────────────── + 0 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try w.writeAll("(assert (bvule #x0000000c buf_len))\n"); + try w.writeAll("(assert (not (bvule #x0000000c buf_len)))\n"); + try w.writeAll("(check-sat)\n"); + }, + 1 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try w.writeAll("(assert (not (bvule #x0000000c buf_len)))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V2 the payload slice is in bounds ─────────────────────────────── + 2 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try decl(w, "length", 32); + try w.writeAll("(assert (bvule #x0000000c buf_len))\n"); + try w.writeAll("(assert (bvule length (bvsub buf_len #x0000000c)))\n"); + try w.writeAll("(assert (not (bvule (bvadd #x0000000c length) buf_len)))\n"); + try w.writeAll("(check-sat)\n"); + }, + 3 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try decl(w, "length", 32); + try w.writeAll("(assert (bvule #x0000000c buf_len))\n"); + try w.writeAll("(assert (not (bvule (bvadd #x0000000c length) buf_len)))\n"); + try w.writeAll("(check-sat)\n"); + }, + 4 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try decl(w, "length", 32); + try w.writeAll("(assert (bvule #x0000000c buf_len))\n"); + try w.writeAll("(assert (bvule length (bvadd (bvsub buf_len #x0000000c) #x00000001)))\n"); + try w.writeAll("(assert (not (bvule (bvadd #x0000000c length) buf_len)))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V3 @intCast of a usize slice length into u32 fits ─────────────── + 5 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len_usize", 64); + try w.writeAll("(assert (bvule #x000000000000000c buf_len_usize))\n"); + try w.writeAll("(assert (bvule buf_len_usize #x00000000ffffffff))\n"); + try w.writeAll("(assert (not (bvule (bvsub buf_len_usize #x000000000000000c) #x00000000ffffffff)))\n"); + try w.writeAll("(check-sat)\n"); + }, + 6 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len_usize", 64); + try w.writeAll("(assert (not (bvule (bvsub buf_len_usize #x000000000000000c) #x00000000ffffffff)))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V4 MaxPlus step bound for the CRC loop ────────────────────────── + 7 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "steps", 32); + try decl(w, "payload_len", 32); + try w.writeAll("(assert (bvule payload_len #x0000ffff))\n"); + try w.writeAll("(assert (bvule steps (bvadd (bvmul #x00000008 payload_len) #x0000000c)))\n"); + try w.writeAll("(assert (not (bvule steps (bvadd (bvmul #x00000008 #x0000ffff) #x0000000c))))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V5 the magic's endianness ─────────────────────────────────────── + 8 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "byte0", 8); + try decl(w, "byte1", 8); + try w.writeAll("(assert (= byte0 #x41))\n"); + try w.writeAll("(assert (= byte1 #x54))\n"); + try w.writeAll("(assert (not (= (bvor (concat #x00 byte0) (bvshl (concat #x00 byte1) #x0008)) #x5441)))\n"); + try w.writeAll("(check-sat)\n"); + }, + 9 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "byte0", 8); + try decl(w, "byte1", 8); + try w.writeAll("(assert (= byte0 #x41))\n"); + try w.writeAll("(assert (= byte1 #x54))\n"); + try w.writeAll("(assert (= (bvor (concat #x00 byte0) (bvshl (concat #x00 byte1) #x0008)) #x4154))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V6 padding bytes are zero after zeroBytes + field writes ──────── + 10, 11 => { + try header(w, v); + try w.writeAll("(set-logic QF_ABV)\n"); + const payload_off = if (i == 10) payload_offset_witnessed else payload_offset_drifted; + try w.writeAll("(define-fun S () (Array (_ BitVec 32) (_ BitVec 8))\n "); + try storeChain(w, payload_off); + try w.writeAll(")\n"); + try w.writeAll("(assert (not (and"); + for (pad_bytes_64) |b| { + try w.print("\n (= (select S #x{X:0>8}) #x00)", .{b}); + } + try w.writeAll(")))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V7 postcondition: on success payload_len <= in_len - 12 ───────── + 12 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try decl(w, "length", 32); + try w.writeAll("(assert (bvule #x0000000c buf_len))\n"); + try w.writeAll("(assert (not (=> (and (bvule #x0000000c buf_len) (bvule length (bvsub buf_len #x0000000c))) " ++ + "(bvule (ite (and (bvule #x0000000c buf_len) (bvule length (bvsub buf_len #x0000000c))) length #x00000000) " ++ + "(bvsub buf_len #x0000000c)))))\n"); + try w.writeAll("(check-sat)\n"); + }, + // ── V8 vacuity: the precondition must be satisfiable ──────────────── + 13 => { + try header(w, v); + try w.writeAll("(set-logic QF_BV)\n"); + try decl(w, "buf_len", 32); + try w.writeAll("(assert (and (bvule #x0000000c buf_len) (bvule buf_len #xffffffff)))\n"); + try w.writeAll("(check-sat)\n"); + }, + else => unreachable, + } + + return out.toOwnedSlice(); +} + +/// Write every query into `dir` (which must exist). Returns the count. +pub fn generate(alloc: Allocator, dir: std.fs.Dir) !usize { + for (vcs, 0..) |v, i| { + const text = try textFor(alloc, i); + defer alloc.free(text); + var name_buf: [64]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "{s}.smt2", .{v.name}); + var f = try dir.createFile(name, .{}); + defer f.close(); + try f.writeAll(text); + } + return vcs.len; +} + +/// Print the manifest (`nameexpected`) that `verify.sh` diffs against the +/// reviewed `vc/expected.tsv`. +pub fn writeManifest(w: anytype) !void { + try w.writeAll("# name\texpected\n"); + for (vcs) |v| try w.print("{s}\t{s}\n", .{ v.name, v.expected.name() }); +} + +// ───────────────────────────────────────────────────────────────────────────── +// Tests +// ───────────────────────────────────────────────────────────────────────────── + +const testing = std.testing; + +test "the contract binding rejects a drifted contract" { + const good = + \\cspec 1 + \\requires ( <= 12 ( len input ) ) + \\requires ( < input_len 4294967296 ) + \\ensures ( => ( = res 0 ) ( = ( magic out ) 21569 ) ) + \\ensures ( => ( = res 0 ) ( <= ( payload_len out ) ( - ( len input ) 12 ) ) ) + \\bound steps ( + 12 ( * 8 input_len ) ) + \\ + ; + try checkContract(good); + const drifted = + \\cspec 1 + \\requires ( <= 11 ( len input ) ) + \\requires ( < input_len 4294967296 ) + \\ensures ( => ( = res 0 ) ( = ( magic out ) 21569 ) ) + \\ensures ( => ( = res 0 ) ( <= ( payload_len out ) ( - ( len input ) 12 ) ) ) + \\bound steps ( + 12 ( * 8 input_len ) ) + \\ + ; + try testing.expectError(error.ContractDrift, checkContract(drifted)); +} + +test "the VC set is the reviewed set" { + try testing.expectEqual(@as(usize, 14), vcs.len); + try testing.expectEqualStrings("V1_no_underflow", vcs[0].name); + try testing.expectEqualStrings("V8_premise_satisfiable", vcs[13].name); +} + +test "every query is ASCII, LF-terminated and ends in check-sat" { + const ta = testing.allocator; + for (vcs, 0..) |v, i| { + const text = try textFor(ta, i); + defer ta.free(text); + for (text) |c| try testing.expect(c < 0x80); + try testing.expect(std.mem.endsWith(u8, text, "(check-sat)\n")); + try testing.expect(std.mem.indexOf(u8, text, v.why) != null); + } +} + +test "generation is deterministic" { + const ta = testing.allocator; + for (0..vcs.len) |i| { + const a = try textFor(ta, i); + defer ta.free(a); + const b = try textFor(ta, i); + defer ta.free(b); + try testing.expectEqualStrings(a, b); + } +} + +test "the drift query differs from the witnessed one" { + const ta = testing.allocator; + const ok = try textFor(ta, 10); + defer ta.free(ok); + const drift = try textFor(ta, 11); + defer ta.free(drift); + try testing.expect(!std.mem.eql(u8, ok, drift)); + // Offset 12 (0x0C) is a padding hole in the witnessed layout and the + // payload's first byte in the drifted one: that single difference is the + // whole content of V6_mutant_offset_drift. + try testing.expect(std.mem.indexOf(u8, ok, "#x0000000C #xAA") == null); + try testing.expect(std.mem.indexOf(u8, drift, "#x0000000C #xAA") != null); +} From 45e13a628242422bc3234973a10f4538fa63caca Mon Sep 17 00:00:00 2001 From: hyperpolymath <6759885+hyperpolymath@users.noreply.github.com> Date: Thu, 22 Oct 2026 16:05:46 +0000 Subject: [PATCH 6/6] meta: make the About description and the 20 topics reviewable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GitHub repository metadata is part of the project's public description, so it belongs in the tree rather than in a chat log. `scripts/set-repo-metadata.sh` carries the description (215 characters) and exactly 20 topics — the 7 that nearly every hyperpolymath repository carries, then 13 specific to Atoma — and validates them against GitHub's rules (lowercase, hyphens, <= 50 characters, exactly 20) before spending an API call. The application token here is contents-scoped, so `PATCH /repos/...` returns 403. The script is therefore a maintainer action, not a gate: it exits 1 with the `gh auth refresh -s administration` hint. `--dry-run` prints both payloads, which is how the wording was reviewed. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- docs/plan/ULTRAPLAN.adoc | 2 +- scripts/set-repo-metadata.sh | 132 +++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) create mode 100755 scripts/set-repo-metadata.sh diff --git a/docs/plan/ULTRAPLAN.adoc b/docs/plan/ULTRAPLAN.adoc index e0c7ff88..6a0f20f1 100644 --- a/docs/plan/ULTRAPLAN.adoc +++ b/docs/plan/ULTRAPLAN.adoc @@ -1259,7 +1259,7 @@ not a warning from a manual. | `with` vs `with … in eq` | Agda | A plain `with` abstracts the scrutinee away; the `ite` case needs the equation. Cost: one compile cycle. | Store in `soundness` | `Core.agda` | Unprovable without a framing lemma. The fragment is store-free for that reason (T1 removes the restriction properly). | BV vs integer | SMT | `x - 12 ≤ 2^32-1` is false for `x < 12` in BV64. Carry the no-underflow premise; the toy bug is an asserted wrong constant with goal `False`. -| z3 Python API | `vc/gen_vcs.py` | `CheckSatResult` is unhashable; compare with `==`. +| z3 exit status | `verify.sh` G7 | `z3 -smt2` exits 0 for **both** `sat` and `unsat`, so `$?` is not a verdict; parse the `check-sat` line. | SMT-LIB | `vc/*.smt2` | ASCII only; strip `—`, `→`, `∧`. | Mutation coverage | `canon.zig` | Operators need distinct formula/set lines; 8/11 became 11/11 only after adding two `borrow` rows and a second `requires`. | Extract vs hand-written Face B | `spec/` | They drifted (extra `requires`, unbound `forall`). Regenerate; never hand-patch. diff --git a/scripts/set-repo-metadata.sh b/scripts/set-repo-metadata.sh new file mode 100755 index 00000000..9e028564 --- /dev/null +++ b/scripts/set-repo-metadata.sh @@ -0,0 +1,132 @@ +#!/bin/sh +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell +# +# set-repo-metadata.sh — write the GitHub About description and the 20 topics. +# +# Why this is a script and not a one-liner in a chat log: repository metadata is +# part of the project's public description, it has to be reviewable, and it has +# to be reproducible the day someone changes the wording. Committing it means the +# topics are under version control like every other claim this repository makes. +# +# It is NOT run by any gate. It needs a token with `administration: write` +# (`gh auth refresh -s administration`); the CI token this repository usually +# runs under is contents-scoped and gets HTTP 403 here, which is why the metadata +# lives in the tree and is applied deliberately by a maintainer. +# +# Usage: +# scripts/set-repo-metadata.sh apply description + topics +# scripts/set-repo-metadata.sh --dry-run print the payloads, change nothing +# +# Exit codes: 0 applied (or dry run printed), 1 an API call failed, +# 2 setup error (gh missing, wrong topic count). + +set -eu + +REPO="${REPO:-hyperpolymath/atoma}" + +# Estate style: "Name — what it is. Concrete detail: counts, pipeline, what is +# checked." No claim here that the kernel chain has run — it has not, and the +# description says so. +DESCRIPTION='Atoma — program verification for Zig. Contracts, a subset checker, an Agda-checked soundness theorem for a store-free core, and canonical certificates; COMPLETE status only after Dedukti + Coq/Lean4 kernel checks.' + +# 7 topics nearly every hyperpolymath repository carries, then 13 specific to +# Atoma. Order is the order they are written, not a ranking: GitHub sorts them. +TOPICS=' +epistemic-computing +epistemic-infrastructure +equivalence-aware-computing +hyperpolymath +open-source +typed-provenance +veridical-computing +formal-verification +program-verification +deductive-verification +proof-certificates +proof-assistants +theorem-proving +smt-solving +zig +agda +idris2 +dependent-types +proof-engineering +reproducible-research +' + +dry_run=0 +case "${1:-}" in + --dry-run) dry_run=1 ;; + '') : ;; + *) + printf 'usage: %s [--dry-run]\n' "$0" >&2 + exit 2 + ;; +esac + +command -v gh >/dev/null 2>&1 || { + printf 'ERROR: gh is not installed\n' >&2 + exit 2 +} + +# Validate the topic list against GitHub's rules before spending an API call: +# lowercase ASCII letters, digits and single hyphens, at most 50 characters. +count=0 +for t in $TOPICS; do + count=$((count + 1)) + case "$t" in + *[!a-z0-9-]*) + printf 'ERROR: topic %s is not lowercase/digits/hyphen\n' "$t" >&2 + exit 2 + ;; + --*|*-|*--*) + printf 'ERROR: topic %s has an illegal hyphen placement\n' "$t" >&2 + exit 2 + ;; + esac + [ "${#t}" -le 50 ] || { + printf 'ERROR: topic %s is longer than 50 characters\n' "$t" >&2 + exit 2 + } +done +[ "$count" -eq 20 ] || { + printf 'ERROR: expected exactly 20 topics, found %s\n' "$count" >&2 + exit 2 +} + +# Build the JSON body once, so the dry run and the live run cannot diverge. +topics_json=$(printf '%s\n' $TOPICS | awk 'BEGIN{printf "["} {gsub(/"/,""); printf "%s\"%s\"", (NR>1?",":""), $0} END{print "]"}') + +if [ "$dry_run" -eq 1 ]; then + printf 'repo: %s\n' "$REPO" + printf 'description: %s\n' "$DESCRIPTION" + printf 'description length: %s characters\n' "${#DESCRIPTION}" + printf 'topics (%s):\n' "$count" + printf '%s\n' $TOPICS | sed 's/^/ - /' + printf 'PATCH body: {"description": %s}\n' "\"$DESCRIPTION\"" + printf 'PUT body: {"names": %s}\n' "$topics_json" + exit 0 +fi + +gh api -X PATCH "repos/$REPO" -f description="$DESCRIPTION" >/dev/null || { + printf 'ERROR: could not set the description. A 403 here means the token is\n' >&2 + printf ' contents-scoped; refresh it with:\n' >&2 + printf ' gh auth refresh -h github.com -s administration\n' >&2 + exit 1 +} +printf 'description set\n' +printf ' %s\n' "$DESCRIPTION" + +topics_tmp=$(mktemp) +trap 'rm -f "$topics_tmp"' EXIT INT TERM +printf '{"names": %s}\n' "$topics_json" > "$topics_tmp" + +if ! gh api -X PUT "repos/$REPO/topics" \ + -H 'Accept: application/vnd.github+json' --input "$topics_tmp" >/dev/null; then + printf 'ERROR: could not set the topics (a 403 here has the same cause as\n' >&2 + printf ' the description failure above).\n' >&2 + exit 1 +fi +printf '%s topics set\n' "$count" +printf '%s\n' $TOPICS | sed 's/^/ - /'