From 047c0b19a1a4d5264e17cf9ebe04f02a164a0571 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:07:15 +0000 Subject: [PATCH 1/8] docs(claude-md): name Creusot, Pearlite and Verus in the Rust proof row The Rust row of the Proofs table named Creusot alone. The template now states Creusot with Pearlite contracts, and Verus, by default and on the code (PROOF-POLICY section 1.2), and adds the companion paragraph that says to name all three in Rust verification plans and PROOF-STATUS. In this repo the Proofs block is hand-authored below the generated ARRIVAL-PACK region (owner ruling 2026-10-26); the generator does not emit it, so that block is the source. generate.sh was re-run: CLAUDE.md is byte-identical to its output and arrival-pack verify.sh passes. The checked-cone paragraph from the template is not ported here. Follows template main (0044ad9) wording. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDjDR2MdRwZH9b4rKJn --- CLAUDE.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index e85b980..2cbdf41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -150,11 +150,18 @@ Read it there; `verification/proofs/README.adoc` maps it onto this repo. | Code or obligation | Verifier | |---|---| -| Rust code | **Creusot**, on the code (Kani for `unsafe`/FFI seams and Aeneas for Rust that implements an Agda theorem run alongside, never instead) | +| Rust code | **Creusot** with **Pearlite** contracts, and **Verus**, by default and on the code (§1.2). Kani for `unsafe`/FFI seams and Aeneas for Rust that implements an Agda theorem run alongside, never instead | | Ada code | **SPARK** | | APIs, ABIs, engineering properties | **Idris2** | | Theory | **Agda**, rechecked in **Rocq** and **Lean** (no Mathlib) | +Always name Creusot, Pearlite and Verus in Rust verification plans and in +`docs/status/PROOF-STATUS.adoc`. Pearlite is Creusot's specification +language, not a third verifier. Plan scopes for both verifiers, and record +any that is unsupported, inapplicable or not yet run, with its reason; never +present an unexecuted check as a pass. Using both does not make two +independent witnesses (policy §1.2). + Third-party code (crates such as Bevy, libraries, forks) is **not** converted or re-proved. State what a proof relies on as an `ASSUMED` boundary specification, and when choosing between dependencies that fit equally well, From 846d1deaca55ca127609a2b91a5a4b5c8af3598b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:11:25 +0000 Subject: [PATCH 2/8] fix(container): refuse unsupported container engines, and wire the guard test The container recipes passed CONTAINER_ENGINE straight to the shell, so a stack component name such as rokur or svalinn was run as if it were an OCI engine. Add the engine guard to the shared _engine snippet in build/just/container.just and to build/container/stapeln/ct-build.sh: only podman, nerdctl and docker are accepted, anything else exits 2 with a message naming the supported engines. Add tests/workflows/container_engine_test.sh (refusal cases, a control for each supported engine, and a check that container.just uses no Bash 4 lowercase expansion). It is wired into estate-rules.yml, which gains a pinned Just 1.56.0 install (same checksum as mise.lock) because the test drives `just container-verify`. Without the guard the test fails 5 checks. container.just in this repo has no `${var,,}` lowercase (its container-init predates the _OWNER snippet), so the portable-lowercase change has nothing to replace here; the test keeps that property from regressing. Ported from the unmerged template PR hyperpolymath/rsr-template-repo#421 at f846da9. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDjDR2MdRwZH9b4rKJn --- .github/workflows/estate-rules.yml | 13 ++++++++ build/container/stapeln/ct-build.sh | 4 +++ build/just/container.just | 13 ++++++++ tests/workflows/container_engine_test.sh | 40 ++++++++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100755 tests/workflows/container_engine_test.sh diff --git a/.github/workflows/estate-rules.yml b/.github/workflows/estate-rules.yml index d52526d..636c352 100644 --- a/.github/workflows/estate-rules.yml +++ b/.github/workflows/estate-rules.yml @@ -201,6 +201,19 @@ jobs: fi - name: Converted container configs keep their data (template only) run: bash tests/workflows/container_kyaml_test.sh + - name: Install verified Just 1.56.0 (matching mise.lock) + run: | + set -euo pipefail + curl --proto '=https' --proto-redir '=https' --fail --silent --show-error --location \ + https://github.com/casey/just/releases/download/1.56.0/just-1.56.0-x86_64-unknown-linux-musl.tar.gz \ + --output "$RUNNER_TEMP/just.tar.gz" + echo "fa2a8ec1015d9df5330941ade12437488fc40d33f9c9f8cd4eb70a26de11b639 $RUNNER_TEMP/just.tar.gz" | sha256sum --check --strict + mkdir -p "$RUNNER_TEMP/just-bin" + tar -xzf "$RUNNER_TEMP/just.tar.gz" -C "$RUNNER_TEMP/just-bin" just + chmod +x "$RUNNER_TEMP/just-bin/just" + echo "$RUNNER_TEMP/just-bin" >> "$GITHUB_PATH" + - name: Container engine guard (only podman, nerdctl or docker; refuses the rest) + run: bash tests/workflows/container_engine_test.sh - name: KYAML ratchet self-test (installs verify, gate propagates, narrowing) run: bash tests/workflows/kyaml_ratchet_test.sh - name: I-JSON (RFC 7493) + JCS (RFC 8785) canonical gate & self-test diff --git a/build/container/stapeln/ct-build.sh b/build/container/stapeln/ct-build.sh index 13a1d74..21071ca 100755 --- a/build/container/stapeln/ct-build.sh +++ b/build/container/stapeln/ct-build.sh @@ -36,6 +36,10 @@ REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" # build/container/stapeln -> r # Container engine — podman (recommended), nerdctl or docker. ENGINE="${CONTAINER_ENGINE:-podman}" +case "$ENGINE" in + podman|nerdctl|docker) ;; + *) echo "error: unsupported container engine: '$ENGINE' (supported: podman, nerdctl, docker)." >&2; exit 2 ;; +esac PUSH="" for arg in "$@"; do diff --git a/build/just/container.just b/build/just/container.just index f880f64..73837ab 100644 --- a/build/just/container.just +++ b/build/just/container.just @@ -32,6 +32,19 @@ _engine := ''' echo "Install one or set CONTAINER_ENGINE." >&2 exit 1 fi + # Only these three OCI engines are supported. rokur, svalinn, selur and the + # other stapeln components are services or tools inside the stack, not engines: + # an unsupported value fails here instead of being passed on to be run. + case "$ENGINE" in + podman|nerdctl|docker) ;; + *) + echo "error: unsupported container engine: '$ENGINE'." >&2 + echo "Supported: podman, nerdctl, docker (set CONTAINER_ENGINE to one of them," >&2 + echo "or unset it to auto-detect). rokur and svalinn are stack components," >&2 + echo "not container engines." >&2 + exit 2 + ;; + esac ''' # Initialise container templates — substitute placeholders with project values diff --git a/tests/workflows/container_engine_test.sh b/tests/workflows/container_engine_test.sh new file mode 100755 index 0000000..c7e580c --- /dev/null +++ b/tests/workflows/container_engine_test.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# +# The container recipes support exactly podman, nerdctl and docker. An engine +# name outside that set (rokur and svalinn are stack components, not engines) +# must fail loudly: non-zero exit and a message naming the supported engines. +# Control: a supported name must NOT be refused for being unsupported, so the +# check cannot pass by refusing everything. Also: container.just must not use +# the Bash 4 lowercase expansion, which macOS's Bash 3.2 rejects. +set -uo pipefail +repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +cd "$repo" || exit 1 +command -v just >/dev/null || { echo "FAIL: just is required" >&2; exit 1; } +fail=0 +bad() { echo "FAIL: $*" >&2; fail=1; } + +for e in rokur svalinn selur bogus; do + out=$(CONTAINER_ENGINE="$e" just container-verify 2>&1); rc=$? + if [ "$rc" -ne 0 ] && grep -q 'unsupported container engine' <<<"$out" && grep -q 'podman, nerdctl, docker' <<<"$out"; then + echo "PASS: CONTAINER_ENGINE=$e refused (exit $rc)" + else + bad "CONTAINER_ENGINE=$e was not refused loudly (exit $rc): $out" + fi +done + +out=$(CONTAINER_ENGINE=rokur bash build/container/stapeln/ct-build.sh 2>&1); rc=$? +if [ "$rc" -eq 2 ] && grep -q 'unsupported container engine' <<<"$out"; then + echo "PASS: ct-build.sh refuses CONTAINER_ENGINE=rokur" +else bad "ct-build.sh accepted an unsupported engine (exit $rc): $out"; fi + +# Control: a supported engine is not refused as unsupported. +for e in podman nerdctl docker; do + out=$(CONTAINER_ENGINE="$e" just container-verify 2>&1) + if grep -q 'unsupported container engine' <<<"$out"; then bad "CONTAINER_ENGINE=$e wrongly refused"; else echo "PASS: control: CONTAINER_ENGINE=$e not refused as unsupported"; fi +done + +if grep -nE '\$\{[A-Za-z_]+,,\}' build/just/container.just; then + bad "build/just/container.just uses \${var,,} (Bash 4 only)" +else echo "PASS: container.just uses no Bash 4 lowercase expansion"; fi +exit "$fail" From b034fbcf553c0860e2664078c0b0d478507b0ea9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:14:21 +0000 Subject: [PATCH 3/8] fix(proofs): refuse OPTIONS pragmas that set a warning flag in the Agda gates A module's own {-# OPTIONS -W noerror #-} overrides the gate's command-line `-W error`, so a warning (or a downgrade of one) could pass the gate unnoticed in that module. scripts/check-agda.sh now scans every module it checks (src/, tests/unit and tests/reject, 24 today) before Agda runs and fails with `Error: OPTIONS pragma sets a warning flag, overriding the gate's -W error: :: `. Unlike the template's line-based grep, the scan reads each file whole, so a pragma split over lines is caught and the line reported is where it starts. The module listing runs to a file so a find failure stops the gate. The existing command-line `-W noUnsupportedIndexedMatch` is left as it is. scripts/check-proofs.sh gets the template change on its agda branch: the same refusal, and `-W error` on the command line. Tests, wired into estate-rules.yml: check_agda_pragma_test.sh (stub prover; src, tests/unit and tests/reject, `-W`, `--warning`, multi-line, nested module, plus clean and comment-only controls) and check_proofs_agda_test.sh (the template's fake-prover harness, agda cases only: the template's full check_proofs_test.sh assumes `coqc`, this repo uses `rocq compile`). Both fail against the previous scripts. The real gate passes on the 24 current modules, and a real-prover run with `-W noerror` planted in Core.agda is refused. Ported from the unmerged template PR hyperpolymath/rsr-template-repo#421 at f846da9. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDjDR2MdRwZH9b4rKJn --- .github/workflows/estate-rules.yml | 4 + scripts/check-agda.sh | 35 ++++++ scripts/check-proofs.sh | 11 +- tests/workflows/check_agda_pragma_test.sh | 124 ++++++++++++++++++++++ tests/workflows/check_proofs_agda_test.sh | 103 ++++++++++++++++++ 5 files changed, 276 insertions(+), 1 deletion(-) create mode 100755 tests/workflows/check_agda_pragma_test.sh create mode 100755 tests/workflows/check_proofs_agda_test.sh diff --git a/.github/workflows/estate-rules.yml b/.github/workflows/estate-rules.yml index 636c352..d8b9bb2 100644 --- a/.github/workflows/estate-rules.yml +++ b/.github/workflows/estate-rules.yml @@ -226,3 +226,7 @@ jobs: set -euo pipefail bash tests/workflows/squabble_gate_test.sh bash scripts/check-required-contexts.sh . + - name: Proof gate self-test, agda branch (stub prover; a warning pragma is refused) + run: bash tests/workflows/check_proofs_agda_test.sh + - name: Agda gate self-test (an OPTIONS pragma that sets a warning flag is refused) + run: bash tests/workflows/check_agda_pragma_test.sh diff --git a/scripts/check-agda.sh b/scripts/check-agda.sh index 2afe0bf..4baf687 100755 --- a/scripts/check-agda.sh +++ b/scripts/check-agda.sh @@ -25,6 +25,41 @@ find src -name '*.agda' -print0 > "$cone_list" \ || { echo "ERROR: could not list the import cone (src/)" >&2; exit 1; } mapfile -d '' cone < "$cone_list" (( ${#cone[@]} > 0 )) || { echo "ERROR: no Agda sources in the import cone" >&2; exit 1; } +# A module's own OPTIONS pragma overrides the command line, so one that sets a +# warning flag (-W / --warning, e.g. {-# OPTIONS -W noerror #-}) would undo the +# gate's -W error for that module. Refuse it before Agda runs, in every module +# the gate checks: the import cone (src/), the unit tests and the expected- +# rejection fixtures. The scan reads each file whole, so a pragma split over +# several lines is read as one; a pragma-looking text inside a comment is also +# refused (fail closed). The listing runs to a file so a find failure stops the +# gate, as for the cone above. +pragma_list="$work/pragma-files" +find src tests/unit tests/reject -name '*.agda' -print0 > "$pragma_list" \ + || { echo "ERROR: could not list the modules the gate checks (src/, tests/unit, tests/reject)" >&2; exit 1; } +mapfile -d '' pragma_files < "$pragma_list" +(( ${#pragma_files[@]} > 0 )) || { echo "ERROR: no Agda modules to scan for OPTIONS pragmas" >&2; exit 1; } +pragma_status=0 +perl -0777 -ne ' + while (/\{-#\s*OPTIONS(?[^#]*)#-\}/g) { + my ($start, $pragma, $opts) = ($-[0], $&, $+{opts}); + next unless $opts =~ /(?:^|\s)(?:-W|--warning)/; + my $line = (substr($_, 0, $start) =~ tr/\n//) + 1; + (my $hit = $pragma) =~ s/\s+/ /g; + print "$ARGV:$line: $hit\n"; + $found = 1; + } + END { $? = 3 if $found } +' "${pragma_files[@]}" > "$work/pragma.hits" || pragma_status=$? +if (( pragma_status == 3 )); then + while IFS= read -r hit; do + echo "Error: OPTIONS pragma sets a warning flag, overriding the gate's -W error: $hit" >&2 + done < "$work/pragma.hits" + exit 1 +elif (( pragma_status != 0 )); then + echo "ERROR: could not scan the modules for OPTIONS pragmas (perl exit $pragma_status)" >&2 + exit 1 +fi +echo "PASS: no OPTIONS pragma sets a warning flag in the ${#pragma_files[@]} modules the gate checks" if ! perl scripts/scan-postulates.pl "${cone[@]}"; then echo "ERROR: postulate in the import cone (src/), or an unreadable file" >&2 exit 1 diff --git a/scripts/check-proofs.sh b/scripts/check-proofs.sh index 32501a9..645a76a 100755 --- a/scripts/check-proofs.sh +++ b/scripts/check-proofs.sh @@ -84,7 +84,16 @@ check_one() { case "$PROVER" in idris2) out="$(cd "$ROOT/$root" && idris2 --check "$rel" 2>&1)"; rc=$? ;; lean4) out="$(cd "$ROOT/$root" && lean "$rel" 2>&1)"; rc=$? ;; - agda) out="$(cd "$ROOT/$root" && agda --safe --without-K --cubical-compatible "$rel" 2>&1)"; rc=$? ;; + # Canonical theory invocation, PROOF-POLICY §2.1 (standards): --safe --without-K + # --cubical-compatible, with -W error so any warning fails. Suppress NO warning + # (no -W noX). Do not weaken. A module's own OPTIONS pragma could override the + # command line (e.g. {-# OPTIONS -W noerror #-}), so a gated module that sets + # any warning flag (-W / --warning) in a pragma fails before Agda runs. + agda) if pragma="$(grep -nE '\{-#[[:space:]]*OPTIONS[^#]*(-W|--warning)' "$ROOT/$root/$rel")"; then + out="Error: OPTIONS pragma sets a warning flag, overriding the gate's -W error: $pragma"; rc=1 + else + out="$(cd "$ROOT/$root" && agda --safe --without-K --cubical-compatible -W error "$rel" 2>&1)"; rc=$? + fi ;; coq) out="$(cd "$ROOT/$root" && rocq compile "$rel" 2>&1)"; rc=$? ;; esac set -e diff --git a/tests/workflows/check_agda_pragma_test.sh b/tests/workflows/check_agda_pragma_test.sh new file mode 100755 index 0000000..62cbf6d --- /dev/null +++ b/tests/workflows/check_agda_pragma_test.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +# +# check_agda_pragma_test.sh — controls for scripts/check-agda.sh's refusal of an +# OPTIONS pragma that sets a warning flag (-W / --warning). +# +# A module's own pragma overrides the gate's command line, so +# {-# OPTIONS -W noerror #-} would undo `-W error` for that module. The gate +# must refuse it in EVERY module it checks (src/, tests/unit, tests/reject), +# before Agda runs, and name the file and line. Each case is a throwaway copy +# of the gate with one planted module and a STUB prover that answers --version +# and records any other call, so the refusal is tested on its own: nothing here +# runs a real Agda, and a refused case must not reach the prover at all. The +# clean cases must get past the scan (its PASS line is printed and no refusal). +# Whether the repository's real modules pass is the real gate's job +# (scripts/check-agda.sh, run by proofs.yml with the pinned Agda). +# +# Exit: 0 all controls hold; 1 a control failed. + +set -uo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT +command -v perl >/dev/null || { echo "FAIL: perl is required" >&2; exit 1; } + +STUB="$WORK/stub-agda" +cat >"$STUB" <<'FAKE' +#!/usr/bin/env bash +if [ "${1:-}" = "--version" ]; then echo "stub 0"; exit 0; fi +printf '%s\n' "$*" >>"$STUB_LOG" +exit 0 +FAKE +chmod +x "$STUB" + +FAILED=0; CHECKS=0 +note() { CHECKS=$((CHECKS + 1)); if [ "$1" = ok ]; then echo " PASS $2"; else FAILED=$((FAILED + 1)); echo " FAIL $2"; fi; } + +# fixture NAME — a gate copy whose three module directories each hold one clean module. +fixture() { + local d="$WORK/$1" m + mkdir -p "$d/scripts" "$d/src/ResourceAlgebra" "$d/tests/unit" "$d/tests/reject" + cp "$REPO_DIR/scripts/check-agda.sh" "$REPO_DIR/scripts/scan-postulates.pl" "$d/scripts/" + for m in src/ResourceAlgebra/All tests/unit/AllTests tests/reject/Bad; do + printf '{-# OPTIONS --safe --without-K #-}\nmodule %s where\n' "$(basename "$m")" >"$d/$m.agda" + done + echo "$d" +} +# gate DIR — run the gate copy with the stub prover; sets OUT, RC and the stub log. +gate() { + : >"$WORK/stub.log" + OUT="$(cd "$1" && STUB_LOG="$WORK/stub.log" AGDA="$STUB" bash scripts/check-agda.sh 2>&1)"; RC=$? +} +# refused LABEL DIR FILE:LINE — the gate stopped on the pragma, named the place, +# and never ran the prover on a module. +refused() { + gate "$2" + if [ "$RC" -ne 0 ] \ + && grep -qF -- "Error: OPTIONS pragma sets a warning flag, overriding the gate's -W error: $3:" <<<"$OUT" \ + && ! grep -qF 'PASS: no OPTIONS pragma' <<<"$OUT" \ + && [ ! -s "$WORK/stub.log" ]; then + note ok "$1" + else + note bad "$1 (rc=$RC)"; sed 's/^/ /' <<<"$OUT" | tail -8 + fi +} +# passes_scan LABEL DIR — the pragma scan passed (the gate may stop later on the stub). +passes_scan() { + gate "$2" + if grep -qF 'PASS: no OPTIONS pragma sets a warning flag' <<<"$OUT" \ + && ! grep -qF 'OPTIONS pragma sets a warning flag, overriding' <<<"$OUT"; then + note ok "$1" + else + note bad "$1 (rc=$RC)"; sed 's/^/ /' <<<"$OUT" | tail -8 + fi +} +plant() { printf '%s' "$3" >"$1/$2"; } + +# --- positive controls ----------------------------------------------------------- +d="$(fixture clean)" +passes_scan "clean modules in src, tests/unit and tests/reject pass the scan" "$d" + +d="$(fixture comment)" +plant "$d" src/ResourceAlgebra/All.agda $'{-# OPTIONS --safe --without-K #-}\n-- never write -W noerror or --warning in a pragma\nmodule All where\n' +passes_scan "-W named in a comment outside any pragma passes the scan" "$d" + +d="$(fixture realflags)" +plant "$d" src/ResourceAlgebra/All.agda $'{-# OPTIONS --safe --without-K --cubical-compatible --exact-split --no-sized-types --no-guardedness #-}\nmodule All where\n' +passes_scan "the repository's own pragma flags pass the scan" "$d" + +# --- negative controls ----------------------------------------------------------- +d="$(fixture src-W)" +plant "$d" src/ResourceAlgebra/All.agda $'{-# OPTIONS -W noerror #-}\nmodule All where\n' +refused "src: {-# OPTIONS -W noerror #-} is refused" "$d" src/ResourceAlgebra/All.agda:1 + +d="$(fixture src-warning)" +plant "$d" src/ResourceAlgebra/All.agda $'{-# OPTIONS --safe --warning=noerror #-}\nmodule All where\n' +refused "src: the --warning spelling is refused" "$d" src/ResourceAlgebra/All.agda:1 + +d="$(fixture src-warning-arg)" +plant "$d" src/ResourceAlgebra/All.agda $'{-# OPTIONS --safe --warning noerror #-}\nmodule All where\n' +refused "src: --warning with a separate argument is refused" "$d" src/ResourceAlgebra/All.agda:1 + +d="$(fixture src-multiline)" +plant "$d" src/ResourceAlgebra/All.agda $'-- header\n{-# OPTIONS --safe\n --without-K\n -W noerror #-}\nmodule All where\n' +refused "src: a pragma split over lines is refused, at the line it starts" "$d" src/ResourceAlgebra/All.agda:2 + +d="$(fixture src-nested)" +mkdir -p "$d/src/ResourceAlgebra/Instances" +printf '{-# OPTIONS --safe #-}\nmodule Inst where\n' >"$d/src/ResourceAlgebra/Instances/Inst.agda" +plant "$d" src/ResourceAlgebra/Instances/Inst.agda $'{-# OPTIONS --safe -Wnoerror #-}\nmodule Inst where\n' +refused "src: a nested module is scanned too (-Wnoerror, no space)" "$d" src/ResourceAlgebra/Instances/Inst.agda:1 + +d="$(fixture unit-W)" +plant "$d" tests/unit/AllTests.agda $'{-# OPTIONS --safe -W noerror #-}\nmodule AllTests where\n' +refused "tests/unit: a warning flag is refused" "$d" tests/unit/AllTests.agda:1 + +d="$(fixture reject-W)" +plant "$d" tests/reject/Bad.agda $'{-# OPTIONS --safe --warning=noerror #-}\nmodule Bad where\n' +refused "tests/reject: a warning flag is refused" "$d" tests/reject/Bad.agda:1 + +echo "$CHECKS controls, $FAILED failed" +[ "$FAILED" -eq 0 ] diff --git a/tests/workflows/check_proofs_agda_test.sh b/tests/workflows/check_proofs_agda_test.sh new file mode 100755 index 0000000..40f51f6 --- /dev/null +++ b/tests/workflows/check_proofs_agda_test.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: MPL-2.0 +# SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) +# +# check_proofs_agda_test.sh — controls for the agda branch of scripts/check-proofs.sh. +# +# The gate refuses a gated Agda module whose own OPTIONS pragma sets a warning +# flag (-W / --warning): such a pragma overrides the gate's `-W error` +# (e.g. {-# OPTIONS -W noerror #-}). A FAKE agda goes first on PATH, so these +# controls test the gate's verdict logic and not the prover; nothing here runs +# a real Agda. The fake records its arguments so the clean case can also check +# that `-W error` reaches the prover. This is a test of the gate, not a proof +# that any proof checks. (The prover-independent gate for this repository's +# own modules is scripts/check-agda.sh; tests/workflows/check_agda_pragma_test.sh.) +# +# Exit: 0 all controls hold; 1 a control failed. + +set -uo pipefail + +REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +# A PATH with the shell tools the gate needs and NO prover; the fake is added per case. +BASEBIN="$WORK/basebin"; mkdir -p "$BASEBIN" +for t in bash sed grep find sort comm mktemp cat head dirname basename rm tr cut wc awk env; do + p="$(command -v "$t" 2>/dev/null || true)" + [ -n "$p" ] && ln -s "$p" "$BASEBIN/$t" +done +FAKEBIN="$WORK/fakebin"; mkdir -p "$FAKEBIN" +cat >"$FAKEBIN/agda" <<'FAKE' +#!/usr/bin/env bash +if [ "${1:-}" = "--version" ]; then echo "fake 0"; exit 0; fi +printf '%s\n' "$*" >>"${FAKE_AGDA_LOG:-/dev/null}" +exit 0 +FAKE +chmod +x "$FAKEBIN/agda" + +FAILED=0; CHECKS=0 +# fixture NAME — a throwaway repo root holding only the gate and its scanner. +fixture() { + local d="$WORK/$1"; mkdir -p "$d/scripts" "$d/verification/proofs/agda" + cp "$REPO_DIR/scripts/check-proofs.sh" "$REPO_DIR/scripts/scan-dangerous.sh" "$d/scripts/" + echo "$d" +} +# module DIR CONTENT — one gated Agda module A.agda and its MANIFEST. +module() { + printf '%s' "$2" >"$1/verification/proofs/agda/A.agda" + echo 'verification/proofs/agda|A.agda|gated|' >"$1/verification/proofs/agda/MANIFEST" +} +# run LABEL WANT_RC DIR PATTERN — PATTERN must appear in the output. +run() { + local label="$1" want="$2" dir="$3" pat="${4:-}" rc=0 out + : >"$WORK/agda.args" + out="$(FAKE_AGDA_LOG="$WORK/agda.args" PATH="$FAKEBIN:$BASEBIN" bash "$dir/scripts/check-proofs.sh" agda 2>&1)" || rc=$? + CHECKS=$((CHECKS + 1)) + if [ "$rc" -ne "$want" ]; then + FAILED=$((FAILED + 1)); echo " FAIL $label (want rc=$want, got rc=$rc)"; sed 's/^/ /' <<<"$out" | tail -12 + elif [ -n "$pat" ] && ! grep -qF -- "$pat" <<<"$out"; then + FAILED=$((FAILED + 1)); echo " FAIL $label (rc ok, output lacks: $pat)"; sed 's/^/ /' <<<"$out" | tail -12 + else + echo " PASS $label" + fi +} +# prover_ran LABEL WANT(yes|no) — whether the fake agda was invoked on a module. +prover_ran() { + local label="$1" want="$2" ran=no + [ -s "$WORK/agda.args" ] && ran=yes + CHECKS=$((CHECKS + 1)) + if [ "$ran" = "$want" ]; then echo " PASS $label" + else FAILED=$((FAILED + 1)); echo " FAIL $label (prover ran: $ran, want: $want)"; fi +} + +# --- positive control ------------------------------------------------------------ +d="$(fixture agdaok)" +module "$d" $'{-# OPTIONS --safe --without-K #-}\nmodule A where\n' +run "agda: a pragma without a warning flag passes" 0 "$d" "RESULT: PASS" +if grep -qE -- '(^| )-W error( |$)' "$WORK/agda.args"; then + CHECKS=$((CHECKS + 1)); echo " PASS agda: the gate runs the prover with -W error" +else + CHECKS=$((CHECKS + 1)); FAILED=$((FAILED + 1)); echo " FAIL agda: -W error did not reach the prover: $(cat "$WORK/agda.args")" +fi + +d="$(fixture agdacomment)" +module "$d" $'{-# OPTIONS --safe #-}\n-- never use -W noerror or --warning here\nmodule A where\n' +run "agda: -W in a comment outside any pragma passes" 0 "$d" "RESULT: PASS" + +# --- negative controls ----------------------------------------------------------- +d="$(fixture agdawarn)" +module "$d" $'{-# OPTIONS -W noerror #-}\nmodule A where\n' +run "agda: an OPTIONS pragma that overrides -W error fails" 1 "$d" "OPTIONS pragma sets a warning flag" +prover_ran "agda: the refused module never reaches the prover" no + +d="$(fixture agdawarnlong)" +module "$d" $'{-# OPTIONS --safe --warning=noerror #-}\nmodule A where\n' +run "agda: the --warning spelling fails" 1 "$d" "OPTIONS pragma sets a warning flag" + +d="$(fixture agdawarnspace)" +module "$d" $'{-# OPTIONS --safe --warning noerror #-}\nmodule A where\n' +run "agda: --warning with a separate argument fails" 1 "$d" "OPTIONS pragma sets a warning flag" + +echo "$CHECKS controls, $FAILED failed" +[ "$FAILED" -eq 0 ] From 8a6b47d2f94661b535abc378d91b01125d30d4d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:24:58 +0000 Subject: [PATCH 4/8] refactor: remove the template ABI/FFI scaffold (pure-theory Agda repository) Owner decision, 2026-11-16: resource-algebra is pure Agda theory and ships no ABI or FFI, so the template's Idris2 ABI / Zig FFI scaffold is removed: src/interface/ (Abi, abi.ipkg, ffi, generated), tests/ffi_strings_test.sh and docs/developer/ABI-FFI-README.adoc. This follows the template's own prune path (archetype prune.txt drops src/interface/, the removals are recorded in the deed's (variant (paths :removed)), the README badges go), not a new pattern. .machine_readable/coaptation/core/Coaptation.idr is untouched. Nothing is left silently green: - `just test` runs scripts/check-agda.sh through the praxis deed's :test verb override, so the golden path `just test && just quality` gates on the real Agda check (it ran idris2 and zig only before, never Agda). `build`, `lint`, `fmt` and `fmt-check` print that no language is detected and ran nothing, as the template does after a prune. - Provisioning no longer detects idris2 or zig: `just doctor` passes where it failed on the missing idris2 and zig. Zig and the Idris2 system packages are dropped from mise.toml, mise.lock, build/manifest.scm, build/guix.scm and docs/SETUP.adoc; the proven-tests job no longer installs Zig. Checks that required the template's seam are fixed at their source, as the template's prune does, never weakened: - build/just/validate.just and scripts/validate-template.sh: a tree with no src/interface/ is complete; a tree that has it must still carry all of it. - scripts/run-proven-suite.sh: the Zig lane is reported NOT APPLICABLE, counted apart from passes (template main's mechanism, ported with its test in tests/run_proven_suite_test.sh); --require-zig still fails closed if an ffi directory returns without a compiler. - tests/proven_suite_test.sh, .machine_readable/mint-verbatim.txt: drop the removed test. docs/status/PROOF-NEEDS.adoc records, dated 2026-11-16, that no ABI/FFI exists and so carries no ABI/FFI proof obligations, worded as the unmerged template PR hyperpolymath/rsr-template-repo#421 (f846da9) words the ABI group: it applies to any ABI or FFI, not only an Idris2 one. The eclexiaiser manifest loses its two entries naming the removed Zig files, and the onboarding and setup docs, README, REPOSITORY-MAP and CHANGELOG are updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDjDR2MdRwZH9b4rKJn --- .github/workflows/proven-tests.yml | 11 - .machine_readable/configs/eclexiaiser.toml | 14 +- .../descriptiles/provisioning_praxis.deed | 4 +- .machine_readable/mint-verbatim.txt | 1 - CHANGELOG.adoc | 23 + Justfile | 20 +- README.adoc | 4 - build/guix.scm | 12 +- build/just/validate.just | 19 +- build/manifest.scm | 9 +- docs/README.adoc | 2 +- docs/SETUP.adoc | 21 +- docs/architecture/REPOSITORY-MAP.adoc | 2 - docs/developer/ABI-FFI-README.adoc | 405 ------------------ docs/onboarding/QUICKSTART-DEV.adoc | 2 - docs/onboarding/llm-warmup-dev.adoc | 18 +- docs/onboarding/llm-warmup-user.adoc | 4 +- docs/status/PROOF-NEEDS.adoc | 20 +- docs/status/TEST-NEEDS.adoc | 5 + mise.lock | 32 -- mise.toml | 6 +- resource-algebra_chora.deed | 17 +- scripts/run-proven-suite.sh | 48 ++- scripts/validate-template.sh | 111 +++-- src/interface/Abi/Foreign.idr | 83 ---- src/interface/Abi/Layout.idr | 128 ------ src/interface/Abi/README.adoc | 3 - src/interface/Abi/Types.idr | 112 ----- src/interface/README.adoc | 3 - src/interface/abi.ipkg | 36 -- src/interface/ffi/README.adoc | 3 - src/interface/ffi/build.zig | 29 -- src/interface/ffi/src/README.adoc | 3 - src/interface/ffi/src/main.zig | 293 ------------- src/interface/ffi/test/README.adoc | 3 - src/interface/ffi/test/integration_test.zig | 66 --- src/interface/generated/README.adoc | 3 - src/interface/generated/abi/README.adoc | 3 - tests/ffi_strings_test.sh | 119 ----- tests/proven_suite_test.sh | 3 - tests/run_proven_suite_test.sh | 29 +- www/.well-known/humans.txt | 2 +- 42 files changed, 249 insertions(+), 1482 deletions(-) delete mode 100644 docs/developer/ABI-FFI-README.adoc delete mode 100644 src/interface/Abi/Foreign.idr delete mode 100644 src/interface/Abi/Layout.idr delete mode 100644 src/interface/Abi/README.adoc delete mode 100644 src/interface/Abi/Types.idr delete mode 100644 src/interface/README.adoc delete mode 100644 src/interface/abi.ipkg delete mode 100644 src/interface/ffi/README.adoc delete mode 100644 src/interface/ffi/build.zig delete mode 100644 src/interface/ffi/src/README.adoc delete mode 100644 src/interface/ffi/src/main.zig delete mode 100644 src/interface/ffi/test/README.adoc delete mode 100644 src/interface/ffi/test/integration_test.zig delete mode 100644 src/interface/generated/README.adoc delete mode 100644 src/interface/generated/abi/README.adoc delete mode 100644 tests/ffi_strings_test.sh diff --git a/.github/workflows/proven-tests.yml b/.github/workflows/proven-tests.yml index 8135e18..c85aea5 100644 --- a/.github/workflows/proven-tests.yml +++ b/.github/workflows/proven-tests.yml @@ -55,17 +55,6 @@ jobs: echo "${NICKEL_SHA256} $RUNNER_TEMP/nickel-bin/nickel" | sha256sum --check --strict chmod +x "$RUNNER_TEMP/nickel-bin/nickel" echo "$RUNNER_TEMP/nickel-bin" >> "$GITHUB_PATH" - - name: Install verified Zig 0.16.0 (matching mise.lock) - run: | - set -euo pipefail - curl --proto '=https' --proto-redir '=https' --fail --silent --show-error --location \ - https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz \ - --output "$RUNNER_TEMP/zig.tar.xz" - echo "70e49664a74374b48b51e6f3fdfbf437f6395d42509050588bd49abe52ba3d00 $RUNNER_TEMP/zig.tar.xz" | sha256sum --check --strict - mkdir -p "$RUNNER_TEMP/zig" - tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP/zig" --strip-components=1 - echo "$RUNNER_TEMP/zig" >> "$GITHUB_PATH" - - name: Install verified Just 1.56.0 (matching mise.lock) run: | set -euo pipefail diff --git a/.machine_readable/configs/eclexiaiser.toml b/.machine_readable/configs/eclexiaiser.toml index f90fbe4..7afd005 100644 --- a/.machine_readable/configs/eclexiaiser.toml +++ b/.machine_readable/configs/eclexiaiser.toml @@ -4,17 +4,9 @@ [project] name = "resource-algebra" -[[functions]] -name = "build" -source = "src/interface/ffi/build.zig" -energy-budget-mj = 15.0 -carbon-budget-mg = 3.0 - -[[functions]] -name = "setError" -source = "src/interface/ffi/src/main.zig" -energy-budget-mj = 5.0 -carbon-budget-mg = 1.0 +# No [[functions]] entries: the two template entries budgeted functions of the +# removed Zig FFI (src/interface/ffi, removed 2026-11-16). This repository has no +# executable code to budget; add an entry only when it has a source file to name. [carbon] provider = "static" diff --git a/.machine_readable/descriptiles/provisioning_praxis.deed b/.machine_readable/descriptiles/provisioning_praxis.deed index d822560..fcdcc17 100644 --- a/.machine_readable/descriptiles/provisioning_praxis.deed +++ b/.machine_readable/descriptiles/provisioning_praxis.deed @@ -13,10 +13,10 @@ :canonical-name "resource-algebra-provisioning" :repo "hyperpolymath/resource-algebra" :archetype "library" ; app | library | tool | theory | docs - :languages "idris2 zig" ; detected; informational + :languages "docs" ; detected; informational (no build language: the Agda proofs are checked by :test) ;; Contract-verb overrides ("" = per-language default, which `just langs` shows) :build "" - :test "" + :test "bash scripts/check-agda.sh" :bench "" :lint "" :fmt "" diff --git a/.machine_readable/mint-verbatim.txt b/.machine_readable/mint-verbatim.txt index cd6ffd7..abadf02 100644 --- a/.machine_readable/mint-verbatim.txt +++ b/.machine_readable/mint-verbatim.txt @@ -32,5 +32,4 @@ tests/workflows/self_name_pass_test.sh # template-name fixtures tests/workflows/template_conformance_test.sh # template-slug fixtures tests/workflows/julia_library_test.sh # PACKAGE_UUID brace-token fixture tests/workflows/resolve_template_pin_test.sh # template-slug fixtures -tests/ffi_strings_test.sh # FFI token fixture, filled in a scratch copy tests/workflows/container_kyaml_test.sh # container token fixtures (template only) diff --git a/CHANGELOG.adoc b/CHANGELOG.adoc index a2dbf89..05f8fec 100644 --- a/CHANGELOG.adoc +++ b/CHANGELOG.adoc @@ -1,5 +1,28 @@ == Changelog +== 2026-11-16 — ABI/FFI scaffold removed (pure-theory Agda repository) + +* Owner decision: this repository ships no ABI or FFI, so the template's + Idris2 ABI / Zig FFI scaffold is removed: `src/interface/` (`Abi/`, + `abi.ipkg`, `ffi/`, `generated/`), `tests/ffi_strings_test.sh` and + `docs/developer/ABI-FFI-README.adoc`. The paths are recorded in the repo + deed as `(variant (paths :removed))`, as the template's own prune does. +* `docs/status/PROOF-NEEDS.adoc` records that no ABI/FFI exists, so there are + no ABI/FFI proof obligations. +* `just test` now runs `scripts/check-agda.sh` (the praxis deed's `:test`) + instead of `idris2 --typecheck` and `zig build test`. `just build`, `lint`, + `fmt` and `fmt-check` report that no language is detected and ran nothing; + they are not a pass. `just quality` therefore gates on the Agda check alone. +* The template's guards for a pruned seam are ported: `validate.just` and + `scripts/validate-template.sh` accept a tree with no `src/interface/` + (a tree that has one must still carry all of it), and + `scripts/run-proven-suite.sh` reports the Zig lane as NOT APPLICABLE, + counted apart from passes. `--require-zig` still fails closed if an + `src/interface/ffi` returns without a compiler. +* Zig is dropped from `mise.toml`, `mise.lock`, `build/manifest.scm`, + `build/guix.scm` and the `proven-tests.yml` job, and the Idris-Inside and + Zig badges and the ABI/FFI bullet are dropped from `README.adoc`. + == 2026-11-11 — Proof receipt and grades at f211fc1 * `verification/receipts/resource-algebra-proofs_praxis.deed`: the proof diff --git a/Justfile b/Justfile index 9a1e89c..3329d63 100644 --- a/Justfile +++ b/Justfile @@ -88,9 +88,10 @@ import? "build/just/assess.just" # BUILD & COMPILE # ═══════════════════════════════════════════════════════════════════════════════ -# Build the project with every detected language's toolchain (here: pack/idris2 for -# the ABI, then `zig build` in src/interface/ffi). Replace the delegation with a -# body of your own when the project needs a different build. +# Build the project with every detected language's toolchain. None is detected here +# (pure Agda theory, no FFI), so this prints that it is N/A and builds nothing; the +# Agda proofs are checked by `just test` (scripts/check-agda.sh). Replace the +# delegation with a body of your own when the project needs a different build. build: provision::build # Build in release mode with optimizations @@ -99,7 +100,6 @@ build-release *args: # Examples: # cargo build --release {{args}} # MIX_ENV=prod mix compile {{args}} - # zig build -Doptimize=ReleaseFast {{args}} @echo "FAIL: 'just build-release' is not wired yet — nothing was built. Edit the 'build-release' recipe." >&2; exit 1 # Build and watch for changes (requires entr or similar) @@ -130,10 +130,10 @@ clean-all: clean # TEST & QUALITY # ═══════════════════════════════════════════════════════════════════════════════ -# Run every detected language's tests: `zig build test` covers src/interface/ffi -# (unit tests in src/main.zig, test/integration_test.zig). It compiles only after -# `just repo-init` has filled the template tokens, so an un-initialised template -# fails here loudly instead of reporting a pass over nothing. +# Run the tests. This repository is pure Agda theory with no FFI, so the praxis deed +# (.machine_readable/descriptiles/provisioning_praxis.deed, :test) points this at +# scripts/check-agda.sh: the canonical Agda invocation over src/, the unit tests and +# the expected rejections. A missing Agda fails loudly; nothing is skipped. test: provision::test # Run tests with verbose output @@ -212,8 +212,8 @@ fmt: provision::fmt # Check formatting without changes fmt-check: provision::fmt-check -# Run linter (`zig fmt --check` on src/interface/ffi; like `test`, it parses the -# FFI sources only after `just repo-init` has filled the template tokens) +# Run linter. No linter exists for the languages here (no language is detected), so +# this prints that it is N/A; `-W error` in `just test` is the Agda lint. lint: provision::lint # ═══════════════════════════════════════════════════════════════════════════════ diff --git a/README.adoc b/README.adoc index 1491aa0..adc3edf 100644 --- a/README.adoc +++ b/README.adoc @@ -120,8 +120,6 @@ image:https://sonarcloud.io/api/project_badges/measure?project=hyperpolymath_res image:https://archive.softwareheritage.org/badge/origin/https://github.com/hyperpolymath/resource-algebra/[Archived in Software Heritage,link="https://archive.softwareheritage.org/browse/origin/?origin_url=https://github.com/hyperpolymath/resource-algebra"] // ── Provenance & ecosystem ────────────────────────────────────────────────── -image:https://img.shields.io/badge/Idris-Inside-5E5086?logo=idris&logoColor=white[Idris Inside,link="https://github.com/hyperpolymath/proven"] -image:https://img.shields.io/badge/Zig-Zero--overhead-F7A41D?logo=zig&logoColor=black[Zig Zero-overhead FFI,link="https://github.com/hyperpolymath/typed-wasm"] image:https://api.thegreenwebfoundation.org/greencheckimage/github.com[Green Web,link="https://www.thegreenwebfoundation.org/green-web-check/?url=github.com"] The parametric grade algebra shared by the hyperpolymath type family @@ -177,8 +175,6 @@ maintainers can brief an AI with `just ai-warmup dev` / `just ai-warmup maintain * *AI gatekeeper protocol* — `resource-algebra_chora.deed` (the repo deed) is the universal entry point that tells an AI agent how to work in this repo before it touches anything; it carries the AI allocation policy and the ply directory tree. -* *Typed ABI/FFI seam* — `src/interface/Abi/` (Idris2 type + layout proofs) over - `src/interface/ffi/` (Zig implementation), with generated C headers. * *CI/CD* — GitHub Actions for quality, security (CodeQL, Scorecard, secret scanning), multi-forge mirroring, and RSR anti-pattern enforcement. * *Supply-chain & reproducibility* — container layering (stapeln), Guix shells, diff --git a/build/guix.scm b/build/guix.scm index 204831e..3b49e08 100755 --- a/build/guix.scm +++ b/build/guix.scm @@ -6,9 +6,9 @@ ;; guix build -f build/guix.scm # installs the source tree to share/resource-algebra ;; guix shell -D -f build/guix.scm # the full development toolchain ;; -;; This is a SOURCE package, and says so: a hermetic compiled build needs this -;; repository's idris2 and zig dependencies packaged in Guix, which they are not -;; (Guix builds offline). The toolchain below is real — `guix shell -D -f build/guix.scm` +;; This is a SOURCE package, and says so: it installs the source tree and builds +;; nothing (the Agda proofs are checked by scripts/check-agda.sh, which Guix does +;; not run). The toolchain below is real — `guix shell -D -f build/guix.scm` ;; then `just setup` gives a working environment. See docs/SETUP.adoc §Guix. (use-modules (guix packages) (guix gexp) (guix build-system copy) @@ -37,10 +37,10 @@ (build-system copy-build-system) (arguments (list #:install-plan #~'(("." "share/resource-algebra/")))) (native-inputs (map spec->input (list "git" "bash" "coreutils" "nss-certs" "just" "mise" - "shellcheck" "chez-scheme" "gmp" "gcc-toolchain" "zig"))) + "shellcheck"))) (home-page "https://github.com/hyperpolymath/resource-algebra") (synopsis "Rhodium Standard Repository template") - (description "The estate's repository template: the RSR layout, an Idris2 ABI -seam with a Zig FFI, CI gates, and the provisioning set (launcher, Justfile, + (description "The estate's repository template: the RSR layout, CI gates, +and the provisioning set (launcher, Justfile, mise, Guix, setup and AI-assisted installation guides).") (license license:mpl2.0)) diff --git a/build/just/validate.just b/build/just/validate.just index dc6d724..12fb0cb 100644 --- a/build/just/validate.just +++ b/build/just/validate.just @@ -25,12 +25,21 @@ validate-rsr: for f in docs/legal/EXHIBIT-A-ETHICAL-USE.txt docs/legal/EXHIBIT-B-QUANTUM-SAFE.txt LICENSES/MPL-2.0.txt; do [ -f "$f" ] || MISSING="$MISSING $f" done - if [ ! -d "src/interface/abi" ] && [ ! -d "src/interface/Abi" ]; then - MISSING="$MISSING src/interface/abi" + # The polyglot seam (Idris2 ABI over a Zig FFI) is INHERITED from the + # template's spine, not required of every repository: a repository with no + # ABI or FFI prunes src/interface/ (the template does this per archetype, + # archetypes//prune.txt; ADR-0003) and records it in its deed's + # (variant (paths :removed)). So: a tree that carries the seam must carry + # all of it; a tree that carries none of it is complete without it. + # Deleting one part of a present seam still fails. + if [ -d src/interface ]; then + if [ ! -d "src/interface/abi" ] && [ ! -d "src/interface/Abi" ]; then + MISSING="$MISSING src/interface/abi" + fi + for f in src/interface/ffi src/interface/generated; do + [ -d "$f" ] || MISSING="$MISSING $f" + done fi - for f in src/interface/ffi src/interface/generated; do - [ -d "$f" ] || MISSING="$MISSING $f" - done for f in docs/governance/MAINTENANCE-CHECKLIST.adoc docs/governance/SOFTWARE-DEVELOPMENT-APPROACH.adoc; do [ -f "$f" ] || MISSING="$MISSING $f" done diff --git a/build/manifest.scm b/build/manifest.scm index 607826a..0a05297 100644 --- a/build/manifest.scm +++ b/build/manifest.scm @@ -6,10 +6,11 @@ ;; guix shell -m manifest.scm # or: just dev-shell ;; guix time-machine -C channels.scm -- shell -m manifest.scm # the pinned Guix ;; -;; Minted by provision-set from the languages detected here (idris2, zig). -;; Tools Guix does not package: idris2 (via pack). They come from mise, which this -;; shell provides: guix shell -m manifest.scm -- mise install +;; Languages detected here: none. This repository has no FFI or build language (the +;; scaffold was removed 2026-11-16); the Agda proofs are checked by scripts/check-agda.sh. +;; Tools Guix does not package come from mise, which this shell provides: +;; guix shell -m manifest.scm -- mise install ;; Canon: hyperpolymath/standards 3-practice/provisioning/PROVISIONING-STANDARD.adoc (specifications->manifest (list "git" "bash" "coreutils" "nss-certs" "just" "mise" - "shellcheck" "chez-scheme" "gmp" "gcc-toolchain" "zig")) + "shellcheck")) diff --git a/docs/README.adoc b/docs/README.adoc index dc7274f..5b338d6 100644 --- a/docs/README.adoc +++ b/docs/README.adoc @@ -23,7 +23,7 @@ and CI fails if it goes stale, so prefer it over any hand-written listing. | `architecture/` | Topology, threat model, and the generated repository map. | `attribution/` | CODEOWNERS rationale and credit. | `decisions/` | ADRs. `0000-template.adoc` is the template; number upwards from there. -| `developer/` | Developer-facing deep dives (ABI/FFI, tooling integrations). +| `developer/` | Developer-facing deep dives (tooling integrations). | `governance/` | Governance model, maintenance checklist, development approach, audits, planning. | `legal/` | Licence exhibits. | `onboarding/` | Quickstarts and the LLM warm-up documents. diff --git a/docs/SETUP.adoc b/docs/SETUP.adoc index 802e758..9ad4c9b 100644 --- a/docs/SETUP.adoc +++ b/docs/SETUP.adoc @@ -11,7 +11,7 @@ exactly what is written here, so this page is also what to read when they stop. [horizontal] Repository:: https://github.com/hyperpolymath/resource-algebra -Kind:: library (idris2, zig) +Kind:: library (Agda theory; no build language is detected) Toolchain declared in:: `mise.toml` (versions `latest`, made concrete in `mise.lock`), and `build/manifest.scm` / `build/guix.scm` / `build/channels.scm` for Guix Every command below is also a `just` recipe:: run `just` to list them @@ -42,16 +42,6 @@ for you in step 3. NOTE: On Windows, use WSL2 (`wsl --install`) and follow the Linux steps inside it. The launcher detects the platform and says so in `./launcher.sh --version`. -=== System packages for Idris2 - -Idris2 is built by pack on top of Chez Scheme and GMP, which come from your OS: - -* Fedora: `sudo dnf install chez-scheme gmp-devel` -* Debian/Ubuntu: `sudo apt install chezscheme libgmp-dev` -* macOS: `brew install chezscheme gmp` - -The Guix development shell (`build/manifest.scm`) already includes both. - == 2. Get the code [source,bash] @@ -81,8 +71,7 @@ That installs: |=== |Language |Tools |If mise cannot supply it -|idris2 |`idris2` |not a mise tool: install pack (https://github.com/stefan-hoeck/idris2-pack#installation), then `pack install-app idris2` -|zig |`zig` |https://ziglang.org/download/ or Guix `zig` +|agda |`agda` (`just test` runs `scripts/check-agda.sh`; CI pins Debian `agda-bin` 2.6.4.3) |not a mise tool: install it from your OS package manager, e.g. `apt install agda-bin` |(recipes) |`just`, `shellcheck` |your OS package manager, e.g. `dnf install just ShellCheck` |=== @@ -98,7 +87,7 @@ just setup ---- `just setup` repeats step 3 (harmless), fetches this repository's own -dependencies (idris2, zig), and finishes by running `just doctor`. +dependencies (none: no build language is detected), and finishes by running `just doctor`. == 5. Check it @@ -144,8 +133,8 @@ guix time-machine -C build/channels.scm -- shell -m build/manifest.scm # the e guix build -f build/guix.scm # the package ---- -Tools Guix does not package: idris2 (via pack). The Guix shell includes mise, so -inside it run `mise install` for those. `just dev-shell` picks Guix when it is present and mise +Tools Guix does not package come from mise. The Guix shell includes mise, so +inside it run `mise install`. `just dev-shell` picks Guix when it is present and mise when it is not. [[opsm]] diff --git a/docs/architecture/REPOSITORY-MAP.adoc b/docs/architecture/REPOSITORY-MAP.adoc index b923a6c..adfbe5f 100644 --- a/docs/architecture/REPOSITORY-MAP.adoc +++ b/docs/architecture/REPOSITORY-MAP.adoc @@ -249,8 +249,6 @@ your own repo - but do not read their emptiness as neglect here. | `src/core/` | `src/definitions/` | `src/errors/` -| `src/interface/generated/` -| `src/interface/generated/abi/` | `tests/fuzz/` | `verification/benchmarks/` | `verification/coverage/` diff --git a/docs/developer/ABI-FFI-README.adoc b/docs/developer/ABI-FFI-README.adoc deleted file mode 100644 index 537fabf..0000000 --- a/docs/developer/ABI-FFI-README.adoc +++ /dev/null @@ -1,405 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= ABI/FFI Standards -{{~ Aditionally delete this line and fill out the template below ~}} - -== RESOURCE_ALGEBRA ABI/FFI Documentation - -=== Overview - -This library follows the **Hyperpolymath RSR Standard** for ABI and FFI design: - -- **ABI (Application Binary Interface)** defined in **Idris2** with formal proofs -- **FFI (Foreign Function Interface)** implemented in **Zig** for C compatibility -- **Generated C headers** bridge Idris2 ABI to Zig FFI -- **Any language** can call through standard C ABI - -=== Architecture - ----- -┌─────────────────────────────────────────────┐ -│ ABI Definitions (Idris2) │ -│ src/interface/Abi/ │ -│ - Types.idr (Type definitions) │ -│ - Layout.idr (Memory layout proofs) │ -│ - Foreign.idr (FFI declarations) │ -└─────────────────┬───────────────────────────┘ - │ - │ generates (at compile time) - ▼ -┌─────────────────────────────────────────────┐ -│ C Headers (auto-generated) │ -│ generated/abi/resource_algebra.h │ -└─────────────────┬───────────────────────────┘ - │ - │ imported by - ▼ -┌─────────────────────────────────────────────┐ -│ FFI Implementation (Zig) │ -│ ffi/zig/src/main.zig │ -│ - Implements C-compatible functions │ -│ - Zero-cost abstractions │ -│ - Memory-safe by default │ -└─────────────────┬───────────────────────────┘ - │ - │ compiled to libresource_algebra.so/.a - ▼ -┌─────────────────────────────────────────────┐ -│ Any Language via C ABI │ -│ - Rust, , Julia, Python, etc. │ -└─────────────────────────────────────────────┘ ----- - -=== Directory Structure - ----- -resource_algebra/ -├── src/ -│ ├── abi/ # ABI definitions (Idris2) -│ │ ├── Types.idr # Core type definitions with proofs -│ │ ├── Layout.idr # Memory layout verification -│ │ └── Foreign.idr # FFI function declarations -│ └── lib/ # Core library (any language) -│ -├── ffi/ -│ └── zig/ # FFI implementation (Zig) -│ ├── build.zig # Build configuration -│ ├── build.zig.zon # Dependencies -│ ├── src/ -│ │ └── main.zig # C-compatible FFI implementation -│ ├── test/ -│ │ └── integration_test.zig -│ └── include/ -│ └── resource_algebra.h # C header (optional, can be generated) -│ -├── generated/ # Auto-generated files -│ └── abi/ -│ └── resource_algebra.h # Generated from Idris2 ABI -│ -└── bindings/ # Language-specific wrappers (optional) - ├── rust/ - ├── / - └── julia/ ----- - -=== Why Idris2 for ABI? - -==== 1. **Formal Verification** - -Idris2's dependent types allow proving properties about the ABI at compile-time: - -[source,idris] ----- --- Prove struct size is correct -public export -exampleStructSize : HasSize ExampleStruct 16 - --- Prove field alignment is correct -public export -fieldAligned : Divides 8 (offsetOf ExampleStruct.field) - --- Prove ABI is platform-compatible -public export -abiCompatible : Compatible (ABI 1) (ABI 2) ----- - -==== 2. **Type Safety** - -Encode invariants that C/Zig cannot express: - -[source,idris] ----- --- Non-null pointer guaranteed at type level -data Handle : Type where - MkHandle : (ptr : Bits64) -> {auto 0 nonNull : So (ptr /= 0)} -> Handle - --- Array with length proof -data Buffer : (n : Nat) -> Type where - MkBuffer : Vect n Byte -> Buffer n ----- - -==== 3. **Platform Abstraction** - -Platform-specific types with compile-time selection: - -[source,idris] ----- -CInt : Platform -> Type -CInt Linux = Bits32 -CInt Windows = Bits32 - -CSize : Platform -> Type -CSize Linux = Bits64 -CSize Windows = Bits64 ----- - -==== 4. **Safe Evolution** - -Prove that new ABI versions are backward-compatible: - -[source,idris] ----- --- Compiler enforces compatibility -abiUpgrade : ABI 1 -> ABI 2 -abiUpgrade old = MkABI2 { - -- Must preserve all v1 fields - v1_compat = old, - -- Can add new fields - new_features = defaults -} ----- - -=== Why Zig for FFI? - -==== 1. **C ABI Compatibility** - -Zig exports C-compatible functions naturally: - -[source,zig] ----- -export fn library_function(param: i32) i32 { - return param * 2; -} ----- - -==== 2. **Memory Safety** - -Compile-time safety without runtime overhead: - -[source,zig] ----- -// Null check enforced at compile time -const handle = init() orelse return error.InitFailed; -defer free(handle); ----- - -==== 3. **Cross-Compilation** - -Built-in cross-compilation to any platform: - -[source,bash] ----- -zig build -Dtarget=x86_64-linux -zig build -Dtarget=aarch64-macos -zig build -Dtarget=x86_64-windows ----- - -==== 4. **Zero Dependencies** - -No runtime, no libc required (unless explicitly needed): - -[source,zig] ----- -// Minimal binary size -pub const lib = @import("std"); -// Only includes what you use ----- - -=== Building - -==== Build FFI Library - -[source,bash] ----- -cd ffi/zig -zig build # Build debug -zig build -Doptimize=ReleaseFast # Build optimized -zig build test # Run tests ----- - -==== Generate C Header from Idris2 ABI - -[source,bash] ----- -cd src/abi -idris2 --cg c-header Types.idr -o ../../generated/abi/resource_algebra.h ----- - -==== Cross-Compile - -[source,bash] ----- -cd ffi/zig - -# Linux x86_64 -zig build -Dtarget=x86_64-linux - -# macOS ARM64 -zig build -Dtarget=aarch64-macos - -# Windows x86_64 -zig build -Dtarget=x86_64-windows ----- - -=== Usage - -==== From C - -[source,c] ----- -#include "resource_algebra.h" - -int main() { - void* handle = resource_algebra_init(); - if (!handle) return 1; - - int result = resource_algebra_process(handle, 42); - if (result != 0) { - const char* err = resource_algebra_last_error(); - fprintf(stderr, "Error: %s\n", err); - } - - resource_algebra_free(handle); - return 0; -} ----- - -Compile with: -[source,bash] ----- -gcc -o example example.c -lresource_algebra -L./zig-out/lib ----- - -==== From Idris2 - -[source,idris] ----- -import RESOURCE_ALGEBRA.ABI.Foreign - -main : IO () -main = do - Just handle <- init - | Nothing => putStrLn "Failed to initialize" - - Right result <- process handle 42 - | Left err => putStrLn $ "Error: " ++ errorDescription err - - free handle - putStrLn "Success" ----- - -==== From Rust - -[source,rust] ----- -#[link(name = "resource_algebra")] -extern "C" { - fn resource_algebra_init() -> *mut std::ffi::c_void; - fn resource_algebra_free(handle: *mut std::ffi::c_void); - fn resource_algebra_process(handle: *mut std::ffi::c_void, input: u32) -> i32; -} - -fn main() { - unsafe { - let handle = resource_algebra_init(); - assert!(!handle.is_null()); - - let result = resource_algebra_process(handle, 42); - assert_eq!(result, 0); - - resource_algebra_free(handle); - } -} ----- - -==== From Julia - -[source,julia] ----- -const libresource_algebra = "libresource_algebra" - -function init() - handle = ccall((:resource_algebra_init, libresource_algebra), Ptr{Cvoid}, ()) - handle == C_NULL && error("Failed to initialize") - handle -end - -function process(handle, input) - result = ccall((:resource_algebra_process, libresource_algebra), Cint, (Ptr{Cvoid}, UInt32), handle, input) - result -end - -function cleanup(handle) - ccall((:resource_algebra_free, libresource_algebra), Cvoid, (Ptr{Cvoid},), handle) -end - -# Usage -handle = init() -try - result = process(handle, 42) - println("Result: $result") -finally - cleanup(handle) -end ----- - -=== Testing - -==== Unit Tests (Zig) - -[source,bash] ----- -cd ffi/zig -zig build test ----- - -==== Integration Tests - -[source,bash] ----- -cd ffi/zig -zig build test-integration ----- - -==== ABI Verification (Idris2) - -[source,idris] ----- --- Compile-time verification -%runElab verifyABI - --- Runtime checks -main : IO () -main = do - verifyLayouorrect - verifyAlignmenorrect - putStrLn "ABI verification passed" ----- - -=== Contributing - -When modifying the ABI/FFI: - -1. **Update ABI first** (`src/interface/Abi/*.idr`) - - Modify type definitions - - Update proofs - - Ensure backward compatibility - -2. **Generate C header** - ```bash - idris2 --cg c-header src/interface/Abi/Types.idr -o generated/abi/resource_algebra.h - ``` - -3. **Update FFI implementation** (`ffi/zig/src/main.zig`) - - Implement new functions - - Match ABI types exactly - -4. **Add tests** - - Unit tests in Zig - - Integration tests - - ABI verification tests - -5. **Update documentation** - - Function signatures - - Usage examples - - Migration guide (if breaking changes) - -=== License - -MPL-2.0 - -=== See Also - -- https://idris2.readthedocs.io[Idris2 Documentation] -- https://ziglang.org/documentation/master/[Zig Documentation] -- https://github.com/hyperpolymath/rhodium-standard-repositories[Rhodium Standard Repositories] diff --git a/docs/onboarding/QUICKSTART-DEV.adoc b/docs/onboarding/QUICKSTART-DEV.adoc index bb6e136..2399acf 100644 --- a/docs/onboarding/QUICKSTART-DEV.adoc +++ b/docs/onboarding/QUICKSTART-DEV.adoc @@ -48,8 +48,6 @@ UNASSIGNED ---- resource-algebra/ ├── src/ # Source code -├── src/interface/Abi/ # Idris2 ABI definitions (if applicable) -├── ffi/zig/ # Zig FFI bridge (if applicable) ├── tests/ # Test suite ├── docs/ # Documentation ├── .machine_readable/ # Checkpoint files (STATE, META, ECOSYSTEM) diff --git a/docs/onboarding/llm-warmup-dev.adoc b/docs/onboarding/llm-warmup-dev.adoc index 8cabc49..86235f5 100644 --- a/docs/onboarding/llm-warmup-dev.adoc +++ b/docs/onboarding/llm-warmup-dev.adoc @@ -6,15 +6,11 @@ Paste this into an AI assistant before changing code in resource-algebra. == Orientation -resource-algebra (https://github.com/hyperpolymath/resource-algebra): a library in idris2, zig. +resource-algebra (https://github.com/hyperpolymath/resource-algebra): a library of Agda proofs, with Rocq and Lean rechecks. -The template's own code is the ABI/FFI seam that every minted repo inherits: - -* `src/interface/Abi/` + `src/interface/abi.ipkg`: Idris2 types and layout proofs - (the ABI owns the contract). -* `src/interface/ffi/`: the Zig implementation (`build.zig`, `src/main.zig`, - `test/integration_test.zig`), exporting C symbols named `_*`. -* `src/interface/generated/`: C headers generated from the ABI. +It ships no ABI or FFI: the template's Idris2 ABI / Zig FFI scaffold was removed on +2026-11-16 (owner decision; see `docs/status/PROOF-NEEDS.adoc`). The code is the Agda +source in `src/ResourceAlgebra/`. Everything else is scaffolding: `.machine_readable/` (descriptiles, contractiles, policies), `build/just/*.just` (the task phases the root `Justfile` imports), and @@ -53,9 +49,9 @@ just test-all # test, e2e, aspect, bench, readiness just repo-map # regenerate docs/architecture/REPOSITORY-MAP.adoc (CI checks it) ---- -The golden path is `just test && just quality`. In the template itself `test` and -`lint` fail on the placeholder tokens in `src/interface/ffi/src/main.zig`; that is -deliberate. Test a change to the FFI in a scratch copy after `repo-init`. +The golden path is `just test && just quality`. Here `just test` runs +`scripts/check-agda.sh` (the praxis deed's `:test`); `build`, `lint`, `fmt` and +`fmt-check` report that no language is detected and run nothing. == Where things are diff --git a/docs/onboarding/llm-warmup-user.adoc b/docs/onboarding/llm-warmup-user.adoc index 6f2de84..f6748ec 100644 --- a/docs/onboarding/llm-warmup-user.adoc +++ b/docs/onboarding/llm-warmup-user.adoc @@ -8,12 +8,12 @@ running, and where to look when something goes wrong. == What it is -resource-algebra (https://github.com/hyperpolymath/resource-algebra) is a library written in idris2, zig. +resource-algebra (https://github.com/hyperpolymath/resource-algebra) is a library of Agda proofs, with Rocq and Lean rechecks. It is not a project in its own right: it is the template every new hyperpolymath repository is created from. It ships CI/CD, machine-readable metadata (`.machine_readable/descriptiles/`), an AI gatekeeper deed -(`resource-algebra_chora.deed`), a typed ABI/FFI seam (Idris2 over Zig), Guix and +(`resource-algebra_chora.deed`), Guix and mise toolchains, and governance files, all passing the RSR validators before you add a line of your own. diff --git a/docs/status/PROOF-NEEDS.adoc b/docs/status/PROOF-NEEDS.adoc index 8f20b57..b9e3922 100644 --- a/docs/status/PROOF-NEEDS.adoc +++ b/docs/status/PROOF-NEEDS.adoc @@ -1,7 +1,7 @@ // SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright (c) Jonathan D.A. Jewell = Proof Requirements — resource-algebra -:revdate: 2026-11-09 +:revdate: 2026-11-16 What this repository owes, classified by the estate proof policy (`3-practice/PROOF-POLICY.adoc` in `hyperpolymath/standards`). What has been @@ -26,7 +26,10 @@ The repository ships no executable code, ABI, FFI, wire format or protocol. | No exported functions, memory layout or foreign interface exist to state them about. The template's mandatory ABI rows (ABI-1..5) and its typing rows (TP-1, TP-2) named template example files, not this repository's code; -they were removed with those files on 2026-11-09. +they were removed with those files on 2026-11-09. The ABI group applies to a +repository that ships an ABI or FFI, whatever implements it, not only to an +Idris2 one; this repository ships neither, so it carries no ABI/FFI proof +obligations (see "Removed scaffold" below). | Rust (Creusot, Pearlite, Verus) and Ada (SPARK) | No @@ -76,6 +79,19 @@ semiring). | `PROOF-STATUS.adoc` |=== +== Removed scaffold + +On 2026-11-16, by owner decision, the template's ABI/FFI scaffold was removed +from this repository: `src/interface/` (the Idris2 ABI in `Abi/`, `abi.ipkg`, +the Zig FFI in `ffi/`, and the `generated/` header stubs), +`tests/ffi_strings_test.sh` and `docs/developer/ABI-FFI-README.adoc`. The +reason is that this is a pure-theory Agda repository with no executable code, no +foreign interface and no memory layout to state ABI or FFI properties about. +No ABI or FFI exists here, so there are *no ABI/FFI proof obligations*. The +paths are recorded as `(variant (paths :removed))` in the repo deed. If an ABI +or FFI is ever added, its obligations must be stated here first, in the ABI +group, against that interface's own files and verifier. + == Out of scope here * K-CUT-LOSS, and its transport along a morphism, belong to diff --git a/docs/status/TEST-NEEDS.adoc b/docs/status/TEST-NEEDS.adoc index 59809bf..610a628 100644 --- a/docs/status/TEST-NEEDS.adoc +++ b/docs/status/TEST-NEEDS.adoc @@ -4,6 +4,11 @@ == CRG Grade: C — ACHIEVED 2026-04-04 +NOTE: On 2026-11-16 the template ABI/FFI scaffold this record describes +(`src/interface/`, the Idris2 ABI and Zig FFI rows, `tests/ffi_strings_test.sh`) was +removed from this repository (see `docs/status/PROOF-NEEDS.adoc`). The rows that name +them are the 2026-04-04 template record, not claims about the current tree. + == Current State (Updated 2026-04-04) [cols="2,1,4", options="header"] diff --git a/mise.lock b/mise.lock index 504562b..f15185f 100644 --- a/mise.lock +++ b/mise.lock @@ -123,35 +123,3 @@ checksum = "sha256:94c40e0696e4b907a74b7b2e1438d5d72ebaca83115817407f568a002d520 url = "https://github.com/aquasecurity/trivy/releases/download/v0.74.0/trivy_0.74.0_windows-64bit.zip" url_api = "https://api.github.com/repos/aquasecurity/trivy/releases/assets/514339469" provenance = "cosign" - -[[tools.zig]] -version = "0.16.0" -backend = "core:zig" - -[tools.zig."platforms.linux-arm64"] -checksum = "sha256:ea4b09bfb22ec6f6c6ceac57ab63efb6b46e17ab08d21f69f3a48b38e1534f17" -url = "https://ziglang.org/download/0.16.0/zig-aarch64-linux-0.16.0.tar.xz" - -[tools.zig."platforms.linux-arm64-musl"] -checksum = "sha256:ea4b09bfb22ec6f6c6ceac57ab63efb6b46e17ab08d21f69f3a48b38e1534f17" -url = "https://ziglang.org/download/0.16.0/zig-aarch64-linux-0.16.0.tar.xz" - -[tools.zig."platforms.linux-x64"] -checksum = "sha256:70e49664a74374b48b51e6f3fdfbf437f6395d42509050588bd49abe52ba3d00" -url = "https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz" - -[tools.zig."platforms.linux-x64-musl"] -checksum = "sha256:70e49664a74374b48b51e6f3fdfbf437f6395d42509050588bd49abe52ba3d00" -url = "https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz" - -[tools.zig."platforms.macos-arm64"] -checksum = "sha256:b23d70deaa879b5c2d486ed3316f7eaa53e84acf6fc9cc747de152450d401489" -url = "https://ziglang.org/download/0.16.0/zig-aarch64-macos-0.16.0.tar.xz" - -[tools.zig."platforms.macos-x64"] -checksum = "sha256:0387557ed1877bc6a2e1802c8391953baddba76081876301c522f52977b52ba7" -url = "https://ziglang.org/download/0.16.0/zig-x86_64-macos-0.16.0.tar.xz" - -[tools.zig."platforms.windows-x64"] -checksum = "sha256:68659eb5f1e4eb1437a722f1dd889c5a322c9954607f5edcf337bc3684a75a7e" -url = "https://ziglang.org/download/0.16.0/zig-x86_64-windows-0.16.0.zip" diff --git a/mise.toml b/mise.toml index 6423bc8..fc01b11 100644 --- a/mise.toml +++ b/mise.toml @@ -1,13 +1,14 @@ # SPDX-License-Identifier: MPL-2.0 # SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) # -# The toolchain for resource-algebra (idris2, zig). Specs are `latest`; mise.lock +# The toolchain for resource-algebra (no build language is detected; the Agda leg is +# checked by scripts/check-agda.sh with the Agda pinned in .github/workflows/proofs.yml). +# Specs are `latest`; mise.lock # records the concrete version and per-platform checksum of each, so every # checkout installs the same bits. Refresh both with: just toolchain-refresh # Canon: hyperpolymath/standards 3-practice/provisioning (TRUST-DEFAULTS §toolchain). # Estate policy: no python, deno, node/npm/yarn, make or nix here; the JS runtime is bun. # -# Idris2 is not a mise tool: it comes from pack (`just setup` says how). # A repository created from this template gets this file re-minted for its own # languages by `launch-scaffolder provision-set realign` (the deed's :repo differs). @@ -18,4 +19,3 @@ lockfile = true just = "latest" shellcheck = "latest" trivy = "latest" # just deps-audit -zig = "latest" diff --git a/resource-algebra_chora.deed b/resource-algebra_chora.deed index 67bf8c0..0cd3428 100644 --- a/resource-algebra_chora.deed +++ b/resource-algebra_chora.deed @@ -193,7 +193,7 @@ (methodology :instructions-clause "bot-directives" :default-mode hybrid)) (manifest :version "0.1.0" - :last-updated "2026-10-14" + :last-updated "2026-11-16" :project "resource-algebra" :purpose "Parametric resource algebra in Agda, with checked instances, separation witnesses and strict/lax morphism classifications." (agent :name CLAUDE :role "proofs, compilers, repo-local implementation, CI/CD, formal verification, Rust/Idris2/Zig") @@ -309,16 +309,7 @@ (directory :id "source-unit-contracts" :ply 2 :path "src/contracts" :description "Contracts unit for high-rigor source code.") (directory :id "source-unit-core" :ply 2 :path "src/core" :description "Primary application logic and core domain models.") (directory :id "source-unit-definitions" :ply 2 :path "src/definitions" :description "Definitions unit for high-rigor source code.") - (directory :id "source-unit-errors" :ply 2 :path "src/errors" :description "Errors unit for high-rigor source code.") - (directory :id "interface-seams-unit" :ply 2 :path "src/interface" :description "Consolidated \"Verified Interface Seams\" unit. This directory unifies the\nformal specification (ABI), the bridge implementation (FFI), and the\nresulting artifacts (Generated)." - (canonical-locations :abi "abi/" :ffi "ffi/" :generated "generated/") - :invariants ("ABI MUST be Idris2 (.idr)" "FFI MUST be Zig (.zig)" "Generated artifacts MUST be C-compatible" "The 'Truth' lives in abi/; the 'Implementation' lives in ffi/") - (directory :id "abi-logic" :ply 3 :path "src/interface/Abi" :description "Specialised Level 3 logic for abi.") - (directory :id "ffi-logic" :ply 3 :path "src/interface/ffi" :description "Specialised Level 3 logic for ffi." - (directory :id "src-unit" :ply 4 :path "src/interface/ffi/src" :description "Src logic at level 4.") - (directory :id "test-unit" :ply 4 :path "src/interface/ffi/test" :description "Test logic at level 4.")) - (directory :id "generated-logic" :ply 3 :path "src/interface/generated" :description "Specialised Level 3 logic for generated." - (directory :id "abi-unit" :ply 4 :path "src/interface/generated/abi" :description "Abi logic at level 4.")))) + (directory :id "source-unit-errors" :ply 2 :path "src/errors" :description "Errors unit for high-rigor source code.")) (directory :id "verification-pillar" :ply 1 :path "verification" :description "Primary verification pillar. Contains evidence for correctness,\nperformance, formal proofs, randomized testing, and aerospace-grade\nhigh-assurance metrics (MC/DC coverage, traceability, safety cases)." (canonical-locations :benchmarks "benchmarks/" :coverage "coverage/" :fuzzing "fuzzing/" :proofs "proofs/" :safety_case "safety_case/" :simulations "simulations/" :tests "tests/" :traceability "traceability/") :invariants ("Evidence MUST be reproducible and documented" "High-assurance deployments MUST satisfy traceability and safety_case requirements") @@ -1073,7 +1064,9 @@ ; Files a minted repo owns from birth are (paths :diverged …). (paths :added () - :removed () + ; 2026-11-16, owner decision: this repository is pure Agda theory and ships no + ; ABI or FFI, so the template's Idris2 ABI / Zig FFI scaffold is removed. + :removed ("src/interface/" "tests/ffi_strings_test.sh" "docs/developer/ABI-FFI-README.adoc") :diverged ("resource-algebra_chora.deed" "docs/status/ROADMAP.adoc"))) ; provenance — what this repo was minted FROM. Written once, at mint, ; by build/just/repo-init.just. Tools that want "what is this repo" read diff --git a/scripts/run-proven-suite.sh b/scripts/run-proven-suite.sh index b67ee9f..560dbb1 100755 --- a/scripts/run-proven-suite.sh +++ b/scripts/run-proven-suite.sh @@ -6,6 +6,11 @@ # # Usage: scripts/run-proven-suite.sh [--require-zig] [--bench] [--report FILE] # +# --require-zig: the zig compiler must be present WHEN src/interface/ffi exists. +# With no src/interface/ffi (pruned: this repository ships no FFI) the Zig lane is +# reported as NOT APPLICABLE (distinct from PASS, counted in the summary), not an +# error. +# # Exit contract: # 0 = every tier passed (Silence on clean tree + Firing on every negative mutant) # 1 = a subject check, proof honesty lint, or contract test failed @@ -50,6 +55,9 @@ fi subject_failures=0 setup_failures=0 +passed_lanes=0 +na_lanes=0 +NA_LABELS=() # run_lane LABEL COMMAND... — run a lane and accumulate its outcome without # propagating its exit status: 2 increments setup_failures; other nonzero @@ -60,7 +68,7 @@ run_lane() { printf '==> [proven-suite] %s\n' "$label" "$@" || rc=$? case "$rc" in - 0) printf ' PASS (0): %s\n' "$label" ;; + 0) printf ' PASS (0): %s\n' "$label"; passed_lanes=$((passed_lanes + 1)) ;; 2) printf ' INERT/SETUP (2): %s\n' "$label" >&2 setup_failures=$((setup_failures + 1)) @@ -167,7 +175,31 @@ run_zig_ffi_tests() { (cd "$work/ffi" && zig build test) } -if command -v zig >/dev/null 2>&1; then +# mark_not_applicable LABEL REASON — record a lane that has no subject in this +# tree. It is a distinct outcome: not PASS (nothing was verified) and not FAIL +# (nothing is wrong). It is printed at the lane and again, counted, in the +# closing summary, so a green run can never be read as "the lane passed". +mark_not_applicable() { + printf '==> [proven-suite] %s\n' "$1" + printf ' NOT APPLICABLE: %s\n' "$2" + na_lanes=$((na_lanes + 1)) + NA_LABELS+=("$1 ($2)") + return 0 +} + +# --require-zig means "when there is Zig to test, the compiler must be present". +# It does NOT mean "src/interface/ffi must exist": this repository pruned the FFI +# seam on purpose, and CI passes the flag unconditionally. With no ffi directory +# there is no subject, so the lane is NOT APPLICABLE whether or not zig is +# installed and whether or not --require-zig is given; that is checked FIRST so a +# pruned tree is not failed for lacking a compiler it has no use for. The lane is +# reported, never silently dropped, and is counted apart from passes in the +# summary. If an FFI directory returns, the lane runs again and --require-zig +# fails closed without a compiler. +if [ ! -d src/interface/ffi ]; then + mark_not_applicable "Zig FFI ABI layout & memory-leak unit tests" \ + "not applicable: src/interface/ffi absent (pruned: this repository ships no FFI)" +elif command -v zig >/dev/null 2>&1; then run_lane "Zig FFI ABI layout & memory-leak unit tests" run_zig_ffi_tests elif [ "$REQUIRE_ZIG" -eq 1 ]; then printf ' INERT/SETUP (2): zig compiler required (--require-zig) but missing on PATH\n' >&2 @@ -195,6 +227,12 @@ if [ "$RUN_BENCH" -eq 1 ]; then fi fi +printf 'proven-suite: lanes: %d passed, %d failed, %d setup/inert, %d not applicable\n' \ + "$passed_lanes" "$subject_failures" "$setup_failures" "$na_lanes" +for _na in "${NA_LABELS[@]+"${NA_LABELS[@]}"}"; do + printf 'proven-suite: NOT APPLICABLE (not a pass): %s\n' "$_na" +done + if [ "$setup_failures" -gt 0 ]; then printf 'proven-suite: SETUP/INERT FAILURE (%d setup, %d subject)\n' "$setup_failures" "$subject_failures" >&2 exit 2 @@ -203,5 +241,9 @@ if [ "$subject_failures" -gt 0 ]; then printf 'proven-suite: SUBJECT FAILURE (%d failing lane(s))\n' "$subject_failures" >&2 exit 1 fi -printf 'proven-suite: ALL LANES PASSED\n' +if [ "$na_lanes" -gt 0 ]; then + printf 'proven-suite: ALL APPLICABLE LANES PASSED (%d lane(s) not applicable and NOT verified)\n' "$na_lanes" +else + printf 'proven-suite: ALL LANES PASSED\n' +fi exit 0 diff --git a/scripts/validate-template.sh b/scripts/validate-template.sh index 09f0de8..359f19d 100755 --- a/scripts/validate-template.sh +++ b/scripts/validate-template.sh @@ -158,6 +158,13 @@ has_placeholder() { # VALIDATION PHASE 1: CORE STRUCTURE #============================================================================== +# The ABI/FFI seam (Idris2 ABI over a Zig FFI) is inherited from the template spine. +# A repository that pruned src/interface/ (recorded in its deed as +# (variant (paths :removed))) is complete without it; a tree that carries the +# directory must carry all of it, so deleting one part of a present seam still fails. +HAS_SEAM=0 +[ -d "$REPO_ROOT/src/interface" ] && HAS_SEAM=1 + echo "" log_info "Phase 1: Core repository structure" echo "" @@ -173,9 +180,13 @@ check_file_either "AUDIT.adoc" "docs/AUDIT.adoc" "Release audit gate" # Directories check_dir_either ".machine_readable" "machine-readable" "Machine-readable metadata" check_dir_exists ".github" "GitHub community metadata" -check_abi_dir_exists "Idris2 ABI definitions" -check_dir_exists "src/interface/ffi" "Zig FFI implementation" -check_dir_exists "src/interface/generated/abi" "Generated C headers" +if [ "$HAS_SEAM" = 1 ]; then + check_abi_dir_exists "Idris2 ABI definitions" + check_dir_exists "src/interface/ffi" "Zig FFI implementation" + check_dir_exists "src/interface/generated/abi" "Generated C headers" +else + log_info "ABI/FFI seam: not applicable (src/interface/ absent; recorded in the repo deed's (variant (paths :removed)))" +fi check_dir_exists "docs" "Documentation" #============================================================================== @@ -300,15 +311,19 @@ echo "" log_info "Phase 4: Idris2 ABI and Zig FFI source files" echo "" -# Idris2 ABI files -check_abi_file_exists "Types.idr" "Core type definitions" -check_abi_file_exists "Layout.idr" "Memory layout specifications" -check_abi_file_exists "Foreign.idr" "FFI foreign declarations" +if [ "$HAS_SEAM" = 1 ]; then + # Idris2 ABI files + check_abi_file_exists "Types.idr" "Core type definitions" + check_abi_file_exists "Layout.idr" "Memory layout specifications" + check_abi_file_exists "Foreign.idr" "FFI foreign declarations" -# Zig FFI files -check_file_exists "src/interface/ffi/build.zig" "Zig build configuration" -check_file_exists "src/interface/ffi/src/main.zig" "Zig implementation" -check_file_exists "src/interface/ffi/test/integration_test.zig" "Integration tests" + # Zig FFI files + check_file_exists "src/interface/ffi/build.zig" "Zig build configuration" + check_file_exists "src/interface/ffi/src/main.zig" "Zig implementation" + check_file_exists "src/interface/ffi/test/integration_test.zig" "Integration tests" +else + log_info "ABI/FFI source files: not applicable (src/interface/ absent)" +fi #============================================================================== # VALIDATION PHASE 5: PLACEHOLDER TOKENS @@ -401,49 +416,53 @@ echo "" log_info "Phase 7: Build system verification" echo "" -# Check Zig build -if [ -f "$REPO_ROOT/src/interface/ffi/build.zig" ]; then - if command -v zig &> /dev/null; then - cd "$REPO_ROOT/src/interface/ffi" - if zig build 2>&1 | grep -q "error"; then - log_error "Zig build failed" +if [ "$HAS_SEAM" = 1 ]; then + # Check Zig build + if [ -f "$REPO_ROOT/src/interface/ffi/build.zig" ]; then + if command -v zig &> /dev/null; then + cd "$REPO_ROOT/src/interface/ffi" + if zig build 2>&1 | grep -q "error"; then + log_error "Zig build failed" + else + log_pass "Zig build successful" + fi + cd - > /dev/null else - log_pass "Zig build successful" + log_warning "Zig compiler not found - skipping Zig build check" fi - cd - > /dev/null else - log_warning "Zig compiler not found - skipping Zig build check" + log_error "Zig build.zig not found" fi -else - log_error "Zig build.zig not found" -fi -# Check Idris2. Prefer a REAL typecheck via the package (abi.ipkg sets the -# sourcedir so the `module Abi.*` namespace resolves); this catches namespace / -# path / import breakage that a bare per-file `idris2 --check` masks as a -# tolerated "module name does not match file name" warning. -if command -v idris2 &> /dev/null; then - if [ -f "$REPO_ROOT/src/interface/abi.ipkg" ]; then - if (cd "$REPO_ROOT" && idris2 --typecheck src/interface/abi.ipkg) > /dev/null 2>&1; then - log_pass "Idris2 ABI typechecks (abi.ipkg)" + # Check Idris2. Prefer a REAL typecheck via the package (abi.ipkg sets the + # sourcedir so the `module Abi.*` namespace resolves); this catches namespace / + # path / import breakage that a bare per-file `idris2 --check` masks as a + # tolerated "module name does not match file name" warning. + if command -v idris2 &> /dev/null; then + if [ -f "$REPO_ROOT/src/interface/abi.ipkg" ]; then + if (cd "$REPO_ROOT" && idris2 --typecheck src/interface/abi.ipkg) > /dev/null 2>&1; then + log_pass "Idris2 ABI typechecks (abi.ipkg)" + else + log_error "Idris2 ABI does NOT typecheck (abi.ipkg)" + fi else - log_error "Idris2 ABI does NOT typecheck (abi.ipkg)" + # No package: fall back to a best-effort per-file syntax check (warns on + # the expected namespace/path mismatch). Look in either case of the dir. + IDS_FILES=$(find "$REPO_ROOT/src/interface/Abi" "$REPO_ROOT/src/interface/abi" -name "*.idr" -type f 2>/dev/null || true) + while IFS= read -r ids_file; do + if [ -z "$ids_file" ]; then continue; fi + if ! idris2 --check "$ids_file" 2>&1 | grep -q "Error"; then + log_pass "Idris2 syntax OK: $(basename "$ids_file")" + else + log_warning "Idris2 syntax issue: $(basename "$ids_file")" + fi + done <<< "$IDS_FILES" fi else - # No package: fall back to a best-effort per-file syntax check (warns on - # the expected namespace/path mismatch). Look in either case of the dir. - IDS_FILES=$(find "$REPO_ROOT/src/interface/Abi" "$REPO_ROOT/src/interface/abi" -name "*.idr" -type f 2>/dev/null || true) - while IFS= read -r ids_file; do - if [ -z "$ids_file" ]; then continue; fi - if ! idris2 --check "$ids_file" 2>&1 | grep -q "Error"; then - log_pass "Idris2 syntax OK: $(basename "$ids_file")" - else - log_warning "Idris2 syntax issue: $(basename "$ids_file")" - fi - done <<< "$IDS_FILES" + log_warning "Idris2 compiler not found - skipping Idris2 syntax checks" fi else - log_warning "Idris2 compiler not found - skipping Idris2 syntax checks" + log_info "Zig and Idris2 builds: not applicable (src/interface/ absent)" fi #============================================================================== @@ -454,7 +473,9 @@ echo "" log_info "Phase 8: Documentation requirements" echo "" -check_file_exists "docs/developer/ABI-FFI-README.adoc" "ABI/FFI documentation" +if [ "$HAS_SEAM" = 1 ]; then + check_file_exists "docs/developer/ABI-FFI-README.adoc" "ABI/FFI documentation" +fi # TOPOLOGY may live at root or under docs/architecture/, .md or .adoc if [ -f "$REPO_ROOT/TOPOLOGY.adoc" ] || [ -f "$REPO_ROOT/TOPOLOGY.md" ] || \ [ -f "$REPO_ROOT/docs/architecture/TOPOLOGY.adoc" ] || [ -f "$REPO_ROOT/docs/architecture/TOPOLOGY.md" ]; then diff --git a/src/interface/Abi/Foreign.idr b/src/interface/Abi/Foreign.idr deleted file mode 100644 index ca66b08..0000000 --- a/src/interface/Abi/Foreign.idr +++ /dev/null @@ -1,83 +0,0 @@ --- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell -||| Foreign Function Interface Bridge -||| -||| This module defines the raw FFI calls and their safe wrappers, -||| implemented in the Zig FFI layer. - -module Abi.Foreign - -import Abi.Types -import Abi.Layout - -%default total - --------------------------------------------------------------------------------- --- Library Lifecycle --------------------------------------------------------------------------------- - -||| Raw FFI call to initialize the library -%foreign "C:rsr_init,librsr" -prim__init : PrimIO Bits64 - -||| Raw FFI call to free library resources -%foreign "C:rsr_free,librsr" -prim__free : Bits64 -> PrimIO () - -||| Safe wrapper for initialization -export -init : IO (Maybe Handle) -init = do - ptr <- primIO prim__init - pure (createHandle ptr) - -||| Safe wrapper for cleanup -export -free : Handle -> IO () -free h = primIO (prim__free h.ptr) - --------------------------------------------------------------------------------- --- Core Operations --------------------------------------------------------------------------------- - -||| Raw FFI call for main processing -%foreign "C:rsr_process,librsr" -prim__process : Bits64 -> Bits32 -> PrimIO Bits32 - -||| Safe wrapper with error handling -export -process : Handle -> Bits32 -> IO (Either Result Bits32) -process h input = do - result <- primIO (prim__process h.ptr input) - if result == 0 - then pure (Left Error) - else pure (Right result) - --------------------------------------------------------------------------------- --- Status and Metrics --------------------------------------------------------------------------------- - -||| Get the current error description from the library -%foreign "C:rsr_get_error,librsr" -prim__getError : Bits64 -> PrimIO (Ptr String) - -||| Detailed error string helper -export -errorDescription : Result -> String -errorDescription Ok = "Success" -errorDescription Error = "Generic error" -errorDescription InvalidParam = "Invalid parameter" -errorDescription Busy = "Library is busy" - --------------------------------------------------------------------------------- --- Documentation --------------------------------------------------------------------------------- - -||| Summary of ABI safety properties: -||| 1. All functions are total (total keyword enforced). -||| 2. Pointers are verified non-null before being wrapped in Handle. -||| 3. Memory layouts are proven C-ABI compliant in Abi.Layout. -||| 4. FFI boundary uses explicitly tagged types from Abi.Types. -public export -abiSafetyGuarantees : String -abiSafetyGuarantees = "RSR-Template ABI: 4 proven safety properties for FFI integration" diff --git a/src/interface/Abi/Layout.idr b/src/interface/Abi/Layout.idr deleted file mode 100644 index e1f4275..0000000 --- a/src/interface/Abi/Layout.idr +++ /dev/null @@ -1,128 +0,0 @@ --- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell -||| ABI Layout Verification -||| -||| This module provides formal proofs about memory layout, alignment, -||| and padding for C-compatible structs. - -module Abi.Layout - -import Abi.Types -import Data.Vect -import Data.So - -%default total - --------------------------------------------------------------------------------- --- Alignment Invariants --------------------------------------------------------------------------------- - -||| Predicate: n divides m -public export -data Divides : (n, m : Nat) -> Type where - MkDivides : (k : Nat) -> (0 prf : m = k * n) -> Divides n m - -||| Implementation of divides for common sizes -public export -div8_24 : Divides 8 24 -div8_24 = MkDivides 3 Refl - -public export -div4_0 : Divides 4 0 -div4_0 = MkDivides 0 Refl - -public export -div8_8 : Divides 8 8 -div8_8 = MkDivides 1 Refl - -public export -div8_16 : Divides 8 16 -div8_16 = MkDivides 2 Refl - -||| Calculate padding required for an offset to meet alignment -public export -paddingFor : (offset : Nat) -> (alignment : Nat) -> Nat -paddingFor offset 0 = 0 -paddingFor offset alignment = - let m = offset `mod` alignment in - if m == 0 - then 0 - else alignment `minus` m - -||| Align a size up to the next multiple of alignment -public export -alignUp : (size : Nat) -> (alignment : Nat) -> Nat -alignUp size alignment = - size + paddingFor size alignment - --------------------------------------------------------------------------------- --- Struct Model --------------------------------------------------------------------------------- - -||| Representation of a single field in a struct -public export -record Field where - constructor MkField - name : String - offset : Nat - size : Nat - alignment : Nat - -||| Valid memory layout for a C struct -public export -record StructLayout where - constructor MkStructLayout - {n : Nat} - fields : Vect n Field - totalSize : Nat - alignment : Nat - {auto 0 aligned : Divides alignment totalSize} - --------------------------------------------------------------------------------- --- Compliance Predicates --------------------------------------------------------------------------------- - -||| Proof that all fields in a struct are correctly aligned -public export -data FieldsAligned : Vect n Field -> Type where - NoFields : FieldsAligned [] - ConsField : - (f : Field) -> - (rest : Vect n Field) -> - (0 prf : Divides f.alignment f.offset) -> - FieldsAligned rest -> - FieldsAligned (f :: rest) - -||| Predicate: Struct is C-ABI compliant -public export -data CABICompliant : StructLayout -> Type where - CABIOk : (l : StructLayout) -> - (0 prf : FieldsAligned l.fields) -> - CABICompliant l - --------------------------------------------------------------------------------- --- Example and Proofs --------------------------------------------------------------------------------- - -||| Example: struct { int32_t x; int64_t y; double z; } -||| On 64-bit Linux, this should have size 24, alignment 8. -public export -exampleLayout : StructLayout -exampleLayout = - MkStructLayout - [ MkField "x" 0 4 4 -- Bits32 at offset 0 - , MkField "y" 8 8 8 -- Bits64 at offset 8 (4 bytes padding) - , MkField "z" 16 8 8 -- Double at offset 16 - ] - 24 -- Total size: 24 bytes - 8 -- Alignment: 8 bytes - {aligned = div8_24} - -||| Proof that example layout is valid -public export -exampleLayoutValid : CABICompliant Abi.Layout.exampleLayout -exampleLayoutValid = CABIOk Abi.Layout.exampleLayout ( - ConsField (MkField "x" 0 4 4) _ div4_0 ( - ConsField (MkField "y" 8 8 8) _ div8_8 ( - ConsField (MkField "z" 16 8 8) _ div8_16 ( - NoFields)))) diff --git a/src/interface/Abi/README.adoc b/src/interface/Abi/README.adoc deleted file mode 100644 index 4a99517..0000000 --- a/src/interface/Abi/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= abi Logic diff --git a/src/interface/Abi/Types.idr b/src/interface/Abi/Types.idr deleted file mode 100644 index 9d30051..0000000 --- a/src/interface/Abi/Types.idr +++ /dev/null @@ -1,112 +0,0 @@ --- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell -||| ABI Type Definitions Template -||| -||| This module defines the Application Binary Interface (ABI) for this library. -||| All type definitions include formal proofs of correctness. - -module Abi.Types - -import Data.Bits -import Data.So -import Data.Vect -import Decidable.Equality - -%default total - --------------------------------------------------------------------------------- --- Platform Model --------------------------------------------------------------------------------- - -||| Target platforms for the FFI bridge -public export -data Platform = Linux | MacOS | Windows | WASM | RISCV - -||| Pointer size in bits per platform -public export -ptrSize : Platform -> Nat -ptrSize Linux = 64 -ptrSize MacOS = 64 -ptrSize Windows = 64 -ptrSize WASM = 32 -ptrSize RISCV = 64 - -||| Current target platform (detected at compile-time) -public export -thisPlatform : Platform -thisPlatform = Linux -- Simplified for template - --------------------------------------------------------------------------------- --- Core Types --------------------------------------------------------------------------------- - -||| Return codes for FFI calls -public export -data Result = Ok | Error | InvalidParam | Busy - -||| Results are decidably equal -public export -implementation DecEq Result where - decEq Ok Ok = Yes Refl - decEq Error Error = Yes Refl - decEq InvalidParam InvalidParam = Yes Refl - decEq Busy Busy = Yes Refl - decEq Ok Error = No (\case Refl impossible) - decEq Ok InvalidParam = No (\case Refl impossible) - decEq Ok Busy = No (\case Refl impossible) - decEq Error Ok = No (\case Refl impossible) - decEq Error InvalidParam = No (\case Refl impossible) - decEq Error Busy = No (\case Refl impossible) - decEq InvalidParam Ok = No (\case Refl impossible) - decEq InvalidParam Error = No (\case Refl impossible) - decEq InvalidParam Busy = No (\case Refl impossible) - decEq Busy Ok = No (\case Refl impossible) - decEq Busy Error = No (\case Refl impossible) - decEq Busy InvalidParam = No (\case Refl impossible) - -||| Opaque handle for library resources -||| Invariant: Handle pointer must be non-null -public export -record Handle where - constructor MkHandle - ptr : Bits64 - 0 prf : So (ptr /= 0) - -||| Returns Nothing if pointer is null -public export -createHandle : Bits64 -> Maybe Handle -createHandle 0 = Nothing -createHandle ptr = case decSo (ptr /= 0) of - Yes p => Just (MkHandle ptr p) - No _ => Nothing - --------------------------------------------------------------------------------- --- C-Types Mapping --------------------------------------------------------------------------------- - -||| Tagged types for C-FFI boundary -public export -data CType = CInt | CUInt | CLong | CULong | CPtrType - -||| Pointer type for platform -public export -CPtr : Platform -> CType -> Type -CPtr p _ = Bits64 -- Simplified for 64-bit template - -||| Size of C types (platform-specific) -public export -cSizeOf : (p : Platform) -> (t : CType) -> Nat -cSizeOf p CInt = 4 -cSizeOf p CUInt = 4 -cSizeOf p CLong = 8 -cSizeOf p CULong = 8 -cSizeOf p CPtrType = 8 - -||| Alignment of C types (platform-specific) -public export -cAlignOf : (p : Platform) -> (t : CType) -> Nat -cAlignOf p CInt = 4 -cAlignOf p CUInt = 4 -cAlignOf p CLong = 8 -cAlignOf p CULong = 8 -cAlignOf p CPtrType = 8 diff --git a/src/interface/README.adoc b/src/interface/README.adoc deleted file mode 100644 index 4fde708..0000000 --- a/src/interface/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= interface Unit diff --git a/src/interface/abi.ipkg b/src/interface/abi.ipkg deleted file mode 100644 index 14ec249..0000000 --- a/src/interface/abi.ipkg +++ /dev/null @@ -1,36 +0,0 @@ --- SPDX-License-Identifier: MPL-2.0 --- Copyright (c) Jonathan D.A. Jewell --- --- Idris2 package for the formally-typed ABI seam. --- --- The seam lives in a single, case-consistent directory src/interface/Abi/ --- (uppercase) so the physical path matches the `module Abi.*` namespace on --- EVERY filesystem. Idris2 requires capitalised namespace components, and a --- lowercase abi/ directory cannot satisfy that without a case-twin symlink --- (src/interface/Abi -> abi) that collides on case-insensitive filesystems --- (macOS/Windows). One case-consistent directory has exactly one path identity --- under case-folding, so the collision is impossible by construction. --- --- A bare `idris2 --check src/interface/Abi/Foo.idr` still warns ("module name --- does not match file name") because Idris derives the expected module from the --- full path; that is expected. Use the package for a real typecheck: --- idris2 --typecheck src/interface/abi.ipkg (or --build) --- --- The RSR validators accept either Abi/ (canonical, case-consistent) or a --- lowercase abi/ for downstream repos that ship lowercase — but never both. - -package abi - -version = 0.1.0 - -authors = "Jonathan D.A. Jewell" - -brief = "Formally-typed ABI/FFI seam (Idris2 type + layout proofs) for an RSR-templated repository" - -sourcedir = "." - -depends = base - -modules = Abi.Types - , Abi.Layout - , Abi.Foreign diff --git a/src/interface/ffi/README.adoc b/src/interface/ffi/README.adoc deleted file mode 100644 index ca14320..0000000 --- a/src/interface/ffi/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= ffi Logic diff --git a/src/interface/ffi/build.zig b/src/interface/ffi/build.zig deleted file mode 100644 index 0596e52..0000000 --- a/src/interface/ffi/build.zig +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -// -// Template FFI build (Zig 0.15.2+). -// -// zig build test runs the unit tests in src/main.zig and test/integration_test.zig -// -// src/main.zig carries template tokens until `just repo-init` fills them, so the -// test step compiles only in an instantiated repository. - -const std = @import("std"); - -pub fn build(b: *std.Build) void { - const target = b.standardTargetOptions(.{}); - const optimize = b.standardOptimizeOption(.{}); - - const test_step = b.step("test", "Run the FFI unit and integration tests"); - for ([_][]const u8{ "src/main.zig", "test/integration_test.zig" }) |path| { - const t = b.addTest(.{ - .root_module = b.createModule(.{ - .root_source_file = b.path(path), - .target = target, - .optimize = optimize, - .link_libc = true, // main.zig allocates with std.heap.c_allocator - }), - }); - test_step.dependOn(&b.addRunArtifact(t).step); - } -} diff --git a/src/interface/ffi/src/README.adoc b/src/interface/ffi/src/README.adoc deleted file mode 100644 index d5631f6..0000000 --- a/src/interface/ffi/src/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Src Logic diff --git a/src/interface/ffi/src/main.zig b/src/interface/ffi/src/main.zig deleted file mode 100644 index 073e78b..0000000 --- a/src/interface/ffi/src/main.zig +++ /dev/null @@ -1,293 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -// RESOURCE_ALGEBRA FFI Implementation -// -// This module implements the C-compatible FFI declared in src/abi/Foreign.idr -// All types and layouts must match the Idris2 ABI definitions. -// - -const std = @import("std"); - -// Version information (keep in sync with project) -const VERSION = "0.1.0"; -const BUILD_INFO = "RESOURCE_ALGEBRA built with Zig " ++ @import("builtin").zig_version_string; - -/// Thread-local error storage -threadlocal var last_error: ?[]const u8 = null; - -/// Set the last error message -fn setError(msg: []const u8) void { - last_error = msg; -} - -/// Clear the last error -fn clearError() void { - last_error = null; -} - -/// Duplicate a byte slice as a NUL-terminated buffer across Zig 0.15/0.16/0.17 -/// (`Allocator.dupeZ` was removed in Zig 0.17). -/// The caller owns the returned slice and must free it with `allocator`. -/// Propagates allocation failure. -fn dupeZ(allocator: std.mem.Allocator, bytes: []const u8) ![:0]u8 { - const buf = try allocator.allocSentinel(u8, bytes.len, 0); - @memcpy(buf[0..bytes.len], bytes); - return buf; -} - -//============================================================================== -// Core Types (must match src/abi/Types.idr) -//============================================================================== - -/// Result codes (must match Idris2 Result type) -pub const Result = enum(c_int) { - ok = 0, - @"error" = 1, - invalid_param = 2, - out_of_memory = 3, - null_pointer = 4, -}; - -/// Library handle. C sees only a pointer, so the fields stay private to Zig. -pub const Handle = struct { - // Internal state hidden from C - allocator: std.mem.Allocator, - initialized: bool, - // Add your fields here -}; - -//============================================================================== -// Library Lifecycle -//============================================================================== - -/// Initialize the library -/// Returns a handle, or null on failure -export fn resource_algebra_init() ?*Handle { - const allocator = std.heap.c_allocator; - - const handle = allocator.create(Handle) catch { - setError("Failed to allocate handle"); - return null; - }; - - // Initialize handle - handle.* = .{ - .allocator = allocator, - .initialized = true, - }; - - clearError(); - return handle; -} - -/// Free the library handle -export fn resource_algebra_free(handle: ?*Handle) void { - const h = handle orelse return; - const allocator = h.allocator; - - // Clean up resources - h.initialized = false; - - allocator.destroy(h); - clearError(); -} - -//============================================================================== -// Core Operations -//============================================================================== - -/// Process data (example operation) -export fn resource_algebra_process(handle: ?*Handle, input: u32) Result { - const h = handle orelse { - setError("Null handle"); - return .null_pointer; - }; - - if (!h.initialized) { - setError("Handle not initialized"); - return .@"error"; - } - - // Example processing logic - _ = input; - - clearError(); - return .ok; -} - -//============================================================================== -// String Operations -//============================================================================== - -/// Get a string result (example) -/// Return a NUL-terminated "Example result" owned by the caller; free it with -/// `resource_algebra_free_string`. Return null and set the thread-local error for a -/// null or uninitialized handle, or allocation failure. Clear the error on success. -export fn resource_algebra_get_string(handle: ?*Handle) ?[*:0]const u8 { - const h = handle orelse { - setError("Null handle"); - return null; - }; - - if (!h.initialized) { - setError("Handle not initialized"); - return null; - } - - // Example: allocate and return a string - const result = dupeZ(h.allocator, "Example result") catch { - setError("Failed to allocate string"); - return null; - }; - - clearError(); - return result.ptr; -} - -/// Free a string allocated by the library -export fn resource_algebra_free_string(str: ?[*:0]const u8) void { - const s = str orelse return; - const allocator = std.heap.c_allocator; - - const slice = std.mem.span(s); - allocator.free(slice); -} - -//============================================================================== -// Array/Buffer Operations -//============================================================================== - -/// Process an array of data -export fn resource_algebra_process_array( - handle: ?*Handle, - buffer: ?[*]const u8, - len: u32, -) Result { - const h = handle orelse { - setError("Null handle"); - return .null_pointer; - }; - - const buf = buffer orelse { - setError("Null buffer"); - return .null_pointer; - }; - - if (!h.initialized) { - setError("Handle not initialized"); - return .@"error"; - } - - // Access the buffer - const data = buf[0..len]; - _ = data; - - // Process data here - - clearError(); - return .ok; -} - -//============================================================================== -// Error Handling -//============================================================================== - -/// Get the last error message. -/// Return an allocated NUL-terminated copy of the current thread's error, or -/// null if no error is set or allocation fails. Leave the stored error unchanged. -/// Caller must free a non-null returned string with `resource_algebra_free_string`. -export fn resource_algebra_last_error() ?[*:0]const u8 { - const err = last_error orelse return null; - - const allocator = std.heap.c_allocator; - const c_str = dupeZ(allocator, err) catch return null; - return c_str.ptr; -} - -//============================================================================== -// Version Information -//============================================================================== - -/// Get the library version -export fn resource_algebra_version() [*:0]const u8 { - return VERSION.ptr; -} - -/// Get build information -export fn resource_algebra_build_info() [*:0]const u8 { - return BUILD_INFO.ptr; -} - -//============================================================================== -// Callback Support -//============================================================================== - -/// Callback function type (C ABI) -pub const Callback = *const fn (u64, u32) callconv(.c) u32; - -/// Register a callback -export fn resource_algebra_register_callback( - handle: ?*Handle, - callback: ?Callback, -) Result { - const h = handle orelse { - setError("Null handle"); - return .null_pointer; - }; - - const cb = callback orelse { - setError("Null callback"); - return .null_pointer; - }; - - if (!h.initialized) { - setError("Handle not initialized"); - return .@"error"; - } - - // Store callback for later use - _ = cb; - - clearError(); - return .ok; -} - -//============================================================================== -// Utility Functions -//============================================================================== - -/// Check if handle is initialized -export fn resource_algebra_is_initialized(handle: ?*Handle) u32 { - const h = handle orelse return 0; - return if (h.initialized) 1 else 0; -} - -//============================================================================== -// Tests -//============================================================================== - -test "lifecycle" { - const handle = resource_algebra_init() orelse return error.InitFailed; - defer resource_algebra_free(handle); - - try std.testing.expect(resource_algebra_is_initialized(handle) == 1); - - const str = resource_algebra_get_string(handle) orelse return error.StringFailed; - defer resource_algebra_free_string(str); - try std.testing.expectEqualStrings("Example result", std.mem.span(str)); -} - -test "error handling" { - const result = resource_algebra_process(null, 0); - try std.testing.expectEqual(Result.null_pointer, result); - - const err = resource_algebra_last_error(); - defer resource_algebra_free_string(err); - try std.testing.expect(err != null); -} - -test "version" { - const ver = resource_algebra_version(); - const ver_str = std.mem.span(ver); - try std.testing.expectEqualStrings(VERSION, ver_str); -} diff --git a/src/interface/ffi/test/README.adoc b/src/interface/ffi/test/README.adoc deleted file mode 100644 index e6ff267..0000000 --- a/src/interface/ffi/test/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Test Logic diff --git a/src/interface/ffi/test/integration_test.zig b/src/interface/ffi/test/integration_test.zig deleted file mode 100644 index 484e156..0000000 --- a/src/interface/ffi/test/integration_test.zig +++ /dev/null @@ -1,66 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) Jonathan D.A. Jewell -// RSR Template FFI Integration Tests -// -// These tests verify that the Zig FFI correctly implements the Idris2 ABI. -// This is a TEMPLATE FILE — when instantiating a new project: -// 1. Replace "template" with your project name in lowercase -// 2. Link against your actual FFI implementation library -// 3. Uncomment the test functions below -// -// For now, this file contains documentation of what tests should exist. - -const std = @import("std"); - -// NOTE: When instantiated, declare the actual FFI functions here: -// extern fn mylib_init() ?*Handle; -// extern fn mylib_free(?*Handle) void; -// ... etc - -// And define Handle appropriately: -// const Handle = opaque {}; - -test "placeholder test - implementation required" { - // This test ensures the file compiles - // Actual tests depend on FFI implementation - try std.testing.expect(true); -} - -// ============================================================================== -// Example tests (uncomment when instantiated with real FFI): -// ============================================================================== -// -// test "lifecycle: create and destroy handle" { -// const handle = mylib_init() orelse return error.InitFailed; -// defer mylib_free(handle); -// } -// -// test "operations: process with valid handle" { -// const handle = mylib_init() orelse return error.InitFailed; -// defer mylib_free(handle); -// -// const result = mylib_process(handle, 42); -// try std.testing.expectEqual(@as(c_int, 0), result); -// } -// -// test "memory safety: double free is safe" { -// const handle = mylib_init() orelse return error.InitFailed; -// mylib_free(handle); -// mylib_free(handle); // Should not crash -// } -// -// test "strings: get string result from handle" { -// const handle = mylib_init() orelse return error.InitFailed; -// defer mylib_free(handle); -// -// const str = mylib_get_string(handle); -// defer if (str) |s| mylib_free_string(s); -// -// try std.testing.expect(str != null); -// } -// -// test "version: returns non-empty version string" { -// const ver = mylib_version(); -// const ver_str = std.mem.span(ver); -// try std.testing.expect(ver_str.len > 0); -// } diff --git a/src/interface/generated/README.adoc b/src/interface/generated/README.adoc deleted file mode 100644 index 9e94b29..0000000 --- a/src/interface/generated/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= generated Logic diff --git a/src/interface/generated/abi/README.adoc b/src/interface/generated/abi/README.adoc deleted file mode 100644 index f3b3808..0000000 --- a/src/interface/generated/abi/README.adoc +++ /dev/null @@ -1,3 +0,0 @@ -// SPDX-License-Identifier: CC-BY-SA-4.0 -// Copyright (c) Jonathan D.A. Jewell -= Abi Logic diff --git a/tests/ffi_strings_test.sh b/tests/ffi_strings_test.sh deleted file mode 100644 index a63ece5..0000000 --- a/tests/ffi_strings_test.sh +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env bash -# SPDX-License-Identifier: MPL-2.0 -# Regression tests for the dupeZ compatibility helper and its two callers. -# Instantiate only the FFI fixture, using the repository's zig build test. -# Usage: bash tests/ffi_strings_test.sh (requires Zig 0.15.2+) -set -euo pipefail -repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) -work=$(mktemp -d) -trap 'rm -rf "$work"' EXIT -command -v zig >/dev/null || { echo 'FAIL: Zig is required' >&2; exit 1; } -zig_bin=$(command -v zig) -# Resolve mise shims while still inside the configured repository. -if command -v mise >/dev/null 2>&1; then - zig_bin=$(mise which zig 2>/dev/null || printf '%s' "$zig_bin") -fi -cp -R "$repo/src/interface/ffi" "$work/ffi" -sed -i -e 's/{{project}}/test_project/g' -e 's/{{PROJECT}}/TEST_PROJECT/g' \ - "$work/ffi/build.zig" "$work/ffi/src/main.zig" "$work/ffi/test/integration_test.zig" -# A minted repository has its own export prefix where the template has the -# token; map that prefix too, so the appended tests name the same functions. -prefix=$(sed -nE 's/^export fn ([a-z0-9_]+)_init\(\).*/\1/p' "$work/ffi/src/main.zig" | head -1) -[ -n "$prefix" ] || { echo 'FAIL: no `export fn _init()` in src/interface/ffi/src/main.zig' >&2; exit 1; } -if [ "$prefix" != test_project ]; then - sed -i -E "s/\\b${prefix}_/test_project_/g" \ - "$work/ffi/build.zig" "$work/ffi/src/main.zig" "$work/ffi/test/integration_test.zig" -fi -# Tests share the production module so the private helper can be exercised -# with the leak-detecting allocator without changing the public FFI surface. -cat >> "$work/ffi/src/main.zig" <<'ZIG' - -test "dupeZ owns a sentinel terminated copy including empty and binary inputs" { - for ([_][]const u8{ "", "abc", "héllo 😀", "a\x00b" }) |input| { - const copy = try dupeZ(std.testing.allocator, input); - defer std.testing.allocator.free(copy); - try std.testing.expectEqualSlices(u8, input, copy); - try std.testing.expectEqual(@as(u8, 0), copy.ptr[copy.len]); - } - var input = [_]u8{ 'a', 'b' }; - const copy = try dupeZ(std.testing.allocator, &input); - defer std.testing.allocator.free(copy); - input[0] = 'z'; - try std.testing.expectEqualStrings("ab", copy); -} - -test "dupeZ propagates allocation failure without leaking" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - try std.testing.expectError(error.OutOfMemory, dupeZ(failing.allocator(), "data")); -} - -test "get_string returns independent owned C strings and clears an old error" { - const handle = test_project_init() orelse return error.InitFailed; - defer test_project_free(handle); - _ = test_project_process(null, 0); - const first = test_project_get_string(handle) orelse return error.StringFailed; - defer test_project_free_string(first); - const second = test_project_get_string(handle) orelse return error.StringFailed; - defer test_project_free_string(second); - try std.testing.expect(first != second); - try std.testing.expectEqualStrings("Example result", std.mem.span(first)); - try std.testing.expectEqual(@as(u8, 0), first[14]); - try std.testing.expect(test_project_last_error() == null); -} - -test "last_error copies survive subsequent error clearing" { - const handle = test_project_init() orelse return error.InitFailed; - defer test_project_free(handle); - try std.testing.expect(test_project_get_string(null) == null); - const first = test_project_last_error() orelse return error.ExpectedError; - defer test_project_free_string(first); - const second = test_project_last_error() orelse return error.ExpectedError; - defer test_project_free_string(second); - try std.testing.expect(first != second); - try std.testing.expectEqualStrings("Null handle", std.mem.span(first)); - try std.testing.expectEqual(Result.ok, test_project_process(handle, 0)); - try std.testing.expect(test_project_last_error() == null); - try std.testing.expectEqualStrings("Null handle", std.mem.span(second)); -} - -test "get_string reports allocation failure on an initialized handle" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - var handle = Handle{ .allocator = failing.allocator(), .initialized = true }; - defer clearError(); - try std.testing.expect(test_project_get_string(&handle) == null); - const message = test_project_last_error() orelse return error.ExpectedError; - defer test_project_free_string(message); - try std.testing.expectEqualStrings("Failed to allocate string", std.mem.span(message)); -} - -test "an empty C string still needs allocation for its sentinel" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - try std.testing.expectError(error.OutOfMemory, dupeZ(failing.allocator(), "")); -} - -test "get_string refuses an uninitialized handle before allocating" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - var handle = Handle{ .allocator = failing.allocator(), .initialized = false }; - defer clearError(); - try std.testing.expect(test_project_get_string(&handle) == null); - const message = test_project_last_error() orelse return error.ExpectedError; - defer test_project_free_string(message); - try std.testing.expectEqualStrings("Handle not initialized", std.mem.span(message)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "freeing one error copy preserves the stored error and other copies" { - defer clearError(); - try std.testing.expect(test_project_get_string(null) == null); - const first = test_project_last_error() orelse return error.ExpectedError; - test_project_free_string(first); - const second = test_project_last_error() orelse return error.ExpectedError; - defer test_project_free_string(second); - try std.testing.expectEqualStrings("Null handle", std.mem.span(second)); - test_project_free_string(null); - const third = test_project_last_error() orelse return error.ExpectedError; - defer test_project_free_string(third); - try std.testing.expectEqualStrings("Null handle", std.mem.span(third)); -} -ZIG -(cd "$work/ffi" && "$zig_bin" build test) diff --git a/tests/proven_suite_test.sh b/tests/proven_suite_test.sh index b3317d8..2a44ca5 100755 --- a/tests/proven_suite_test.sh +++ b/tests/proven_suite_test.sh @@ -444,9 +444,6 @@ assert_rc 0 'failure does not suppress later aggregation' cmp "$WORK/expected-ca echo "=== 7. Isolated runner and lock portability regressions ===" assert_rc 0 'runner outcome and benchmark output contracts' bash "$REPO_ROOT/tests/run_proven_suite_test.sh" assert_rc 0 'actions.lock guards on POSIX mawk' bash "$REPO_ROOT/tests/workflows/check_lock_sync_test.sh" -if command -v zig >/dev/null 2>&1; then - assert_rc 0 'FFI string ownership and sentinel regressions' bash "$REPO_ROOT/tests/ffi_strings_test.sh" -fi echo "proven_suite_test: $pass passed, $fail failed" [ "$fail" -eq 0 ] diff --git a/tests/run_proven_suite_test.sh b/tests/run_proven_suite_test.sh index b4af719..131e901 100644 --- a/tests/run_proven_suite_test.sh +++ b/tests/run_proven_suite_test.sh @@ -43,13 +43,40 @@ run() { #