diff --git a/.github/workflows/atoma.yml b/.github/workflows/atoma.yml index 6bd714c0..f80ef077 100644 --- a/.github/workflows/atoma.yml +++ b/.github/workflows/atoma.yml @@ -16,8 +16,41 @@ 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 + cd "$RUNNER_TEMP" + 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 scalar-zig.tar.xz + echo '02aa270f183da276e5b5920b1dac44a63f1a49e55050ebde3aecc9eb82f93239 scalar-zig.tar.xz' | sha256sum -c - + tar -xf scalar-zig.tar.xz + echo "$RUNNER_TEMP/zig-x86_64-linux-0.15.2" >> "$GITHUB_PATH" + curl --proto '=https' --proto-redir '=https' -fL --retry 3 https://github.com/leanprover/lean4/releases/download/v4.15.0/lean-4.15.0-linux.tar.zst -o scalar-lean.tar.zst + 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: @@ -40,3 +73,15 @@ jobs: examples/atoma/frame-v1/witness/ if-no-files-found: error retention-days: 30 + + gate: + name: CI/gate + needs: [soundness] + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 2 + steps: + - name: Require successful source, contract and proof checks + env: + SOUNDNESS_RESULT: ${{ needs.soundness.result }} + run: test "$SOUNDNESS_RESULT" = success diff --git a/docs/decisions/2026-11-16-consumer-boundary-proof-design.adoc b/docs/decisions/2026-11-16-consumer-boundary-proof-design.adoc index ccf58625..b04b0dbb 100644 --- a/docs/decisions/2026-11-16-consumer-boundary-proof-design.adoc +++ b/docs/decisions/2026-11-16-consumer-boundary-proof-design.adoc @@ -36,10 +36,14 @@ Probe inputs, in order: lone CR, lone LF, CRLF, `clean`, embedded CR in `a\rZ`. Idris2 0.8.0 RefC output: `True True True False True`. Zig 0.15.2 output: `false false true false false`, each with status 0. This is executable evidence of disagreement, not just two models disagreeing. -Reproduce with `ZIG=/path/to/zig-0.15.2 IDRIS2=/path/to/idris2 -bash tests/consumer-boundary/proven-header-probe.sh /path/to/proven`. -The diagnostic deliberately exits 1 on disagreement and retains its -input identities, build output and differing results outside the repository. +These are historical results for the pinned Proven revision above. To replay +that mismatch, use the diagnostic from Atoma commit +`8377513cb93beec96148c5995bec8aadb8e74c09` with Proven at `c13619f9a67a1b9e8234e22e22dae0940d2480cb`. +That diagnostic exits 1 on disagreement and retains the input identities, +build output and differing results outside the repository. The current +diagnostic instead requires the repaired RefC bundle builder and checks the +five matching rows; follow link:../../tests/consumer-boundary/README.adoc[its instructions] +with Proven at `24fd48e954b7c124a195412a35c9c0be6f54990b` or a compatible later repair. == Decision 1: preserve boundary semantics, not spelling conventions @@ -177,9 +181,12 @@ behavioral disagreement, not the unproved source/compiler refinement relation. The adapter's finite decoder now has both decoding laws and its partial registration model has a no-fabricated-handler theorem. Its executable RefC matrix covers all 256 tags and four registration states. The actual Zig -registration table and network transports are still pending. See -link:../../tests/consumer-boundary/README.adoc[the consumer diagnostic] for -reproduction and the explicit receipt boundary. +registration table and network transports are still pending. Reproduce that +matrix at unified-api-adapter commit `259eff356e72fde2dadb1e144442f7a736da3601` +with `bash scripts/check-registry.sh`; see +link:https://github.com/hyperpolymath/unified-api-adapter/blob/259eff356e72fde2dadb1e144442f7a736da3601/scripts/check-registry.sh[the pinned registry gate]. +The link:../../tests/consumer-boundary/README.adoc[consumer diagnostic] +documents only the Proven experiment and its explicit receipt boundary. [cols="1,3,4",options="header"] |=== diff --git a/scripts/atoma-scalar-capsule.sh b/scripts/atoma-scalar-capsule.sh new file mode 100644 index 00000000..ce53b960 --- /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 '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..4236b757 --- /dev/null +++ b/scripts/atoma-scalar-proof-gate.sh @@ -0,0 +1,69 @@ +#!/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 '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 ScalarReflection.agda + lean ScalarReflection.lean > "$out/lean-assumptions.txt" 2>&1 + [[ $(grep -c 'does not depend on any axioms' "$out/lean-assumptions.txt") == 2 ]] + coqc -q ScalarSource.v > "$out/coq-assumptions.txt" 2>&1 + [[ $(grep -c '^Closed under the global context$' "$out/coq-assumptions.txt") == 2 ]] + coqchk -silent -Q . '' ScalarSource > "$out/coqchk.txt" 2>&1 + agda --safe --cubical --double-check ScalarReflectionCubical.agda +) > "$out/theory.txt" 2>&1 +(cd tools/atoma && zig build test && zig build) +atoma="$root/tools/atoma/zig-out/bin/atoma" +# 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" + (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.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-boundary/README.adoc b/tests/consumer-boundary/README.adoc index ead8b577..768f3fda 100644 --- a/tests/consumer-boundary/README.adoc +++ b/tests/consumer-boundary/README.adoc @@ -5,6 +5,13 @@ Run `bash tests/consumer-boundary/proven-header-probe.sh /path/to/proven` with Idris2 `b6cbc25d5cd2ef2a250556266fd7b68dfc360f8b` and Zig 0.15.2 on native Linux x86_64 GNU. `IDRIS2`, `ZIG` and `EVIDENCE_DIR` may select explicit paths. +The repaired experiment was checked against Proven commit +`24fd48e954b7c124a195412a35c9c0be6f54990b`; older revisions without +`scripts/build-header-refc.sh` cannot run this version of the diagnostic. +To reproduce the historical mismatch at Proven `c13619f9a67a1b9e8234e22e22dae0940d2480cb`, +use this script from Atoma `8377513cb93beec96148c5995bec8aadb8e74c09` instead. +For that historical script, set both `IDRIS2` and `ZIG` to absolute executable +paths; its directory changes do not preserve relative tool overrides. The diagnostic compiles the existing Idris String predicate independently, builds Proven's actual RefC byte kernel and SDK bundle, then links the exported diff --git a/tests/consumer-boundary/proven-header-probe.sh b/tests/consumer-boundary/proven-header-probe.sh index 126d6f1d..247f12aa 100644 --- a/tests/consumer-boundary/proven-header-probe.sh +++ b/tests/consumer-boundary/proven-header-probe.sh @@ -4,12 +4,18 @@ # Execute the actual Idris predicate and Zig export, not handwritten oracles. # A disagreement is exit 1. This is a diagnostic, not a proof certificate. set -euo pipefail +# A caller's CDPATH must not add stdout to captured directory resolutions. +unset CDPATH proven=${1:?usage: proven-header-probe.sh /path/to/proven} proven=$(cd "$proven" && pwd) zig=${ZIG:-zig} idris=${IDRIS2:-idris2} -command -v "$zig" >/dev/null -command -v "$idris" >/dev/null +# Resolve overrides before any subshell changes directory. Preserve the +# executable's basename (Idris wrappers may locate their data through $0). +zig=$(command -v "$zig") +zig=$(cd "$(dirname "$zig")" && printf '%s/%s' "$PWD" "$(basename "$zig")") +idris=$(command -v "$idris") +idris=$(cd "$(dirname "$idris")" && printf '%s/%s' "$PWD" "$(basename "$idris")") evidence=${EVIDENCE_DIR:-$(mktemp -d -t atoma-header-evidence.XXXXXXXX)} mkdir -p "$evidence" evidence=$(cd "$evidence" && pwd) @@ -23,6 +29,9 @@ cp -R "$proven/src/Proven" "$work/src/Proven" "$zig" version git -C "$proven" diff --stat sha256sum "$proven/src/Proven/SafeHeader/Types.idr" "$proven/src/Proven/Core.idr" "$proven/src/Proven/SafeHeader/ByteKernel.idr" "$proven/ffi/zig/src/core.zig" "$proven/ffi/zig/src/header_refc.zig" "$proven/ffi/zig/src/main_refc.zig" + if [[ -d "$proven/ffi/zig/src/refc" ]]; then + find "$proven/ffi/zig/src/refc" -type f -name '*.zig' -exec sha256sum {} + + fi } > "$evidence/inputs.log" cat > "$work/src/AtomaHeaderProbe.idr" <<'IDRIS' module AtomaHeaderProbe 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..c95ea52c --- /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 Import 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..419f50c5 --- /dev/null +++ b/verification/atoma/consumer/agda/ScalarReflection.agda @@ -0,0 +1,45 @@ +-- 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 Fin : Nat → Set where + first : ∀ {n} → Fin (suc n) + next : ∀ {n} → Fin n → Fin (suc 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..750bc641 --- /dev/null +++ b/verification/atoma/consumer/coq/ScalarSource.v @@ -0,0 +1,176 @@ +(* 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. + +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..a35c37ca --- /dev/null +++ b/verification/atoma/consumer/lean4/ScalarReflection.lean @@ -0,0 +1,28 @@ +-- 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 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 := Bool.and_eq_true.mp h + intro i hi + rcases Nat.eq_or_lt_of_le (Nat.le_of_lt_succ hi) with he | hl + · simpa [he] using 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