diff --git a/.github/workflows/atoma.yml b/.github/workflows/atoma.yml index d736af41..47cb93a5 100644 --- a/.github/workflows/atoma.yml +++ b/.github/workflows/atoma.yml @@ -16,8 +16,39 @@ concurrency: cancel-in-progress: true jobs: + scalar: + name: Scalar source proof gate + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7.0.1 + with: + persist-credentials: false + - name: Provision scalar proof profile + run: | + set -euo pipefail + sudo apt-get update + sudo apt-get install -y --no-install-recommends agda-bin=2.6.3-1build1 coq=8.18.0+dfsg-1build2 zstd + bash scripts/atoma-download-zig.sh "$RUNNER_TEMP/scalar-zig" + cd "$RUNNER_TEMP" + curl --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 240 -fL --retry 1 https://github.com/leanprover/lean4/releases/download/v4.15.0/lean-4.15.0-linux.tar.zst -o scalar-lean.tar.zst + echo 'af71a2569a9f68337de2434829b3008cd8e32c436e9cb6bd8c84a2c2ba3585c9 scalar-lean.tar.zst' | sha256sum -c - + tar --zstd -xf scalar-lean.tar.zst + echo "$RUNNER_TEMP/lean-4.15.0-linux/bin" >> "$GITHUB_PATH" + mkdir -p "$GITHUB_WORKSPACE/build/scalar-proof-evidence" + sha256sum scalar-lean.tar.zst > "$GITHUB_WORKSPACE/build/scalar-proof-evidence/lean-archive.sha256" + - name: Agda then Lean and Coq, Cubical, source falsifiers + run: bash scripts/atoma-scalar-proof-gate.sh + - uses: actions/upload-artifact@v7.0.2 + if: always() + with: + name: scalar-proof-evidence-${{ github.sha }} + path: build/scalar-proof-evidence/ + if-no-files-found: error + soundness: name: Atoma soundness gate + needs: [scalar] runs-on: ubuntu-24.04 timeout-minutes: 45 steps: diff --git a/README.adoc b/README.adoc index 9947e6eb..62b3df68 100644 --- a/README.adoc +++ b/README.adoc @@ -6,7 +6,8 @@ Atoma develops source-bound verification for an explicitly closed Zig subset. It currently provides canonical contracts, a syntax screen, typechecked Idris2 -specifications, Agda proofs of a store-free model and a finite u8 source pilot. +specifications, Agda proofs of a store-free model, a finite u8 source pilot, +and a closed scalar source checker for real Proven and UAA helpers. It is not yet a general sound verifier for Zig. Evidence remains *INCOMPLETE (Warrant)*: finite-model replay now runs through ECHIDNA and coqchk, while compiler/refinement arguments and the full kernel chain remain @@ -14,12 +15,13 @@ unfinished. == Build and check -Use Zig 0.15.2, Z3 4.13.3 and the Agda/Idris2/ECHIDNA/Coq profiles in +Use Zig 0.15.2, Z3 4.13.3, Lean 4.15.0 and the Agda/Idris2/ECHIDNA/Coq profiles in link:docs/decisions/ATOMA-TOOLCHAIN.adoc[the toolchain decision]. From the repository root: [source,bash] ---- +bash scripts/atoma-scalar-proof-gate.sh bash scripts/atoma-gate.sh ---- @@ -31,6 +33,31 @@ checks the compiled libraries with coqchk and audits theorem assumptions. Evidence is written to `build/atoma-evidence/`. The hosted workflow publishes the same evidence and is required on `main`. +== Experimental scalar MVP + +The hosted workflow requires the scalar proof gate before the soundness gate. +It checks strict compatible Agda, Lean/Coq finite reflection, full Cubical and +source falsifiers, then consumes the exact revisions in +`tests/consumer-scalar/consumers.tsv`. Proven's byte-word encoder and UAA's tag +classifier remain pure Zig; their authoritative contracts/oracles are Idris2. +Each helper is compared with a freshly compiled Idris table for all 256 inputs +in all four Zig optimization modes. Coq independently interprets the original +source bytes, followed by ECHIDNA compilation, coqchk and assumption audits. + +For one admitted helper and a table containing exactly 256 `index value` rows: + +[source,bash] +---- +bash scripts/atoma-scalar-replay.sh helper.zig contract.tsv /tmp/new-scalar-evidence +---- + +The evidence directory must be new. `atoma scalar-coq` only exports a proof +capsule; successful export is not verification. A supplied table has no Idris +authority by itself: the consumer gate binds its fresh producer and inputs. +Whole-boundary receipts remain INCOMPLETE. This experimental scalar path does +not cover pointer leases, stateful wrappers or compiler refinement. See the +link:docs/decisions/ATOMA-SCALAR-SOURCE.adoc[admitted grammar and MVP acceptance]. + == Current verification boundary `tools/atoma` owns the command-line tooling and closed source pilot. diff --git a/docs/decisions/ATOMA-SCALAR-SOURCE.adoc b/docs/decisions/ATOMA-SCALAR-SOURCE.adoc new file mode 100644 index 00000000..2f20bc8f --- /dev/null +++ b/docs/decisions/ATOMA-SCALAR-SOURCE.adoc @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// Copyright (c) 2026 Jonathan D.A. Jewell += Closed scalar source checking for the first experimental MVP +:revdate: 2026-11-24 + +Status: implementation under remote validation. Passing evidence must name +the exact commit and hosted run. This decision does not change COMPLETE, +the v1 gates, or the estate architecture: Idris2 defines ABI contracts; +foreign-facing FFI and API implementations are pure Zig. + +== Why this slice + +The earlier u8 replay checks a theorem about a model emitted by the Zig +frontend. A faulty frontend could emit a correct model for an incorrect body. +The new path sends original source bytes to a separate Coq parser and +interpreter. The Zig command only serializes bytes and a complete contract +table; it cannot supply the parser's answer or the interpreted expression. + +The first actual sources are Proven's RefC byte-to-word marshaling helper and +UAA's protocol classifier. They are factored from the production Zig wrappers, +not rewritten application algorithms. Proven retains its SDK/target guard and +calls Idris for header semantics. UAA retains its registration table and +callback behavior. The helpers introduce no C FFI or C API implementation. +Idris's private RefC backend and a foreign C test caller remain separate. + +== Admitted grammar and meaning + +Each source contains exactly one public, non-exported pure function, one u8 +parameter and one return expression. ASCII whitespace and line comments are +allowed. The alternatives are: + +* A u64 shift/OR: `return (@as(u64, x) << S) | T;`, with decimal S at most 56 + and T at most 255. +* A Boolean interval: `return x >= LO and x <= HI;`, with both bounds at most + 255; Boolean results are represented as 0 or 1 in the contract table. + +No imports, calls, pointers, state, additional declarations, generics, loops, +overflowing arithmetic or arbitrary comptime evaluation are admitted. +The Coq source interpreter defines the meaning used in this claim. Its proof +establishes every input below 256 agrees with the supplied table and every +result fits u64. It does not prove equivalence to the full Zig language or +compiler. Native compilation is an additional required consumer gate, so a +string accepted by the closed parser but rejected by Zig cannot pass that gate. + +== Authority, replay and falsifiers + +The consumer runner fetches exact commits from `tests/consumer-scalar/consumers.tsv` +and compiles an Idris oracle in a new directory with totality, warnings-as-errors +and a no-holes check. Proven's word-profile contract and UAA's existing finite +decoder supply all 256 rows. The compiler, primitive Bits8 conversion and RefC +execution remain trusted; an oracle run is not a theorem about Idris compilation. + +An independent `od`/awk serializer compares source bytes and table literals +against the generated Coq capsule. ECHIDNA compiles the theorem; `coqchk` +rechecks it; a separately generated audit checks its type against fresh input +literals and prints its assumptions. The source-checker object is compiled +before dispatch and must remain unchanged afterward. Evidence binds sources, +contract, checker source/object, theorem, tools and replay results. + +The actual helper is also compiled with Zig 0.15.2 in Debug, ReleaseSafe, +ReleaseFast and ReleaseSmall on the hosted native target. Every input must +match the fresh Idris oracle. Wrong shifts, tags, ranges, contracts, trailing +imports and stale capsules are refusal controls. Consumer mutations must +compile successfully and then fail both native comparison and proof replay. + +Finite-reflection mathematics is developed in strict compatible Agda, re-proved +in Lean without Mathlib and instantiated in the Coq source checker. Full Cubical +checks a path-equality leg. These are related hand-written proofs, with statement +correspondence pending; Lean and Agda do not independently certify the Coq parser. +Cubical is not another independent kernel. No external verified-checker or +Mathesis admission claim is made. Generic finite reflection is established +mathematics, not a claim of a new result. + +== Experimental MVP acceptance and remaining work + +The scalar MVP requires a green exact-head remote gate, both pinned real +consumer helpers, fresh Idris tables, all-input native comparisons, kernel +replay, independent serialization and assumption audits, and intended negative +controls. It produces explicitly scoped evidence, with the whole-boundary +receipt still INCOMPLETE. Prototype implementation alone is not acceptance. + +The next semantic milestone must cover a genuinely different boundary: +Proven's decode/call relation with pointer carriers and leases, and UAA's +registration/callback state and refusal behavior. Prove framing, ownership, +failure paths and source correspondence before admitting those constructs. +The scalar work does not discharge that milestone or reduce v1 to two helpers. +Compiler refinement, general import/call closure, runtime state, the complete +required checker chain and reproducible tool provisioning remain open. + +Use extra reasoning effort for these semantic and trust-boundary decisions; +routine CI plumbing and documentation need less. All heavy validation is +hosted while the local resource hold remains in force. diff --git a/docs/decisions/ATOMA-TOOLCHAIN.adoc b/docs/decisions/ATOMA-TOOLCHAIN.adoc index 08da0c72..0c8a409a 100644 --- a/docs/decisions/ATOMA-TOOLCHAIN.adoc +++ b/docs/decisions/ATOMA-TOOLCHAIN.adoc @@ -21,6 +21,15 @@ the entire transitive system environment. | Actions | checkout v7.0.1, upload-artifact v7.0.2 | Immutable commits recorded by `gh actions-lock` in `actions.lock`; no credential persistence; read-only repository token |=== +The Zig downloader also permits HTTPS mirrors while retaining the exact same +archive SHA-256. Each transfer has a bounded timeout; an integrity mismatch is +fatal. Availability fallback does not admit a different compiler. Scalar proof +CI additionally pins Lean 4.15.0's release archive SHA-256 to +`af71a2569a9f68337de2434829b3008cd8e32c436e9cb6bd8c84a2c2ba3585c9`. +This is the official release URL's archive observed in hosted run +`45472034875`, not an independently published upstream signature. The whole +system/package closure remains outside the reproducibility claim. + Agda runs `--safe --without-K` and fresh interface checks in both profiles. These flags do not prove that a Dedukti/CIC export exists. CI must demonstrate the pinned release profile; a local pass on newer Idris/Agda is not substituted diff --git a/docs/plan/ULTRAPLAN.adoc b/docs/plan/ULTRAPLAN.adoc index f86b700a..47d44783 100644 --- a/docs/plan/ULTRAPLAN.adoc +++ b/docs/plan/ULTRAPLAN.adoc @@ -1,7 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell = Atoma — soundness-first plan to v1 -:revdate: 2026-11-07 +:revdate: 2026-11-24 :toc: Atoma is experimental. The release objective is a useful verifier for an @@ -45,6 +45,21 @@ The following gaps remain central: == Definition of v1 +The first experimental MVP is the closed scalar consumer path described in +link:../decisions/ATOMA-SCALAR-SOURCE.adoc[the scalar source decision]. Its first +complete hosted evidence is +https://github.com/hyperpolymath/atoma/actions/runs/45491963944[run 45491963944] +at `3ea192650d752da1e4dbb504c7fa2a6568778aed`: fresh Idris contracts, actual +Proven/UAA Zig helpers, all-input native comparisons, independent source +interpretation, kernel replay and negative controls. Later manifest-hardening +changes must also pass the required exact-head gate before merge. +Whole-boundary receipts remain INCOMPLETE. +This milestone precedes v1; it does not discharge memory, state, compiler +refinement or the full checker chain. #28 merged on 2026-11-24 after its required +soundness and CI checks passed; consumer source checking and its evidence are +in #30. Next, prove the full-word decoder relation and the registry state/effect +contract before extending source interpretation to calls, memory or ownership. + All applicable rows must pass on the release commit. They are conjunctive gates, not a readiness percentage. diff --git a/docs/status/ROADMAP.adoc b/docs/status/ROADMAP.adoc index f605209d..ad42ea67 100644 --- a/docs/status/ROADMAP.adoc +++ b/docs/status/ROADMAP.adoc @@ -1,7 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Atoma roadmap -:revdate: 2026-11-07 +:revdate: 2026-11-24 The active link:../plan/ULTRAPLAN.adoc[v1 plan] owns milestone acceptance and estimates. Atoma is experimental. There is no overall readiness percentage. @@ -19,12 +19,32 @@ Identity/ownership repair instantiates the original RSR template provenance, removes its production claims, and names `atoma_chora.deed`. The PR's current head must independently pass hosted checks before merge. -== Next acceptance - -* Extend the locally passing finite-model replay slice to a checked - source-to-model argument. Its ECHIDNA/coqchk path requires fresh source/proof - identity and closed assumptions; it does not establish Zig refinement. -* Typed semantic boundary and explicit memory/alias counterexample. +== Experimental scalar MVP and next acceptance + +The immediate experimental MVP is scoped by +link:../decisions/ATOMA-SCALAR-SOURCE.adoc[the closed scalar source decision]. +Complete hosted evidence was obtained at +`3ea192650d752da1e4dbb504c7fa2a6568778aed` in +https://github.com/hyperpolymath/atoma/actions/runs/45491963944[run 45491963944]: +both real consumers, every byte input in four Zig build modes, source replay, +closed assumptions and all five scalar replay attacks. Subsequent gate +hardening requires both consumers exactly once, validates complete manifest +records and requires completed evidence from each. Every PR head must pass +the required checks before merge. The implemented path connects +the actual Proven word encoder and UAA protocol classifier to fresh Idris2 +contracts and independently interprets their source bytes in Coq. It leaves +pointer/ownership and stateful foreign-boundary obligations explicit. + +* Proven: prove decoder acceptance iff the entire 64-bit word is a canonical + byte encoding, then bind the actual raw-word decoder source and its encoder + dependency. Immediate tagged words are not allocated objects; pointer-carrier + correspondence and later buffer leases remain separate obligations. +* UAA: prove state-preserving refusals, selected callback/context identity, + busy-state framing and restoration after a normally returning callback. + State the serialized access and borrowed-lifetime preconditions explicitly. +* Extend checked source interpretation to these operations, with an explicit + memory/alias counterexample before admitting pointer-bearing effects. The + ECHIDNA/coqchk path does not establish general Zig/compiler refinement. * Second-language transfer spike before choosing the full sibling sequence. Store, loops, permissions, compiler refinement and the complete required @@ -32,7 +52,8 @@ kernel chain remain open. A passing scoped gate is not production readiness. == Dogfooding status -The frame and u8 examples exercise the local verifier/tooling path. No external -consumer evidence window or broad CRG qualification has been established. +The frame and u8 examples exercise the local verifier/tooling path. Proven and +UAA now supply real scalar helpers and fresh Idris2 oracle evidence in hosted +CI. No production deployment window or broad CRG qualification is established. The four inherited Idris ABI quarantines remain documented and excluded from claims about checked implementations. See link:PROOF-STATUS.adoc[proof status]. diff --git a/examples/atoma/frame-v1/verify.sh b/examples/atoma/frame-v1/verify.sh index 7dbf304c..f54ab200 100755 --- a/examples/atoma/frame-v1/verify.sh +++ b/examples/atoma/frame-v1/verify.sh @@ -66,7 +66,7 @@ bash "$root/scripts/atoma-check-idris.sh" || die "F0.1 Idris2 contract/extractio atoma_tests=0 test_log=$(mktemp) trap 'rm -f "$test_log"' EXIT -for m in canon frontend vc source; do +for m in canon frontend vc source scalar; do "$ZIG" test "$root/tools/atoma/src/$m.zig" > "$test_log" 2>&1 || { cat "$test_log" >&2; die "unit tests in $m.zig" } @@ -74,7 +74,7 @@ for m in canon frontend vc source; do [ -n "$n" ] || die "cannot count the tests in $m.zig" atoma_tests=$((atoma_tests + n)) done -printf 'atoma %s tests (canon + frontend + vc + source)\n' "$atoma_tests" +printf 'atoma %s tests (canon + frontend + vc + source + scalar)\n' "$atoma_tests" cd "$here" diff --git a/scripts/atoma-ci-toolchain.sh b/scripts/atoma-ci-toolchain.sh index bcf0681e..9b2401c4 100644 --- a/scripts/atoma-ci-toolchain.sh +++ b/scripts/atoma-ci-toolchain.sh @@ -6,14 +6,12 @@ set -euo pipefail : "${RUNNER_TEMP:?GitHub runner scratch directory required}" : "${GITHUB_PATH:?GitHub PATH file required}" task="$RUNNER_TEMP/atoma-toolchain" +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) mkdir -p "$task" cd "$task" sudo apt-get update sudo apt-get install -y --no-install-recommends agda-bin=2.6.3-1build1 chezscheme build-essential libgmp-dev curl ca-certificates unzip xz-utils -curl --proto '=https' --proto-redir '=https' -fL --retry 3 https://ziglang.org/download/0.15.2/zig-x86_64-linux-0.15.2.tar.xz -o zig.tar.xz -echo '02aa270f183da276e5b5920b1dac44a63f1a49e55050ebde3aecc9eb82f93239 zig.tar.xz' | sha256sum -c - -tar -xf zig.tar.xz -echo "$task/zig-x86_64-linux-0.15.2" >> "$GITHUB_PATH" +bash "$root/scripts/atoma-download-zig.sh" "$task" curl --proto '=https' --proto-redir '=https' -fL --retry 3 https://github.com/Z3Prover/z3/releases/download/z3-4.13.3/z3-4.13.3-x64-glibc-2.35.zip -o z3.zip echo '32c7377026733c9d7b33c21cd77a68f50ba682367207b031a6bfd80140a8722f z3.zip' | sha256sum -c - unzip -q z3.zip diff --git a/scripts/atoma-consumer-manifest.sh b/scripts/atoma-consumer-manifest.sh new file mode 100644 index 00000000..54d5b18d --- /dev/null +++ b/scripts/atoma-consumer-manifest.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +# Both real consumers are mandatory, exactly once, before any expensive work. +set -euo pipefail +[[ $# == 1 ]] || exit 2 +declare -A seen=() +while read -r repo revision helper oracle extra || [[ -n ${repo:-} ]]; do + [[ $repo == \#* || -z $repo ]] && continue + case "$repo" in proven|unified-api-adapter) ;; *) echo 'Invalid consumer manifest: unknown repository' >&2; exit 1 ;; esac + [[ -z ${seen[$repo]:-} ]] || { echo 'Invalid consumer manifest: duplicate repository' >&2; exit 1; } + [[ -z ${extra:-} && $revision =~ ^[0-9a-f]{40}$ && -n $helper && -n $oracle ]] || { + echo 'Invalid consumer manifest: malformed row' >&2; exit 1; + } + seen[$repo]=1 +done < "$1" +[[ ${seen[proven]:-} == 1 && ${seen[unified-api-adapter]:-} == 1 && ${#seen[@]} == 2 ]] || { + echo 'Invalid consumer manifest: both Proven and UAA are required' >&2; exit 1; +} diff --git a/scripts/atoma-consumer-scalar-gate.sh b/scripts/atoma-consumer-scalar-gate.sh new file mode 100644 index 00000000..057c6e2e --- /dev/null +++ b/scripts/atoma-consumer-scalar-gate.sh @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +# Hosted CI only: fresh Idris contracts, actual consumer source, native witnesses. +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +evidence_root="$root/build/atoma-evidence/scalar-consumers" +mkdir -p "$evidence_root" +out=$(mktemp -d "$evidence_root/run.XXXXXXXX") +echo "Scalar consumer evidence: $out" +cp "$root/tests/consumer-scalar/consumers.tsv" "$out/" +bash "$root/scripts/atoma-consumer-manifest.sh" "$out/consumers.tsv" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +for tool in git idris2 zig coqc coqchk echidna jq; do command -v "$tool" >/dev/null; done +[[ $(zig version) == 0.15.2 ]] +idris2 --version > "$out/idris-version.txt" +zig env > "$out/zig-environment.json" + +while read -r repo revision helper oracle extra || [[ -n ${repo:-} ]]; do + [[ $repo == \#* || -z $repo ]] && continue + [[ -z ${extra:-} && $revision =~ ^[0-9a-f]{40}$ ]] + case "$repo" in proven|unified-api-adapter) ;; *) exit 1 ;; esac + checkout="$work/$repo" + git init -q "$checkout" + git -C "$checkout" remote add origin "https://github.com/hyperpolymath/$repo.git" + git -C "$checkout" fetch -q --depth 1 origin "$revision" + git -C "$checkout" checkout -q --detach FETCH_HEAD + [[ $(git -C "$checkout" rev-parse HEAD) == "$revision" ]] + evidence="$out/$repo" + mkdir "$evidence" + run="$work/$repo-run" + mkdir "$run" + cp "$checkout/$helper" "$run/source.zig" + cp "$checkout/$oracle" "$run/Main.idr" + if [[ $repo == proven ]]; then + mkdir -p "$run/Proven/FFI" + cp "$checkout/src/Proven/FFI/RefCBits8.idr" "$run/Proven/FFI/" + cp "$checkout/ffi/zig/src/refc/bits8.zig" "$evidence/consumer-wrapper.zig" + call='source.encodeWord(byte)' + mutation='s/| 1/| 0/' + else + cp -R "$checkout/src/interface/Abi" "$run/" + cp "$checkout/src/interface/ffi/src/registry.zig" "$evidence/consumer-wrapper.zig" + call='@as(u64, @intFromBool(source.known(byte)))' + mutation='s/<= 9/<= 10/' + fi + ( + cd "$run" + find . -name '*.idr' -print0 | LC_ALL=C sort -z | xargs -0 sha256sum + sha256sum source.zig + ) > "$evidence/inputs.sha256" + (cd "$run"; idris2 --total -Werror --codegen refc -o oracle Main.idr) > "$evidence/idris-build.txt" 2>&1 || { + cat "$evidence/idris-build.txt" >&2; exit 1; + } + if grep -q '^Error:' "$evidence/idris-build.txt"; then cat "$evidence/idris-build.txt" >&2; exit 1; fi + [[ -x "$run/build/exec/oracle" ]] + (cd "$run"; printf ':m\n:q\n' | idris2 --no-banner Main.idr) > "$evidence/idris-holes.txt" 2>&1 + grep -q 'No holes' "$evidence/idris-holes.txt" + if grep -q '^Error:' "$evidence/idris-holes.txt"; then cat "$evidence/idris-holes.txt" >&2; exit 1; fi + "$run/build/exec/oracle" > "$evidence/contract.tsv" + # A standalone pure Zig caller tests the compiled helper. No C FFI is added. + cat > "$run/runner.zig" < "$evidence/zig-$mode.txt" 2>&1 || { + cat "$evidence/zig-$mode.txt" >&2; exit 1; + } + "$run/native-$mode" > "$evidence/native-$mode.tsv" + cmp "$evidence/contract.tsv" "$evidence/native-$mode.tsv" + done + bash "$root/scripts/atoma-scalar-replay.sh" "$run/source.zig" "$evidence/contract.tsv" "$evidence/replay" + # Compile the wrong body successfully, then require an observable mismatch. + sed "$mutation" "$run/source.zig" > "$run/mutant.zig" + ! cmp -s "$run/source.zig" "$run/mutant.zig" + cp "$run/source.zig" "$run/original.zig" + cp "$run/mutant.zig" "$run/source.zig" + zig build-exe "$run/runner.zig" -O ReleaseSafe -femit-bin="$run/mutant" > "$evidence/mutant-build.txt" 2>&1 + "$run/mutant" > "$evidence/mutant.tsv" + if cmp -s "$evidence/contract.tsv" "$evidence/mutant.tsv"; then + echo "FAIL native mutation survived: $repo" >&2; exit 1 + fi + if bash "$root/scripts/atoma-scalar-replay.sh" "$run/source.zig" "$evidence/contract.tsv" "$evidence/rejected-mutant" > "$evidence/mutant-replay.txt" 2>&1; then + echo "FAIL source mutation proved: $repo" >&2; exit 1 + fi + grep -q 'ECHIDNA did not verify' "$evidence/mutant-replay.txt" + cp "$run/original.zig" "$run/source.zig" + (cd "$run"; sha256sum -c "$evidence/inputs.sha256") > "$evidence/recheck.txt" + jq -cnS --arg repo "$repo" --arg revision "$revision" --arg helper "$helper" --arg oracle "$oracle" \ + '{schema:"atoma.consumer.scalar/1",status:"INCOMPLETE",repository:$repo,revision:$revision, + helper:$helper,oracle:$oracle,inputs:256,contract:"fresh total Idris2 RefC oracle; no holes", + native_modes:["Debug","ReleaseSafe","ReleaseFast","ReleaseSmall"], + replay:"original bytes interpreted in Coq; ECHIDNA plus coqchk and assumption audit", + open:["Zig compiler refinement","Idris primitive/compiler correspondence","pointer leases","whole-wrapper effects"]}' > "$evidence/receipt.json" + printf 'CONSUMER-SCALAR-CHECKED %s %s\n' "$repo" "$revision" +done < "$out/consumers.tsv" +[[ -s "$out/proven/receipt.json" && -s "$out/unified-api-adapter/receipt.json" ]] || { + echo 'FAIL both consumer executions must complete' >&2; exit 1; +} +bash "$root/scripts/atoma-scalar-replay-falsifiers.sh" "$out/proven/replay/source.zig" \ + "$out/proven/contract.tsv" "$out/replay-falsifiers" +echo 'CONSUMER SCALARS PASS: source interpretation and native witnesses; full boundary remains INCOMPLETE' diff --git a/scripts/atoma-download-zig.sh b/scripts/atoma-download-zig.sh new file mode 100644 index 00000000..fb9ccc82 --- /dev/null +++ b/scripts/atoma-download-zig.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +# Mirrors change availability, never the accepted archive identity. +set -euo pipefail +[[ $# == 1 && $1 == /* ]] +: "${GITHUB_PATH:?GitHub PATH file required}" +mkdir -p "$1" +cd "$1" +archive=zig-x86_64-linux-0.15.2.tar.xz +downloaded=false +for url in \ + "https://zigmirror.hryx.net/zig/$archive" \ + "https://zig.linus.dev/zig/$archive" \ + "https://ziglang.org/download/0.15.2/$archive"; do + if curl --proto '=https' --proto-redir '=https' --connect-timeout 20 --max-time 120 -fL "$url" -o "$archive"; then + echo "02aa270f183da276e5b5920b1dac44a63f1a49e55050ebde3aecc9eb82f93239 $archive" | sha256sum -c - + downloaded=true + break + fi +done +[[ $downloaded == true ]] || { echo 'FAIL all pinned Zig download locations unavailable' >&2; exit 1; } +tar -xf "$archive" +echo "$PWD/zig-x86_64-linux-0.15.2" >> "$GITHUB_PATH" diff --git a/scripts/atoma-gate.sh b/scripts/atoma-gate.sh index 8a1a2650..51799886 100644 --- a/scripts/atoma-gate.sh +++ b/scripts/atoma-gate.sh @@ -74,6 +74,7 @@ grep -q 'TestExpectedEqual' "$evidence/compiled-bad.txt" bash scripts/atoma-gate-falsifiers.sh | tee "$evidence/falsifiers.txt" bash scripts/atoma-replay-gate.sh | tee "$evidence/replay.txt" +bash scripts/atoma-consumer-scalar-gate.sh | tee "$evidence/scalar-consumers.txt" # Bind the source, contracts, proof sources and gate definitions to this run. # Exclude generated caches/witnesses to avoid self-referential digests. find tools/atoma/src examples/atoma/frame-v1/src examples/atoma/frame-v1/abi \ diff --git a/scripts/atoma-scalar-capsule.sh b/scripts/atoma-scalar-capsule.sh new file mode 100644 index 00000000..01363915 --- /dev/null +++ b/scripts/atoma-scalar-capsule.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +# Independently bind the emitted literal bytes/table to the original inputs. +set -euo pipefail +[[ $# == 3 ]] || { echo 'usage: atoma-scalar-capsule.sh SOURCE TABLE PROOF' >&2; exit 2; } +expected=$(mktemp) +actual=$(mktemp) +trap 'rm -f "$expected" "$actual"' EXIT +{ + printf 'Definition source_bytes : list nat := [' + od -An -v -tu1 "$1" | awk '{for(i=1;i<=NF;i++){printf "%s%s", sep, $i; sep="; "}}' + printf '].\nDefinition specification : list N := [' + awk '{sub(/\r$/, "")} NF != 2 || $1 !~ /^[0-9]+$/ || $2 !~ /^[0-9]+$/ || $1 != NR-1 {exit 1} + {printf "%s%s%%N", sep, $2; sep="; "} END {if(NR != 256) exit 1}' "$2" + printf '].\n' +} > "$expected" +grep '^Definition \(source_bytes\|specification\) :' "$3" > "$actual" +cmp -s "$expected" "$actual" || { echo 'SCALAR-REFUSED: capsule differs from source/contract bytes' >&2; exit 1; } diff --git a/scripts/atoma-scalar-proof-gate.sh b/scripts/atoma-scalar-proof-gate.sh new file mode 100644 index 00000000..ce6fbdf0 --- /dev/null +++ b/scripts/atoma-scalar-proof-gate.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +# Proof development and adversarial controls; consumer CI adds Idris authority. +set -euo pipefail +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$root" +for tool in zig agda lean coqc coqchk; do command -v "$tool" >/dev/null; done +[[ $(zig version) == 0.15.2 ]] +[[ $(lean --version) == 'Lean (version 4.15.0,'* ]] +out="$root/build/scalar-proof-evidence" +mkdir -p "$out" +work=$(mktemp -d) +trap 'status=$?; if ((status)); then tail -n 50 "$out"/*.txt >&2; fi; rm -rf "$work"' EXIT +cp verification/atoma/consumer/agda/ScalarReflection.agda "$work/" +cp verification/atoma/consumer/agda/ScalarReflectionCubical.agda "$work/" +cp verification/atoma/consumer/lean4/ScalarReflection.lean "$work/" +cp verification/atoma/consumer/coq/ScalarSource.v "$work/" +( + cd "$work" + agda --safe --without-K --cubical-compatible --double-check --warning=error ScalarReflection.agda + # Collect each independent leg's diagnostics, but every leg is mandatory. + theory_failed=0 + if ! lean ScalarReflection.lean > "$out/lean-assumptions.txt" 2>&1; then theory_failed=1; fi + if [[ $(grep -c 'does not depend on any axioms' "$out/lean-assumptions.txt") != 2 ]]; then theory_failed=1; fi + if ! coqc -q ScalarSource.v > "$out/coq-assumptions.txt" 2>&1; then theory_failed=1; fi + if [[ $(grep -c '^Closed under the global context$' "$out/coq-assumptions.txt") != 2 ]]; then theory_failed=1; fi + if ! coqchk -silent -Q . '' ScalarSource > "$out/coqchk.txt" 2>&1; then theory_failed=1; fi + if ! agda --safe --cubical --double-check --warning=error ScalarReflectionCubical.agda > "$out/cubical.txt" 2>&1; then theory_failed=1; fi + [[ $theory_failed == 0 ]] +) > "$out/theory.txt" 2>&1 +(cd tools/atoma && zig build test && zig build) +atoma="$root/tools/atoma/zig-out/bin/atoma" +bash scripts/atoma-consumer-manifest.sh tests/consumer-scalar/consumers.tsv +for missing in proven unified-api-adapter; do + sed "/^${missing}[[:space:]]/d" tests/consumer-scalar/consumers.tsv > "$work/missing.tsv" + if bash scripts/atoma-consumer-manifest.sh "$work/missing.tsv" > "$out/missing-$missing.txt" 2>&1; then + echo "FAIL accepted missing consumer $missing" >&2; exit 1 + fi + grep -q 'both Proven and UAA are required' "$out/missing-$missing.txt" +done +cat tests/consumer-scalar/consumers.tsv tests/consumer-scalar/consumers.tsv > "$work/duplicate.tsv" +if bash scripts/atoma-consumer-manifest.sh "$work/duplicate.tsv" > "$out/duplicate-consumer.txt" 2>&1; then + echo 'FAIL accepted duplicate consumers' >&2; exit 1 +fi +grep -q 'duplicate repository' "$out/duplicate-consumer.txt" +cp tests/consumer-scalar/consumers.tsv "$work/unterminated.tsv" +truncate -s -1 "$work/unterminated.tsv" +bash scripts/atoma-consumer-manifest.sh "$work/unterminated.tsv" +cat tests/consumer-scalar/consumers.tsv > "$work/unterminated-duplicate.tsv" +awk '/^proven[[:space:]]/ {printf "%s", $0}' tests/consumer-scalar/consumers.tsv >> "$work/unterminated-duplicate.tsv" +if bash scripts/atoma-consumer-manifest.sh "$work/unterminated-duplicate.tsv" > "$out/unterminated-duplicate.txt" 2>&1; then + echo 'FAIL accepted unterminated duplicate consumer' >&2; exit 1 +fi +grep -q 'duplicate repository' "$out/unterminated-duplicate.txt" +# These fixture tables are test data only. Real consumer receipts require fresh +# tables from the pinned Idris ABI modules; never promote these fixtures. +awk 'BEGIN {for(i=0;i<256;i++) printf "%d %.0f\n",i,i*4294967296+1}' > "$work/encode.tsv" +awk 'BEGIN {for(i=0;i<256;i++) print i,(i>=1 && i<=9 ? 1 : 0)}' > "$work/known.tsv" +for fixture in encode known; do + "$atoma" scalar-coq "tests/consumer-scalar/$fixture.zig" "$work/$fixture.tsv" > "$work/AtomaProof.v" + bash scripts/atoma-scalar-capsule.sh "tests/consumer-scalar/$fixture.zig" "$work/$fixture.tsv" "$work/AtomaProof.v" + # Table line endings affect the input digest, not its numeric contract. + sed 's/$/\r/' "$work/$fixture.tsv" > "$work/$fixture-crlf.tsv" + "$atoma" scalar-coq "tests/consumer-scalar/$fixture.zig" "$work/$fixture-crlf.tsv" > "$work/CRLF.v" + cmp "$work/AtomaProof.v" "$work/CRLF.v" + bash scripts/atoma-scalar-capsule.sh "tests/consumer-scalar/$fixture.zig" "$work/$fixture-crlf.tsv" "$work/CRLF.v" + (cd "$work" && coqc -q AtomaProof.v && coqchk -silent -Q . '' AtomaProof) > "$out/$fixture.txt" 2>&1 + "$atoma" scalar-coq-audit "tests/consumer-scalar/$fixture.zig" "$work/$fixture.tsv" > "$work/Audit.v" + (cd "$work" && coqc -q Audit.v) > "$out/$fixture-audit.txt" 2>&1 + [[ $(grep -c '^Closed under the global context$' "$out/$fixture-audit.txt") == 2 ]] +done +reject_proof() { + local name=$1 source=$2 table=$3 + "$atoma" scalar-coq "$source" "$table" > "$work/Bad.v" + if (cd "$work" && coqc -q Bad.v) > "$out/$name.txt" 2>&1; then + echo "FAIL accepted $name" >&2; exit 1 + fi + grep -q 'Unable to unify' "$out/$name.txt" +} +sed 's/<< 32/<< 31/' tests/consumer-scalar/encode.zig > "$work/shift.zig" +reject_proof wrong-shift "$work/shift.zig" "$work/encode.tsv" +sed 's/| 1/| 0/' tests/consumer-scalar/encode.zig > "$work/tag.zig" +reject_proof wrong-tag "$work/tag.zig" "$work/encode.tsv" +sed 's/<= 9/<= 10/' tests/consumer-scalar/known.zig > "$work/range.zig" +reject_proof wrong-range "$work/range.zig" "$work/known.tsv" +cat tests/consumer-scalar/known.zig > "$work/import.zig" +printf '\nconst hidden = @import("hidden.zig");\n' >> "$work/import.zig" +reject_proof unsupported-import "$work/import.zig" "$work/known.tsv" +cp "$work/known.tsv" "$work/wrong-contract.tsv" +sed -i 's/^9 1$/9 0/' "$work/wrong-contract.tsv" +reject_proof wrong-contract tests/consumer-scalar/known.zig "$work/wrong-contract.tsv" +"$atoma" scalar-coq tests/consumer-scalar/known.zig "$work/known.tsv" > "$work/stale.v" +if bash scripts/atoma-scalar-capsule.sh "$work/range.zig" "$work/known.tsv" "$work/stale.v" > "$out/stale-source.txt" 2>&1; then + echo 'FAIL accepted stale source capsule' >&2; exit 1 +fi +grep -q 'capsule differs' "$out/stale-source.txt" +sha256sum verification/atoma/consumer/{coq,agda,lean4}/* tools/atoma/src/scalar.zig > "$out/inputs.sha256" +echo 'SCALAR THEORY PASS: finite reflection and raw-source fixtures; consumer and compiler boundaries remain separate' diff --git a/scripts/atoma-scalar-replay-falsifiers.sh b/scripts/atoma-scalar-replay-falsifiers.sh new file mode 100644 index 00000000..0377c2f8 --- /dev/null +++ b/scripts/atoma-scalar-replay-falsifiers.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +set -euo pipefail +[[ $# == 3 ]] || exit 2 +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +source_path=$(realpath "$1") +table_path=$(realpath "$2") +out=$(realpath -m "$3") +mkdir "$out" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +export REAL_COQC +REAL_COQC=$(command -v coqc) +mkdir "$work/bin" +cat > "$work/bin/echidna" <<'FAKE' +#!/usr/bin/env bash +set -euo pipefail +[[ $1 == prove ]] +goal=$2 +case "$FAKE_MODE" in + verdict-only) ;; + wrong-theorem) + cat > "$goal" <<'COQ' +Theorem atoma_scalar : True. Proof. exact I. Qed. +Theorem atoma_scalar_range : True. Proof. exact I. Qed. +COQ + "$REAL_COQC" -q "$goal" >&2 ;; + admitted) + sed -i '/^Proof\. exact (ScalarSource\.check_/c\Admitted.' "$goal" + "$REAL_COQC" -q "$goal" >&2 ;; + changed-checker) + "$REAL_COQC" -q "$goal" >&2 + printf 'tamper' >> ScalarSource.vo ;; + changed-capsule) + # Whitespace preserves interpreted behavior, but cannot preserve identity. + sed -i '/^Definition source_bytes :/s/\]\.$/; 10]./' "$goal" + "$REAL_COQC" -q "$goal" >&2 ;; + *) exit 2 ;; +esac +jq -cn --arg goal "$goal" '{schema:"echidna.prove.result/1",status:"verified",prover:"Coq",goal:$goal,trust:{axioms:[],confidence:null}}' +FAKE +chmod +x "$work/bin/echidna" +for mode in verdict-only wrong-theorem admitted changed-checker changed-capsule; do + if PATH="$work/bin:$PATH" FAKE_MODE="$mode" bash "$root/scripts/atoma-scalar-replay.sh" \ + "$source_path" "$table_path" "$out/$mode" > "$out/$mode.txt" 2>&1; then + echo "FAIL scalar replay accepted $mode" >&2; exit 1 + fi + case "$mode" in + verdict-only) grep -q 'missing compiled proof' "$out/$mode.txt" ;; + wrong-theorem) grep -q 'expected to have type' "$out/$mode/assumptions.txt" ;; + admitted) grep -q 'unexpected assumption closure' "$out/$mode.txt" ;; + changed-checker) grep -q 'backend changed the independently compiled source checker' "$out/$mode.txt" ;; + changed-capsule) grep -q 'capsule differs' "$out/$mode.txt" ;; + esac +done +echo 'SCALAR REPLAY CONTROLS PASS: verdict, theorem, assumptions, checker and capsule attacks refused' diff --git a/scripts/atoma-scalar-replay.sh b/scripts/atoma-scalar-replay.sh new file mode 100644 index 00000000..8c572322 --- /dev/null +++ b/scripts/atoma-scalar-replay.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# Copyright (c) 2026 Jonathan D.A. Jewell +set -euo pipefail +[[ $# == 3 ]] || { echo 'usage: atoma-scalar-replay.sh SOURCE TABLE NEW_EVIDENCE_DIRECTORY' >&2; exit 2; } +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +ATOMA=${ATOMA:-$root/tools/atoma/zig-out/bin/atoma} +fail() { echo "SCALAR-REPLAY-REFUSED: $*" >&2; exit 1; } +for tool in "$ATOMA" echidna coqc coqchk jq timeout sha256sum; do + command -v "$tool" >/dev/null || fail "missing tool: $tool" +done +ATOMA=$(realpath "$(command -v "$ATOMA")") +source_path=$(realpath "$1") +table_path=$(realpath "$2") +out=$(realpath -m "$3") +mkdir "$out" || fail 'evidence directory must be new' +cp "$source_path" "$out/source.zig" +cp "$table_path" "$out/contract.tsv" +cp "$root/verification/atoma/consumer/coq/ScalarSource.v" "$out/" +"$ATOMA" scalar-coq "$out/source.zig" "$out/contract.tsv" > "$out/AtomaProof.v" +bash "$root/scripts/atoma-scalar-capsule.sh" "$out/source.zig" "$out/contract.tsv" "$out/AtomaProof.v" +cd "$out" +coqc --version > coqc-version.txt +case $(head -n 1 coqc-version.txt) in + 'The Coq Proof Assistant, version 8.18.0'|'The Rocq Prover, version 9.2') ;; + *) fail 'unsupported Coq/Rocq profile' ;; +esac +timeout -k 5 120 coqc -q ScalarSource.v > library-assumptions.txt 2>&1 +[[ $(grep -c '^Closed under the global context$' library-assumptions.txt) == 2 ]] +checker_digest=$(sha256sum ScalarSource.vo) +timeout -k 5 120 echidna prove "$out/AtomaProof.v" --prover coq --timeout 90 --output json > echidna.json 2> echidna.stderr \ + || fail 'ECHIDNA did not verify the source interpretation' +jq -e -s --arg goal "$out/AtomaProof.v" ' + length == 1 and (.[0] | .schema == "echidna.prove.result/1" and + .status == "verified" and .prover == "Coq" and .goal == $goal and + .trust.axioms == [] and .trust.confidence == null)' echidna.json >/dev/null +[[ -s AtomaProof.vo ]] || fail 'missing compiled proof' +[[ $(sha256sum ScalarSource.vo) == "$checker_digest" ]] || fail 'backend changed the independently compiled source checker' +timeout -k 5 120 coqchk -silent -Q . '' ScalarSource AtomaProof > coqchk.txt 2>&1 +"$ATOMA" scalar-coq-audit source.zig contract.tsv > Audit.v +bash "$root/scripts/atoma-scalar-capsule.sh" source.zig contract.tsv Audit.v +timeout -k 5 120 coqc -q -Q . '' Audit.v > assumptions.txt 2>&1 +[[ $(grep -c '^Closed under the global context$' assumptions.txt) == 2 ]] || fail 'unexpected assumption closure' +! grep -q '^Axioms:' assumptions.txt +cmp -s source.zig "$source_path" || fail 'source changed during replay' +cmp -s contract.tsv "$table_path" || fail 'contract changed during replay' +cmp -s ScalarSource.v "$root/verification/atoma/consumer/coq/ScalarSource.v" || fail 'checker changed during replay' +bash "$root/scripts/atoma-scalar-capsule.sh" source.zig contract.tsv AtomaProof.v +sha256sum source.zig contract.tsv ScalarSource.v ScalarSource.vo AtomaProof.v AtomaProof.vo Audit.v Audit.vo echidna.json coqchk.txt assumptions.txt > inputs.sha256 +for tool in "$ATOMA" echidna coqc coqchk; do sha256sum "$(command -v "$tool")"; done > tools.sha256 +jq -cnS --arg source "$(sha256sum source.zig | cut -d ' ' -f 1)" \ + --arg contract "$(sha256sum contract.tsv | cut -d ' ' -f 1)" \ + '{schema:"atoma.scalar.source/1",status:"INCOMPLETE",scope:"closed scalar source interpretation", + source_sha256:$source,contract_sha256:$contract,inputs:256,source_parser:"checked-in-Coq", + coqchk:"checked",assumptions:[],compiler_refinement:"unproved", + contract_authority:"caller must bind the table producer; see consumer evidence"}' > receipt.json +echo 'SCALAR-SOURCE-CHECKED: original bytes independently interpreted; compiler and foreign-boundary obligations remain' diff --git a/tests/consumer-scalar/consumers.tsv b/tests/consumer-scalar/consumers.tsv new file mode 100644 index 00000000..b6022496 --- /dev/null +++ b/tests/consumer-scalar/consumers.tsv @@ -0,0 +1,3 @@ +# repository commit helper contract-oracle +proven 21346ae1c85b7773a4bc16df51cb1ec5977f6b65 ffi/zig/src/refc/bits8_word.zig verification/header/ScalarOracle.idr +unified-api-adapter 730d0c775c9ce84edbe37854d49680cb3b3ed84d src/interface/ffi/src/protocol_tag.zig src/interface/ProtocolTagOracle.idr diff --git a/tests/consumer-scalar/encode.zig b/tests/consumer-scalar/encode.zig new file mode 100644 index 00000000..e565d400 --- /dev/null +++ b/tests/consumer-scalar/encode.zig @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell +pub fn encodeWord(value: u8) u64 { + return (@as(u64, value) << 32) | 1; +} diff --git a/tests/consumer-scalar/known.zig b/tests/consumer-scalar/known.zig new file mode 100644 index 00000000..231632af --- /dev/null +++ b/tests/consumer-scalar/known.zig @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell +pub fn known(tag: u8) bool { + return tag >= 1 and tag <= 9; +} diff --git a/tools/atoma/build.zig b/tools/atoma/build.zig index 41c218ba..ef15f40a 100644 --- a/tools/atoma/build.zig +++ b/tools/atoma/build.zig @@ -28,7 +28,7 @@ pub fn build(b: *std.Build) void { 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", "src/vc.zig", "src/source.zig" }) |path| { + for ([_][]const u8{ "src/canon.zig", "src/frontend.zig", "src/vc.zig", "src/source.zig", "src/scalar.zig" }) |path| { const unit_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path(path), diff --git a/tools/atoma/src/main.zig b/tools/atoma/src/main.zig index 5226f814..50a8e253 100644 --- a/tools/atoma/src/main.zig +++ b/tools/atoma/src/main.zig @@ -27,6 +27,7 @@ const canon = @import("canon.zig"); const frontend = @import("frontend.zig"); const vc = @import("vc.zig"); const source = @import("source.zig"); +const scalar = @import("scalar.zig"); const gpa = std.heap.page_allocator; @@ -71,7 +72,7 @@ fn sourceReport(comptime fmt: []const u8, args: anytype) void { } fn usage() noreturn { - sayLine("usage: atoma [args]"); + sayLine("usage: atoma [args]"); std.process.exit(2); } @@ -85,7 +86,27 @@ pub fn main() !void { if (args.len < 2) usage(); const cmd = args[1]; - if (std.mem.eql(u8, cmd, "source-vc") or std.mem.eql(u8, cmd, "source-coq") or std.mem.eql(u8, cmd, "source-coq-audit") or std.mem.eql(u8, cmd, "source-check")) { + if (std.mem.eql(u8, cmd, "scalar-coq") or std.mem.eql(u8, cmd, "scalar-coq-audit")) { + if (args.len != 4) usage(); + const src = readFile(args[2]) catch |e| { + std.debug.print("SCALAR-IO-ERROR: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + const table = readFile(args[3]) catch |e| { + std.debug.print("SCALAR-IO-ERROR: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + var out = std.Io.Writer.Allocating.init(gpa); + defer out.deinit(); + scalar.emit(&out.writer, src, table, std.mem.eql(u8, cmd, "scalar-coq-audit")) catch |e| { + std.debug.print("SCALAR-REFUSED: {s}\n", .{@errorName(e)}); + std.process.exit(1); + }; + std.fs.File.stdout().writeAll(out.written()) catch |e| { + std.debug.print("SCALAR-IO-ERROR: {s}\n", .{@errorName(e)}); + std.process.exit(3); + }; + } else if (std.mem.eql(u8, cmd, "source-vc") or std.mem.eql(u8, cmd, "source-coq") or std.mem.eql(u8, cmd, "source-coq-audit") or std.mem.eql(u8, cmd, "source-check")) { if (args.len != 3) usage(); const src = readFile(args[2]) catch |e| { print("SOURCE-IO-ERROR {s}: {s}\n", .{ args[2], @errorName(e) }); diff --git a/tools/atoma/src/scalar.zig b/tools/atoma/src/scalar.zig new file mode 100644 index 00000000..97f73357 --- /dev/null +++ b/tools/atoma/src/scalar.zig @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell +//! Serialize original source bytes and a complete authoritative byte table. +//! ScalarSource.v independently parses and interprets those bytes in Coq. +//! No Zig-side evaluator, lowering decision or success verdict enters a proof. +const std = @import("std"); + +pub fn contractTable(bytes: []const u8) ![256]u64 { + var values: [256]u64 = undefined; + var lines = std.mem.splitScalar(u8, bytes, '\n'); + var count: usize = 0; + while (lines.next()) |line| { + // Only the final empty line is permitted. + if (line.len == 0 and count == 256 and lines.peek() == null) break; + if (count == 256) return error.InvalidContractTable; + var words = std.mem.tokenizeAny(u8, line, " \t\r"); + const index = words.next() orelse return error.InvalidContractTable; + const value = words.next() orelse return error.InvalidContractTable; + if (words.next() != null) return error.InvalidContractTable; + if ((std.fmt.parseInt(usize, index, 10) catch return error.InvalidContractTable) != count) + return error.InvalidContractTable; + values[count] = std.fmt.parseInt(u64, value, 10) catch return error.InvalidContractTable; + count += 1; + } + if (count != 256) return error.InvalidContractTable; + return values; +} + +fn sourceLiteral(w: *std.Io.Writer, bytes: []const u8) !void { + try w.writeByte('['); + for (bytes, 0..) |b, i| { + if (i != 0) try w.writeAll("; "); + try w.print("{d}", .{b}); + } + try w.writeByte(']'); +} +fn tableLiteral(w: *std.Io.Writer, values: [256]u64) !void { + try w.writeByte('['); + for (values, 0..) |value, i| { + if (i != 0) try w.writeAll("; "); + try w.print("{d}%N", .{value}); + } + try w.writeByte(']'); +} + +pub fn emit(w: *std.Io.Writer, bytes: []const u8, table: []const u8, audit: bool) !void { + if (bytes.len == 0 or bytes.len > 16384) return error.UnsupportedSourceSize; + const values = try contractTable(table); + try w.writeAll("From Coq Require Import List Arith NArith.\nRequire Import ScalarSource.\nImport ListNotations.\n"); + try w.writeAll("Definition source_bytes : list nat := "); + try sourceLiteral(w, bytes); + try w.writeAll(".\nDefinition specification : list N := "); + try tableLiteral(w, values); + try w.writeAll(".\n"); + if (audit) { + try w.writeAll( + \\Require AtomaProof. + \\Check (AtomaProof.atoma_scalar : forall x, x < 256 -> + \\ ScalarSource.run source_bytes x = Some (nth x specification 0%N)). + \\Check (AtomaProof.atoma_scalar_range : forall x, x < 256 -> + \\ exists result, ScalarSource.run source_bytes x = Some result /\ (result < N.pow 2 64)%N). + \\Print Assumptions AtomaProof.atoma_scalar. + \\Print Assumptions AtomaProof.atoma_scalar_range. + \\ + ); + } else { + try w.writeAll( + \\Lemma source_accepted : ScalarSource.accepts source_bytes = true. + \\Proof. vm_compute. reflexivity. Qed. + \\Lemma table_checked : ScalarSource.check source_bytes specification = true. + \\Proof. vm_compute. reflexivity. Qed. + \\Theorem atoma_scalar : forall x, x < 256 -> + \\ ScalarSource.run source_bytes x = Some (nth x specification 0%N). + \\Proof. exact (ScalarSource.check_sound source_bytes specification table_checked). Qed. + \\Theorem atoma_scalar_range : forall x, x < 256 -> + \\ exists result, ScalarSource.run source_bytes x = Some result /\ (result < N.pow 2 64)%N. + \\Proof. exact (ScalarSource.check_range source_bytes specification table_checked). Qed. + \\Print Assumptions atoma_scalar. + \\Print Assumptions atoma_scalar_range. + \\ + ); + } +} + +test "contract tables reject missing, reordered, oversized and extra rows" { + try std.testing.expectError(error.InvalidContractTable, contractTable("")); + try std.testing.expectError(error.InvalidContractTable, contractTable("1 0\n")); + try std.testing.expectError(error.InvalidContractTable, contractTable("0 18446744073709551616\n")); + var bytes = std.Io.Writer.Allocating.init(std.testing.allocator); + defer bytes.deinit(); + for (0..256) |i| try bytes.writer.print("{d} {d}\n", .{ i, i }); + const values = try contractTable(bytes.written()); + try std.testing.expectEqual(@as(u64, 255), values[255]); + try bytes.writer.writeAll("256 0\n"); + try std.testing.expectError(error.InvalidContractTable, contractTable(bytes.written())); +} diff --git a/verification/atoma/consumer/agda/ScalarReflection.agda b/verification/atoma/consumer/agda/ScalarReflection.agda new file mode 100644 index 00000000..891233d1 --- /dev/null +++ b/verification/atoma/consumer/agda/ScalarReflection.agda @@ -0,0 +1,52 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell +{-# OPTIONS --safe --without-K --cubical-compatible --double-check #-} +module ScalarReflection where +open import Agda.Builtin.Nat using (Nat; zero; suc) +open import Agda.Builtin.Bool using (Bool; true; false) +open import Agda.Builtin.Equality using (_≡_; refl) + +data Empty : Set where + +-- An unindexed sum avoids constructor-index injectivity in Cubical matching. +data Step (A : Set) : Set where + first : Step A + next : A → Step A + +Fin : Nat → Set +Fin zero = Empty +Fin (suc n) = Step (Fin n) + +_&&_ : Bool → Bool → Bool +true && b = b +false && b = false + +allFin : (n : Nat) → (Fin n → Bool) → Bool +allFin zero p = true +allFin (suc n) p = p first && allFin n (λ i → p (next i)) + +left : ∀ {a b} → (a && b) ≡ true → a ≡ true +left {true} h = refl +left {false} () + +right : ∀ {a b} → (a && b) ≡ true → b ≡ true +right {true} h = h +right {false} () + +allFin-sound : (n : Nat) (p : Fin n → Bool) → + allFin n p ≡ true → (i : Fin n) → p i ≡ true +allFin-sound zero p h () +allFin-sound (suc n) p h first = left h +allFin-sound (suc n) p h (next i) = + allFin-sound n (λ j → p (next j)) (right {a = p first} h) i + +-- A successful exhaustive check establishes equality for every inhabitant, +-- provided the equality test reflects equality. It does not certify a parser. +reflection-sound : {A : Set} (eq : A → A → Bool) → + ((a b : A) → eq a b ≡ true → a ≡ b) → + (n : Nat) (body contract : Fin n → A) → + allFin n (λ i → eq (body i) (contract i)) ≡ true → + (i : Fin n) → body i ≡ contract i +reflection-sound eq eq-sound n body contract checked i = + eq-sound (body i) (contract i) + (allFin-sound n (λ j → eq (body j) (contract j)) checked i) diff --git a/verification/atoma/consumer/agda/ScalarReflectionCubical.agda b/verification/atoma/consumer/agda/ScalarReflectionCubical.agda new file mode 100644 index 00000000..a0d6ad5d --- /dev/null +++ b/verification/atoma/consumer/agda/ScalarReflectionCubical.agda @@ -0,0 +1,19 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell +{-# OPTIONS --safe --cubical --double-check #-} +module ScalarReflectionCubical where +open import Agda.Builtin.Bool using (Bool; true) +open import Agda.Builtin.Equality using (_≡_; refl) +open import Agda.Builtin.Cubical.Path using (PathP) +open import ScalarReflection + +toPath : ∀ {A : Set} {x y : A} → x ≡ y → PathP (λ _ → A) x y +toPath {x = x} refl i = x + +reflection-path : {A : Set} (eq : A → A → Bool) → + ((a b : A) → eq a b ≡ true → a ≡ b) → + ∀ n (body contract : Fin n → A) → + allFin n (λ i → eq (body i) (contract i)) ≡ true → + (i : Fin n) → PathP (λ _ → A) (body i) (contract i) +reflection-path eq eq-sound n body contract checked i = + toPath (reflection-sound eq eq-sound n body contract checked i) diff --git a/verification/atoma/consumer/coq/ScalarSource.v b/verification/atoma/consumer/coq/ScalarSource.v new file mode 100644 index 00000000..fddd8fd2 --- /dev/null +++ b/verification/atoma/consumer/coq/ScalarSource.v @@ -0,0 +1,177 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* Copyright (c) 2026 Jonathan D.A. Jewell *) +(* Independent interpretation of a closed, ASCII Zig source grammar. + The bytes, not an emitter-supplied AST or verdict, are the proof input. + This defines the admitted source semantics; Zig/compiler correspondence + outside this grammar and native pointer validity are not claimed. *) +From Coq Require Import List String Ascii Arith Bool NArith. +Import ListNotations. +Open Scope string_scope. +Open Scope nat_scope. + +Definition white (c : nat) := existsb (Nat.eqb c) [9; 10; 13; 32]. +Definition digit (c : nat) := (48 <=? c) && (c <=? 57). +Definition letter (c : nat) := + ((65 <=? c) && (c <=? 90)) || ((97 <=? c) && (c <=? 122)) || (c =? 95). +Definition wordchar (c : nat) := letter c || digit c. + +Fixpoint take_word (xs : list nat) : string * list nat := + match xs with + | [] => (EmptyString, []) + | c :: rest => if wordchar c then + let '(s, tail) := take_word rest in (String (ascii_of_nat c) s, tail) + else (EmptyString, xs) + end. + +Fixpoint after_comment (xs : list nat) : list nat := + match xs with + | [] => [] + | c :: rest => if c =? 10 then rest else after_comment rest + end. + +(* Fuel decreases on every token, whitespace byte or line comment. *) +Fixpoint lex (fuel : nat) (xs : list nat) : option (list string) := + match xs with + | [] => Some [] + | c :: rest => + match fuel with + | 0 => None + | S fuel' => + if white c then lex fuel' rest else + if c =? 47 then + match rest with + | 47 :: tail => lex fuel' (after_comment tail) + | _ => None + end + else + let token_tail := + if wordchar c then Some (take_word xs) else + match xs with + | 62 :: 61 :: tail => Some (">=", tail) + | 60 :: 61 :: tail => Some ("<=", tail) + | 60 :: 60 :: tail => Some ("<<", tail) + | _ => if existsb (Nat.eqb c) [40; 41; 58; 123; 125; 59; 64; 44; 124] + then Some (String (ascii_of_nat c) EmptyString, rest) + else None + end in + match token_tail with + | None => None + | Some (t, tail) => + match lex fuel' tail with + | Some ts => Some (t :: ts) + | None => None + end + end + end + end. + +Fixpoint decimal_acc (s : string) (acc : nat) : option nat := + match s with + | EmptyString => Some acc + | String c rest => + let n := nat_of_ascii c in + if digit n then decimal_acc rest (10 * acc + (n - 48)) else None + end. +Definition decimal (s : string) : option nat := + (* A small, explicit literal grammar; no hex, suffixes or coercions. *) + if (1 <=? String.length s) && (String.length s <=? 3) + then decimal_acc s 0 else None. + +Fixpoint identifier_tail (s : string) : bool := + match s with + | EmptyString => true + | String c rest => wordchar (nat_of_ascii c) && identifier_tail rest + end. +Definition identifier (s : string) : bool := + let reserved := ["pub"; "fn"; "return"; "u8"; "u64"; "bool"; + "and"; "or"; "as"; "true"; "false"; "undefined"; "_"] in + match s with + | EmptyString => false + | String c rest => letter (nat_of_ascii c) && identifier_tail rest && + negb (existsb (String.eqb s) reserved) + end. + +Inductive expression := +| shift_or (shift tag : nat) +| inclusive_range (lo hi : nat). + +Definition parse_tokens (ts : list string) : option expression := + match ts with + | ["pub"; "fn"; f; "("; x; ":"; "u8"; ")"; "u64"; "{"; + "return"; "("; "@"; "as"; "("; "u64"; ","; y; ")"; + "<<"; shift; ")"; "|"; tag; ";"; "}"] => + if identifier f && identifier x && negb (String.eqb f x) && String.eqb x y + then match decimal shift, decimal tag with + | Some s, Some t => if (s <=? 56) && (t <=? 255) + then Some (shift_or s t) else None + | _, _ => None + end + else None + | ["pub"; "fn"; f; "("; x; ":"; "u8"; ")"; "bool"; "{"; + "return"; y; ">="; lo; "and"; z; "<="; hi; ";"; "}"] => + if identifier f && identifier x && negb (String.eqb f x) && + String.eqb x y && String.eqb x z + then match decimal lo, decimal hi with + | Some l, Some h => if (l <=? 255) && (h <=? 255) + then Some (inclusive_range l h) else None + | _, _ => None + end + else None + | _ => None + end. + +Definition parse (bytes : list nat) : option expression := + if forallb (fun c => c parse_tokens ts + | None => None + end + else None. + +Definition evaluate (e : expression) (x : nat) : N := + match e with + | shift_or shift tag => N.lor (N.shiftl (N.of_nat x) (N.of_nat shift)) (N.of_nat tag) + | inclusive_range lo hi => if (lo <=? x) && (x <=? hi) then 1%N else 0%N + end. +Definition run (bytes : list nat) (x : nat) : option N := + match parse bytes with Some e => Some (evaluate e x) | None => None end. +Definition accepts (bytes : list nat) : bool := + match parse bytes with Some _ => true | None => false end. +Definition check (bytes : list nat) (expected : list N) : bool := + match parse bytes with + | None => false + | Some e => (List.length expected =? 256) && + forallb (fun x => N.eqb (evaluate e x) (nth x expected 0%N) && + N.ltb (evaluate e x) (N.pow 2 64)) (seq 0 256) + end. + +Theorem check_sound : forall bytes expected, + check bytes expected = true -> forall x, x < 256 -> + run bytes x = Some (nth x expected 0%N). +Proof. + intros bytes expected H x Hx. + unfold check in H. unfold run. + destruct (parse bytes) as [e|] eqn:E; [|discriminate]. + apply andb_true_iff in H as [_ H]. + rewrite forallb_forall in H. + assert (Hin : In x (seq 0 256)). + { apply in_seq. split; [apply Nat.le_0_l | exact Hx]. } + specialize (H x Hin). apply andb_true_iff in H as [H _]. + apply N.eqb_eq in H. now rewrite H. +Qed. + +Theorem check_range : forall bytes expected, + check bytes expected = true -> forall x, x < 256 -> + exists result, run bytes x = Some result /\ (result < N.pow 2 64)%N. +Proof. + intros bytes expected H x Hx. + unfold check in H. unfold run. + destruct (parse bytes) as [e|] eqn:E; [|discriminate]. + apply andb_true_iff in H as [_ H]. rewrite forallb_forall in H. + assert (Hin : In x (seq 0 256)). + { apply in_seq. split; [apply Nat.le_0_l | exact Hx]. } + specialize (H x Hin). apply andb_true_iff in H as [_ H]. + exists (evaluate e x). split; [reflexivity | now apply N.ltb_lt]. +Qed. +Print Assumptions check_sound. +Print Assumptions check_range. diff --git a/verification/atoma/consumer/lean4/ScalarReflection.lean b/verification/atoma/consumer/lean4/ScalarReflection.lean new file mode 100644 index 00000000..8cb8ad04 --- /dev/null +++ b/verification/atoma/consumer/lean4/ScalarReflection.lean @@ -0,0 +1,37 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Copyright (c) 2026 Jonathan D.A. Jewell +-- Re-proof of finite reflection. No Mathlib; not a Zig parser theorem. +def allBefore : Nat → (Nat → Bool) → Bool + | 0, _ => true + | n + 1, p => allBefore n p && p n + +theorem and_parts (a b : Bool) (h : (a && b) = true) : + a = true ∧ b = true := by + cases a <;> cases b + · cases h + · cases h + · cases h + · exact ⟨rfl, rfl⟩ + +theorem allBefore_sound (n : Nat) (p : Nat → Bool) + (h : allBefore n p = true) : ∀ i, i < n → p i = true := by + induction n with + | zero => intro i hi; exact False.elim (Nat.not_lt_zero i hi) + | succ n ih => + have parts := and_parts (allBefore n p) (p n) h + intro i hi + rcases Nat.eq_or_lt_of_le (Nat.le_of_lt_succ hi) with he | hl + · cases he + exact parts.2 + · exact ih parts.1 i hl + +theorem reflection_sound {A : Type} (eq : A → A → Bool) + (eq_sound : ∀ a b, eq a b = true → a = b) + (n : Nat) (body contract : Nat → A) + (checked : allBefore n (fun i => eq (body i) (contract i)) = true) : + ∀ i, i < n → body i = contract i := by + intro i hi + exact eq_sound _ _ (allBefore_sound n _ checked i hi) + +#print axioms allBefore_sound +#print axioms reflection_sound diff --git a/verification/proofs/agda/MANIFEST b/verification/proofs/agda/MANIFEST index 4c86d40e..0c645062 100644 --- a/verification/proofs/agda/MANIFEST +++ b/verification/proofs/agda/MANIFEST @@ -6,3 +6,5 @@ verification/atoma/agda|Bv.agda|gated| Atoma finite arithmetic model; safe witho verification/atoma/agda|Lin.agda|gated| Atoma resource model; safe without-K verification/atoma/agda|Core.agda|gated| Atoma store-free core; safe without-K verification/atoma/agda|Soundness.agda|gated| Atoma store-free theorem; not Zig refinement +verification/atoma/consumer/agda|ScalarReflection.agda|gated| finite reflection; safe cubical-compatible double-check +verification/atoma/consumer/agda|ScalarReflectionCubical.agda|gated| Cubical path leg of finite reflection diff --git a/verification/proofs/coq/MANIFEST b/verification/proofs/coq/MANIFEST index aa71524e..39cc17c5 100644 --- a/verification/proofs/coq/MANIFEST +++ b/verification/proofs/coq/MANIFEST @@ -2,3 +2,4 @@ # Format: ||gated|quarantine| # Ground-truthed 2026-07-17 with coqc. verification/proofs/coq|TypeSafety.v|gated| compiles under `coqc` +verification/atoma/consumer/coq|ScalarSource.v|gated| independent closed-source interpreter and finite reflection diff --git a/verification/proofs/lean4/MANIFEST b/verification/proofs/lean4/MANIFEST index f94230d9..1181b3b4 100644 --- a/verification/proofs/lean4/MANIFEST +++ b/verification/proofs/lean4/MANIFEST @@ -2,3 +2,4 @@ # Format: ||gated|quarantine| # Ground-truthed 2026-07-17 with Lean leanprover/lean4:v4.15.0 (via elan). verification/proofs/lean4|ApiTypes.lean|gated| compiles under Lean 4.15.0 (lean-toolchain); bounded_nat_le depends on no axioms; promoted 2026-11-09 when check-proofs.sh reported an unexpected pass +verification/atoma/consumer/lean4|ScalarReflection.lean|gated| finite reflection re-proof; no Mathlib