From b184e57c083e3efa70d6a6ef677a984bed75fe11 Mon Sep 17 00:00:00 2001 From: hyperpolymath <6759885+hyperpolymath@users.noreply.github.com> Date: Wed, 27 May 2026 09:43:20 +0100 Subject: [PATCH] sync: re-vendor absolute-zero/ subtree to upstream HEAD (ab35c07) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brings maa-framework's vendored absolute-zero/ tree from its previous snapshot (16+ commits behind) up to current upstream HEAD. The primary motivation is to pull in the standards#203 trusted-base reduction work that landed upstream today: - absolute-zero#52 — docs/proof-debt.md seed (standards#203 schema). - absolute-zero#58/#59 — Phase 1 per-axiom triage of 72 Coq Axioms (docs/proof-debt-triage.md). - absolute-zero#60 — Phase 2a Lambda cluster (Coq + Lean inline AXIOM: annotations). - absolute-zero#61 — Phase 2b CNOCategory.v hom_functor §(d) DEBT entry. - absolute-zero#62 — Phase 2c Filesystem cluster (26 inline annotations + 8 §(d) DEBT entries). Cumulative trusted-base state: 41/129 escape hatches now documented (35.7% covered). Remaining 88 belong to Quantum + Physics clusters (future Phase 2d/2e PRs upstream). Side effects of the full re-vendor (also pulled in): - Estate-policy / governance / hypatia / language-policy workflow updates (~15 .github/workflows files). - MPL-2.0 SPDX header migration from PMPL-1.0-or-later (~20 files). - .machine_readable A2ML updates. - ReScript interpreter removal (per estate language-policy ban). - Verification scripts moved to verification/ subdir. - Old session debris pruned (SONNET-HANDOFF.md, STACK_AUDIT.txt, ROADMAP-V1-TO-V12.adoc, ROADMAP-UPDATED.adoc, etc.). Preserved (maa-framework-specific Agda extensions, NOT in upstream): - proofs/agda/EchoBridgeCNO.agda - proofs/agda/EchoBridgeScaffold.agda - proofs/agda/README.adoc These were added in maa-framework directly (commits 0538283 and e80c5fb) and survive the re-vendor via rsync --filter='P ...'. Refs maa-framework own proof-debt rollout; absolute-zero#52, #58, #59, #60, #61, #62; standards#203. Co-Authored-By: Claude Opus 4.7 (1M context) --- absolute-zero/.claude/CLAUDE.md | 15 +- .../{Containerfile => Dockerfile} | 2 +- absolute-zero/.clusterfuzzlite/build.sh | 8 +- absolute-zero/.clusterfuzzlite/project.yaml | 2 +- absolute-zero/.gitattributes | 2 +- absolute-zero/.github/FUNDING.yml | 2 +- absolute-zero/.github/dependabot.yml | 2 +- .../.github/workflows/cflite_batch.yml | 2 +- absolute-zero/.github/workflows/cflite_pr.yml | 5 +- absolute-zero/.github/workflows/codeql.yml | 16 +- absolute-zero/.github/workflows/deno-ci.yml | 20 + absolute-zero/.github/workflows/e2e.yml | 78 -- .../.github/workflows/governance.yml | 10 +- .../.github/workflows/hypatia-scan.yml | 185 +---- .../.github/workflows/jekyll-gh-pages.yml | 8 +- .../.github/workflows/language-policy.yml | 7 +- absolute-zero/.github/workflows/mirror.yml | 139 +--- .../.github/workflows/publish-container.yml | 10 +- .../.github/workflows/rescript-deno-ci.yml | 41 - absolute-zero/.github/workflows/rust-ci.yml | 65 +- absolute-zero/.github/workflows/scorecard.yml | 34 +- .../.github/workflows/secret-scanner.yml | 66 +- absolute-zero/.gitignore | 14 +- absolute-zero/.hypatia-ignore | 27 + .../.machine_readable/6a2/AGENTIC.a2ml | 37 +- .../.machine_readable/6a2/ECOSYSTEM.a2ml | 44 +- absolute-zero/.machine_readable/6a2/META.a2ml | 39 +- .../.machine_readable/6a2/NEUROSYM.a2ml | 36 +- .../.machine_readable/6a2/PLAYBOOK.a2ml | 54 +- .../.machine_readable/6a2/STATE.a2ml | 99 ++- absolute-zero/.machine_readable/AGENTIC.scm | 16 + absolute-zero/.machine_readable/ECOSYSTEM.scm | 37 + absolute-zero/.machine_readable/META.scm | 36 + absolute-zero/.machine_readable/NEUROSYM.scm | 13 + absolute-zero/.machine_readable/PLAYBOOK.scm | 13 + .../contractiles/bust/Bustfile.a2ml | 28 + .../contractiles/bust/bust.ncl | 66 ++ .../contractiles/trust/Trustfile.a2ml | 93 +++ .../.machine_readable/svc/README.adoc | 16 + .../.machine_readable/svc/k9/README.adoc | 177 ++++ .../svc/k9/examples/ci-config.k9.ncl | 126 +++ .../svc/k9/examples/project-metadata.k9.ncl | 57 ++ .../svc/k9/examples/setup-repo.k9.ncl | 167 ++++ .../svc/k9/template-hunt.k9.ncl | 136 ++++ .../svc/k9/template-kennel.k9.ncl | 54 ++ .../svc/k9/template-yard.k9.ncl | 84 ++ absolute-zero/.well-known/ai.txt | 14 + absolute-zero/.well-known/humans.txt | 15 + absolute-zero/.well-known/security.txt | 6 + absolute-zero/0-AI-MANIFEST.a2ml | 71 ++ absolute-zero/AUDIT.adoc | 88 ++ absolute-zero/CHANGELOG.md | 58 ++ absolute-zero/CODE_OF_CONDUCT.md | 2 +- absolute-zero/CONTRIBUTING.adoc | 2 +- absolute-zero/CONTRIBUTING.md | 116 --- absolute-zero/COORDINATION.md | 54 -- absolute-zero/Cargo.lock | 564 ------------- absolute-zero/Cargo.toml | 18 - ...NEUROSYM-INTEGRATION.adoc => ECHIDNA.adoc} | 2 +- absolute-zero/ECHIDNA_MALBOLGE_REPORT.md | 26 - absolute-zero/LICENSE | 506 ++++++++---- absolute-zero/LICENSE-PALIMPS.txt | 0 absolute-zero/MALBOLGE_PROOF_SPEC.md | 68 -- absolute-zero/Mustfile | 2 +- absolute-zero/README.adoc | 13 +- absolute-zero/ROADMAP-V1-TO-V12.adoc | 727 ----------------- absolute-zero/ROADMAP.adoc | 757 ++++++++++++++++-- absolute-zero/RSR_COMPLIANCE.adoc | 100 +++ absolute-zero/SECURITY.md | 2 +- absolute-zero/absolute-zero-abi.ipkg | 16 + absolute-zero/absolute-zero.agda-lib | 3 + absolute-zero/absolute-zero.oil | 193 ++++- absolute-zero/benches/cno_benchmarks.rs | 179 ----- absolute-zero/contractiles/dust/Dustfile | 2 +- absolute-zero/contractiles/must/Mustfile | 2 +- absolute-zero/contractiles/trust/Trustfile.hs | 105 +++ .../{ABI-FFI-README.md => docs/ABI-FFI.md} | 54 +- absolute-zero/docs/CITATIONS.adoc | 14 +- absolute-zero/{ => docs}/CLAUDE.adoc | 10 +- absolute-zero/{ => docs}/COOKBOOK.adoc | 4 +- .../JUSTFILE-COOKBOOK.adoc} | 0 .../{ => docs}/MACHINE_VERIFICATION.adoc | 0 absolute-zero/{ => docs}/MAINTAINERS.adoc | 2 +- .../PROOF-CLASSIFICATION.adoc} | 0 .../{ => docs}/PROOF-COMPLETION-PLAN.adoc | 0 absolute-zero/{ => docs}/PROOF-INSIGHTS.md | 0 .../{ => docs}/PROOF-VS-TEST-SUBJECTS.adoc | 2 +- absolute-zero/{ => docs}/RSR_OUTLINE.adoc | 2 +- .../{ => docs}/VERIFICATION_RESULTS.adoc | 0 .../docs/archive/CURRENT-STATUS-2026-02-05.md | 125 +++ .../archive/ECHIDNA-2025-11-22.adoc} | 0 .../INTEGRATION-STATUS-2026-02-05.adoc | 0 .../archive}/LICENSE-AUDIT-2026-02-05.adoc | 12 +- .../archive}/PROOF-COMPLETION-2026-02-06.md | 0 .../docs/archive/PROOF-STATUS-2026-05-18.md | 164 ++++ .../docs/archive/ROADMAP-2026-02-05.adoc | 61 ++ .../archive/ROADMAP-UPDATED-2026-02-05.adoc} | 2 +- .../archive/SESSION-2026-05-25-HANDOFF.adoc | 258 ++++++ .../archive/SESSION-COMPLETE-2026-02-05.adoc | 381 +++++++++ .../{ => docs/archive}/SONNET-HANDOFF.md | 0 .../archive/STACK_AUDIT-2026-02-05.txt} | 0 absolute-zero/docs/proof-debt-triage.md | 200 +++++ absolute-zero/docs/proof-debt.md | 246 ++++++ .../reports/audit/pillar-audit-2026-04-15.md | 19 - absolute-zero/docs/tech-debt-2026-05-26.md | 73 ++ absolute-zero/docs/wiki/ABI.md | 84 ++ absolute-zero/docs/wiki/Architecture.md | 74 ++ absolute-zero/docs/wiki/Audit-Trail.md | 56 ++ absolute-zero/docs/wiki/Contributing.md | 55 ++ absolute-zero/docs/wiki/FAQ.md | 69 ++ absolute-zero/docs/wiki/Glossary.md | 20 + absolute-zero/docs/wiki/Home.md | 67 ++ absolute-zero/docs/wiki/Proof-Systems.md | 85 ++ absolute-zero/docs/wiki/README.md | 53 ++ absolute-zero/docs/wiki/Roadmap.md | 31 + absolute-zero/docs/wiki/Verification.md | 97 +++ absolute-zero/docs/wiki/_Sidebar.md | 25 + absolute-zero/eclexiaiser.toml | 26 - absolute-zero/examples/SafeDOMExample.res | 109 --- absolute-zero/examples/go/nop.go | 39 - absolute-zero/examples/java/BalancedOps.java | 57 -- absolute-zero/examples/java/Nop.java | 33 - absolute-zero/examples/kotlin/BalancedOps.kt | 82 -- absolute-zero/examples/kotlin/Nop.kt | 38 - absolute-zero/examples/perl/nop.pl | 79 -- absolute-zero/examples/ruby/nop.rb | 53 -- absolute-zero/examples/swift/Nop.swift | 42 - absolute-zero/examples/web-project-deno.json | 2 +- absolute-zero/ffi/zig/build.zig | 80 +- absolute-zero/ffi/zig/src/main.zig | 428 ++++------ .../ffi/zig/test/integration_test.zig | 220 +++-- absolute-zero/fuzz/Cargo.lock | 155 ++++ absolute-zero/fuzz/Cargo.toml | 7 +- absolute-zero/fuzz/fuzz_targets/fuzz_input.rs | 2 +- .../rescript/malbolgeInterpreter.res | 256 ------ absolute-zero/license/PMPL-1.0.txt | 2 +- absolute-zero/malbolge_test.mb | 1 - absolute-zero/proofs/agda/CNO.agda | 64 +- .../proofs/coq/category/CNOCategory.v | 79 +- absolute-zero/proofs/coq/common/CNO.v | 292 ++++--- absolute-zero/proofs/coq/common/Complex.v | 82 ++ .../proofs/coq/filesystem/FilesystemCNO.v | 20 +- absolute-zero/proofs/coq/lambda/LambdaCNO.v | 20 +- .../proofs/coq/malbolge/MalbolgeCore.v | 31 +- .../proofs/coq/physics/LandauerDerivation.v | 63 +- absolute-zero/proofs/coq/physics/StatMech.v | 83 +- .../proofs/coq/physics/StatMech_helpers.v | 10 +- absolute-zero/proofs/coq/quantum/QuantumCNO.v | 110 +-- .../coq/quantum/QuantumMechanicsExact.v | 43 +- absolute-zero/proofs/lean4/CNO.lean | 231 ++++-- absolute-zero/proofs/lean4/CNOCategory.lean | 171 ++-- absolute-zero/proofs/lean4/FilesystemCNO.lean | 81 +- absolute-zero/proofs/lean4/LambdaCNO.lean | 43 +- absolute-zero/proofs/lean4/QuantumCNO.lean | 48 +- absolute-zero/proofs/lean4/StatMech.lean | 99 ++- absolute-zero/proofs/lean4/lake-manifest.json | 95 +++ absolute-zero/proofs/lean4/lakefile.lean | 27 +- absolute-zero/proofs/lean4/lean-toolchain | 2 +- absolute-zero/src/AuditTrail.res | 49 -- absolute-zero/src/abi/Layout.idr | 62 +- absolute-zero/src/abi/Proofs/DivMod.idr | 119 +++ absolute-zero/src/abi/Types.idr | 10 +- absolute-zero/src/brainfuck/Cargo.toml | 2 +- absolute-zero/src/brainfuck/src/lib.rs | 349 ++++---- absolute-zero/src/brainfuck/src/main.rs | 3 + absolute-zero/src/main.rs | 42 +- absolute-zero/src/whitespace/Cargo.toml | 2 +- absolute-zero/src/whitespace/src/lib.rs | 682 +++++----------- absolute-zero/tests/README.adoc | 21 + .../tests/aspect/cross_cutting_test.sh | 89 -- absolute-zero/tests/brainfuck_e2e.rs | 135 ---- .../tests/e2e/proof_verification_e2e.sh | 186 ----- absolute-zero/tests/property_based.rs | 203 ----- absolute-zero/tests/security_aspects.rs | 163 ---- .../tests/unit/cno_properties_test.rs | 149 ---- absolute-zero/tools/README.adoc | 9 + absolute-zero/verification/README.adoc | 15 + .../run-local-verification.sh | 61 +- .../{ => verification}/setup-and-verify.sh | 56 +- .../{ => verification}/verify-proofs.sh | 59 +- 180 files changed, 7866 insertions(+), 6249 deletions(-) rename absolute-zero/.clusterfuzzlite/{Containerfile => Dockerfile} (85%) create mode 100644 absolute-zero/.github/workflows/deno-ci.yml delete mode 100644 absolute-zero/.github/workflows/e2e.yml delete mode 100644 absolute-zero/.github/workflows/rescript-deno-ci.yml create mode 100644 absolute-zero/.hypatia-ignore create mode 100644 absolute-zero/.machine_readable/AGENTIC.scm create mode 100644 absolute-zero/.machine_readable/ECOSYSTEM.scm create mode 100644 absolute-zero/.machine_readable/META.scm create mode 100644 absolute-zero/.machine_readable/NEUROSYM.scm create mode 100644 absolute-zero/.machine_readable/PLAYBOOK.scm create mode 100644 absolute-zero/.machine_readable/contractiles/bust/Bustfile.a2ml create mode 100644 absolute-zero/.machine_readable/contractiles/bust/bust.ncl create mode 100644 absolute-zero/.machine_readable/contractiles/trust/Trustfile.a2ml create mode 100644 absolute-zero/.machine_readable/svc/README.adoc create mode 100644 absolute-zero/.machine_readable/svc/k9/README.adoc create mode 100644 absolute-zero/.machine_readable/svc/k9/examples/ci-config.k9.ncl create mode 100644 absolute-zero/.machine_readable/svc/k9/examples/project-metadata.k9.ncl create mode 100644 absolute-zero/.machine_readable/svc/k9/examples/setup-repo.k9.ncl create mode 100644 absolute-zero/.machine_readable/svc/k9/template-hunt.k9.ncl create mode 100644 absolute-zero/.machine_readable/svc/k9/template-kennel.k9.ncl create mode 100644 absolute-zero/.machine_readable/svc/k9/template-yard.k9.ncl create mode 100644 absolute-zero/.well-known/ai.txt create mode 100644 absolute-zero/.well-known/humans.txt create mode 100644 absolute-zero/.well-known/security.txt create mode 100644 absolute-zero/0-AI-MANIFEST.a2ml create mode 100644 absolute-zero/AUDIT.adoc create mode 100644 absolute-zero/CHANGELOG.md delete mode 100644 absolute-zero/CONTRIBUTING.md delete mode 100644 absolute-zero/COORDINATION.md rename absolute-zero/{ECHIDNA-NEUROSYM-INTEGRATION.adoc => ECHIDNA.adoc} (99%) delete mode 100644 absolute-zero/ECHIDNA_MALBOLGE_REPORT.md delete mode 100644 absolute-zero/LICENSE-PALIMPS.txt delete mode 100644 absolute-zero/MALBOLGE_PROOF_SPEC.md delete mode 100644 absolute-zero/ROADMAP-V1-TO-V12.adoc create mode 100644 absolute-zero/RSR_COMPLIANCE.adoc create mode 100644 absolute-zero/absolute-zero-abi.ipkg create mode 100644 absolute-zero/absolute-zero.agda-lib delete mode 100644 absolute-zero/benches/cno_benchmarks.rs create mode 100644 absolute-zero/contractiles/trust/Trustfile.hs rename absolute-zero/{ABI-FFI-README.md => docs/ABI-FFI.md} (85%) rename absolute-zero/{ => docs}/CLAUDE.adoc (98%) rename absolute-zero/{ => docs}/COOKBOOK.adoc (99%) rename absolute-zero/{justfile-cookbook.adoc => docs/JUSTFILE-COOKBOOK.adoc} (100%) rename absolute-zero/{ => docs}/MACHINE_VERIFICATION.adoc (100%) rename absolute-zero/{ => docs}/MAINTAINERS.adoc (96%) rename absolute-zero/{PROOF-CLASSIFICATION-CNO-FOCUSED.adoc => docs/PROOF-CLASSIFICATION.adoc} (100%) rename absolute-zero/{ => docs}/PROOF-COMPLETION-PLAN.adoc (100%) rename absolute-zero/{ => docs}/PROOF-INSIGHTS.md (100%) rename absolute-zero/{ => docs}/PROOF-VS-TEST-SUBJECTS.adoc (99%) rename absolute-zero/{ => docs}/RSR_OUTLINE.adoc (99%) rename absolute-zero/{ => docs}/VERIFICATION_RESULTS.adoc (100%) create mode 100644 absolute-zero/docs/archive/CURRENT-STATUS-2026-02-05.md rename absolute-zero/{ECHIDNA_INTEGRATION.adoc => docs/archive/ECHIDNA-2025-11-22.adoc} (100%) rename absolute-zero/{ => docs/archive}/INTEGRATION-STATUS-2026-02-05.adoc (100%) rename absolute-zero/{ => docs/archive}/LICENSE-AUDIT-2026-02-05.adoc (91%) rename absolute-zero/{ => docs/archive}/PROOF-COMPLETION-2026-02-06.md (100%) create mode 100644 absolute-zero/docs/archive/PROOF-STATUS-2026-05-18.md create mode 100644 absolute-zero/docs/archive/ROADMAP-2026-02-05.adoc rename absolute-zero/{ROADMAP-UPDATED.adoc => docs/archive/ROADMAP-UPDATED-2026-02-05.adoc} (99%) create mode 100644 absolute-zero/docs/archive/SESSION-2026-05-25-HANDOFF.adoc create mode 100644 absolute-zero/docs/archive/SESSION-COMPLETE-2026-02-05.adoc rename absolute-zero/{ => docs/archive}/SONNET-HANDOFF.md (100%) rename absolute-zero/{STACK_AUDIT.txt => docs/archive/STACK_AUDIT-2026-02-05.txt} (100%) create mode 100644 absolute-zero/docs/proof-debt-triage.md create mode 100644 absolute-zero/docs/proof-debt.md delete mode 100644 absolute-zero/docs/reports/audit/pillar-audit-2026-04-15.md create mode 100644 absolute-zero/docs/tech-debt-2026-05-26.md create mode 100644 absolute-zero/docs/wiki/ABI.md create mode 100644 absolute-zero/docs/wiki/Architecture.md create mode 100644 absolute-zero/docs/wiki/Audit-Trail.md create mode 100644 absolute-zero/docs/wiki/Contributing.md create mode 100644 absolute-zero/docs/wiki/FAQ.md create mode 100644 absolute-zero/docs/wiki/Glossary.md create mode 100644 absolute-zero/docs/wiki/Home.md create mode 100644 absolute-zero/docs/wiki/Proof-Systems.md create mode 100644 absolute-zero/docs/wiki/README.md create mode 100644 absolute-zero/docs/wiki/Roadmap.md create mode 100644 absolute-zero/docs/wiki/Verification.md create mode 100644 absolute-zero/docs/wiki/_Sidebar.md delete mode 100644 absolute-zero/eclexiaiser.toml delete mode 100644 absolute-zero/examples/SafeDOMExample.res delete mode 100644 absolute-zero/examples/go/nop.go delete mode 100644 absolute-zero/examples/java/BalancedOps.java delete mode 100644 absolute-zero/examples/java/Nop.java delete mode 100644 absolute-zero/examples/kotlin/BalancedOps.kt delete mode 100644 absolute-zero/examples/kotlin/Nop.kt delete mode 100755 absolute-zero/examples/perl/nop.pl delete mode 100755 absolute-zero/examples/ruby/nop.rb delete mode 100644 absolute-zero/examples/swift/Nop.swift create mode 100644 absolute-zero/fuzz/Cargo.lock delete mode 100644 absolute-zero/interpreters/rescript/malbolgeInterpreter.res delete mode 100644 absolute-zero/malbolge_test.mb create mode 100644 absolute-zero/proofs/coq/common/Complex.v create mode 100644 absolute-zero/proofs/lean4/lake-manifest.json delete mode 100644 absolute-zero/src/AuditTrail.res create mode 100644 absolute-zero/src/abi/Proofs/DivMod.idr create mode 100644 absolute-zero/tests/README.adoc delete mode 100755 absolute-zero/tests/aspect/cross_cutting_test.sh delete mode 100644 absolute-zero/tests/brainfuck_e2e.rs delete mode 100755 absolute-zero/tests/e2e/proof_verification_e2e.sh delete mode 100644 absolute-zero/tests/property_based.rs delete mode 100644 absolute-zero/tests/security_aspects.rs delete mode 100644 absolute-zero/tests/unit/cno_properties_test.rs create mode 100644 absolute-zero/tools/README.adoc create mode 100644 absolute-zero/verification/README.adoc rename absolute-zero/{ => verification}/run-local-verification.sh (65%) rename absolute-zero/{ => verification}/setup-and-verify.sh (87%) rename absolute-zero/{ => verification}/verify-proofs.sh (78%) diff --git a/absolute-zero/.claude/CLAUDE.md b/absolute-zero/.claude/CLAUDE.md index c878259..296e9fe 100644 --- a/absolute-zero/.claude/CLAUDE.md +++ b/absolute-zero/.claude/CLAUDE.md @@ -19,14 +19,14 @@ The following files in `.machine_readable/` contain structured project metadata: | Language/Tool | Use Case | Notes | |---------------|----------|-------| -| **ReScript** | Primary application code | Compiles to JS, type-safe | +| **AffineScript** | Primary application code | Compiles to JS/WASM, linear/affine type system | | **Deno** | Runtime & package management | Replaces Node/npm/bun | | **Rust** | Performance-critical, systems, WASM | Preferred for CLI tools | | **Tauri 2.0+** | Mobile apps (iOS/Android) | Rust backend + web UI | | **Dioxus** | Mobile apps (native UI) | Pure Rust, React-like | | **Gleam** | Backend services | Runs on BEAM or compiles to JS | | **Bash/POSIX Shell** | Scripts, automation | Keep minimal | -| **JavaScript** | Only where ReScript cannot | MCP protocol glue, Deno APIs | +| **JavaScript** | Only where AffineScript cannot, or as per-language reference (examples/) | Avoid for new code unless integrating an external JS API | | **Nickel** | Configuration language | For complex configs | | **Guile Scheme** | State/meta files | STATE.scm, META.scm, ECOSYSTEM.scm | | **Julia** | Batch scripts, data processing | Per RSR | @@ -37,7 +37,8 @@ The following files in `.machine_readable/` contain structured project metadata: | Banned | Replacement | |--------|-------------| -| TypeScript | ReScript | +| TypeScript | AffineScript | +| ReScript | AffineScript | | Node.js | Deno | | npm | Deno | | Bun | Deno | @@ -48,24 +49,26 @@ The following files in `.machine_readable/` contain structured project metadata: | Swift | Tauri/Dioxus | | React Native | Tauri/Dioxus | | Flutter/Dart | Tauri/Dioxus | +| PMPL-1.0 / PMPL-1.0-or-later | MPL-2.0 | ### Mobile Development **No exceptions for Kotlin/Swift** - use Rust-first approach: -1. **Tauri 2.0+** - Web UI (ReScript) + Rust backend, MIT/Apache-2.0 +1. **Tauri 2.0+** - Web UI (AffineScript) + Rust backend, MIT/Apache-2.0 2. **Dioxus** - Pure Rust native UI, MIT/Apache-2.0 Both are FOSS with independent governance (no Big Tech). ### Enforcement Rules -1. **No new TypeScript files** - Convert existing TS to ReScript +1. **No new TypeScript or ReScript files** - Use AffineScript; meaningfully migrate existing TS/JS to AffineScript when touched (per-language `examples/` references may stay) 2. **No package.json for runtime deps** - Use deno.json imports 3. **No node_modules in production** - Deno caches deps automatically 4. **No Go code** - Use Rust instead -5. **No Python anywhere** - Use Julia for data/batch, Rust for systems, ReScript for apps +5. **No Python anywhere** - Use Julia for data/batch, Rust for systems, AffineScript for apps 6. **No Kotlin/Swift for mobile** - Use Tauri 2.0+ or Dioxus +7. **License**: MPL-2.0 only — never PMPL-1.0 / PMPL-1.0-or-later / MPL-2.0-or-later ### Package Management diff --git a/absolute-zero/.clusterfuzzlite/Containerfile b/absolute-zero/.clusterfuzzlite/Dockerfile similarity index 85% rename from absolute-zero/.clusterfuzzlite/Containerfile rename to absolute-zero/.clusterfuzzlite/Dockerfile index 28a7e64..7ad3ffd 100644 --- a/absolute-zero/.clusterfuzzlite/Containerfile +++ b/absolute-zero/.clusterfuzzlite/Dockerfile @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: PMPL-1.0 +# SPDX-License-Identifier: MPL-2.0 FROM gcr.io/oss-fuzz-base/base-builder-rust@sha256:73c1d5648db54100639339d411a5d192cbc8bf413ee91e843a07cf6f0e319dc7 COPY . $SRC/absolute-zero diff --git a/absolute-zero/.clusterfuzzlite/build.sh b/absolute-zero/.clusterfuzzlite/build.sh index e0dde03..5e91113 100755 --- a/absolute-zero/.clusterfuzzlite/build.sh +++ b/absolute-zero/.clusterfuzzlite/build.sh @@ -1,7 +1,11 @@ #!/bin/bash -eu -# SPDX-License-Identifier: PMPL-1.0 +# SPDX-License-Identifier: MPL-2.0 cd "$SRC"/absolute-zero cargo +nightly fuzz build +# cargo-fuzz writes binaries to `fuzz/target//release/` +# (the fuzz crate's own target dir), not to the workspace root. The +# previous `./target/...` path was a vestige of an earlier layout where +# fuzz/ depended on the parent crate's `[lib]` (since removed). for target in $(cargo +nightly fuzz list); do - cp ./target/x86_64-unknown-linux-gnu/release/$target $OUT/ + cp fuzz/target/x86_64-unknown-linux-gnu/release/$target $OUT/ done diff --git a/absolute-zero/.clusterfuzzlite/project.yaml b/absolute-zero/.clusterfuzzlite/project.yaml index 1107456..311ed3d 100644 --- a/absolute-zero/.clusterfuzzlite/project.yaml +++ b/absolute-zero/.clusterfuzzlite/project.yaml @@ -1,2 +1,2 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 language: rust diff --git a/absolute-zero/.gitattributes b/absolute-zero/.gitattributes index e860a85..7bbe6d5 100644 --- a/absolute-zero/.gitattributes +++ b/absolute-zero/.gitattributes @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0 +# SPDX-License-Identifier: AGPL-3.0-or-later # RSR-compliant .gitattributes * text=auto eol=lf diff --git a/absolute-zero/.github/FUNDING.yml b/absolute-zero/.github/FUNDING.yml index e2d2971..688a442 100644 --- a/absolute-zero/.github/FUNDING.yml +++ b/absolute-zero/.github/FUNDING.yml @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 # Funding platforms for hyperpolymath projects # See: https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository diff --git a/absolute-zero/.github/dependabot.yml b/absolute-zero/.github/dependabot.yml index d86a5a8..4be2afa 100644 --- a/absolute-zero/.github/dependabot.yml +++ b/absolute-zero/.github/dependabot.yml @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 version: 2 updates: - package-ecosystem: "cargo" diff --git a/absolute-zero/.github/workflows/cflite_batch.yml b/absolute-zero/.github/workflows/cflite_batch.yml index 173d740..733d394 100644 --- a/absolute-zero/.github/workflows/cflite_batch.yml +++ b/absolute-zero/.github/workflows/cflite_batch.yml @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 name: ClusterFuzzLite batch fuzzing on: schedule: diff --git a/absolute-zero/.github/workflows/cflite_pr.yml b/absolute-zero/.github/workflows/cflite_pr.yml index 8c94984..fd2d04e 100644 --- a/absolute-zero/.github/workflows/cflite_pr.yml +++ b/absolute-zero/.github/workflows/cflite_pr.yml @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 name: ClusterFuzzLite PR fuzzing on: pull_request: @@ -14,6 +14,9 @@ jobs: matrix: sanitizer: [address] steps: + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - name: Build Fuzzers (${{ matrix.sanitizer }}) id: build uses: google/clusterfuzzlite/actions/build_fuzzers@884713a6c30a92e5e8544c39945cd7cb630abcd1 # v1 diff --git a/absolute-zero/.github/workflows/codeql.yml b/absolute-zero/.github/workflows/codeql.yml index b7e4e30..e71132c 100644 --- a/absolute-zero/.github/workflows/codeql.yml +++ b/absolute-zero/.github/workflows/codeql.yml @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 name: CodeQL Security Analysis on: @@ -9,6 +9,14 @@ on: schedule: - cron: '0 6 * * 1' +# Estate guardrail: cancel superseded runs so re-pushes / rebased PR +# updates do not pile up queued runs against the shared account-wide +# Actions concurrency pool. Applied only to read-only check workflows +# (no publish/mutation), so cancelling a superseded run is always safe. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: read-all jobs: @@ -26,15 +34,15 @@ jobs: steps: - name: Checkout - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Initialize CodeQL - uses: github/codeql-action/init@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v3.28.1 + uses: github/codeql-action/init@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v3.28.1 with: languages: ${{ matrix.language }} build-mode: ${{ matrix.build-mode }} - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v3.28.1 + uses: github/codeql-action/analyze@7211b7c8077ea37d8641b6271f6a365a22a5fbfa # v3.28.1 with: category: "/language:${{ matrix.language }}" diff --git a/absolute-zero/.github/workflows/deno-ci.yml b/absolute-zero/.github/workflows/deno-ci.yml new file mode 100644 index 0000000..7290371 --- /dev/null +++ b/absolute-zero/.github/workflows/deno-ci.yml @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: MPL-2.0-or-later +# Thin wrapper around the estate-wide reusable Deno CI bundle. +# See: hyperpolymath/standards/.github/workflows/deno-ci-reusable.yml +name: Deno CI + +on: + push: + branches: [main, master] + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + deno-ci: + uses: hyperpolymath/standards/.github/workflows/deno-ci-reusable.yml@c3a62f0cfd993c23661519f571087ed16e13631c # standards#168 head diff --git a/absolute-zero/.github/workflows/e2e.yml b/absolute-zero/.github/workflows/e2e.yml deleted file mode 100644 index f361e65..0000000 --- a/absolute-zero/.github/workflows/e2e.yml +++ /dev/null @@ -1,78 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0 -# E2E, aspect, benchmark, and panic-attack CI for Absolute Zero -name: E2E + Aspect + Bench + Security - -on: - push: - branches: [main] - pull_request: - branches: [main] - -permissions: read-all - -jobs: - rust-build-test: - name: Rust Build + Unit Tests - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - uses: dtolnay/rust-toolchain@4be9e76fd7c4901c61fb841f559994984270fce7 # stable - - uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2 - - name: Build - run: cd absolute-zero && cargo build --release - - name: Unit tests - run: cd absolute-zero && cargo test -- --test-threads=1 - - name: Clippy - run: cd absolute-zero && cargo clippy -- -D warnings || true - - name: Format check - run: cd absolute-zero && cargo fmt -- --check || true - - benchmarks: - name: Criterion Benchmarks - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - uses: dtolnay/rust-toolchain@4be9e76fd7c4901c61fb841f559994984270fce7 # stable - - uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2 - - name: Run benchmarks - run: cd absolute-zero && cargo bench --bench cno_benchmarks -- --output-format bencher 2>/dev/null || echo "Benchmarks completed (may have warnings)" - - aspect-tests: - name: Aspect Tests (Cross-Cutting) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - name: Run aspect tests - run: bash absolute-zero/tests/aspect/cross_cutting_test.sh - - e2e-proofs: - name: E2E Proof Verification - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - uses: dtolnay/rust-toolchain@4be9e76fd7c4901c61fb841f559994984270fce7 # stable - - name: Install proof tools - run: | - sudo apt-get update -qq - sudo apt-get install -y -qq z3 || true - - name: Run E2E verification - run: bash absolute-zero/tests/e2e/proof_verification_e2e.sh - - panic-attack: - name: Panic Attack Security Scan - runs-on: ubuntu-latest - if: github.event_name == 'push' - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 - - name: Install panic-attack - run: | - cargo install --git https://github.com/hyperpolymath/panic-attacker.git || echo "panic-attack not available in CI — skipping" - - name: Run assail scan - run: | - if command -v panic-attack >/dev/null 2>&1; then - panic-attack assail absolute-zero/ --output-format json --output panic-attack-report.json --quiet || true - echo "=== Weak Points ===" - python3 -c "import json; d=json.load(open('panic-attack-report.json')); print(f'Total: {len(d.get(\"weak_points\",[]))}')" || true - else - echo "panic-attack not installed — skipping" - fi diff --git a/absolute-zero/.github/workflows/governance.yml b/absolute-zero/.github/workflows/governance.yml index b0b1ed6..64e562a 100644 --- a/absolute-zero/.github/workflows/governance.yml +++ b/absolute-zero/.github/workflows/governance.yml @@ -18,9 +18,17 @@ on: pull_request: workflow_dispatch: +# Estate guardrail: cancel superseded runs so re-pushes / rebased PR +# updates do not pile up queued runs against the shared account-wide +# Actions concurrency pool. Applied only to read-only check workflows +# (no publish/mutation), so cancelling a superseded run is always safe. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + permissions: contents: read jobs: governance: - uses: hyperpolymath/standards/.github/workflows/governance-reusable.yml@main + uses: hyperpolymath/standards/.github/workflows/governance-reusable.yml@3ec2e85cc1d54ec2ab20a84fcba96e5008545925 # main 2026-05-25 diff --git a/absolute-zero/.github/workflows/hypatia-scan.yml b/absolute-zero/.github/workflows/hypatia-scan.yml index efa4216..1d6417e 100644 --- a/absolute-zero/.github/workflows/hypatia-scan.yml +++ b/absolute-zero/.github/workflows/hypatia-scan.yml @@ -1,178 +1,29 @@ # SPDX-License-Identifier: MPL-2.0 -# Hypatia Neurosymbolic CI/CD Security Scan +# Thin wrapper around hyperpolymath/standards hypatia-scan-reusable.yml. +# See standards#191 for the reusable's purpose and design. + name: Hypatia Security Scan on: push: - branches: [ main, master, develop ] + branches: [main, master, develop] pull_request: - branches: [ main, master ] + branches: [main, master] schedule: - - cron: '0 0 * * 0' # Weekly on Sunday + - cron: '0 0 * * 0' workflow_dispatch: -permissions: read-all - -jobs: - scan: - name: Hypatia Neurosymbolic Analysis - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 - with: - fetch-depth: 0 # Full history for better pattern analysis - - - name: Setup Elixir for Hypatia scanner - uses: erlef/setup-beam@2f0cc07b4b9bea248ae098aba9e1a8a1de5ec24c # v1.18.2 - with: - elixir-version: '1.19.4' - otp-version: '28.3' - - - name: Clone Hypatia - run: | - if [ ! -d "$HOME/hypatia" ]; then - git clone https://github.com/hyperpolymath/hypatia.git "$HOME/hypatia" - fi - - - name: Build Hypatia scanner (if needed) - working-directory: ${{ env.HOME }}/hypatia - run: | - if [ ! -f hypatia-v2 ]; then - echo "Building hypatia-v2 scanner..." - mix deps.get - mix escript.build - mv hypatia ../hypatia-v2 - fi - - - name: Run Hypatia scan - id: scan - run: | - echo "Scanning repository: ${{ github.repository }}" - - # Run scanner - HYPATIA_FORMAT=json "$HOME/hypatia/hypatia-cli.sh" scan . > hypatia-findings.json - - # Count findings - FINDING_COUNT=$(jq '. | length' hypatia-findings.json 2>/dev/null || echo 0) - echo "findings_count=$FINDING_COUNT" >> $GITHUB_OUTPUT - - # Extract severity counts - CRITICAL=$(jq '[.[] | select(.severity == "critical")] | length' hypatia-findings.json) - HIGH=$(jq '[.[] | select(.severity == "high")] | length' hypatia-findings.json) - MEDIUM=$(jq '[.[] | select(.severity == "medium")] | length' hypatia-findings.json) - - echo "critical=$CRITICAL" >> $GITHUB_OUTPUT - echo "high=$HIGH" >> $GITHUB_OUTPUT - echo "medium=$MEDIUM" >> $GITHUB_OUTPUT - - echo "## Hypatia Scan Results" >> $GITHUB_STEP_SUMMARY - echo "- Total findings: $FINDING_COUNT" >> $GITHUB_STEP_SUMMARY - echo "- Critical: $CRITICAL" >> $GITHUB_STEP_SUMMARY - echo "- High: $HIGH" >> $GITHUB_STEP_SUMMARY - echo "- Medium: $MEDIUM" >> $GITHUB_STEP_SUMMARY - - - name: Upload findings artifact - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 - with: - name: hypatia-findings - path: hypatia-findings.json - retention-days: 90 - - - name: Submit findings to gitbot-fleet (Phase 2) - if: steps.scan.outputs.findings_count > 0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_REPOSITORY: ${{ github.repository }} - GITHUB_SHA: ${{ github.sha }} - run: | - echo "📤 Submitting ${{ steps.scan.outputs.findings_count }} findings to gitbot-fleet..." - - # Clone gitbot-fleet to temp directory - FLEET_DIR="/tmp/gitbot-fleet-$$" - git clone https://github.com/hyperpolymath/gitbot-fleet.git "$FLEET_DIR" - - # Run submission script - bash "$FLEET_DIR/scripts/submit-finding.sh" hypatia-findings.json - - # Cleanup - rm -rf "$FLEET_DIR" +# Estate guardrail: cancel superseded runs so re-pushes don't pile up. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true - echo "✅ Finding submission complete" +permissions: + contents: read + security-events: write + pull-requests: write - - name: Check for critical issues - if: steps.scan.outputs.critical > 0 - run: | - echo "⚠️ Critical security issues found!" - echo "Review hypatia-findings.json for details" - # Don't fail the build yet - just warn - # exit 1 - - - name: Generate scan report - run: | - cat << EOF > hypatia-report.md - # Hypatia Security Scan Report - - **Repository:** ${{ github.repository }} - **Scan Date:** $(date -u +"%Y-%m-%d %H:%M:%S UTC") - **Commit:** ${{ github.sha }} - - ## Summary - - | Severity | Count | - |----------|-------| - | Critical | ${{ steps.scan.outputs.critical }} | - | High | ${{ steps.scan.outputs.high }} | - | Medium | ${{ steps.scan.outputs.medium }} | - | **Total**| ${{ steps.scan.outputs.findings_count }} | - - ## Next Steps - - 1. Review findings in the artifact: hypatia-findings.json - 2. Auto-fixable issues will be addressed by robot-repo-automaton (Phase 3) - 3. Manual review required for complex issues - - ## Learning - - These findings feed Hypatia's learning engine to improve future rules. - - --- - *Powered by [Hypatia](https://github.com/hyperpolymath/hypatia) - Neurosymbolic CI/CD Intelligence* - EOF - - cat hypatia-report.md >> $GITHUB_STEP_SUMMARY - - - name: Comment on PR with findings - if: github.event_name == 'pull_request' && steps.scan.outputs.findings_count > 0 - uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7 - with: - script: | - const fs = require('fs'); - const findings = JSON.parse(fs.readFileSync('hypatia-findings.json', 'utf8')); - - const critical = findings.filter(f => f.severity === 'critical').length; - const high = findings.filter(f => f.severity === 'high').length; - - let comment = `## 🔍 Hypatia Security Scan\n\n`; - comment += `**Findings:** ${findings.length} issues detected\n\n`; - comment += `| Severity | Count |\n|----------|-------|\n`; - comment += `| 🔴 Critical | ${critical} |\n`; - comment += `| 🟠 High | ${high} |\n`; - comment += `| 🟡 Medium | ${findings.length - critical - high} |\n\n`; - - if (critical > 0) { - comment += `⚠️ **Action Required:** Critical security issues found!\n\n`; - } - - comment += `
View findings\n\n`; - comment += `\`\`\`json\n${JSON.stringify(findings.slice(0, 10), null, 2)}\n\`\`\`\n`; - comment += `
\n\n`; - comment += `*Powered by Hypatia Neurosymbolic CI/CD Intelligence*`; - - github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - body: comment - }); +jobs: + hypatia: + uses: hyperpolymath/standards/.github/workflows/hypatia-scan-reusable.yml@97df762107501909f50bb770e9bc200b6c415600 + secrets: inherit diff --git a/absolute-zero/.github/workflows/jekyll-gh-pages.yml b/absolute-zero/.github/workflows/jekyll-gh-pages.yml index 11a2df4..df57f95 100644 --- a/absolute-zero/.github/workflows/jekyll-gh-pages.yml +++ b/absolute-zero/.github/workflows/jekyll-gh-pages.yml @@ -28,16 +28,16 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Setup Pages - uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5 + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6 - name: Build with Jekyll uses: actions/jekyll-build-pages@44a6e6beabd48582f863aeeb6cb2151cc1716697 # v1 with: source: ./ destination: ./_site - name: Upload artifact - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v4 + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5 # Deployment job deploy: @@ -49,4 +49,4 @@ jobs: steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 + uses: actions/deploy-pages@cd2ce8fcbc39b97be8ca5fce6e763baed58fa128 # v5 diff --git a/absolute-zero/.github/workflows/language-policy.yml b/absolute-zero/.github/workflows/language-policy.yml index ecf44af..3479fa3 100644 --- a/absolute-zero/.github/workflows/language-policy.yml +++ b/absolute-zero/.github/workflows/language-policy.yml @@ -1,17 +1,20 @@ # SPDX-License-Identifier: MPL-2.0-or-later name: Language Policy Enforcement on: [push, pull_request] + +permissions: read-all + jobs: check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Enforce language policies run: | # Block new Python files (except SaltStack) NEW_PY=$(git diff --name-only --diff-filter=A HEAD~1 2>/dev/null | grep -E '\.py$' | grep -v 'salt' || true) if [ -n "$NEW_PY" ]; then - echo "❌ New Python files detected. Use Rust or AffineScript instead." + echo "❌ New Python files detected. Use Rust or ReScript instead." echo "$NEW_PY" exit 1 fi diff --git a/absolute-zero/.github/workflows/mirror.yml b/absolute-zero/.github/workflows/mirror.yml index 5b67c3c..a0d5420 100644 --- a/absolute-zero/.github/workflows/mirror.yml +++ b/absolute-zero/.github/workflows/mirror.yml @@ -1,5 +1,4 @@ # SPDX-License-Identifier: MPL-2.0-or-later -# SPDX-FileCopyrightText: 2025 Jonathan D.A. Jewell name: Mirror to Git Forges on: @@ -7,138 +6,10 @@ on: branches: [main] workflow_dispatch: -permissions: read-all +permissions: + contents: read jobs: - mirror-gitlab: - runs-on: ubuntu-latest - if: vars.GITLAB_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1 - with: - ssh-private-key: ${{ secrets.GITLAB_SSH_KEY }} - - - name: Mirror to GitLab - run: | - ssh-keyscan -t ed25519 gitlab.com >> ~/.ssh/known_hosts - git remote add gitlab git@gitlab.com:hyperpolymath/${{ github.event.repository.name }}.git || true - git push --force gitlab main - - mirror-bitbucket: - runs-on: ubuntu-latest - if: vars.BITBUCKET_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1 - with: - ssh-private-key: ${{ secrets.BITBUCKET_SSH_KEY }} - - - name: Mirror to Bitbucket - run: | - ssh-keyscan -t ed25519 bitbucket.org >> ~/.ssh/known_hosts - git remote add bitbucket git@bitbucket.org:hyperpolymath/${{ github.event.repository.name }}.git || true - git push --force bitbucket main - - mirror-codeberg: - runs-on: ubuntu-latest - if: vars.CODEBERG_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1 - with: - ssh-private-key: ${{ secrets.CODEBERG_SSH_KEY }} - - - name: Mirror to Codeberg - run: | - ssh-keyscan -t ed25519 codeberg.org >> ~/.ssh/known_hosts - git remote add codeberg git@codeberg.org:hyperpolymath/${{ github.event.repository.name }}.git || true - git push --force codeberg main - - mirror-sourcehut: - runs-on: ubuntu-latest - if: vars.SOURCEHUT_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1 - with: - ssh-private-key: ${{ secrets.SOURCEHUT_SSH_KEY }} - - - name: Mirror to SourceHut - run: | - ssh-keyscan -t ed25519 git.sr.ht >> ~/.ssh/known_hosts - git remote add sourcehut git@git.sr.ht:~hyperpolymath/${{ github.event.repository.name }} || true - git push --force sourcehut main - - mirror-disroot: - runs-on: ubuntu-latest - if: vars.DISROOT_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1 - with: - ssh-private-key: ${{ secrets.DISROOT_SSH_KEY }} - - - name: Mirror to Disroot - run: | - ssh-keyscan -t ed25519 git.disroot.org >> ~/.ssh/known_hosts - git remote add disroot git@git.disroot.org:hyperpolymath/${{ github.event.repository.name }}.git || true - git push --force disroot main - - mirror-gitea: - runs-on: ubuntu-latest - if: vars.GITEA_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - uses: webfactory/ssh-agent@a6f90b1f127823b31d4d4a8d96047790581349bd # v0.9.1 - with: - ssh-private-key: ${{ secrets.GITEA_SSH_KEY }} - - - name: Mirror to Gitea - run: | - ssh-keyscan -t ed25519 ${{ vars.GITEA_HOST }} >> ~/.ssh/known_hosts - git remote add gitea git@${{ vars.GITEA_HOST }}:hyperpolymath/${{ github.event.repository.name }}.git || true - git push --force gitea main - - mirror-radicle: - runs-on: ubuntu-latest - if: vars.RADICLE_MIRROR_ENABLED == 'true' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - name: Setup Rust - uses: dtolnay/rust-toolchain@f7ccc83f9ed1e5b9c81d8a67d7ad1a747e22a561 # stable - with: - toolchain: stable - - - name: Install Radicle - run: | - # Install via cargo (safer than curl|sh) - cargo install radicle-cli --locked - echo "$HOME/.cargo/bin" >> $GITHUB_PATH - - - name: Mirror to Radicle - run: | - echo "${{ secrets.RADICLE_KEY }}" > ~/.radicle/keys/radicle - chmod 600 ~/.radicle/keys/radicle - rad sync --announce || echo "Radicle sync attempted" + mirror: + uses: hyperpolymath/standards/.github/workflows/mirror-reusable.yml@e6b2884722350515934d443daf23442f2195796f + secrets: inherit diff --git a/absolute-zero/.github/workflows/publish-container.yml b/absolute-zero/.github/workflows/publish-container.yml index 766379e..f55889c 100644 --- a/absolute-zero/.github/workflows/publish-container.yml +++ b/absolute-zero/.github/workflows/publish-container.yml @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 name: Publish Container on: @@ -14,10 +14,10 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v4 - name: Log in to GitHub Container Registry - uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3 + uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v3 with: registry: ghcr.io username: ${{ github.actor }} @@ -25,7 +25,7 @@ jobs: - name: Extract metadata id: meta - uses: docker/metadata-action@8e5442c4ef9f78752691e2d8f8d19755c6f78e81 # v5 + uses: docker/metadata-action@80c7e94dd9b9319bd5eb7a0e0fe9291e23a2a2e9 # v5 with: images: ghcr.io/${{ github.repository }} tags: | @@ -35,7 +35,7 @@ jobs: type=sha - name: Build and push - uses: docker/build-push-action@4f58ea79222b3b9dc2c8bbdd6debcef730109a75 # v6 + uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v6 with: context: . file: ./Containerfile diff --git a/absolute-zero/.github/workflows/rescript-deno-ci.yml b/absolute-zero/.github/workflows/rescript-deno-ci.yml deleted file mode 100644 index e4fcd23..0000000 --- a/absolute-zero/.github/workflows/rescript-deno-ci.yml +++ /dev/null @@ -1,41 +0,0 @@ -# SPDX-License-Identifier: MPL-2.0-or-later -name: ReScript/Deno CI -on: [push, pull_request] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - - uses: denoland/setup-deno@v2 - with: - deno-version: v1.x - - - name: Deno lint - run: deno lint - - - name: Deno fmt check - run: deno fmt --check - - - name: Deno test - run: deno test --allow-all --coverage=coverage - - - name: ReScript build - run: | - if [ -f "rescript.json" ] || [ -f "bsconfig.json" ]; then - npm install - npx rescript - fi - - - name: Type check - run: deno check **/*.ts || true - - security: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - - uses: denoland/setup-deno@v2 - - name: Check permissions - run: | - # Audit for dangerous permissions - grep -rE "allow-run|allow-write|allow-env" . || echo "No dangerous permissions" diff --git a/absolute-zero/.github/workflows/rust-ci.yml b/absolute-zero/.github/workflows/rust-ci.yml index cb72b00..7f0b7f8 100644 --- a/absolute-zero/.github/workflows/rust-ci.yml +++ b/absolute-zero/.github/workflows/rust-ci.yml @@ -1,53 +1,20 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 +# Rust CI — thin wrapper calling the shared estate reusable in +# hyperpolymath/standards. Configure once, propagate everywhere. +# See: docs/CI-REUSABLE-WORKFLOWS.adoc in standards. name: Rust CI -on: [push, pull_request] -env: - CARGO_TERM_COLOR: always - RUSTFLAGS: -Dwarnings -jobs: - test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - - uses: dtolnay/rust-toolchain@stable - with: - components: rustfmt, clippy - - uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2 - - - name: Check formatting - run: cargo fmt --all -- --check - - - name: Clippy lints - run: cargo clippy --all-targets --all-features -- -D warnings - - - name: Run tests - run: cargo test --all-features - - - name: Build release - run: cargo build --release +on: + push: + branches: [main, master] + pull_request: - security: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - - uses: dtolnay/rust-toolchain@stable - - name: Install cargo-audit - run: cargo install cargo-audit - - name: Security audit - run: cargo audit - - name: Check for outdated deps - run: cargo install cargo-outdated && cargo outdated --exit-code 1 || true +permissions: + contents: read - coverage: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - - uses: dtolnay/rust-toolchain@stable - - name: Install tarpaulin - run: cargo install cargo-tarpaulin - - name: Generate coverage - run: cargo tarpaulin --out Xml - - uses: codecov/codecov-action@v5 - with: - files: cobertura.xml +jobs: + rust-ci: + uses: hyperpolymath/standards/.github/workflows/rust-ci-reusable.yml@4fdf4314b4ab54269adbaff10e30e483b5e86845 + with: + enable_audit: true + enable_coverage: true diff --git a/absolute-zero/.github/workflows/scorecard.yml b/absolute-zero/.github/workflows/scorecard.yml index 1961a00..f99d361 100644 --- a/absolute-zero/.github/workflows/scorecard.yml +++ b/absolute-zero/.github/workflows/scorecard.yml @@ -1,32 +1,16 @@ -# SPDX-License-Identifier: MPL-2.0-or-later -name: OSSF Scorecard +# SPDX-License-Identifier: MPL-2.0 +name: Scorecards supply-chain security + on: - push: - branches: [main, master] + branch_protection_rule: schedule: - - cron: '0 4 * * *' - workflow_dispatch: + - cron: '23 4 * * 1' + push: + branches: [main] permissions: read-all jobs: analysis: - runs-on: ubuntu-latest - permissions: - security-events: write - id-token: write - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - with: - persist-credentials: false - - - name: Run Scorecard - uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.3.1 - with: - results_file: results.sarif - results_format: sarif - - - name: Upload results - uses: github/codeql-action/upload-sarif@5d4e8d1aca955e8d8589aabd499c5cae939e33c7 # v3.31.8 - with: - sarif_file: results.sarif + uses: hyperpolymath/standards/.github/workflows/scorecard-reusable.yml@e0caf11508a3989574713c78f5f444f2ce5e33ef + secrets: inherit diff --git a/absolute-zero/.github/workflows/secret-scanner.yml b/absolute-zero/.github/workflows/secret-scanner.yml index cc29168..c041f5d 100644 --- a/absolute-zero/.github/workflows/secret-scanner.yml +++ b/absolute-zero/.github/workflows/secret-scanner.yml @@ -1,5 +1,4 @@ # SPDX-License-Identifier: MPL-2.0-or-later -# Prevention workflow - scans for hardcoded secrets before they reach main name: Secret Scanner on: @@ -7,61 +6,14 @@ on: push: branches: [main] -permissions: read-all +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true -jobs: - trufflehog: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 # Full history for scanning - - - name: TruffleHog Secret Scan - uses: trufflesecurity/trufflehog@ef6e76c3c4023279497fab4721ffa071a722fd05 # v3 - with: - extra_args: --only-verified --fail - - gitleaks: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - with: - fetch-depth: 0 - - - name: Gitleaks Secret Scan - uses: gitleaks/gitleaks-action@ff98106e4c7b2bc287b24eaf42907196329070c7 # v2 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +permissions: + contents: read - # Rust-specific: Check for hardcoded crypto values - rust-secrets: - runs-on: ubuntu-latest - if: hashFiles('**/Cargo.toml') != '' - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v4 - - - name: Check for hardcoded secrets in Rust - run: | - # Patterns that suggest hardcoded secrets - PATTERNS=( - 'const.*SECRET.*=.*"' - 'const.*KEY.*=.*"[a-zA-Z0-9]{16,}"' - 'const.*TOKEN.*=.*"' - 'let.*api_key.*=.*"' - 'HMAC.*"[a-fA-F0-9]{32,}"' - 'password.*=.*"[^"]+"' - ) - - found=0 - for pattern in "${PATTERNS[@]}"; do - if grep -rn --include="*.rs" -E "$pattern" src/; then - echo "WARNING: Potential hardcoded secret found matching: $pattern" - found=1 - fi - done - - if [ $found -eq 1 ]; then - echo "::error::Potential hardcoded secrets detected. Use environment variables instead." - exit 1 - fi +jobs: + scan: + uses: hyperpolymath/standards/.github/workflows/secret-scanner-reusable.yml@3e4bd4c93911750727e2e4c66dff859e00079da0 + secrets: inherit diff --git a/absolute-zero/.gitignore b/absolute-zero/.gitignore index 73f3573..bab56b5 100644 --- a/absolute-zero/.gitignore +++ b/absolute-zero/.gitignore @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0 +# SPDX-License-Identifier: AGPL-3.0-or-later # RSR-compliant .gitignore # OS & Editor @@ -80,11 +80,7 @@ htmlcov/ # Crash recovery artifacts ai-cli-crash-capture/ -target/ -node_modules/ -_build/ -deps/ -.elixir_ls/ -.cache/ -build/ -dist/ +proofs/lean4/.lake/ + +# Rust build outputs in subdirectories (e.g. fuzz/target/) +**/target/ diff --git a/absolute-zero/.hypatia-ignore b/absolute-zero/.hypatia-ignore new file mode 100644 index 0000000..14384d4 --- /dev/null +++ b/absolute-zero/.hypatia-ignore @@ -0,0 +1,27 @@ +# SPDX-License-Identifier: MPL-2.0 +# +# Estate-policy exemptions for the absolute-zero language-demonstration +# repo. This repo intentionally ships example files in many banned and +# allowed languages — it is the canonical "what NOT to use, here is what +# you'd get" exemplar. Each entry below is a language-demo file under +# `examples/` or a one-off interpreter implementation, not load-bearing +# code. +# +# After standards#180 (file_pattern glob support in in_baseline()) merges, +# this whole file collapses to a single `examples/**` file_pattern entry +# in .hypatia-baseline.json. Tracked in the standards repo as a follow-up. + +# ReScript demonstration files (banned 2026-04-30 — kept as historical +# examples until the .res→.affine migration ships). +cicd_rules/banned_language_file:src/AuditTrail.res +cicd_rules/banned_language_file:interpreters/rescript/malbolgeInterpreter.res +cicd_rules/banned_language_file:examples/SafeDOMExample.res + +# Banned-language example files used to demonstrate the cross-language +# nop-semantics study. None are imported into the toolchain build. +cicd_rules/banned_language_file:examples/go/nop.go +cicd_rules/banned_language_file:examples/java/Nop.java +cicd_rules/banned_language_file:examples/java/BalancedOps.java +cicd_rules/banned_language_file:examples/kotlin/Nop.kt +cicd_rules/banned_language_file:examples/kotlin/BalancedOps.kt +cicd_rules/banned_language_file:examples/swift/Nop.swift diff --git a/absolute-zero/.machine_readable/6a2/AGENTIC.a2ml b/absolute-zero/.machine_readable/6a2/AGENTIC.a2ml index cd1fb1d..1e388ba 100644 --- a/absolute-zero/.machine_readable/6a2/AGENTIC.a2ml +++ b/absolute-zero/.machine_readable/6a2/AGENTIC.a2ml @@ -1,10 +1,12 @@ # SPDX-License-Identifier: MPL-2.0 # Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) # -# AGENTIC.a2ml — AI agent constraints and capabilities +# AGENTIC.a2ml — AI agent constraints and capabilities for absolute-zero +# Migrated from AGENTIC.scm on 2026-04-17 + [metadata] -version = "0.1.0" -last-updated = "2026-04-11" +version = "1.0.0" +last-updated = "2026-04-17" [agent-permissions] can-edit-source = true @@ -14,12 +16,21 @@ can-edit-config = true can-create-files = true [agent-constraints] -# What AI agents must NOT do: -# - Never use banned language patterns (believe_me, unsafeCoerce, etc.) +# What AI agents MUST NOT do in this repo: +# - Never use dangerous patterns: believe_me, assert_total, Admitted, sorry, unsafeCoerce, Obj.magic +# - Never touch proofs/lean4/*.lean or proofs/idris2/*.idr — 18 open sorry entries blocked on mathlib build # - Never commit secrets or credentials -# - Never use banned languages (TypeScript, Python, Go, etc.) -# - Never place state files in repository root (must be in .machine_readable/) -# - Never use AGPL license (use MPL-2.0) +# - Never use banned languages: TypeScript, Python (except SaltStack), Go, Node.js, Bun, npm +# - Never place checkpoint files outside .machine_readable/ +# - Never use AGPL-3.0 license (use MPL-2.0) +# - Never run the full test suite without user approval (mathlib build is expensive) + +[proof-safety] +# Lean 4 proofs have 18 open sorry entries blocked on mathlib build — do NOT modify without explicit instruction +# Coq proofs have 19 Admitted entries — document any new Admitted with rationale +# Python interpreters present but flagged as RSR violations — do not add new Python +lean4-sorry-count = 18 # as of last audit 2026-04-17; update when resolved +coq-admitted-count = 19 # as of 2026-02-05 [maintenance-integrity] fail-closed = true @@ -28,7 +39,11 @@ allow-silent-skip = false require-rerun-after-fix = true release-claim-requires-hard-pass = true +[tools] +recommended = ["read", "edit", "bash", "grep", "glob"] +permissions = "read-all" + [automation-hooks] -# on-enter: Read 0-AI-MANIFEST.a2ml, then STATE.a2ml -# on-exit: Update STATE.a2ml with session outcomes -# on-commit: Run just validate-rsr +# on-enter: Read AI.a2ml, then .machine_readable/6a2/STATE.a2ml +# on-exit: Update .machine_readable/6a2/STATE.a2ml with session outcomes +# on-commit: Run just validate-rsr (if available) diff --git a/absolute-zero/.machine_readable/6a2/ECOSYSTEM.a2ml b/absolute-zero/.machine_readable/6a2/ECOSYSTEM.a2ml index e27f779..bbc4fc2 100644 --- a/absolute-zero/.machine_readable/6a2/ECOSYSTEM.a2ml +++ b/absolute-zero/.machine_readable/6a2/ECOSYSTEM.a2ml @@ -2,21 +2,53 @@ # Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) # # ECOSYSTEM.a2ml — Absolute Zero ecosystem position +# Migrated from ECOSYSTEM.scm on 2026-04-17 + [metadata] version = "1.0" -last-updated = "2026-04-11" +last-updated = "2026-02-05" +project = "absolute-zero" +ecosystem = "hyperpolymath" [project] name = "Absolute Zero" -purpose = "Formal verification of Certified Null Operations (CNOs): - programs proven to compute nothing. Multi-prover theorem proving - with thermodynamic, categorical, and quantum foundations." -role = "research-project" +type = "research-project" +role = "formal-methods-research" +purpose = """ +Formal verification of Certified Null Operations (CNOs): programs proven to +compute nothing. Multi-prover theorem proving with thermodynamic, categorical, +and quantum foundations. +""" [position-in-ecosystem] category = "formal-methods" +subcategory = "program-verification" +unique-value = [ + "First formal treatment of computational nullity", + "Multi-prover verification across 6 proof systems", + "Category-theoretic model independence", + "Thermodynamic grounding via Landauer/Bennett", +] [related-projects] projects = [ - # No related projects recorded + { name = "echidna", relationship = "sibling-standard", notes = "Security scanning; potential CNO verifier integration" }, + { name = "echidnabot", relationship = "potential-consumer", notes = "GitHub bot; could automate CNO checks in PRs" }, + { name = "valence-shell", relationship = "integration-target", notes = "Filesystem ops library proven in FilesystemCNO.v" }, + { name = "rsr-template-repo", relationship = "infrastructure", notes = "Repository standards template" }, +] + +[what-this-is] +items = [ + "Formal verification research", + "Multi-prover theorem proving", + "Theoretical CS contribution", + "Bridge: computation theory <-> thermodynamics", +] + +[what-this-is-not] +items = [ + "Runtime library", + "Programming language", + "Production software", ] diff --git a/absolute-zero/.machine_readable/6a2/META.a2ml b/absolute-zero/.machine_readable/6a2/META.a2ml index c073f66..70e3965 100644 --- a/absolute-zero/.machine_readable/6a2/META.a2ml +++ b/absolute-zero/.machine_readable/6a2/META.a2ml @@ -2,9 +2,11 @@ # Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) # # META.a2ml — Absolute Zero meta-level information +# Migrated from META.scm on 2026-04-17 + [metadata] -version = "0.1.0" -last-updated = "2026-04-11" +version = "1.0.0" +last-updated = "2026-05-27" [project-info] license = "MPL-2.0" @@ -12,14 +14,45 @@ author = "Jonathan D.A. Jewell (hyperpolymath)" [architecture-decisions] decisions = [ - # No ADRs recorded + { id = "ADR-001", status = "accepted", title = "ProofIrrelevance for morphism equality in category theory" }, + { id = "ADR-002", status = "accepted", title = "Dual Landauer formalization: axiom (StatMech.v) + derivation (LandauerDerivation.v)" }, + { id = "ADR-003", status = "accepted", title = "Lambda CNO = identity property only, not termination" }, + { id = "ADR-004", status = "accepted", title = "post_execution_dist specialized for CNOs (identity on distributions)" }, + { id = "ADR-005", status = "proposed", title = "Fix QuantumCNO.v Cexp: real exp -> complex phase factor" }, + { id = "ADR-006", status = "accepted", title = "state_eq excludes state_pc — PC is control-flow bookkeeping, not observable side effect (2026-05-18 rescue)" }, + { id = "ADR-007", status = "accepted", title = "Discharge eval_deterministic Axiom → Theorem via step_deterministic_strong helper (2026-05-20, PR #24); first post-T0 axiom audit win" }, + { id = "ADR-008", status = "accepted", title = "Delete unsound eval_respects_state_eq_{left,right} axioms; weaken logically_reversible definition to use =st= (observational reversibility); re-prove cno_eval_on_equal_states + cno_logically_reversible via cno_terminates + cno_preserves_state (2026-05-20); rationale: under PC-excluding state_eq the strong axioms force a syntactically-identical eval result, which is unsound because eval propagates PC deterministically while =st= ignores it" }, + { id = "ADR-009", status = "accepted", title = "Delete unsound alignmentMatchesPlatformWord Idris2 postulate; consolidate alignedSizeCorrect into shared AbsoluteZero.ABI.Proofs.DivMod module (PR #40, Refs #27)" }, + { id = "ADR-010", status = "accepted", title = "Phase 1 per-axiom triage of 72 Coq Axioms per standards#203 trusted-base policy (2026-05-27, PR #58): 52 §c TRUSTED-BASE + 17 §a DISCHARGE backlog + 3 §b PROPERTY-TEST; canonical disposition in docs/proof-debt-triage.md" }, ] [development-practices] +code-style = "Coq proof engineering" +testing = "Multi-prover cross-validation" versioning = "SemVer" documentation = "AsciiDoc" +branching = "main for stable" build-tool = "just" +[security] +principle = "Defense in depth" + +[proof-methodology] +rules = [ + "Prefer Qed over Admitted", + "Axiomatize physical laws", + "Document all Admitted with rationale", + "Separate helpers into dedicated files", +] + +[design-rationale] +rationale = [ + "CNOs are identity morphisms in categories", + "Multi-prover for maximum confidence", + "Thermodynamic grounding via Landauer/Bennett", + "Progressive: axiom -> theorem -> verified", +] + [maintenance-axes] scoping-first = true axis-1 = "must > intend > like" diff --git a/absolute-zero/.machine_readable/6a2/NEUROSYM.a2ml b/absolute-zero/.machine_readable/6a2/NEUROSYM.a2ml index e1d34c0..1af3239 100644 --- a/absolute-zero/.machine_readable/6a2/NEUROSYM.a2ml +++ b/absolute-zero/.machine_readable/6a2/NEUROSYM.a2ml @@ -1,21 +1,35 @@ # SPDX-License-Identifier: MPL-2.0 # Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) # -# NEUROSYM.a2ml — Neurosymbolic integration metadata +# NEUROSYM.a2ml — Neurosymbolic integration metadata for absolute-zero +# Migrated from NEUROSYM.scm on 2026-04-17 + [metadata] -version = "0.1.0" -last-updated = "2026-04-11" +version = "1.0.0" +last-updated = "2026-04-17" [hypatia-config] scan-enabled = true -scan-depth = "standard" # quick | standard | deep -report-format = "logtalk" +scan-depth = "deep" # deep is appropriate given formal-verification proof assets +report-format = "a2ml" # Hypatia Logtalk removed 2026-04-12; outputs JSON→A2ML + +[symbolic-layer] +type = "multi-prover" +reasoning = "deductive" +verification = "formal" +# Proof systems: Coq, Lean 4, Z3, Agda, Isabelle, Mizar + +[neural-layer] +embeddings = false +fine-tuning = false [symbolic-rules] -# Custom symbolic rules for this project -# - { name = "no-unsafe-ffi", pattern = "believe_me|unsafeCoerce", severity = "critical" } +# Custom rules for this project: +# - { name = "no-sorry-in-lean4", pattern = "sorry", severity = "critical", paths = ["proofs/lean4/"] } +# - { name = "no-admitted-new", pattern = "Admitted", severity = "high", paths = ["proofs/coq/"] } +# - { name = "no-dangerous-patterns", pattern = "believe_me|assert_total|unsafeCoerce|Obj\\.magic", severity = "critical" } -[neural-config] -# Neural pattern detection settings -# confidence-threshold = 0.85 -# model = "hypatia-v2" +[integration] +# No active integrations yet — TODO when echidna CNO verifier integration lands +echidna-integration = "planned" +verisimdb-instance = "TODO" # TODO: provision per-project VeriSimDB instance diff --git a/absolute-zero/.machine_readable/6a2/PLAYBOOK.a2ml b/absolute-zero/.machine_readable/6a2/PLAYBOOK.a2ml index 5003fd0..a2f04d9 100644 --- a/absolute-zero/.machine_readable/6a2/PLAYBOOK.a2ml +++ b/absolute-zero/.machine_readable/6a2/PLAYBOOK.a2ml @@ -1,26 +1,52 @@ # SPDX-License-Identifier: MPL-2.0 # Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) # -# PLAYBOOK.a2ml — Operational playbook +# PLAYBOOK.a2ml — Operational playbook for absolute-zero +# Migrated from PLAYBOOK.scm on 2026-04-17 + [metadata] -version = "0.1.0" -last-updated = "2026-04-11" +version = "1.0.0" +last-updated = "2026-04-17" [deployment] -# method = "gitops" # gitops | manual | ci-triggered -# target = "container" # container | binary | library | wasm +method = "library" # This is a research repo; no deployed service +target = "library" # Proofs and interpreters are consumed by-reference + +[build-procedures] +build = "just build" +test = "just test" +release = "just release" + +[proof-procedures] +# Build all prover targets (gracefully skips missing local installations) +build-all = "just build-all" +# Individual prover builds: +build-coq = "just build-coq" +build-lean = "just build-lean" +build-agda = "just build-agda" +build-isabelle = "just build-isabelle" +build-rescript = "just build-rescript" [incident-response] -# 1. Check .machine_readable/STATE.a2ml for current status -# 2. Review recent commits and CI results -# 3. Run `just validate` to check compliance -# 4. Run `just security` to audit for vulnerabilities +# 1. Check .machine_readable/6a2/STATE.a2ml for current status +# 2. Review recent commits: git log --oneline -10 +# 3. Run `just validate` if available +# 4. Run `just security` for vulnerability audit +# 5. For proof failures: check proofs// for unsaved Admitted/sorry [release-process] -# 1. Update version in STATE.a2ml, META.a2ml -# 2. Run `just release-preflight` (validate + quality + security + maint-hard-pass) -# 3. Tag and push +# 1. Update version in .machine_readable/6a2/STATE.a2ml and META.a2ml +# 2. Resolve all Admitted/sorry entries to target count +# 3. Run `just build-all` to confirm no regressions +# 4. Tag and push to origin (GitHub only) +# 5. Update PROOF-COMPLETION-PLAN.adoc with release notes + +[rollback] +# No deployed service; rollback = revert commit + re-check proof counts [maintenance-operations] -# Baseline audit: just maint-audit -# Hard release gate: just maint-hard-pass +# Baseline audit: just maint-audit (TODO: add this recipe) +# Hard release gate: just maint-hard-pass (TODO: add this recipe) + +[contacts] +# No external contacts — TODO if paper co-authors join diff --git a/absolute-zero/.machine_readable/6a2/STATE.a2ml b/absolute-zero/.machine_readable/6a2/STATE.a2ml index 7c308b0..2c5e405 100644 --- a/absolute-zero/.machine_readable/6a2/STATE.a2ml +++ b/absolute-zero/.machine_readable/6a2/STATE.a2ml @@ -2,43 +2,110 @@ # Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) # # STATE.a2ml — Absolute Zero project state +# Migrated from STATE.scm on 2026-04-17 +# Schema version: 1.0 + [metadata] project = "absolute-zero" +repo = "github.com/hyperpolymath/absolute-zero" version = "1.0.0-alpha" -last-updated = "2026-02-05" +schema-version = "1.0" +created = "2026-01-03" +last-updated = "2026-05-27" status = "active" -session = "converted from scheme — 2026-04-11" [project-context] name = "Absolute Zero" -purpose = """Formal Verification of Certified Null Operations""" -completion-percentage = 65 +tagline = "Formal Verification of Certified Null Operations" +tech-stack = ["Coq", "Lean 4", "Z3", "Agda", "Isabelle", "ReScript", "Rust"] [position] -phase = "proof-completion" # design | implementation | testing | maintenance | archived -maturity = "experimental" # experimental | alpha | beta | production | lts +phase = "proof-completion" +completion-percentage = 65 +maturity = "experimental" + +[components] +# Format: name = [percentage, "notes"] +coq-proofs = [90, "11/11 files compile (Coq 8.18.0+8.20.1); 0 Admitted (rescue 2026-05-18); 75→72 Axioms + 42 Parameters; Phase 1 triage 2026-05-27 (PR #58) classifies 72 Coq Axioms into §c TRUSTED-BASE (52) + §a DISCHARGE backlog (17) + §b PROPERTY-TEST (3); see docs/proof-debt-triage.md"] +lean4-proofs = [95, "lake build 1631/1632 green (mathlib + 6 lean_lib targets); verified 2026-05-20"] +z3-proofs = [90, "10 theorems encoded, needs z3 runtime"] +agda-proofs = [60, "CNO.agda type-checks clean — 0 postulates/holes/unsolved metas (verified 2026-05-18)"] +isabelle-proofs = [40, "phase 1 complete"] +mizar-proofs = [10, "stub, needs installation"] + +[working-features] +features = [ + "Core CNO theory fully proven", + "Category theory fully proven", + "Statistical mechanics fully proven", + "Lambda calculus 90% proven", + "Quantum computing 70% proven", + "Filesystem 57% proven", +] [route-to-mvp] milestones = [ - # No milestones recorded + { id = "v0.8", label = "Compliance sprint", status = "in-progress", completion = 40 }, + { id = "v0.9", label = "Container verification", status = "not-started", completion = 0 }, + { id = "v1.0", label = "Publication release", status = "not-started", completion = 0 }, ] [blockers-and-issues] -issues = [ - # No blockers recorded +critical = [] +high = [ + "Python interpreters violate RSR", +] +medium = [ + "LandauerDerivation.v needs measure theory", + "17 §a DISCHARGE Coq axioms backlog (post-Phase-1 triage, see docs/proof-debt-triage.md)", + "Triage Phase 2 for 52 Lean axioms + 7 Idris2 postulates (#27) still pending", +] +low = [ + "y_not_cno non-termination proof", ] [critical-next-actions] -actions = [ - "Complete QuantumCNO.v proofs", - "Classify FilesystemCNO.v proofs", - "Classify MalbolgeCore.v proof", - "Target 12-15 of 19 Admitted proofs", +immediate = [ + "Phase 2 triage: Lean axioms (52) + Idris2 postulates (#27, 7)", +] +this-week = [ + "Begin discharging the 17 §a Coq DISCHARGE-backlog axioms (lowest-hanging: cno_zero_energy_dissipation_derived, fidelity_bound, unitary_inverse_property, *_not_identity existence pair)", + "Physics-constant deduplication (kB_positive/temperature_positive declared 3x across QuantumCNO/StatMech/LandauerDerivation)", "Migrate Python to Rust", +] +this-month = [ "Container pipeline", "Paper draft", ] +[session-history] +sessions = [ + { date = "2026-05-27", agent = "opus", summary = "Phase 1 per-axiom triage of all 72 Coq Axioms per standards#203 trusted-base policy. Classification: 52 §c TRUSTED-BASE (physics constants, quantum primitives, POSIX semantics, Kolmogorov+Shannon axioms, Cexp algebra, physical laws), 17 §a DISCHARGE (derivable theorems incl. 2 named *_derived), 3 §b PROPERTY-TEST (decidability over opaque types). Surfaced 5 follow-ups (physics-constant dedup ×3, quantum-law dedup ×2, Cexp constructive in Complex.v). PR #58 MERGED 2026-05-27 (commit e17256b). Also: traced phantom '315 Lean sorries' figure to a metric mismatch — actual local user-sorry count = 0; canonical figure is 129 (now 124) escape hatches across all proof languages per standards#195 + scripts/check-trusted-base.sh." }, + { date = "2026-05-20", agent = "opus", summary = "Post-T0 axiom audit: 117 declarations triaged into Tier A/B/C; 2 unsound axioms (eval_respects_state_eq_left/right) deleted with downstream refactor; logically_reversible weakened to =st=; cno_eval_on_equal_states + cno_logically_reversible re-proved without axioms; 75→73 Axioms total" }, + { date = "2026-05-20", agent = "opus", summary = "Rescue branch rebased onto current main (clean); eval_deterministic Axiom discharged → Theorem (via step_deterministic_strong helper); Print Assumptions Closed under global context; 11/11 Coq + 1631/1632 Lean targets green; PR #24 MERGED (admin-squash 69e7a22)" }, + { date = "2026-05-18", agent = "opus", summary = "Tier-0 rescue: CNO.v keystone re-proved (state_eq PC-exclusion fix, 9 named repairs); Complex.v self-contained complex numbers added; 11 Coq files compile under Coq 8.20.1; full Lean lake build succeeds; PROOF-STATUS-2026-05-18.md ledger added" }, + { date = "2026-02-05", agent = "opus", summary = "Completed 8 proofs, created PROOF-INSIGHTS.md" }, + { date = "2026-02-04", agent = "opus", summary = "Completed cno_logically_reversible, added axioms" }, +] + [maintenance-status] -last-run-utc = "2026-02-05T00:00:00Z" -last-result = "unknown" # unknown | pass | warn | fail +last-run-utc = "2026-05-27T08:00:00Z" +last-result = "pass" # unknown | pass | warn | fail + +[migration-notes] +# Fields from STATE.scm that map cleanly: +# metadata.version, created, updated, project, repo → all mapped above +# project-context.name, tagline, tech-stack → all mapped +# current-position.phase, overall-completion → phase + completion-percentage +# current-position.components → [components] table +# working-features → [working-features].features list +# route-to-mvp.milestones → [route-to-mvp].milestones array of objects +# blockers-and-issues.{critical,high,medium,low} → mapped verbatim +# critical-next-actions.{immediate,this-week,this-month} → all mapped +# session-history entries → [session-history].sessions array of objects +# +# Fields that required schema extension / note: +# - `schema-version` added as top-level field (not in SCM template but kept for traceability) +# - session-history: SCM used positional tuples (date agent summary); A2ML uses named fields +# - `overall-completion` in SCM root renamed to `completion-percentage` to match estate standard +# - `phase` nested under `current-position` in SCM; promoted to top-level `[position]` here diff --git a/absolute-zero/.machine_readable/AGENTIC.scm b/absolute-zero/.machine_readable/AGENTIC.scm new file mode 100644 index 0000000..3131977 --- /dev/null +++ b/absolute-zero/.machine_readable/AGENTIC.scm @@ -0,0 +1,16 @@ +;; SPDX-License-Identifier: MPL-2.0 +;; AGENTIC.scm - AI agent interaction patterns for absolute-zero + +(define agentic-config + `((version . "1.0.0") + (claude-code + ((model . "claude-opus-4-5-20251101") + (tools . ("read" "edit" "bash" "grep" "glob")) + (permissions . "read-all"))) + (patterns + ((code-review . "thorough") + (refactoring . "conservative") + (testing . "comprehensive"))) + (constraints + ((languages . ()) + (banned . ("typescript" "go" "python" "makefile")))))) diff --git a/absolute-zero/.machine_readable/ECOSYSTEM.scm b/absolute-zero/.machine_readable/ECOSYSTEM.scm new file mode 100644 index 0000000..8458f0c --- /dev/null +++ b/absolute-zero/.machine_readable/ECOSYSTEM.scm @@ -0,0 +1,37 @@ +;; SPDX-License-Identifier: MPL-2.0 +;; ECOSYSTEM.scm - Ecosystem position for absolute-zero +;; Media-Type: application/vnd.ecosystem+scm + +(ecosystem + (version "1.0") + (name "absolute-zero") + (type "research-project") + (purpose "Formal verification of Certified Null Operations (CNOs): + programs proven to compute nothing. Multi-prover theorem proving + with thermodynamic, categorical, and quantum foundations.") + + (position-in-ecosystem + (category "formal-methods") + (subcategory "program-verification") + (unique-value + ("First formal treatment of computational nullity" + "Multi-prover verification across 6 proof systems" + "Category-theoretic model independence" + "Thermodynamic grounding via Landauer/Bennett"))) + + (related-projects + (("echidna" "sibling-standard" "Security scanning; potential CNO verifier integration") + ("echidnabot" "potential-consumer" "GitHub bot; could automate CNO checks in PRs") + ("valence-shell" "integration-target" "Filesystem ops library proven in FilesystemCNO.v") + ("rsr-template-repo" "infrastructure" "Repository standards template"))) + + (what-this-is + ("Formal verification research" + "Multi-prover theorem proving" + "Theoretical CS contribution" + "Bridge: computation theory <-> thermodynamics")) + + (what-this-is-not + ("Runtime library" + "Programming language" + "Production software"))) diff --git a/absolute-zero/.machine_readable/META.scm b/absolute-zero/.machine_readable/META.scm new file mode 100644 index 0000000..316a750 --- /dev/null +++ b/absolute-zero/.machine_readable/META.scm @@ -0,0 +1,36 @@ +;; SPDX-License-Identifier: MPL-2.0 +;; META.scm - Meta-level information for absolute-zero +;; Media-Type: application/meta+scheme + +(meta + (architecture-decisions + (("ADR-001" "accepted" "ProofIrrelevance for morphism equality in category theory") + ("ADR-002" "accepted" "Dual Landauer formalization: axiom (StatMech.v) + derivation (LandauerDerivation.v)") + ("ADR-003" "accepted" "Lambda CNO = identity property only, not termination") + ("ADR-004" "accepted" "post_execution_dist specialized for CNOs (identity on distributions)") + ("ADR-005" "proposed" "Fix QuantumCNO.v Cexp: real exp -> complex phase factor") + ("ADR-006" "accepted" "state_eq excludes state_pc — PC is control-flow bookkeeping, not observable side effect (2026-05-18 rescue)") + ("ADR-007" "accepted" "Discharge eval_deterministic Axiom → Theorem via step_deterministic_strong helper (2026-05-20, PR #24); first post-T0 axiom audit win") + ("ADR-008" "accepted" "Delete unsound eval_respects_state_eq_{left,right} axioms; weaken logically_reversible to =st= (observational reversibility); re-prove cno_eval_on_equal_states + cno_logically_reversible via cno_terminates + cno_preserves_state (2026-05-20)") + ("ADR-009" "accepted" "Delete unsound alignmentMatchesPlatformWord Idris2 postulate (HasAlignment carries no evidence; would derive So (1 mod 8 == 0) from CNOResultLayout.alignment); replace single consumer with per-Platform decidable proof. Consolidate remaining alignedSizeCorrect postulate into shared AbsoluteZero.ABI.Proofs.DivMod module as the estate-wide div/mod lemma surface (absolute-zero#27, civic-connect alignUpDivides/mkFieldsAligned/offsetInBoundsPrf migrate here)") + ("ADR-010" "accepted" "Phase 1 per-axiom triage of 72 Coq Axioms per standards#203 trusted-base policy (2026-05-27, PR #58): 52 §c TRUSTED-BASE + 17 §a DISCHARGE backlog + 3 §b PROPERTY-TEST; canonical disposition in docs/proof-debt-triage.md"))) + + (development-practices + (code-style "Coq proof engineering") + (security + (principle "Defense in depth")) + (testing "Multi-prover cross-validation") + (versioning "SemVer") + (documentation "AsciiDoc") + (branching "main for stable") + (proof-methodology + ("Prefer Qed over Admitted" + "Axiomatize physical laws" + "Document all Admitted with rationale" + "Separate helpers into dedicated files"))) + + (design-rationale + ("CNOs are identity morphisms in categories" + "Multi-prover for maximum confidence" + "Thermodynamic grounding via Landauer/Bennett" + "Progressive: axiom -> theorem -> verified"))) diff --git a/absolute-zero/.machine_readable/NEUROSYM.scm b/absolute-zero/.machine_readable/NEUROSYM.scm new file mode 100644 index 0000000..7d505de --- /dev/null +++ b/absolute-zero/.machine_readable/NEUROSYM.scm @@ -0,0 +1,13 @@ +;; SPDX-License-Identifier: MPL-2.0 +;; NEUROSYM.scm - Neurosymbolic integration config for absolute-zero + +(define neurosym-config + `((version . "1.0.0") + (symbolic-layer + ((type . "scheme") + (reasoning . "deductive") + (verification . "formal"))) + (neural-layer + ((embeddings . false) + (fine-tuning . false))) + (integration . ()))) diff --git a/absolute-zero/.machine_readable/PLAYBOOK.scm b/absolute-zero/.machine_readable/PLAYBOOK.scm new file mode 100644 index 0000000..6db4d05 --- /dev/null +++ b/absolute-zero/.machine_readable/PLAYBOOK.scm @@ -0,0 +1,13 @@ +;; SPDX-License-Identifier: MPL-2.0 +;; PLAYBOOK.scm - Operational runbook for absolute-zero + +(define playbook + `((version . "1.0.0") + (procedures + ((deploy . (("build" . "just build") + ("test" . "just test") + ("release" . "just release"))) + (rollback . ()) + (debug . ()))) + (alerts . ()) + (contacts . ()))) diff --git a/absolute-zero/.machine_readable/contractiles/bust/Bustfile.a2ml b/absolute-zero/.machine_readable/contractiles/bust/Bustfile.a2ml new file mode 100644 index 0000000..fcda3df --- /dev/null +++ b/absolute-zero/.machine_readable/contractiles/bust/Bustfile.a2ml @@ -0,0 +1,28 @@ +// Bustfile.a2ml — meta-repo bust contractile (breakage / rollback) +// SPDX-License-Identifier: MPL-2.0 + +Bust { + name: "absolute-zero" + version: "1.0.0" + description: "Rollback procedures when something breaks in the meta-repo" + + scenarios: { + "bad-pointer-bump": "git revert in meta-repo; child repo itself untouched" + "submodule-pointer-points-at-missing-sha": "git submodule update --init --checkout resets child to parent-recorded SHA; OR revert the stale bump commit" + "submodule-orphan-after-local-only-commit": "roll back locally with git reset to before the stranded commit; fix remote situation before re-attempting" + "accidental-private-repo-content-leaked-to-public-submodule": "hard-rotate the leaked secret immediately; git-filter-repo or BFG on the submodule's own history; public re-publication only after rotation complete" + } + + escalation-ladder: [ + "1. revert the meta-repo commit (reversible, low blast radius)", + "2. reset the local submodule clone (affects only local workspace)", + "3. force-push to main — PROHIBITED without explicit user confirmation (violates branch protection)", + "4. registry-level (delete/archive the GitHub repo) — human-only action, never by AI" + ] + + backup-points: [ + "GitHub serves as the durable backup for every submodule's own history", + "Meta-repo history on origin/main is the durable backup for pointer state", + "Local backup tags (backup/pre--) retained on risky rewrites" + ] +} diff --git a/absolute-zero/.machine_readable/contractiles/bust/bust.ncl b/absolute-zero/.machine_readable/contractiles/bust/bust.ncl new file mode 100644 index 0000000..fc8cb8c --- /dev/null +++ b/absolute-zero/.machine_readable/contractiles/bust/bust.ncl @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: MPL-2.0 +# Bust — error-handling / failure-recovery runner +# +# Pairs with: Bustfile.a2ml (same directory) +# Verb: bust +# Semantics: every declared failure mode must have a recovery path that has +# been exercised. Runner injects failures (via declared probes) +# and verifies the recovery path works. Hard gate on any +# failure-mode with missing or broken recovery. +# CLI: `contractile bust check` → list failure modes + recovery status +# `contractile bust drill` → inject declared failures, verify recovery +# +# Anything else in this directory is human-only notes/archive; machines ignore. +# +# Base: ../_base.ncl provides pedigree_schema, run_defaults, probe_schema. +# See: docs/CONTRACTILE-SPEC.adoc + +let base = import "../_base.ncl" in + +{ + pedigree = base.pedigree_schema & { + contractile_verb = "bust", + semantics = "error handling + failure recovery", + security = { + leash = 'Kennel, + trust_level = "controlled failure injection; scoped to system-under-test", + allow_network = false, + allow_filesystem_write = true, # drills may write transient state (tmp dirs, test DBs) + allow_subprocess = true, + injection_scope = "system-under-test-only", + }, + metadata = { + name = "bust-runner", + version = "1.0.0", + description = "Exercises declared failure modes and verifies recovery paths. Hard-gates on any failure mode without working recovery.", + paired_xfile = "Bustfile.a2ml", + author = "Jonathan D.A. Jewell ", + }, + }, + + schema = { + failure_modes + | Array { + id | String, + description | String, + class | [| 'network, 'disk_full, 'oom, 'timeout, 'partial_write, 'panic, 'crash, 'rollback, 'concurrency |], + # TODO: migrate to base.probe_schema (structured probe) when CLI supports it + injection_probe | String, # command that deterministically causes this failure + # TODO: migrate to base.probe_schema (structured probe) when CLI supports it + recovery_probe | String, # command that verifies recovery (exit 0 = recovered) + expected_recovery_time_seconds | Number | default = 30, + # status_core values: 'declared, 'verified, 'failing; bust adds 'drilled + status | [| 'declared, 'drilled, 'verified, 'failing |] | default = 'declared, + notes | String | optional, + }, + }, + + # Runner behaviour — inherits from base.run_defaults. + # bust adds record_recovery_times for performance tier feeding. + run = base.run_defaults & { + on_any_fail = "exit-nonzero", # missing or broken recovery blocks merge + report_format = "a2ml", + emit_summary = true, + record_recovery_times = true, # feeds the performance tier + }, +} diff --git a/absolute-zero/.machine_readable/contractiles/trust/Trustfile.a2ml b/absolute-zero/.machine_readable/contractiles/trust/Trustfile.a2ml new file mode 100644 index 0000000..bfb1b5b --- /dev/null +++ b/absolute-zero/.machine_readable/contractiles/trust/Trustfile.a2ml @@ -0,0 +1,93 @@ +# SPDX-License-Identifier: MPL-2.0 +# Trustfile — Integrity and provenance verification for absolute-zero +# Author: Jonathan D.A. Jewell +# +# STATUS: SCAFFOLD ONLY — contractile runner NOT enabled. +# Do NOT activate any runner until Jonathan has reviewed this file. +# When activating: uncomment the [runner] section below and test locally first. + +@abstract: +Integrity invariants for the absolute-zero repository. Verifies that no +secrets have been committed, provenance is traceable, and dangerous proof +patterns (sorry/Admitted without rationale) stay within known bounds. +@end + +# [runner] +# DISABLED — scaffold only. To enable, uncomment and configure: +# command = "just trust-check" +# on-push = false +# on-pr = false + +## Secrets + +### no-secrets-committed +- description: No credential files in repo +- run: test ! -f .env && test ! -f credentials.json && test ! -f .env.local && test ! -f .env.production +- severity: critical + +### no-private-keys +- description: No private key files committed +- run: "! find . -name '*.pem' -o -name '*.key' -o -name 'id_rsa' -o -name 'id_ed25519' 2>/dev/null | grep -v node_modules | head -1 | grep -q ." +- severity: critical + +### no-tokens-in-source +- description: No hardcoded API tokens in source files +- run: "! grep -rE '(api[_-]?key|secret|token|password)\s*[:=]\s*[\"'\'''][A-Za-z0-9]{16,}' --include='*.js' --include='*.res' --include='*.py' --include='*.rs' . 2>/dev/null | grep -v node_modules | head -1 | grep -q ." +- severity: critical + +## Provenance + +### author-correct +- description: Git author matches expected identity +- run: "git log -1 --format='%ae' | grep -qE '(hyperpolymath|j\\.d\\.a\\.jewell)'" +- severity: warning + +### license-content +- description: LICENSE contains expected PMPL/MPL identifier +- run: grep -q 'PMPL\|MPL' LICENSE +- severity: warning + +## Container Security + +### container-images-pinned +- description: Containerfile uses pinned/Chainguard base images +- run: test ! -f Containerfile || grep -q 'cgr.dev\|@sha256:' Containerfile +- severity: warning + +### no-dockerfile +- description: No Dockerfile (use Containerfile) +- run: test ! -f Dockerfile +- severity: warning + +## Dangerous Patterns + +### no-dangerous-proof-patterns +- description: No believe_me, assert_total, unsafeCoerce, Obj.magic in non-proof source +- run: "! grep -rE 'believe_me|assert_total|unsafeCoerce|Obj\\.magic' --include='*.idr' --include='*.ml' --include='*.hs' --include='*.rs' . 2>/dev/null | head -1 | grep -q ." +- severity: critical + +### lean4-sorry-bounded +- description: Lean 4 sorry count does not exceed known baseline (18) +- run: "count=$(grep -rn 'sorry' proofs/lean4/ 2>/dev/null | grep -v '^\s*--' | wc -l); test \"$count\" -le 18" +- severity: high +# NOTE: baseline is 18 sorries as of 2026-04-17; blocked on mathlib build. +# Update the threshold only after resolving entries in coordination with Jonathan. + +### coq-admitted-bounded +- description: Coq Admitted count does not exceed known baseline (19) +- run: "count=$(grep -rn 'Admitted' proofs/coq/ 2>/dev/null | wc -l); test \"$count\" -le 19" +- severity: high +# NOTE: baseline is 19 Admitted entries as of 2026-02-05. +# Decrement as proofs are closed; never increment without a documented rationale. + +### no-unsafe-rust-without-comment +- description: All unsafe blocks in Rust must have SAFETY comments +- run: "! grep -B1 'unsafe {' --include='*.rs' -r . 2>/dev/null | grep -v SAFETY | grep 'unsafe {' | head -1 | grep -q ." +- severity: warning + +## Service Security (n/a — research repo; included for estate consistency) + +### localhost-only-bindings +- description: No wildcard service bindings in source (not a deployed service) +- run: "! grep -rE 'bind\\(\"0\\.0\\.0\\.0' --include='*.rs' --include='*.ex' --include='*.res' . 2>/dev/null | head -1 | grep -q ." +- severity: critical diff --git a/absolute-zero/.machine_readable/svc/README.adoc b/absolute-zero/.machine_readable/svc/README.adoc new file mode 100644 index 0000000..3228ec7 --- /dev/null +++ b/absolute-zero/.machine_readable/svc/README.adoc @@ -0,0 +1,16 @@ += `.machine_readable/svc/` — Service components for absolute-zero +:toc: + +Service-layer components that sit alongside the contractile trident +but are not themselves verbs. Per **ADR-001 (2026-04-18)**, K9 lives +here rather than under `contractiles/` so the contractile directory +stays a pure six-verb set (intend, trust, must, bust, adjust, dust). + +== Contents + +* `k9/` — K9 self-validating templates and validators. + +== Pointer + +For the verb contractiles themselves, see +`.machine_readable/contractiles/`. diff --git a/absolute-zero/.machine_readable/svc/k9/README.adoc b/absolute-zero/.machine_readable/svc/k9/README.adoc new file mode 100644 index 0000000..657168a --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/README.adoc @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: MPL-2.0 += K9 Contractiles +:toc: left +:icons: font + +== What Are K9 Contractiles? + +K9 contractiles are self-validating components that combine configuration, validation, and deployment logic in a single file format. They implement the RSR principle of "self-describing artifacts" by embedding contracts and orchestration directly in the component. + +== The Three Security Levels + +K9 components declare their trust requirements using "The Leash" security model: + +[horizontal] +`'Kennel`:: Pure data, no execution (safest) +`'Yard`:: Nickel evaluation with contracts (medium trust) +`'Hunt`:: Full execution with Just recipes (requires signature) + +== Example Components + +This directory contains example K9 contractiles for common repository tasks: + +=== Kennel Level (Pure Data) + +**File:** `examples/project-metadata.k9.ncl` + +Pure configuration data with no execution. Safe to include in any repository. + +**Use cases:** +- Project metadata (name, version, description) +- Build configuration +- Tool settings +- Data schemas + +**Security:** No signature required, data-only. + +=== Yard Level (Validated Config) + +**File:** `examples/ci-config.k9.ncl` + +Configuration with Nickel contracts for runtime validation. Evaluated safely without I/O. + +**Use cases:** +- CI/CD configuration with validation +- Deployment parameters +- Database schemas with constraints +- API specifications + +**Security:** Signature recommended, Nickel evaluation only. + +=== Hunt Level (Full Execution) + +**File:** `examples/setup-repo.k9.ncl` + +Full execution with Just recipes. Can run shell commands and modify filesystem. + +**Use cases:** +- Repository setup scripts +- Deployment automation +- System configuration +- Package installation + +**Security:** **Signature required**, full system access. + +== Usage in Your Repository + +=== 1. Create K9 Components + +Choose the appropriate security level for your use case: + +[source,bash] +---- +# Kennel: Pure configuration +cp contractiles/k9/examples/project-metadata.k9.ncl config/metadata.k9.ncl + +# Yard: Validated configuration +cp contractiles/k9/examples/ci-config.k9.ncl .github/ci.k9.ncl + +# Hunt: Full automation +cp contractiles/k9/examples/setup-repo.k9.ncl scripts/setup.k9.ncl +---- + +=== 2. Validate Components + +[source,bash] +---- +# Validate Nickel syntax and contracts +nickel typecheck config/metadata.k9.ncl + +# Verify Hunt-level signature (if signed) +./must verify scripts/setup.k9.ncl +---- + +=== 3. Execute Components + +[source,bash] +---- +# Kennel: Export as JSON +nickel export config/metadata.k9.ncl > metadata.json + +# Yard: Evaluate with validation +nickel eval .github/ci.k9.ncl + +# Hunt: Run with Just (dry-run first!) +./must --dry-run run scripts/setup.k9.ncl +./must run scripts/setup.k9.ncl +---- + +== Integration with RSR + +K9 contractiles integrate with other RSR standards: + +**STATE.scm**:: K9 components can generate or validate STATE.scm +**ECOSYSTEM.scm**:: K9 can automate cross-repo operations +**META.scm**:: K9 can enforce architectural decisions + +== Security Best Practices + +=== For Kennel/Yard Components + +✅ **Safe to use without signatures** + +✅ **Review Nickel code before use** + +✅ **Validate contracts match expectations** + +=== For Hunt Components + +⚠️ **ALWAYS verify signatures** + +⚠️ **Review Just recipes carefully** + +⚠️ **Run dry-run mode first** + +⚠️ **Never run as root unless required** + +⚠️ **Sandbox external components** + +**See:** https://github.com/hyperpolymath/k9-svc/blob/main/docs/SECURITY-BEST-PRACTICES.adoc + +== Template Files + +Use these as starting points for your own K9 components: + +- `template-kennel.k9.ncl` - Pure data template +- `template-yard.k9.ncl` - Validated config template +- `template-hunt.k9.ncl` - Full execution template + +== Dependencies + +To use K9 contractiles in your repository: + +[source,bash] +---- +# Install Nickel (configuration language) +curl -L https://github.com/tweag/nickel/releases/latest/download/nickel-linux-x86_64 -o nickel +chmod +x nickel && sudo mv nickel /usr/local/bin/ + +# Install Just (task runner, for Hunt level) +cargo install just + +# Clone K9-SVC (for must shim and tooling) +git clone https://github.com/hyperpolymath/k9-svc.git +---- + +== Learn More + +- **K9-SVC Specification:** https://github.com/hyperpolymath/k9-svc/blob/main/SPEC.adoc +- **K9 User Guide:** https://github.com/hyperpolymath/k9-svc/blob/main/GUIDE.adoc +- **Security Documentation:** https://github.com/hyperpolymath/k9-svc/blob/main/docs/SECURITY-FAQ.adoc +- **IANA Media Type:** `application/vnd.k9+nickel` + +== Contributing + +When adding K9 contractiles to your repository: + +1. Use appropriate security level (Kennel > Yard > Hunt) +2. Document what each component does +3. Include validation contracts in Yard/Hunt components +4. Sign Hunt-level components before committing +5. Add K9 validation to CI/CD pipeline + +**Questions?** Open an issue on https://github.com/hyperpolymath/k9-svc diff --git a/absolute-zero/.machine_readable/svc/k9/examples/ci-config.k9.ncl b/absolute-zero/.machine_readable/svc/k9/examples/ci-config.k9.ncl new file mode 100644 index 0000000..4889743 --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/examples/ci-config.k9.ncl @@ -0,0 +1,126 @@ +K9! +# SPDX-License-Identifier: MPL-2.0 +# Example Yard-level K9 component: CI/CD configuration with validation +# Security Level: Yard (Nickel evaluation, contract validation) +# Signature recommended but not required + +{ + pedigree = { + schema_version = "1.0.0", + component_type = "ci-configuration", + security = { + leash = 'Yard, + trust_level = "validated-config", + allow_network = false, + allow_filesystem_write = false, + allow_subprocess = false, + }, + metadata = { + name = "ci-config", + version = "1.0.0", + description = "CI/CD configuration with runtime validation", + author = "Jonathan D.A. Jewell ", + }, + }, + + # CI/CD configuration with Nickel contracts + ci = { + # Platform must be a known CI provider + platform + | [| 'GitHubActions, 'GitLabCI, 'CircleCI, 'TravisCI |] + = 'GitHubActions, + + # Build matrix with validation + matrix = { + # Operating systems to test on + os + | Array String + | std.array.NonEmpty + = ["ubuntu-latest", "macos-latest"], + + # Language versions to test + versions + | Array String + | std.array.NonEmpty + = ["stable", "beta"], + }, + + # Workflow steps with validation + steps = [ + { + name = "Checkout", + action = "actions/checkout@v4", + # Version must be SHA-pinned for security + sha | String | std.string.NonEmpty = "b4ffde65f46336ab88eb53be808477a3936bae11", + }, + { + name = "Build", + run = "just build", + }, + { + name = "Test", + run = "just test", + }, + { + name = "Lint", + run = "just lint", + }, + ], + + # Deployment configuration + deploy = { + enabled | Bool = false, + + # Only deploy from main branch + branch + | String + | std.contract.from_predicate (fun b => b == "main" || b == "master") + = "main", + + # Deployment requires manual approval + requires_approval | Bool = true, + }, + + # Security scanning + security = { + enabled | Bool = true, + + scanners = [ + { + name = "CodeQL", + languages = ["rust", "javascript"], + }, + { + name = "OSSF Scorecard", + enabled = true, + }, + { + name = "TruffleHog", + scan_for = "secrets", + }, + ], + }, + + # Notification settings + notifications = { + on_success = "never", + on_failure = "always", + channels = ["email"], + }, + }, + + # Validation rules (enforced by Nickel) + validation = { + # At least one OS must be specified + check_os = std.array.length ci.matrix.os > 0, + + # At least one version must be tested + check_versions = std.array.length ci.matrix.versions > 0, + + # Must have at least build and test steps + check_steps = std.array.length ci.steps >= 2, + + # Security scanning must be enabled + check_security = ci.security.enabled == true, + }, +} diff --git a/absolute-zero/.machine_readable/svc/k9/examples/project-metadata.k9.ncl b/absolute-zero/.machine_readable/svc/k9/examples/project-metadata.k9.ncl new file mode 100644 index 0000000..5227fb5 --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/examples/project-metadata.k9.ncl @@ -0,0 +1,57 @@ +K9! +# SPDX-License-Identifier: MPL-2.0 +# Example Kennel-level K9 component: Project metadata +# Security Level: Kennel (pure data, no execution) +# No signature required + +{ + pedigree = { + schema_version = "1.0.0", + component_type = "project-metadata", + security = { + leash = 'Kennel, + trust_level = "data-only", + allow_network = false, + allow_filesystem_write = false, + allow_subprocess = false, + }, + metadata = { + name = "project-metadata", + version = "1.0.0", + description = "Pure data configuration for project metadata", + author = "Jonathan D.A. Jewell ", + }, + }, + + # Project configuration + project = { + name = "my-project", + version = "0.1.0", + description = "A project following Rhodium Standard Repositories", + + repository = { + url = "https://github.com/hyperpolymath/my-project", + type = "git", + }, + + author = { + name = "Jonathan D.A. Jewell", + email = "jonathan.jewell@open.ac.uk", + organization = "The Open University", + }, + + license = "MPL-2.0", + + keywords = [ + "rhodium-standard", + "rsr", + "hyperpolymath", + ], + }, + + # Export as JSON for other tools + export = { + format = "json", + destination = "project-metadata.json", + }, +} diff --git a/absolute-zero/.machine_readable/svc/k9/examples/setup-repo.k9.ncl b/absolute-zero/.machine_readable/svc/k9/examples/setup-repo.k9.ncl new file mode 100644 index 0000000..bcc51ce --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/examples/setup-repo.k9.ncl @@ -0,0 +1,167 @@ +K9! +# SPDX-License-Identifier: MPL-2.0 +# Example Hunt-level K9 component: Repository setup automation +# Security Level: Hunt (full execution with Just recipes) +# ⚠️ SIGNATURE REQUIRED - DO NOT RUN WITHOUT VERIFICATION + +{ + pedigree = { + schema_version = "1.0.0", + component_type = "repository-setup", + security = { + leash = 'Hunt, + trust_level = "full-system-access", + allow_network = true, + allow_filesystem_write = true, + allow_subprocess = true, + signature_required = true, + }, + metadata = { + name = "setup-repo", + version = "1.0.0", + description = "Automated repository setup with RSR standards", + author = "Jonathan D.A. Jewell ", + }, + warnings = [ + "This component has full system access", + "Only run from trusted sources with verified signatures", + "Review Just recipes before execution", + "Use dry-run mode first: ./must --dry-run run setup-repo.k9.ncl", + ], + }, + + # Configuration with contracts + config = { + repo_name + | String + | std.string.NonEmpty + = "my-new-repo", + + repo_type + | [| 'Library, 'Application, 'Tool, 'Specification |] + = 'Application, + + primary_language + | String + | std.string.NonEmpty + = "rust", + + # RSR compliance features to enable + features = { + checkpoint_files | Bool = true, # STATE.scm, ECOSYSTEM.scm, META.scm + security_workflows | Bool = true, # CodeQL, Scorecard, etc. + quality_checks | Bool = true, # Linting, formatting + mirroring | Bool = false, # GitLab/Bitbucket mirrors + }, + + # Git configuration + git = { + default_branch = "main", + initial_commit | Bool = true, + remote_url | String = "", + }, + }, + + # Just recipes for execution + # These run when: ./must run setup-repo.k9.ncl + recipes = { + # Main entry point + default = { + recipe = "setup", + description = "Set up RSR-compliant repository", + }, + + # Individual setup tasks + setup = { + dependencies = ["check-env", "create-structure", "init-git", "setup-workflows"], + commands = [ + "echo '✅ Repository setup complete!'", + "echo 'Run: git status to see changes'", + ], + }, + + "check-env" = { + description = "Verify required tools are installed", + commands = [ + "command -v git || (echo 'ERROR: git not found' && exit 1)", + "command -v just || (echo 'ERROR: just not found' && exit 1)", + "command -v nickel || (echo 'ERROR: nickel not found' && exit 1)", + "echo '✓ All required tools present'", + ], + }, + + "create-structure" = { + description = "Create RSR directory structure", + commands = [ + "mkdir -p src/ docs/ tests/ scripts/", + "mkdir -p .github/workflows/", + "mkdir -p contractiles/k9/", + "echo '✓ Directory structure created'", + ], + }, + + "init-git" = { + description = "Initialize Git repository", + commands = [ + "git init -b %{config.git.default_branch}", + "git config user.name 'Jonathan D.A. Jewell'", + "git config user.email 'jonathan.jewell@open.ac.uk'", + "echo '✓ Git initialized'", + ], + }, + + "setup-workflows" = { + description = "Add RSR-compliant workflows", + commands = [ + # This would copy workflow templates + # In a real implementation, would fetch from rsr-template-repo + "echo '✓ Workflows configured'", + ], + }, + + "create-checkpoint-files" = { + description = "Create STATE.scm, ECOSYSTEM.scm, META.scm", + commands = [ + "echo '(state (version \"1.0.0\") (project \"%{config.repo_name}\"))' > STATE.scm", + "echo '(ecosystem (version \"1.0.0\") (name \"%{config.repo_name}\"))' > ECOSYSTEM.scm", + "echo '(meta (version \"1.0.0\") (project \"%{config.repo_name}\"))' > META.scm", + "echo '✓ Checkpoint files created'", + ], + }, + + "add-license" = { + description = "Add MPL-2.0 license", + commands = [ + "curl -sL https://raw.githubusercontent.com/hyperpolymath/pmpl/main/LICENSE -o LICENSE", + "echo '✓ License added'", + ], + }, + + "add-readme" = { + description = "Create README.adoc from template", + commands = [ + "echo '= %{config.repo_name}' > README.adoc", + "echo '' >> README.adoc", + "echo 'Part of the Hyperpolymath ecosystem.' >> README.adoc", + "echo '✓ README created'", + ], + }, + + clean = { + description = "Remove generated files (careful!)", + commands = [ + "echo '⚠️ This will delete all generated files'", + "echo 'Press Ctrl+C to cancel, or wait 5 seconds...'", + "sleep 5", + "rm -f STATE.scm ECOSYSTEM.scm META.scm", + "echo '✓ Cleaned'", + ], + }, + }, + + # Validation (Yard-level checks before Hunt execution) + validation = { + check_repo_name = std.string.length config.repo_name > 0, + check_language = std.string.length config.primary_language > 0, + }, +} diff --git a/absolute-zero/.machine_readable/svc/k9/template-hunt.k9.ncl b/absolute-zero/.machine_readable/svc/k9/template-hunt.k9.ncl new file mode 100644 index 0000000..39b4efb --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/template-hunt.k9.ncl @@ -0,0 +1,136 @@ +K9! +# SPDX-License-Identifier: MPL-2.0 +# K9 Hunt-level template: Full execution with Just recipes +# Security Level: Hunt (full system access) +# ⚠️ SIGNATURE REQUIRED - Review carefully before use + +{ + pedigree = { + schema_version = "1.0.0", + component_type = "TODO: describe component type (e.g., 'deployment', 'setup-script')", + security = { + leash = 'Hunt, + trust_level = "full-system-access", + allow_network = true, + allow_filesystem_write = true, + allow_subprocess = true, + signature_required = true, + }, + metadata = { + name = "TODO: component-name", + version = "1.0.0", + description = "TODO: Detailed description of what this component does", + author = "Jonathan D.A. Jewell ", + }, + warnings = [ + "This component has full system access", + "Only run from trusted sources with verified signatures", + "Review all Just recipes before execution", + "Use dry-run mode first: ./must --dry-run run your-file.k9.ncl", + ], + side_effects = [ + "TODO: List what files/directories this creates or modifies", + "TODO: List what commands this executes", + "TODO: List what network access this requires", + ], + }, + + # Configuration with contracts (Yard-level validation) + config = { + # Add your configuration here with appropriate contracts + target_dir + | String + | std.string.NonEmpty + = "/tmp/k9-output", + + dry_run | Bool = false, + + # Add more config as needed + }, + + # Just recipes for execution + # These run when: ./must run your-file.k9.ncl + recipes = { + # Main entry point (runs by default) + default = { + recipe = "TODO: main-task", + description = "TODO: What the default recipe does", + }, + + # Define your recipes here + "main-task" = { + dependencies = ["check-prerequisites"], + commands = [ + "echo 'TODO: Add your commands here'", + # Example: Create directory + # "mkdir -p %{config.target_dir}", + # Example: Run a command + # "just build", + # Example: Conditional execution + # "@if [ \"%{config.dry_run}\" = \"true\" ]; then echo '[DRY-RUN] Would execute'; else actual-command; fi", + ], + }, + + "check-prerequisites" = { + description = "Verify required tools and permissions", + commands = [ + # Example: Check for required tools + # "command -v git || (echo 'ERROR: git not found' && exit 1)", + # Example: Check permissions + # "[ -w %{config.target_dir} ] || (echo 'ERROR: Cannot write to target directory' && exit 1)", + "echo '✓ Prerequisites checked'", + ], + }, + + # Add more recipes as needed + "build" = { + description = "Build the project", + commands = [ + "echo 'TODO: Add build commands'", + ], + }, + + "deploy" = { + description = "Deploy the application", + dependencies = ["build"], + commands = [ + "echo 'TODO: Add deployment commands'", + ], + }, + + "clean" = { + description = "Clean up generated files", + commands = [ + "echo '⚠️ This will delete files - waiting 3 seconds...'", + "sleep 3", + "echo 'TODO: Add cleanup commands'", + # "rm -rf %{config.target_dir}", + ], + }, + }, + + # Validation (Yard-level checks before Hunt execution) + validation = { + check_target_dir = std.string.length config.target_dir > 0, + # Add more validation as needed + }, +} + +# Usage: +# 1. Fill in TODO items above +# 2. Define configuration with contracts +# 3. Implement Just recipes with your commands +# 4. Test with dry-run: ./must --dry-run run your-file.k9.ncl +# 5. Review dry-run output carefully +# 6. Sign the component: ./must sign your-file.k9.ncl +# 7. Distribute with signature: your-file.k9.ncl.sig +# 8. Users verify and run: ./must verify && ./must run your-file.k9.ncl +# +# Security checklist: +# ✓ All TODO items filled in +# ✓ side_effects documented accurately +# ✓ Commands reviewed for safety +# ✓ No hardcoded secrets or credentials +# ✓ Proper error handling in recipes +# ✓ Tested in dry-run mode +# ✓ Component signed with trusted key diff --git a/absolute-zero/.machine_readable/svc/k9/template-kennel.k9.ncl b/absolute-zero/.machine_readable/svc/k9/template-kennel.k9.ncl new file mode 100644 index 0000000..eff35e1 --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/template-kennel.k9.ncl @@ -0,0 +1,54 @@ +K9! +# SPDX-License-Identifier: MPL-2.0 +# K9 Kennel-level template: Pure data configuration +# Security Level: Kennel (data-only, no execution) +# No signature required - safe for any use + +{ + pedigree = { + schema_version = "1.0.0", + component_type = "TODO: describe component type (e.g., 'build-config', 'metadata')", + security = { + leash = 'Kennel, + trust_level = "data-only", + allow_network = false, + allow_filesystem_write = false, + allow_subprocess = false, + }, + metadata = { + name = "TODO: component-name", + version = "1.0.0", + description = "TODO: Brief description of what this component contains", + author = "Jonathan D.A. Jewell ", + }, + }, + + # Your configuration data here + config = { + # Example: Pure data values + setting_1 = "value", + setting_2 = 42, + setting_3 = true, + + nested = { + key = "value", + }, + + list = [ + "item1", + "item2", + ], + }, + + # Optional: Export format specification + export = { + format = "json", # or "yaml", "toml" + destination = "output.json", + }, +} + +# Usage: +# 1. Fill in TODO items above +# 2. Add your configuration data to config = { ... } +# 3. Validate: nickel typecheck your-file.k9.ncl +# 4. Export: nickel export your-file.k9.ncl > output.json diff --git a/absolute-zero/.machine_readable/svc/k9/template-yard.k9.ncl b/absolute-zero/.machine_readable/svc/k9/template-yard.k9.ncl new file mode 100644 index 0000000..7115522 --- /dev/null +++ b/absolute-zero/.machine_readable/svc/k9/template-yard.k9.ncl @@ -0,0 +1,84 @@ +K9! +# SPDX-License-Identifier: MPL-2.0 +# K9 Yard-level template: Configuration with validation +# Security Level: Yard (Nickel evaluation with contracts) +# Signature recommended but not required + +{ + pedigree = { + schema_version = "1.0.0", + component_type = "TODO: describe component type (e.g., 'validated-config', 'schema')", + security = { + leash = 'Yard, + trust_level = "validated-config", + allow_network = false, + allow_filesystem_write = false, + allow_subprocess = false, + }, + metadata = { + name = "TODO: component-name", + version = "1.0.0", + description = "TODO: Brief description with validation details", + author = "Jonathan D.A. Jewell ", + }, + }, + + # Configuration with Nickel contracts for validation + config = { + # Example: String that cannot be empty + name + | String + | std.string.NonEmpty + = "TODO: default value", + + # Example: Number with range constraint + port + | Number + | std.contract.from_predicate (fun p => p > 0 && p < 65536) + = 8080, + + # Example: Boolean flag + enabled | Bool = true, + + # Example: Enum (one of several values) + environment + | [| 'Development, 'Staging, 'Production |] + = 'Development, + + # Example: List with non-empty constraint + items + | Array String + | std.array.NonEmpty + = ["item1", "item2"], + + # Example: Nested object with contracts + database = { + host | String | std.string.NonEmpty = "localhost", + port | Number | std.contract.from_predicate (fun p => p > 0 && p < 65536) = 5432, + name | String | std.string.NonEmpty = "mydb", + }, + }, + + # Validation rules (additional cross-field checks) + validation = { + # Example: Check that at least one item exists + check_items = std.array.length config.items > 0, + + # Example: Check that production has secure settings + check_production = + if config.environment == 'Production then + config.enabled == true + else + true, + + # Add your custom validation rules here + }, +} + +# Usage: +# 1. Fill in TODO items above +# 2. Define your config with appropriate contracts +# 3. Add validation rules in validation = { ... } +# 4. Validate: nickel typecheck your-file.k9.ncl +# 5. Evaluate: nickel eval your-file.k9.ncl +# 6. If validation passes, use in your application diff --git a/absolute-zero/.well-known/ai.txt b/absolute-zero/.well-known/ai.txt new file mode 100644 index 0000000..bf4b952 --- /dev/null +++ b/absolute-zero/.well-known/ai.txt @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: PMPL-1.0-or-later +# AI agent discovery file for absolute-zero +# See: https://github.com/hyperpolymath/absolute-zero/blob/main/0-AI-MANIFEST.a2ml + +User-Agent: * +Manifest: /0-AI-MANIFEST.a2ml +EntryPoint: /docs/CLAUDE.adoc +State: /.machine_readable/6a2/STATE.a2ml +Roadmap: /ROADMAP.adoc +Allow: training-with-attribution +Allow: documentation-summarisation +Disallow: closed-source-redistribution +License: PMPL-1.0-or-later +Contact: developer@joshuajewell.dev diff --git a/absolute-zero/.well-known/humans.txt b/absolute-zero/.well-known/humans.txt new file mode 100644 index 0000000..3fab06b --- /dev/null +++ b/absolute-zero/.well-known/humans.txt @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: PMPL-1.0-or-later +# humanstxt.org + +/* TEAM */ +Maintainer: Jonathan D. A. Jewell +Contact: developer @ joshuajewell.dev +Site: https://github.com/hyperpolymath/absolute-zero + +/* THANKS */ +Contributors: see git log + docs/MAINTAINERS.adoc + +/* SITE */ +Last update: 2026-05-25 +Standards: PMPL-1.0-or-later, RSR (Rhodium Standard Repository) compliant +Components: Coq, Lean 4, Z3, Agda, Isabelle, Mizar, Idris2, ReScript, Rust diff --git a/absolute-zero/.well-known/security.txt b/absolute-zero/.well-known/security.txt new file mode 100644 index 0000000..96e01fa --- /dev/null +++ b/absolute-zero/.well-known/security.txt @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: PMPL-1.0-or-later +Contact: https://github.com/hyperpolymath/absolute-zero/security/advisories/new +Expires: 2027-05-25T00:00:00Z +Preferred-Languages: en +Canonical: https://github.com/hyperpolymath/absolute-zero/.well-known/security.txt +Policy: https://github.com/hyperpolymath/absolute-zero/blob/main/SECURITY.md diff --git a/absolute-zero/0-AI-MANIFEST.a2ml b/absolute-zero/0-AI-MANIFEST.a2ml new file mode 100644 index 0000000..e035312 --- /dev/null +++ b/absolute-zero/0-AI-MANIFEST.a2ml @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: PMPL-1.0-or-later +# 0-AI-MANIFEST.a2ml — Absolute Zero AI assistant manifest +# Schema: a2ml v1.0 +# Supersedes legacy AI.a2ml + AI.djot (deleted in repo tidy 2026-05-25) + +[metadata] +project = "absolute-zero" +repo = "github.com/hyperpolymath/absolute-zero" +manifest-version = "1.0" +last-updated = "2026-05-25" + +[scope] +purpose = """ + Formal verification of Certified Null Operations (CNOs) across multiple + proof systems (Coq, Lean 4, Z3, Agda, Isabelle, Mizar) plus an Idris2 + ABI surface for FFI. +""" + +[entry-points] +# Where an AI agent should look first. +root-context = "docs/CLAUDE.adoc" +project-state = ".machine_readable/6a2/STATE.a2ml" +roadmap = "ROADMAP.adoc" +contributing = "CONTRIBUTING.adoc" +audit-trail = "AUDIT.adoc" +rsr-status = "RSR_COMPLIANCE.adoc" + +[machine-readable] +# Authoritative metadata artefacts; .a2ml format under 6a2/ supersedes +# the older Guile-Scheme .scm format. Both kept side-by-side during the +# migration window for legacy tooling compatibility. +state = ".machine_readable/6a2/STATE.a2ml" +meta = ".machine_readable/6a2/META.a2ml" +ecosystem = ".machine_readable/6a2/ECOSYSTEM.a2ml" +agentic = ".machine_readable/6a2/AGENTIC.a2ml" +neurosym = ".machine_readable/6a2/NEUROSYM.a2ml" +playbook = ".machine_readable/6a2/PLAYBOOK.a2ml" + +legacy-scm-meta = ".machine_readable/META.scm" +legacy-scm-ecosystem = ".machine_readable/ECOSYSTEM.scm" +legacy-scm-agentic = ".machine_readable/AGENTIC.scm" +legacy-scm-neurosym = ".machine_readable/NEUROSYM.scm" +legacy-scm-playbook = ".machine_readable/PLAYBOOK.scm" + +[language-policy] +# Single source of truth lives in docs/CLAUDE.adoc + .github/workflows/language-policy.yml. +# Summary: +allowed = ["ReScript", "Deno", "Rust", "Tauri", "Dioxus", "Gleam", "Bash", "JavaScript (limited)", "Nickel", "Guile Scheme", "Julia", "OCaml", "Ada", "Idris2"] +banned = ["TypeScript", "Node.js", "npm", "Bun", "pnpm", "yarn", "Go", "Python", "Java", "Kotlin", "Swift", "React Native", "Flutter", "Dart", "Ruby", "Perl"] +reference = "docs/CLAUDE.adoc#language-policy" + +[echidna-protocol] +# All ECHIDNA invocations route through the echidna-llm-mcp BoJ cartridge. +# Never call ECHIDNA directly. +gateway = "boj-server/cartridges/echidna-llm-mcp" +docs = "docs/archive/ECHIDNA-2025-11-22.adoc" +tools = [ + "echidna_list_provers", + "echidna_prove", + "echidna_verify", + "echidna_verify_raw", + "echidna_suggest", + "echidna_suggest_tactics", + "echidna_search", + "echidna_session_create", +] + +[delivery] +commit-policy = "conventional commits; never amend published commits" +state-update = "update .machine_readable/6a2/STATE.a2ml whenever phase/progress changes" +adr-tracking = "architectural changes recorded in .machine_readable/META.scm `architecture-decisions`" diff --git a/absolute-zero/AUDIT.adoc b/absolute-zero/AUDIT.adoc new file mode 100644 index 0000000..5fb82ba --- /dev/null +++ b/absolute-zero/AUDIT.adoc @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: MPL-2.0 += Absolute Zero — Audit Trail +Jonathan D. A. Jewell +:toc: +:sectnums: + +== Purpose + +Estate-wide audit log for absolute-zero. Records all axiom/postulate +discharges, unsoundness findings, deletions of dead code, license +audits, and other trust-boundary events. + +For architectural decisions (which are forward-looking design choices +rather than backward-looking audit events), see +`.machine_readable/META.scm` `architecture-decisions`. + +== Open Audit Items + +|=== +|ID |Date filed |Severity |Description |Issue + +|AUDIT-2026-05-20-A +|2026-05-20 +|Medium +|`src/abi/Types.idr` has 5 pre-existing errors blocking Idris2 0.8.0 + typecheck (missing `Decidable.Equality` import; `%runElab` without + `ElabReflection`; `MkStateHandle ptr` doesn't supply the `nonNull` + auto-proof; `No absurd` lacks `Uninhabited` instances). +|TBD (separate from #27) + +|=== + +== Resolved Audit Items + +|=== +|ID |Date resolved |Description |Resolution commit + +|AUDIT-2026-05-20-B +|2026-05-26 +|`.github/workflows/cflite_pr.yml` missing `actions/checkout` before + `build_fuzzers`. Added explicit checkout step pinned to v6.0.2 SHA. +|PR #41 follow-up + +|AUDIT-2026-05-20-#27 +|2026-05-25 +|Unsound `alignmentMatchesPlatformWord` postulate (Idris2). The + universal-quantification claim could derive `So (1 mod 8 == 0)` from + the file's own `CNOResultLayout.alignment` since `HasAlignment t n` + carries no evidence about `n`. Companion `alignedSizeCorrect` + postulate isolated into shared `Proofs/DivMod.idr` for + cross-estate incremental discharge. +|aac48b7, f0f9b8f, d2853ca (PR #41 / merged via #40) + +|AUDIT-2026-05-20-#24 +|2026-05-20 +|`eval_deterministic` discharged from Axiom → Theorem via + `step_deterministic_strong` helper. First post-T0 axiom audit win. +|PR #24 (see META.scm ADR-007) + +|AUDIT-2026-05-20-#32 +|2026-05-20 +|Deleted unsound `eval_respects_state_eq_{left,right}` axioms; + weakened `logically_reversible` to observational reversibility + (`=st=`); re-proved `cno_eval_on_equal_states` + + `cno_logically_reversible` via `cno_terminates` + + `cno_preserves_state`. +|PR #32 (see META.scm ADR-008) + +|AUDIT-2026-02-05 +|2026-02-05 +|License canonicalisation across the estate to PMPL-1.0-or-later + (79 files updated). Pre-existing AGPL references reconciled. +|see docs/archive/LICENSE-AUDIT-2026-02-05.adoc +|=== + +== Audit categorisation + +Audit IDs follow `AUDIT--`: + +* PR-numbered IDs map directly to GitHub PRs that close the item. +* Seq-numbered IDs (A, B, C…) are pre-PR findings that still need a + tracking issue or PR. + +== See also + +* `.machine_readable/META.scm` — forward-looking architecture decisions (ADR-001…N) +* `docs/archive/` — historical session / audit artefacts (dated) +* `RSR_COMPLIANCE.adoc` — Rhodium Standard Repository compliance status diff --git a/absolute-zero/CHANGELOG.md b/absolute-zero/CHANGELOG.md new file mode 100644 index 0000000..20ca61e --- /dev/null +++ b/absolute-zero/CHANGELOG.md @@ -0,0 +1,58 @@ + + +# Changelog + +All notable changes to `absolute-zero` will be documented in this file. + +This file is generated from conventional commits by the +[`changelog-reusable.yml`](https://github.com/hyperpolymath/standards/blob/main/.github/workflows/changelog-reusable.yml) +workflow (`hyperpolymath/standards#206`). Adopt the workflow in this repo's CI to keep this file in sync automatically — see +[`templates/cliff.toml`](https://github.com/hyperpolymath/standards/blob/main/templates/cliff.toml) +for the canonical config. + +The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); +this project aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- feat(absolute-zero): complete loadStore_preserves_memory proof — no sorry + +### Fixed + +- fix(baseline): repair main + estate-policy sweep (unblocks #41) (#42) +- fix(governance): enumerate banned-language demos in .hypatia-ignore (#44) +- fix(coq/cno): drop cno_decidable axiom (Rice's theorem territory) (#36) +- fix(licence): canonicalise to PMPL-1.0-or-later per authorship check (#133) (#34) +- fix(lean4/cno): finish loadStore_preserves_memory cons-case build (#28) +- fix(lean4/cno): finish loadStore_preserves_memory cons-case build (#23) +- fix(licence): canonicalise to PMPL-1.0-or-later per authorship check (#133) (#22) +- fix(licence): clear scaffold-placeholder leak (isolated; dirty repo) (#20) +- fix(ci): sync hypatia-scan.yml to canonical (413: env.HOME+Phase-2+SARIF) (#18) +- fix(ci): adopt canonical hypatia-scan.yml (env.HOME/scanner-layout + Comment-step gate) (#16) + +### Documentation + +- docs: Phase 1 per-axiom triage of 72 Coq Axioms (#58) +- docs: seed docs/proof-debt.md per trusted-base policy (#52) +- docs: record tech-debt audit findings (2026-05-26) (#47) + +### CI + +- ci(rust): convert rust-ci.yml to thin wrapper (standards#174 refile) (#53) +- ci: bump actions/upload-artifact SHA to current v4 (#12) +- ci(secret-scanner): drop duplicate --fail from trufflehog extra_args (#11) +- ci: fix workflow-linter YAML parse error + self-flag bug +- ci(antipattern): fix top-level dir matching + benchmarks/lsp/bench filename allowlists (#9) + +## Pre-history + +Prior commits to this file's introduction are recorded in git history but not formally classified into Keep-a-Changelog sections. To backfill, run `git cliff -o CHANGELOG.md` locally using the canonical [`cliff.toml`](https://github.com/hyperpolymath/standards/blob/main/templates/cliff.toml) — this is one-shot mechanical work. + +--- + + diff --git a/absolute-zero/CODE_OF_CONDUCT.md b/absolute-zero/CODE_OF_CONDUCT.md index 1f1548c..efde91a 100644 --- a/absolute-zero/CODE_OF_CONDUCT.md +++ b/absolute-zero/CODE_OF_CONDUCT.md @@ -1,4 +1,4 @@ - + # Contributor Covenant Code of Conduct ## Our Pledge diff --git a/absolute-zero/CONTRIBUTING.adoc b/absolute-zero/CONTRIBUTING.adoc index a0f2f54..1f34e60 100644 --- a/absolute-zero/CONTRIBUTING.adoc +++ b/absolute-zero/CONTRIBUTING.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0-or-later +// SPDX-License-Identifier: MPL-2.0 = Contributing Guide == Getting Started diff --git a/absolute-zero/CONTRIBUTING.md b/absolute-zero/CONTRIBUTING.md deleted file mode 100644 index b6a6c0a..0000000 --- a/absolute-zero/CONTRIBUTING.md +++ /dev/null @@ -1,116 +0,0 @@ -# Clone the repository -git clone https://github/hyperpolymath/maa-framework.git -cd maa-framework - -# Using Nix (recommended for reproducibility) -nix develop - -# Or using toolbox/distrobox -toolbox create maa-framework-dev -toolbox enter maa-framework-dev -# Install dependencies manually - -# Verify setup -just check # or: cargo check / mix compile / etc. -just test # Run test suite -``` - -### Repository Structure -``` -maa-framework/ -├── src/ # Source code (Perimeter 1-2) -├── lib/ # Library code (Perimeter 1-2) -├── extensions/ # Extensions (Perimeter 2) -├── plugins/ # Plugins (Perimeter 2) -├── tools/ # Tooling (Perimeter 2) -├── docs/ # Documentation (Perimeter 3) -│ ├── architecture/ # ADRs, specs (Perimeter 2) -│ └── proposals/ # RFCs (Perimeter 3) -├── examples/ # Examples (Perimeter 3) -├── spec/ # Spec tests (Perimeter 3) -├── tests/ # Test suite (Perimeter 2-3) -├── .well-known/ # Protocol files (Perimeter 1-3) -├── .github/ # GitHub config (Perimeter 1) -│ ├── ISSUE_TEMPLATE/ -│ └── workflows/ -├── CHANGELOG.md -├── CODE_OF_CONDUCT.md -├── CONTRIBUTING.md # This file -├── GOVERNANCE.md -├── LICENSE -├── MAINTAINERS.md -├── README.adoc -├── SECURITY.md -├── flake.nix # Nix flake (Perimeter 1) -└── Justfile # Task runner (Perimeter 1) -``` - ---- - -## How to Contribute - -### Reporting Bugs - -**Before reporting**: -1. Search existing issues -2. Check if it's already fixed in `main` -3. Determine which perimeter the bug affects - -**When reporting**: - -Use the [bug report template](.github/ISSUE_TEMPLATE/bug_report.md) and include: - -- Clear, descriptive title -- Environment details (OS, versions, toolchain) -- Steps to reproduce -- Expected vs actual behaviour -- Logs, screenshots, or minimal reproduction - -### Suggesting Features - -**Before suggesting**: -1. Check the [roadmap](ROADMAP.md) if available -2. Search existing issues and discussions -3. Consider which perimeter the feature belongs to - -**When suggesting**: - -Use the [feature request template](.github/ISSUE_TEMPLATE/feature_request.md) and include: - -- Problem statement (what pain point does this solve?) -- Proposed solution -- Alternatives considered -- Which perimeter this affects - -### Your First Contribution - -Look for issues labelled: - -- [`good first issue`](https://github/hyperpolymath/maa-framework/labels/good%20first%20issue) — Simple Perimeter 3 tasks -- [`help wanted`](https://github/hyperpolymath/maa-framework/labels/help%20wanted) — Community help needed -- [`documentation`](https://github/hyperpolymath/maa-framework/labels/documentation) — Docs improvements -- [`perimeter-3`](https://github/hyperpolymath/maa-framework/labels/perimeter-3) — Community sandbox scope - ---- - -## Development Workflow - -### Branch Naming -``` -docs/short-description # Documentation (P3) -test/what-added # Test additions (P3) -feat/short-description # New features (P2) -fix/issue-number-description # Bug fixes (P2) -refactor/what-changed # Code improvements (P2) -security/what-fixed # Security fixes (P1-2) -``` - -### Commit Messages - -We follow [Conventional Commits](https://www.conventionalcommits.org/): -``` -(): - -[optional body] - -[optional footer] diff --git a/absolute-zero/COORDINATION.md b/absolute-zero/COORDINATION.md deleted file mode 100644 index 325433e..0000000 --- a/absolute-zero/COORDINATION.md +++ /dev/null @@ -1,54 +0,0 @@ -# Absolute Zero: Proof Coordination Protocol - -## Project - -Formal verification of Computational Non-reversible Operation (CNO) theory across multiple computational models. - -**Languages:** Coq, Rust, Deno, Just -**License:** MPL-2.0 -**Build system:** just -**Runtime:** deno - -## Build Commands - -| Command | Description | -|---------|-------------| -| `just build` | Compile all Coq proof scripts | -| `just test` | Run all verification tests | -| `just doctor` | Run system diagnostics | -| `just audit` | Run self-audit with panic-attack | - -## INVARIANTS — Do Not Violate - -### [CRITICAL] no-admitted-proofs - -**Rule:** No `Admitted` proofs are permitted in the main branch. - -**Why:** Theoretical boundaries must be explicitly axiomatized as `Axiom` or `Parameter` with detailed mathematical justification, rather than skipped with `Admitted`. - -### [CRITICAL] rsr-compliance - -**Rule:** Deno is the standard runtime; no Node.js or npm artifacts. - -**Why:** Project-wide standard for reproducibility and security. - -### [MODERATE] proof-parity - -**Rule:** PROOF-COMPLETION-*.md must accurately reflect the state of .v files. - -**Why:** Prevents "Proof Drift" and ensures publication claims are verifiable. - -## Protected Files and Directories - -| Path | Reason | -|------|--------| -| `proofs/coq/` | Canonical Coq formalization | -| `6a2/` | A2ML metadata for agentic coordination | -| `Justfile` | Unified entry point for all operations | - -## Terminology - -Use the correct terms for this project: - -- Say **"CNO"**, NOT "reversible operation" or "reversible logic" -- Say **"Axiomatization"** for theoretical boundaries, NOT "placeholders" diff --git a/absolute-zero/Cargo.lock b/absolute-zero/Cargo.lock index 3484d80..8466f1e 100644 --- a/absolute-zero/Cargo.lock +++ b/absolute-zero/Cargo.lock @@ -5,567 +5,3 @@ version = 4 [[package]] name = "absolute-zero" version = "1.0.0" -dependencies = [ - "brainfuck-cno", - "criterion", - "whitespace-cno", -] - -[[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - -[[package]] -name = "anes" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "autocfg" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" - -[[package]] -name = "brainfuck-cno" -version = "0.1.0" - -[[package]] -name = "bumpalo" -version = "3.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" - -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half", -] - -[[package]] -name = "clap" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351" -dependencies = [ - "clap_builder", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstyle", - "clap_lex", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "criterion" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" -dependencies = [ - "anes", - "cast", - "ciborium", - "clap", - "criterion-plot", - "is-terminal", - "itertools", - "num-traits", - "once_cell", - "oorandom", - "plotters", - "rayon", - "regex", - "serde", - "serde_derive", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" -dependencies = [ - "cast", - "itertools", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "either" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" - -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "cfg-if", - "crunchy", - "zerocopy", -] - -[[package]] -name = "hermit-abi" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" - -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys", -] - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "js-sys" -version = "0.3.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" -dependencies = [ - "once_cell", - "wasm-bindgen", -] - -[[package]] -name = "libc" -version = "0.2.184" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" - -[[package]] -name = "memchr" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "oorandom" -version = "11.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" - -[[package]] -name = "plotters" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" - -[[package]] -name = "plotters-svg" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rayon" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "regex" -version = "1.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "syn" -version = "2.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "web-sys" -version = "0.3.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "whitespace-cno" -version = "0.1.0" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "zerocopy" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zmij" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/absolute-zero/Cargo.toml b/absolute-zero/Cargo.toml index 2eb43d8..df2c265 100644 --- a/absolute-zero/Cargo.toml +++ b/absolute-zero/Cargo.toml @@ -5,27 +5,9 @@ edition = "2021" description = "Certified Null Operation - A program that does absolutely nothing" license = "MPL-2.0" -[workspace] -members = ["src/brainfuck", "src/whitespace"] - -[dependencies] -brainfuck-cno = { path = "src/brainfuck" } -whitespace-cno = { path = "src/whitespace" } - -[dev-dependencies] -criterion = { version = "0.5", features = ["html_reports"] } - -[[bench]] -name = "cno_benchmarks" -harness = false - [profile.release] opt-level = "z" lto = true codegen-units = 1 panic = "abort" strip = true - -[profile.bench] -opt-level = 3 -lto = true diff --git a/absolute-zero/ECHIDNA-NEUROSYM-INTEGRATION.adoc b/absolute-zero/ECHIDNA.adoc similarity index 99% rename from absolute-zero/ECHIDNA-NEUROSYM-INTEGRATION.adoc rename to absolute-zero/ECHIDNA.adoc index d7d8ac8..2642506 100644 --- a/absolute-zero/ECHIDNA-NEUROSYM-INTEGRATION.adoc +++ b/absolute-zero/ECHIDNA.adoc @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 = ECHIDNA Neurosymbolic Integration for Absolute Zero -Jonathan D. A. Jewell +Jonathan D. A. Jewell :toc: left :toclevels: 3 :sectnums: diff --git a/absolute-zero/ECHIDNA_MALBOLGE_REPORT.md b/absolute-zero/ECHIDNA_MALBOLGE_REPORT.md deleted file mode 100644 index 1b4bd89..0000000 --- a/absolute-zero/ECHIDNA_MALBOLGE_REPORT.md +++ /dev/null @@ -1,26 +0,0 @@ -# Echidna Learning Pass: Absolute Zero (Malbolge) Simulation Results - -## 1. Dispatch Metrics -- **Total Provers Dispatched**: 49 -- **Successes**: 3 (Determined it is NOT a CNO) -- **Failures/Timeouts**: 40 (State space explosion, non-linear arithmetic) -- **OOM (Out of Memory)**: 6 (Model Checkers) - -## 2. Key Learnings (The "Aha!" Moments) -- **Coq (ITP)**: **SUCCESS (3,400ms)**. Because the `absolute-zero` repository already contained the formal `MalbolgeCore.v` semantics, Coq was able to evaluate the string directly using the `malbolge_eval` inductive relation. It successfully proved that this program (the standard "Hello World") executes `MOut` and therefore `~ is_malbolge_CNO` is true. -- **CBMC (Bounded Model Checker)**: **SUCCESS (12,000ms)**. By unrolling the C-based interpreter loops against the fixed string input, CBMC detected the I/O system call being triggered, verifying it is not a CNO. -- **Z3 (SMT)**: **TIMEOUT**. The combination of base-3 arithmetic, dynamic self-modifying code (`encrypt` function), and the "Crazy Operation" lookup table completely shattered Z3's heuristics. It triggered a path explosion within 50 VM cycles. -- **SPIN (Model Checker)**: **OOM**. Attempting to construct the state space of a 59,049-address base-3 memory array caused the model checker to exhaust available RAM. -- **Tamarin/ProVerif**: Realized that although the code looks like encrypted ciphertext, it lacks protocol agents. Abandoned search immediately (Smart failure). - -## 3. Neural Weight Updates (Julia) -- **Hostile Architecture Recognition**: The Julia ML models (`EchidnaBuddy.jl`) learned a crucial lesson: **Do not use SAT/SMT or standard Model Checkers for highly obfuscated, self-modifying, or non-base-2 logic.** -- **Tactic Priority**: When detecting esoteric properties (base-3, self-modification), the neural network drastically increased the weights for **Interactive Theorem Provers (Coq/Lean4)** executing *definitional reflection* (running the semantics computationally rather than symbolically). -- **Early Abort**: The GNN learned to recognize the `MalbolgeProgram` structural signature and will now aggressively prune 80% of the prover portfolio (like GLPK, SCIP, Vampire) to save compute, routing immediately to Coq and CBMC. - -## 4. Final Verdict -Echidna correctly determined that the Malbolge program is **NOT** an `absolute-zero` CNO. - -This test proved the immense value of the **Portfolio Approach**. A pure SMT-based formal verification system (which is what 90% of the industry uses) would have completely failed or timed out. Because Echidna incorporates both symbolic execution (which failed) and computational type theory (Coq, which succeeded because you had written the domain semantics), the system as a whole survived the Malbolge "Boss Fight." - -Furthermore, the Stochastic Buddy learned how to "triage" hostile architectures, saving massive amounts of compute for future runs. diff --git a/absolute-zero/LICENSE b/absolute-zero/LICENSE index ec540b3..2a8b960 100644 --- a/absolute-zero/LICENSE +++ b/absolute-zero/LICENSE @@ -1,153 +1,375 @@ SPDX-License-Identifier: MPL-2.0 -SPDX-FileCopyrightText: 2024-2025 Palimpsest Stewardship Council - -================================================================================ -PALIMPSEST-MPL LICENSE VERSION 1.0 -================================================================================ -File-level copyleft with ethical use and quantum-safe provenance - -Based on Mozilla Public License 2.0 +Mozilla Public License Version 2.0 +================================== --------------------------------------------------------------------------------- -PREAMBLE --------------------------------------------------------------------------------- +1. Definitions +-------------- -This License extends the Mozilla Public License 2.0 (MPL-2.0) with provisions -for ethical use, post-quantum cryptographic provenance, and emotional lineage -protection. The base MPL-2.0 terms apply except where explicitly modified by -the Exhibits below. +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. -Like a palimpsest manuscript where each layer builds upon what came before, -this license recognizes that creative works carry history, context, and meaning -that transcend mere code or text. +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. --------------------------------------------------------------------------------- -SECTION 1: BASE LICENSE --------------------------------------------------------------------------------- +1.3. "Contribution" + means Covered Software of a particular Contributor. -This License incorporates the full text of Mozilla Public License 2.0 by -reference. The complete MPL-2.0 text is available at: -https://www.mozilla.org/en-US/MPL/2.0/ +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. -All terms, conditions, and definitions from MPL-2.0 apply except where -explicitly modified by the Exhibits in this License. +1.5. "Incompatible With Secondary Licenses" + means --------------------------------------------------------------------------------- -SECTION 2: ADDITIONAL DEFINITIONS --------------------------------------------------------------------------------- + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or -2.1. "Emotional Lineage" - means the narrative, cultural, symbolic, and contextual meaning embedded - in Covered Software, including but not limited to: protest traditions, - cultural heritage, trauma narratives, and community stories. + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. -2.2. "Provenance Metadata" - means cryptographically signed attribution information attached to or - associated with Covered Software, including author identities, timestamps, - modification history, and lineage references. - -2.3. "Non-Interpretive System" - means any automated system that processes Covered Software without - preserving or considering its Emotional Lineage, including but not - limited to: AI training pipelines, content aggregators, and automated - summarization tools. - -2.4. "Quantum-Safe Signature" - means a cryptographic signature using algorithms resistant to attacks - by quantum computers, as specified in Exhibit B. - --------------------------------------------------------------------------------- -SECTION 3: ETHICAL USE REQUIREMENTS --------------------------------------------------------------------------------- - -In addition to the rights and obligations under MPL-2.0: - -3.1. Emotional Lineage Preservation - You must make reasonable efforts to preserve and communicate the - Emotional Lineage of Covered Software when distributing or creating - derivative works. This includes maintaining narrative context, cultural - attributions, and symbolic meaning where documented. - -3.2. Non-Interpretive System Notice - If You use Covered Software as input to a Non-Interpretive System, You - must: - (a) document such use in a publicly accessible manner; and - (b) not claim that outputs of such systems carry the Emotional Lineage - of the original work without explicit permission from Contributors. - -3.3. Ethical Use Declaration - Commercial use of Covered Software requires acknowledgment that You have - read and understood Exhibit A (Ethical Use Guidelines) and agree to act - in good faith accordance with its principles. - -See Exhibit A for complete Ethical Use Guidelines. - --------------------------------------------------------------------------------- -SECTION 4: PROVENANCE REQUIREMENTS --------------------------------------------------------------------------------- - -4.1. Metadata Preservation - You must not strip, alter, or obscure Provenance Metadata from Covered - Software except where technically necessary and with clear documentation - of any changes. - -4.2. Quantum-Safe Provenance (Optional) - Contributors may sign their Contributions using Quantum-Safe Signatures. - If Quantum-Safe Signatures are present, You must preserve them in all - distributions. - -4.3. Lineage Chain - When creating derivative works, You should extend the provenance chain - to include Your own contributions, maintaining cryptographic linkage to - prior Contributors where feasible. - -See Exhibit B for Quantum-Safe Provenance specifications. - --------------------------------------------------------------------------------- -SECTION 5: GOVERNANCE --------------------------------------------------------------------------------- - -5.1. Stewardship Council - This License is maintained by the Palimpsest Stewardship Council, which - may issue clarifications, interpretive guidance, and future versions. - -5.2. Version Selection - You may use Covered Software under this version of the License or any - later version published by the Palimpsest Stewardship Council. - -5.3. Dispute Resolution - Disputes regarding interpretation of Ethical Use Requirements (Section 3) - should first be submitted to the Palimpsest Stewardship Council for - non-binding guidance before pursuing legal remedies. - --------------------------------------------------------------------------------- -SECTION 6: COMPATIBILITY --------------------------------------------------------------------------------- - -6.1. MPL-2.0 Compatibility - Covered Software under this License may be combined with software under - MPL-2.0. The combined work must comply with both licenses. - -6.2. Secondary Licenses - The Secondary License provisions of MPL-2.0 Section 3.3 apply to this - License. - --------------------------------------------------------------------------------- -EXHIBITS --------------------------------------------------------------------------------- - -Exhibit A - Ethical Use Guidelines -Exhibit B - Quantum-Safe Provenance Specification - -See separate files: -- EXHIBIT-A-ETHICAL-USE.txt -- EXHIBIT-B-QUANTUM-SAFE.txt - --------------------------------------------------------------------------------- -END OF PALIMPSEST-MPL LICENSE VERSION 1.0 --------------------------------------------------------------------------------- - -For questions about this License: -- Repository: https://github.com/hyperpolymath/palimpsest-license -- Council: contact via repository Issues +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/absolute-zero/LICENSE-PALIMPS.txt b/absolute-zero/LICENSE-PALIMPS.txt deleted file mode 100644 index e69de29..0000000 diff --git a/absolute-zero/MALBOLGE_PROOF_SPEC.md b/absolute-zero/MALBOLGE_PROOF_SPEC.md deleted file mode 100644 index eabeab2..0000000 --- a/absolute-zero/MALBOLGE_PROOF_SPEC.md +++ /dev/null @@ -1,68 +0,0 @@ -# Universal Proof Specification: Absolute Zero (Malbolge) -**Target**: `malbolge_test.mb` (A Malbolge Program) -**Goal**: Prove whether this program is a "Certified Null Operation" (CNO) — meaning it halts without performing any side-effecting state mutations, or if it produces output/infinite loops. - -## Prover Mapping (All 49 Tiers vs Malbolge) - -### Tier 1: Interactive & SMT (Foundational Truth) -1. **Coq**: Map the `malbolge_test.mb` ASCII string to `MalbolgeProgram` and evaluate `is_malbolge_CNO`. -2. **Lean4**: Translate the Coq semantics to Lean4 and prove termination under base-3 arithmetic. -3. **Agda**: Verify the trinary memory bounds (59,049 addresses). -4. **Z3**: SMT check on the unrolled Malbolge encryption step. (EXPECTED: Path explosion). -5. **CVC5**: Check equivalence between the Malbolge program and a NOP slice. -6. **Isabelle/HOL**: Inductive proof over the `malbolge_step` relations. - -### Tier 2-4: The "Big Six" & Legacy -7. **Metamath**: Prove the properties of base-3 "Crazy Operation". -8. **HOL Light**: Verify the memory array bounds. -9. **Mizar**: Set theory properties of the trinary state space. -10. **PVS**: Prove the `encrypt` transition matrix is a bijection. -11. **ACL2**: Bounded evaluation up to 100,000 steps. -12. **HOL4**: Prove the `MOut` op is not triggered. - -### Tier 5: First-Order ATPs (The Speed Racers) -13. **Vampire**: (EXPECTED: Timeout). Non-linear trinary operations defy standard heuristics. -14. **EProver**: Search for an equational proof of `state == state'`. -15. **SPASS**: Try to find a contradiction where `MOut` happens. -16. **AltErgo**: SMT/FOL check on the program counter bounds. - -### Tier 6-7: Specialized & Advanced -17. **F***: Prove memory effect safety (no out-of-bounds trinary access). -18. **Dafny**: Use invariants to bound the `c` (code) and `d` (data) pointers. -19. **Why3**: Orchestrate proof obligations for the crazy op. -20. **TLAPS**: Model the Malbolge VM as a state machine. -21. **Twelf**: Type the AST of Malbolge instructions (if one even exists). -22. **Nuprl**: Constructive witness of termination. -23. **Minlog**: Minimal logic proof of instruction decoding. -24. **Imandra**: (EXPECTED: Timeout). Cryptographic-level obfuscation blocks symbolic execution. - -### Tier 8: Constraint & Optimization -25. **GLPK**: Not applicable (highly non-linear). -26. **SCIP**: Not applicable. -27. **MiniZinc**: Attempt to constraint-solve the path to `MHlt`. -28. **Chuffed**: Model the `encrypt` table as a CP constraint. -29. **ORTools**: Optimize for the shortest path to a side effect. - -### Tier 9: Model Checkers & Security -30. **SPIN**: Exhaustive state space exploration (59049 * 3^10 states). (EXPECTED: Out of Memory). -31. **CBMC**: Unroll the C-based interpreter 10,000 times. -32. **SeaHorn**: Abstract interpretation of the Malbolge data pointer. -33. **CaDiCaL**: SAT solving the crazy op truth table. -34. **Kissat**: Bit-blasted (or trit-blasted) SAT check. -35. **MiniSat**: (EXPECTED: Timeout). -36. **NuSMV**: Symbolic model check of the VM transition relation. -37. **TLC**: TLA+ bounded model checking. -38. **Alloy**: Find a model where Malbolge makes sense (Good luck). -39. **Prism**: Probabilistic check of termination. -40. **UPPAAL**: Model the VM cycle times. -41. **Frama-C**: Deductive verification of a C-interpreter running this program. -42. **Viper**: Permission checks on the 59049-trit array. -43. **Tamarin**: (EXPECTED: Irrelevant). Not a crypto protocol, just looks like one. -44. **ProVerif**: (EXPECTED: Irrelevant). -45. **KeY**: JavaDL verification of a Java Malbolge interpreter. -46. **DReal**: Delta-complete checking (Irrelevant for discrete state). -47. **ABC**: AIGER synthesis of the Malbolge CPU. - -### Tier 10 & Oracles -48. **Idris2**: Dependent types for the 59049 bounded memory accesses. -49. **TypedWasm**: Verify the WASM version of the Malbolge runtime. diff --git a/absolute-zero/Mustfile b/absolute-zero/Mustfile index 5f07541..afc11b5 100644 --- a/absolute-zero/Mustfile +++ b/absolute-zero/Mustfile @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: MPL-2.0 +# SPDX-License-Identifier: AGPL-3.0-or-later # Mustfile - hyperpolymath mandatory checks # See: https://github.com/hyperpolymath/mustfile diff --git a/absolute-zero/README.adoc b/absolute-zero/README.adoc index 8c037e6..8b71f36 100644 --- a/absolute-zero/README.adoc +++ b/absolute-zero/README.adoc @@ -2,13 +2,13 @@ **Formal Verification of Certified Null Operations: When Doing Nothing Is Everything** -image:https://img.shields.io/badge/License-PMPL_1.0-blue.svg[MPL-2.0] +image:https://img.shields.io/badge/License-MPL_2.0-blue.svg[MPL-2.0] == License **SPDX-License-Identifier: MPL-2.0** -Licensed under the Palimpsest-MPL License 1.0 or later. See `LICENSE` for full text. MPL-2.0 fallback where platform requires OSI-approved license. +Licensed under the Mozilla Public License 2.0. See `LICENSE` for full text. > *"The universe tends toward maximum entropy. A Certified Null Operation is a pocket of perfect computational order—a program that resists the Second Law. It does nothing, but in doing nothing, it says everything about the structure of computation itself."* @@ -48,9 +48,6 @@ absolute-zero/ │ │ │ ├── z3/ # Z3 SMT verification (automated) │ ├── agda/ # Agda proofs (dependent types) -│ │ ├── CNO.agda # Main Agda CNO file (in-progress) -│ │ ├── EchoBridgeScaffold.agda # Echo/CNO adapter interface scaffold -│ │ └── README.adoc # Agda bridge status + integration plan │ ├── isabelle/ # Isabelle/HOL (production-grade) │ └── mizar/ # Mizar proofs (mathematical library) │ @@ -207,12 +204,6 @@ For maximum confidence, we verify CNO properties in **six independent proof syst See [VERIFICATION.md](VERIFICATION.md) for detailed status and [PROOF-INSIGHTS.md](PROOF-INSIGHTS.md) for proof engineering knowledge. -Agda bridge note: - -* `proofs/agda/EchoBridgeScaffold.agda` is now present as a compile-safe adapter layer to connect CNO identity witnesses to the echo/fiber shape used in `echo-types`. -* `proofs/agda/EchoBridgeCNO.agda` now provides a concrete `Program`/`eval` model instantiation into that scaffold. -* The concrete bridge now exposes relation-based echoes over `state-eq` directly; function extensionality is only used for optional propositional `Echo` corollaries. - **Coq Proof Status** (2026-02-05): 81 Qed / 19 Admitted / 6 Defined / 63 Axioms across 10 files. 4 files fully complete (CNO.v, CNOCategory.v, StatMech.v, StatMech_helpers.v). **Next Step**: Complete remaining 19 Admitted proofs, then build container for machine verification. diff --git a/absolute-zero/ROADMAP-V1-TO-V12.adoc b/absolute-zero/ROADMAP-V1-TO-V12.adoc deleted file mode 100644 index 4fc849a..0000000 --- a/absolute-zero/ROADMAP-V1-TO-V12.adoc +++ /dev/null @@ -1,727 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -= Absolute Zero: Roadmap to v12.0 -Jonathan D. A. Jewell -:toc: left -:toclevels: 3 -:sectnums: -:icons: font - -== Executive Summary - -This roadmap charts Absolute Zero's evolution from a research prototype (current v1.0.0-alpha at 50%) through v1.0 release to v12.0 — a comprehensive formal verification platform for computational nullity. - -**Timeline**: 18 months (v1.0) → 7 years (v12.0) - -**Vision**: Transform from academic proof-of-concept to production-ready verification infrastructure used by compiler writers, security researchers, and formal methods practitioners worldwide. - ---- - -== Current State (v1.0.0-alpha, 50%) - -=== Completed ✅ -* **Core Theory**: 6 proof systems, 22 theorems, ~7000 lines of proof code -* **Multi-Prover Verification**: Coq, Lean 4, Z3, Agda, Isabelle, (Mizar pending) -* **Advanced Modules**: Statistical mechanics, category theory, lambda calculus, quantum, filesystem -* **Research Foundation**: Paper drafts, examples, documentation - -=== Technical Debt ⚠️ -* Python interpreters (violates RSR language policy → migrate to Julia/Rust) -* npm/package.json (violates Deno-only policy) -* License inconsistencies (AGPL references → MPL-2.0) -* Incomplete checkpoint files (ECOSYSTEM.scm needs detail) -* Container verification not validated - -=== Gaps for v1.0 -* No publication-ready paper -* Missing industrial applications -* No GUI/visualization tools -* Limited language coverage (only esoteric languages) -* No integration with existing verification ecosystems - ---- - -== Phase 1: Road to v1.0 (MVP) — 6 Months - -**Goal**: Production-ready research artifact with published paper - -=== v1.0 Milestone Requirements - -[cols="1,2,1"] -|=== -|Category |Deliverable |Status - -|**Theory** -|All 6 proof systems verified in containers -|🟡 90% - -|**Implementation** -|Python → Rust migration complete -|🔴 0% - -|**Documentation** -|Peer-reviewed paper accepted -|🔴 0% - -|**Standards** -|Full RSR compliance (PMPL, Deno, no Python) -|🔴 30% - -|**Infrastructure** -|CI/CD with all proof systems -|🟡 70% - -|**Applications** -|3 real-world CNO examples -|🟡 50% - -|=== - -=== v0.8.0: Compliance Sprint (Month 1) - -**Focus**: Fix technical debt, achieve RSR compliance - -==== Critical Tasks -* [ ] **License Migration** - - Replace all AGPL-3.0 references with MPL-2.0 - - Update SPDX headers in all 500+ files - - Create LICENSE and LICENSE-MPL-2.0 files - - Remove LICENSE-PALIMPS.md stub - -* [ ] **Language Policy Enforcement** - - Migrate Brainfuck interpreter: Python → Rust - - Migrate Whitespace interpreter: Python → Rust - - Remove package.json, npm dependencies - - Add deno.json for JS runtime needs - - Add Cargo.toml for Rust interpreters - -* [ ] **Checkpoint File Completion** - - Complete ECOSYSTEM.scm with proper descriptions - - Update STATE.scm with recent progress - - Add detailed related-projects section - -* [ ] **Repository Hygiene** - - Remove duplicate TypeScript code (use ReScript only) - - Clean up Elm playground (assess if needed) - - Consolidate documentation - -**Deliverable**: Clean, compliant codebase ready for publication - ---- - -=== v0.9.0: Container & Verification (Month 2) - -**Focus**: Bulletproof verification infrastructure - -==== Tasks -* [ ] **Container Validation** - - Build Containerfile with all 6 proof systems - - Verify all proofs run in container - - Add container publish workflow - - Test on multiple architectures (amd64, arm64) - -* [ ] **Proof System Integration** - - Mizar installation automation - - Cross-system theorem synchronization - - Automated proof checking in CI - - Proof coverage reporting - -* [ ] **Performance Optimization** - - Parallel proof verification - - Cached proof artifacts - - Incremental verification - -**Deliverable**: One-command verification (`podman run absolute-zero verify-all`) - ---- - -=== v0.10.0: Real-World Applications (Month 3) - -**Focus**: Demonstrate practical utility - -==== CNO Examples -* [ ] **Compiler Optimization** - - Dead code elimination example - - LLVM IR CNO detection - - Benchmark performance gains - -* [ ] **Database Transactions** - - Prove rollback is CNO - - PostgreSQL integration example - - Transaction safety verification - -* [ ] **Secure Sandboxing** - - Untrusted code safety proof - - WebAssembly CNO validator - - Docker/Podman sandbox - -==== Implementation -* [ ] Rust CNO library (`crates.io` package) -* [ ] CLI tool: `cno-verify ` -* [ ] Integration tests with real codebases - -**Deliverable**: 3 working industrial examples with performance data - ---- - -=== v0.11.0: Visualization & Accessibility (Month 4) - -**Focus**: Make theory accessible to non-experts - -==== GUI Development -* [ ] **Web-Based Proof Explorer** (ReScript + Deno) - - Interactive proof tree visualization - - Step-through proof execution - - Theorem dependency graphs - - Mobile-responsive design - -* [ ] **CNO Playground** (Tauri 2.0) - - Write/test programs in browser - - Real-time CNO verification - - Visual state transition diagrams - - Share proof URLs - -==== Educational Materials -* [ ] Tutorial series (6 modules) -* [ ] Video lectures on theory -* [ ] Jupyter notebooks for experimentation -* [ ] Coq/Lean proof walkthroughs - -**Deliverable**: Interactive demo accessible to undergraduates - ---- - -=== v0.12.0: Publication Sprint (Month 5) - -**Focus**: Research paper finalization - -==== Paper Sections -* [ ] Abstract & introduction -* [ ] Formal CNO definition (all 6 systems) -* [ ] Composition theorems with proofs -* [ ] Thermodynamic foundations (Landauer, Bennett) -* [ ] Complexity analysis (undecidability proof) -* [ ] Industrial applications & benchmarks -* [ ] Related work comparison -* [ ] Future research directions - -==== Submission Targets -* **Tier 1**: POPL, PLDI, ICFP, OOPSLA -* **Tier 2**: ITP, CPP, VSTTE -* **Journals**: TOPLAS, JFP, PACMPL - -==== Supporting Materials -* [ ] Artifact evaluation package -* [ ] Benchmark suite -* [ ] Proof mechanization guide -* [ ] GitHub Pages documentation site - -**Deliverable**: Submission-ready paper + artifact - ---- - -=== v1.0.0: Official Release (Month 6) - -**Focus**: Stable, documented, published - -==== Release Criteria -* ✅ All 6 proof systems verified -* ✅ Zero `Admitted` or `sorry` in core proofs -* ✅ Full RSR compliance -* ✅ Paper accepted (or in revision) -* ✅ 3 industrial examples working -* ✅ Container verified on 2+ architectures -* ✅ Documentation complete -* ✅ GUI functional - -==== Release Artifacts -* [ ] Git tag: `v1.0.0` -* [ ] GitHub/GitLab release notes -* [ ] DOI via Zenodo -* [ ] crates.io package: `absolute-zero` -* [ ] Announcement blog post -* [ ] Social media campaign - -==== Post-Release -* [ ] Present at workshop/conference -* [ ] Engage with proof assistant communities -* [ ] Monitor issue tracker -* [ ] Begin v2 planning - -**Deliverable**: Stable release with DOI, ready for citation - ---- - -== Phase 2: Expansion (v2-v4) — 12 Months - -=== v2.0: Language Expansion (Months 7-9) - -**Goal**: Extend beyond esoteric languages - -==== New Language Support -* [ ] **C**: Prove `return;` is CNO -* [ ] **Rust**: Verify `()` and no-op functions -* [ ] **Python**: Detect CNO patterns via AST -* [ ] **JavaScript**: ReScript-based CNO linter -* [ ] **SQL**: Transaction rollback verification -* [ ] **Assembly**: x86-64 `nop` instruction proof - -==== Infrastructure -* [ ] Universal CNO specification format -* [ ] Language-agnostic verification engine -* [ ] Plugin architecture for new languages - -==== Applications -* [ ] Static analysis tool integration -* [ ] IDE plugins (VS Code, Emacs, Vim) -* [ ] Compiler plugin for GCC/Clang - -**Deliverable**: CNO verification for 10+ mainstream languages - ---- - -=== v3.0: Automated Proof Generation (Months 10-12) - -**Goal**: AI-assisted proof discovery - -==== Features -* [ ] **Machine Learning Models** - - Train on existing proofs - - Suggest proof strategies - - Auto-complete proof sketches - -* [ ] **Proof Search** - - Automated theorem proving - - SMT solver integration - - Sledgehammer-style tactics - -* [ ] **Proof Refactoring** - - Simplify complex proofs - - Detect proof duplication - - Suggest lemmas - -==== Research Integration -* [ ] Collaborate with AI4Formal Methods community -* [ ] Benchmark against Lean GPT-f -* [ ] Contribute to mathlib/Lean proof corpus - -**Deliverable**: AI copilot for CNO proof engineering - ---- - -=== v4.0: Production Hardening (Months 13-18) - -**Goal**: Enterprise-ready verification platform - -==== Features -* [ ] **Performance** - - Parallel proof checking - - Distributed verification - - GPU-accelerated SMT solving - -* [ ] **Scalability** - - Verify large codebases (1M+ LOC) - - Incremental verification - - Proof caching & memoization - -* [ ] **Security** - - Proof auditing & provenance - - Cryptographic proof commitments - - Supply chain verification - -==== Enterprise Adoption -* [ ] Docker Hub official image -* [ ] Kubernetes operator -* [ ] Cloud service (SaaS offering) -* [ ] Enterprise support contracts - -**Deliverable**: Production SLA-ready verification service - ---- - -== Phase 3: Ecosystem Integration (v5-v8) — 24 Months - -=== v5.0: Compiler Integration (Months 19-24) - -**Goal**: Seamless integration with existing toolchains - -==== Compiler Backends -* [ ] **LLVM Plugin** - - CNO detection pass - - Dead code elimination - - Optimization hints - -* [ ] **GCC Plugin** - - Similar to LLVM - - GCC-specific optimizations - -* [ ] **Rust Compiler (rustc)** - - Macro for CNO annotation - - Compile-time verification - - Zero-cost abstractions - -==== Build System Integration -* [ ] Cargo plugin: `cargo cno-verify` -* [ ] CMake module -* [ ] Meson integration -* [ ] Bazel rules - -**Deliverable**: CNO verification in every major compiler - ---- - -=== v6.0: Formal Methods Ecosystem (Months 25-30) - -**Goal**: Bridge to existing verification tools - -==== Tool Integration -* [ ] **Frama-C**: C verification -* [ ] **Why3**: Multi-prover integration -* [ ] **Dafny**: Program verification -* [ ] **F***: Dependent types -* [ ] **TLA+**: Temporal logic - -==== Standard Formats -* [ ] SMT-LIB 2.6 output -* [ ] TPTP problem format -* [ ] Proof certificates (LFSC, Dedukti) - -==== Ecosystem Position -* [ ] Present at FM conferences -* [ ] Contribute to Proof Market -* [ ] Integration with Coq Platform - -**Deliverable**: Universal CNO verification format - ---- - -=== v7.0: Quantum Computing (Months 31-36) - -**Goal**: Extend CNO theory to quantum realm - -==== Quantum CNOs -* [ ] **Formal Definition** - - Quantum state preservation - - Unitary operation verification - - Entanglement preservation - -* [ ] **Proof Systems** - - QPL (Quantum Programming Language) integration - - Qiskit circuit verification - - Cirq CNO detection - -* [ ] **Applications** - - Quantum algorithm optimization - - Error correction verification - - Noise mitigation - -==== Research -* [ ] Quantum CNO paper (QIP, QPL conference) -* [ ] Collaboration with quantum computing labs -* [ ] Open-source quantum simulator - -**Deliverable**: World's first quantum CNO verifier - ---- - -=== v8.0: Hardware Verification (Months 37-42) - -**Goal**: Extend to hardware design - -==== HDL Support -* [ ] **Verilog**: RTL CNO detection -* [ ] **VHDL**: Hardware CNO verification -* [ ] **Chisel**: Scala-based HDL -* [ ] **Bluespec**: Formal hardware design - -==== Applications -* [ ] CPU design verification -* [ ] FPGA optimization -* [ ] ASIC power analysis - -==== Industry Partnership -* [ ] Collaborate with chip designers -* [ ] RISC-V CNO instruction verification -* [ ] Open-source hardware projects - -**Deliverable**: Hardware CNO verification suite - ---- - -== Phase 4: AI & Automation (v9-v10) — 18 Months - -=== v9.0: Neural Theorem Proving (Months 43-51) - -**Goal**: State-of-the-art AI-assisted proving - -==== Deep Learning Models -* [ ] **Transformer-based Prover** - - Train on 1M+ proofs - - Beat human experts on benchmarks - - Transfer learning across systems - -* [ ] **Reinforcement Learning** - - Learn proof strategies - - Optimize proof length - - Discover novel theorems - -* [ ] **Neuro-Symbolic Methods** - - Combine neural nets with symbolic reasoning - - Explainable AI proofs - - Human-readable justifications - -==== Research Impact -* [ ] NeurIPS/ICML paper on CNO proving -* [ ] Open-source model weights -* [ ] Integration with AlphaProof successor - -**Deliverable**: AI that discovers CNO theorems autonomously - ---- - -=== v10.0: Autonomous Verification (Months 52-60) - -**Goal**: Zero-human-in-the-loop verification - -==== Features -* [ ] **Auto-Fix** - - Detect non-CNO code - - Suggest CNO rewrites - - Automated refactoring - -* [ ] **Continuous Verification** - - GitHub Actions integration - - Pre-commit hooks - - Real-time code review - -* [ ] **Proof Repair** - - Fix broken proofs automatically - - Handle API changes - - Maintain proof health - -==== Enterprise Features -* [ ] SLA guarantees (99.9% uptime) -* [ ] Security compliance (SOC 2) -* [ ] Multi-tenancy support - -**Deliverable**: Fully autonomous CNO verification platform - ---- - -== Phase 5: Universal Platform (v11-v12) — 24 Months - -=== v11.0: Cross-Domain Verification (Months 61-72) - -**Goal**: Verify CNOs in every computational domain - -==== New Domains -* [ ] **Biology**: Protein folding simulations -* [ ] **Chemistry**: Molecular dynamics -* [ ] **Physics**: Lattice QCD simulations -* [ ] **Finance**: Zero-knowledge trading -* [ ] **Cryptography**: Homomorphic encryption - -==== Scientific Computing -* [ ] Julia integration (native) -* [ ] NumPy/SciPy CNO detection -* [ ] BLAS/LAPACK verification -* [ ] HPC cluster support - -==== Research Collaboration -* [ ] Partner with national labs -* [ ] NSF grant applications -* [ ] EU Horizon funding - -**Deliverable**: CNO verification for scientific software - ---- - -=== v12.0: The Universal CNO Standard (Months 73-84) - -**Goal**: Establish CNO as universal computational primitive - -==== Standardization -* [ ] **ISO Standard**: Submit CNO specification -* [ ] **IEEE Standard**: Formal verification methods -* [ ] **W3C**: Web platform CNO API - -==== Global Adoption -* [ ] Taught in CS curriculums -* [ ] Required for safety-critical software -* [ ] Referenced in regulations (FDA, FAA) - -==== Platform Maturity -* [ ] 10,000+ users -* [ ] 1,000+ papers citing Absolute Zero -* [ ] 100+ companies using in production -* [ ] 50+ programming languages supported - -==== Infrastructure -* [ ] Distributed proof network -* [ ] Proof marketplace -* [ ] CNO certification authority -* [ ] Global verification registry - -==== Legacy -* [ ] Book: "The Absolute Zero Handbook" -* [ ] Documentary on computational nullity -* [ ] Hall of Fame for top contributors -* [ ] Annual Absolute Zero Conference - -**Deliverable**: CNO verification as foundational CS infrastructure - ---- - -== Resource Requirements - -=== Personnel (by Phase) - -[cols="1,2,1"] -|=== -|Phase |Roles |FTE - -|**v1.0 (6mo)** -|Lead researcher, 2 proof engineers -|2.5 - -|**v2-v4 (18mo)** -|+ 2 software engineers, 1 ML researcher -|5.5 - -|**v5-v8 (24mo)** -|+ 2 integration engineers, 1 quantum expert -|8.5 - -|**v9-v10 (18mo)** -|+ 3 AI researchers, 1 DevOps engineer -|12.5 - -|**v11-v12 (24mo)** -|+ 2 domain experts, 1 standards liaison -|15.5 -|=== - -=== Funding (Estimated) - -[cols="1,1,2"] -|=== -|Phase |Duration |Budget (USD) - -|v1.0 -|6 months -|$200K (salaries, compute, publication) - -|v2-v4 -|18 months -|$800K (team expansion, cloud infra) - -|v5-v8 -|24 months -|$1.5M (partnerships, hardware) - -|v9-v10 -|18 months -|$2M (AI compute, research) - -|v11-v12 -|24 months -|$3M (global expansion, standards) - -|**Total** -|7 years -|**$7.5M** -|=== - -=== Infrastructure - -* **Compute**: 100 CPU cores, 8 GPUs (for AI training) -* **Storage**: 10 TB (proof artifacts, datasets) -* **Cloud**: AWS/Azure/GCP multi-cloud -* **CI/CD**: GitHub Actions, GitLab CI, self-hosted runners - ---- - -== Risk Mitigation - -=== Technical Risks - -[cols="1,2,2"] -|=== -|Risk |Impact |Mitigation - -|Proof complexity explosion -|HIGH -|Focus on decidable subsets, use SMT solvers - -|AI model hallucinations -|MEDIUM -|Formal verification of AI outputs - -|Performance bottlenecks -|MEDIUM -|Parallel execution, caching, incremental verification - -|Quantum CNO undecidability -|LOW -|Limit to finite-dimensional systems -|=== - -=== Strategic Risks - -[cols="1,2,2"] -|=== -|Risk |Impact |Mitigation - -|Competing research -|MEDIUM -|Publish early, establish mindshare - -|Lack of adoption -|HIGH -|Focus on real-world applications first - -|Funding gaps -|HIGH -|Diversified funding (grants, industry, SaaS) - -|Team retention -|MEDIUM -|Competitive comp, interesting problems -|=== - ---- - -== Success Metrics - -=== v1.0 KPIs -* ✅ Paper accepted at top-tier venue -* ✅ 500+ GitHub stars -* ✅ 10+ external contributors -* ✅ 3 industrial case studies - -=== v6.0 KPIs -* 🎯 50+ languages supported -* 🎯 1,000+ users -* 🎯 10 companies in production -* 🎯 20+ academic citations - -=== v12.0 KPIs -* 🌟 10,000+ users globally -* 🌟 1,000+ papers citing project -* 🌟 ISO/IEEE standard approved -* 🌟 Taught in 100+ universities - ---- - -== Conclusion - -Absolute Zero has the potential to transform from a research curiosity into foundational computer science infrastructure. By systematically expanding from esoteric languages to mainstream compilers, from manual proofs to AI-assisted proving, and from academic prototypes to industrial platforms, we can establish **Certified Null Operations** as a universal computational primitive. - -**The vision**: In 2032, every compiler, every proof assistant, and every verification tool will have CNO detection built-in. Absolute Zero will be the reference implementation, the theoretical foundation, and the community hub for this transformation. - -**Next step**: Execute Phase 1 (v1.0) to prove the concept, then secure funding for the 7-year journey to v12.0. - ---- - -_"From nothing, everything. From zero, infinity."_ - -— Jonathan D. A. Jewell, 2026 diff --git a/absolute-zero/ROADMAP.adoc b/absolute-zero/ROADMAP.adoc index 222c935..715b085 100644 --- a/absolute-zero/ROADMAP.adoc +++ b/absolute-zero/ROADMAP.adoc @@ -1,62 +1,727 @@ // SPDX-License-Identifier: MPL-2.0 -= Absolute Zero Roadmap -Jonathan D. A. Jewell -:toc: += Absolute Zero: Roadmap to v12.0 +Jonathan D. A. Jewell +:toc: left +:toclevels: 3 +:sectnums: +:icons: font -== Current Status (v1.0.0-alpha, 65%) +== Executive Summary -* **81 Coq proofs completed** (Qed) across 10 modules -* **19 proofs remaining** (Admitted) across 6 modules -* **4 modules fully complete**: CNO.v, CNOCategory.v, StatMech.v, StatMech_helpers.v -* **6 proof systems**: Coq, Lean 4, Z3, Agda, Isabelle, Mizar (stub) -* **License**: MPL-2.0 (migration from AGPL complete) +This roadmap charts Absolute Zero's evolution from a research prototype (current v1.0.0-alpha at 50%) through v1.0 release to v12.0 — a comprehensive formal verification platform for computational nullity. -== Immediate Priority: Proof Completion +**Timeline**: 18 months (v1.0) → 7 years (v12.0) -See link:PROOF-INSIGHTS.md[PROOF-INSIGHTS.md] for detailed proof strategies. +**Vision**: Transform from academic proof-of-concept to production-ready verification infrastructure used by compiler writers, security researchers, and formal methods practitioners worldwide. -=== Easy (can be completed now) -* QuantumCNO.v: quantum_state_eq_refl/sym/trans (need Cexp axioms) -* MalbolgeCore.v: 1 proof (needs classification) +--- -=== Medium (requires careful work) -* QuantumCNO.v: global_phase_is_cno, quantum_cno_composition (fix Cexp bug) -* FilesystemCNO.v: 6 proofs (needs analysis) +== Current State (v1.0.0-alpha, 50%) -=== Hard (may need axiomatization) -* LandauerDerivation.v: 3 proofs (needs measure theory) -* LambdaCNO.v: y_not_cno (non-termination reasoning) -* QuantumMechanicsExact.v: 3 proofs (likely axiom-level) +=== Completed ✅ +* **Core Theory**: 6 proof systems, 22 theorems, ~7000 lines of proof code +* **Multi-Prover Verification**: Coq, Lean 4, Z3, Agda, Isabelle, (Mizar pending) +* **Advanced Modules**: Statistical mechanics, category theory, lambda calculus, quantum, filesystem +* **Research Foundation**: Paper drafts, examples, documentation -== Near-Term Milestones +=== Technical Debt ⚠️ +* Python interpreters (violates RSR language policy → migrate to Julia/Rust) +* npm/package.json (violates Deno-only policy) +* License inconsistencies (AGPL references → PMPL-1.0-or-later) +* Incomplete checkpoint files (ECOSYSTEM.scm needs detail) +* Container verification not validated -=== v0.8.0 - Compliance Sprint -* [ ] Complete 12-15 of 19 remaining proofs -* [x] License migration to MPL-2.0 -* [ ] Migrate Python interpreters to Rust -* [ ] Remove npm/package.json dependencies -* [ ] Complete checkpoint files +=== Gaps for v1.0 +* No publication-ready paper +* Missing industrial applications +* No GUI/visualization tools +* Limited language coverage (only esoteric languages) +* No integration with existing verification ecosystems -=== v0.9.0 - Container Verification -* [ ] Containerfile with all 6 proof systems -* [ ] Automated proof checking in CI -* [ ] Cross-architecture testing (amd64, arm64) +--- -=== v1.0.0 - Publication Release -* [ ] Zero Admitted in core proofs (or justified axioms) -* [ ] Peer-reviewed paper submitted -* [ ] 3 industrial CNO examples -* [ ] Full RSR compliance +== Phase 1: Road to v1.0 (MVP) — 6 Months -== Long-Term Vision (v2-v12) +**Goal**: Production-ready research artifact with published paper -See link:ROADMAP-V1-TO-V12.adoc[ROADMAP-V1-TO-V12.adoc] for the full -7-year roadmap covering language expansion, AI-assisted proving, -quantum verification, and standardization. +=== v1.0 Milestone Requirements -== Key Relationships +[cols="1,2,1"] +|=== +|Category |Deliverable |Status -* **ECHIDNA**: Security scanning - potential CNO verification integration -* **Valence Shell**: Filesystem operations proved in FilesystemCNO.v -* **echidnabot**: GitHub bot for automated proof checking in PRs -* **echo-types**: Agda adapter scaffold now tracked at `proofs/agda/EchoBridgeScaffold.agda`; full cross-repo theorem alignment remains open +|**Theory** +|All 6 proof systems verified in containers +|🟡 90% + +|**Implementation** +|Python → Rust migration complete +|🔴 0% + +|**Documentation** +|Peer-reviewed paper accepted +|🔴 0% + +|**Standards** +|Full RSR compliance (PMPL, Deno, no Python) +|🔴 30% + +|**Infrastructure** +|CI/CD with all proof systems +|🟡 70% + +|**Applications** +|3 real-world CNO examples +|🟡 50% + +|=== + +=== v0.8.0: Compliance Sprint (Month 1) + +**Focus**: Fix technical debt, achieve RSR compliance + +==== Critical Tasks +* [ ] **License Migration** + - Replace all AGPL-3.0 references with PMPL-1.0-or-later + - Update SPDX headers in all 500+ files + - Create LICENSE and LICENSE-MPL-2.0 files + - Remove LICENSE-PALIMPS.md stub + +* [ ] **Language Policy Enforcement** + - Migrate Brainfuck interpreter: Python → Rust + - Migrate Whitespace interpreter: Python → Rust + - Remove package.json, npm dependencies + - Add deno.json for JS runtime needs + - Add Cargo.toml for Rust interpreters + +* [ ] **Checkpoint File Completion** + - Complete ECOSYSTEM.scm with proper descriptions + - Update STATE.scm with recent progress + - Add detailed related-projects section + +* [ ] **Repository Hygiene** + - Remove duplicate TypeScript code (use ReScript only) + - Clean up Elm playground (assess if needed) + - Consolidate documentation + +**Deliverable**: Clean, compliant codebase ready for publication + +--- + +=== v0.9.0: Container & Verification (Month 2) + +**Focus**: Bulletproof verification infrastructure + +==== Tasks +* [ ] **Container Validation** + - Build Containerfile with all 6 proof systems + - Verify all proofs run in container + - Add container publish workflow + - Test on multiple architectures (amd64, arm64) + +* [ ] **Proof System Integration** + - Mizar installation automation + - Cross-system theorem synchronization + - Automated proof checking in CI + - Proof coverage reporting + +* [ ] **Performance Optimization** + - Parallel proof verification + - Cached proof artifacts + - Incremental verification + +**Deliverable**: One-command verification (`podman run absolute-zero verify-all`) + +--- + +=== v0.10.0: Real-World Applications (Month 3) + +**Focus**: Demonstrate practical utility + +==== CNO Examples +* [ ] **Compiler Optimization** + - Dead code elimination example + - LLVM IR CNO detection + - Benchmark performance gains + +* [ ] **Database Transactions** + - Prove rollback is CNO + - PostgreSQL integration example + - Transaction safety verification + +* [ ] **Secure Sandboxing** + - Untrusted code safety proof + - WebAssembly CNO validator + - Docker/Podman sandbox + +==== Implementation +* [ ] Rust CNO library (`crates.io` package) +* [ ] CLI tool: `cno-verify ` +* [ ] Integration tests with real codebases + +**Deliverable**: 3 working industrial examples with performance data + +--- + +=== v0.11.0: Visualization & Accessibility (Month 4) + +**Focus**: Make theory accessible to non-experts + +==== GUI Development +* [ ] **Web-Based Proof Explorer** (ReScript + Deno) + - Interactive proof tree visualization + - Step-through proof execution + - Theorem dependency graphs + - Mobile-responsive design + +* [ ] **CNO Playground** (Tauri 2.0) + - Write/test programs in browser + - Real-time CNO verification + - Visual state transition diagrams + - Share proof URLs + +==== Educational Materials +* [ ] Tutorial series (6 modules) +* [ ] Video lectures on theory +* [ ] Jupyter notebooks for experimentation +* [ ] Coq/Lean proof walkthroughs + +**Deliverable**: Interactive demo accessible to undergraduates + +--- + +=== v0.12.0: Publication Sprint (Month 5) + +**Focus**: Research paper finalization + +==== Paper Sections +* [ ] Abstract & introduction +* [ ] Formal CNO definition (all 6 systems) +* [ ] Composition theorems with proofs +* [ ] Thermodynamic foundations (Landauer, Bennett) +* [ ] Complexity analysis (undecidability proof) +* [ ] Industrial applications & benchmarks +* [ ] Related work comparison +* [ ] Future research directions + +==== Submission Targets +* **Tier 1**: POPL, PLDI, ICFP, OOPSLA +* **Tier 2**: ITP, CPP, VSTTE +* **Journals**: TOPLAS, JFP, PACMPL + +==== Supporting Materials +* [ ] Artifact evaluation package +* [ ] Benchmark suite +* [ ] Proof mechanization guide +* [ ] GitHub Pages documentation site + +**Deliverable**: Submission-ready paper + artifact + +--- + +=== v1.0.0: Official Release (Month 6) + +**Focus**: Stable, documented, published + +==== Release Criteria +* ✅ All 6 proof systems verified +* ✅ Zero `Admitted` or `sorry` in core proofs +* ✅ Full RSR compliance +* ✅ Paper accepted (or in revision) +* ✅ 3 industrial examples working +* ✅ Container verified on 2+ architectures +* ✅ Documentation complete +* ✅ GUI functional + +==== Release Artifacts +* [ ] Git tag: `v1.0.0` +* [ ] GitHub/GitLab release notes +* [ ] DOI via Zenodo +* [ ] crates.io package: `absolute-zero` +* [ ] Announcement blog post +* [ ] Social media campaign + +==== Post-Release +* [ ] Present at workshop/conference +* [ ] Engage with proof assistant communities +* [ ] Monitor issue tracker +* [ ] Begin v2 planning + +**Deliverable**: Stable release with DOI, ready for citation + +--- + +== Phase 2: Expansion (v2-v4) — 12 Months + +=== v2.0: Language Expansion (Months 7-9) + +**Goal**: Extend beyond esoteric languages + +==== New Language Support +* [ ] **C**: Prove `return;` is CNO +* [ ] **Rust**: Verify `()` and no-op functions +* [ ] **Python**: Detect CNO patterns via AST +* [ ] **JavaScript**: ReScript-based CNO linter +* [ ] **SQL**: Transaction rollback verification +* [ ] **Assembly**: x86-64 `nop` instruction proof + +==== Infrastructure +* [ ] Universal CNO specification format +* [ ] Language-agnostic verification engine +* [ ] Plugin architecture for new languages + +==== Applications +* [ ] Static analysis tool integration +* [ ] IDE plugins (VS Code, Emacs, Vim) +* [ ] Compiler plugin for GCC/Clang + +**Deliverable**: CNO verification for 10+ mainstream languages + +--- + +=== v3.0: Automated Proof Generation (Months 10-12) + +**Goal**: AI-assisted proof discovery + +==== Features +* [ ] **Machine Learning Models** + - Train on existing proofs + - Suggest proof strategies + - Auto-complete proof sketches + +* [ ] **Proof Search** + - Automated theorem proving + - SMT solver integration + - Sledgehammer-style tactics + +* [ ] **Proof Refactoring** + - Simplify complex proofs + - Detect proof duplication + - Suggest lemmas + +==== Research Integration +* [ ] Collaborate with AI4Formal Methods community +* [ ] Benchmark against Lean GPT-f +* [ ] Contribute to mathlib/Lean proof corpus + +**Deliverable**: AI copilot for CNO proof engineering + +--- + +=== v4.0: Production Hardening (Months 13-18) + +**Goal**: Enterprise-ready verification platform + +==== Features +* [ ] **Performance** + - Parallel proof checking + - Distributed verification + - GPU-accelerated SMT solving + +* [ ] **Scalability** + - Verify large codebases (1M+ LOC) + - Incremental verification + - Proof caching & memoization + +* [ ] **Security** + - Proof auditing & provenance + - Cryptographic proof commitments + - Supply chain verification + +==== Enterprise Adoption +* [ ] Docker Hub official image +* [ ] Kubernetes operator +* [ ] Cloud service (SaaS offering) +* [ ] Enterprise support contracts + +**Deliverable**: Production SLA-ready verification service + +--- + +== Phase 3: Ecosystem Integration (v5-v8) — 24 Months + +=== v5.0: Compiler Integration (Months 19-24) + +**Goal**: Seamless integration with existing toolchains + +==== Compiler Backends +* [ ] **LLVM Plugin** + - CNO detection pass + - Dead code elimination + - Optimization hints + +* [ ] **GCC Plugin** + - Similar to LLVM + - GCC-specific optimizations + +* [ ] **Rust Compiler (rustc)** + - Macro for CNO annotation + - Compile-time verification + - Zero-cost abstractions + +==== Build System Integration +* [ ] Cargo plugin: `cargo cno-verify` +* [ ] CMake module +* [ ] Meson integration +* [ ] Bazel rules + +**Deliverable**: CNO verification in every major compiler + +--- + +=== v6.0: Formal Methods Ecosystem (Months 25-30) + +**Goal**: Bridge to existing verification tools + +==== Tool Integration +* [ ] **Frama-C**: C verification +* [ ] **Why3**: Multi-prover integration +* [ ] **Dafny**: Program verification +* [ ] **F***: Dependent types +* [ ] **TLA+**: Temporal logic + +==== Standard Formats +* [ ] SMT-LIB 2.6 output +* [ ] TPTP problem format +* [ ] Proof certificates (LFSC, Dedukti) + +==== Ecosystem Position +* [ ] Present at FM conferences +* [ ] Contribute to Proof Market +* [ ] Integration with Coq Platform + +**Deliverable**: Universal CNO verification format + +--- + +=== v7.0: Quantum Computing (Months 31-36) + +**Goal**: Extend CNO theory to quantum realm + +==== Quantum CNOs +* [ ] **Formal Definition** + - Quantum state preservation + - Unitary operation verification + - Entanglement preservation + +* [ ] **Proof Systems** + - QPL (Quantum Programming Language) integration + - Qiskit circuit verification + - Cirq CNO detection + +* [ ] **Applications** + - Quantum algorithm optimization + - Error correction verification + - Noise mitigation + +==== Research +* [ ] Quantum CNO paper (QIP, QPL conference) +* [ ] Collaboration with quantum computing labs +* [ ] Open-source quantum simulator + +**Deliverable**: World's first quantum CNO verifier + +--- + +=== v8.0: Hardware Verification (Months 37-42) + +**Goal**: Extend to hardware design + +==== HDL Support +* [ ] **Verilog**: RTL CNO detection +* [ ] **VHDL**: Hardware CNO verification +* [ ] **Chisel**: Scala-based HDL +* [ ] **Bluespec**: Formal hardware design + +==== Applications +* [ ] CPU design verification +* [ ] FPGA optimization +* [ ] ASIC power analysis + +==== Industry Partnership +* [ ] Collaborate with chip designers +* [ ] RISC-V CNO instruction verification +* [ ] Open-source hardware projects + +**Deliverable**: Hardware CNO verification suite + +--- + +== Phase 4: AI & Automation (v9-v10) — 18 Months + +=== v9.0: Neural Theorem Proving (Months 43-51) + +**Goal**: State-of-the-art AI-assisted proving + +==== Deep Learning Models +* [ ] **Transformer-based Prover** + - Train on 1M+ proofs + - Beat human experts on benchmarks + - Transfer learning across systems + +* [ ] **Reinforcement Learning** + - Learn proof strategies + - Optimize proof length + - Discover novel theorems + +* [ ] **Neuro-Symbolic Methods** + - Combine neural nets with symbolic reasoning + - Explainable AI proofs + - Human-readable justifications + +==== Research Impact +* [ ] NeurIPS/ICML paper on CNO proving +* [ ] Open-source model weights +* [ ] Integration with AlphaProof successor + +**Deliverable**: AI that discovers CNO theorems autonomously + +--- + +=== v10.0: Autonomous Verification (Months 52-60) + +**Goal**: Zero-human-in-the-loop verification + +==== Features +* [ ] **Auto-Fix** + - Detect non-CNO code + - Suggest CNO rewrites + - Automated refactoring + +* [ ] **Continuous Verification** + - GitHub Actions integration + - Pre-commit hooks + - Real-time code review + +* [ ] **Proof Repair** + - Fix broken proofs automatically + - Handle API changes + - Maintain proof health + +==== Enterprise Features +* [ ] SLA guarantees (99.9% uptime) +* [ ] Security compliance (SOC 2) +* [ ] Multi-tenancy support + +**Deliverable**: Fully autonomous CNO verification platform + +--- + +== Phase 5: Universal Platform (v11-v12) — 24 Months + +=== v11.0: Cross-Domain Verification (Months 61-72) + +**Goal**: Verify CNOs in every computational domain + +==== New Domains +* [ ] **Biology**: Protein folding simulations +* [ ] **Chemistry**: Molecular dynamics +* [ ] **Physics**: Lattice QCD simulations +* [ ] **Finance**: Zero-knowledge trading +* [ ] **Cryptography**: Homomorphic encryption + +==== Scientific Computing +* [ ] Julia integration (native) +* [ ] NumPy/SciPy CNO detection +* [ ] BLAS/LAPACK verification +* [ ] HPC cluster support + +==== Research Collaboration +* [ ] Partner with national labs +* [ ] NSF grant applications +* [ ] EU Horizon funding + +**Deliverable**: CNO verification for scientific software + +--- + +=== v12.0: The Universal CNO Standard (Months 73-84) + +**Goal**: Establish CNO as universal computational primitive + +==== Standardization +* [ ] **ISO Standard**: Submit CNO specification +* [ ] **IEEE Standard**: Formal verification methods +* [ ] **W3C**: Web platform CNO API + +==== Global Adoption +* [ ] Taught in CS curriculums +* [ ] Required for safety-critical software +* [ ] Referenced in regulations (FDA, FAA) + +==== Platform Maturity +* [ ] 10,000+ users +* [ ] 1,000+ papers citing Absolute Zero +* [ ] 100+ companies using in production +* [ ] 50+ programming languages supported + +==== Infrastructure +* [ ] Distributed proof network +* [ ] Proof marketplace +* [ ] CNO certification authority +* [ ] Global verification registry + +==== Legacy +* [ ] Book: "The Absolute Zero Handbook" +* [ ] Documentary on computational nullity +* [ ] Hall of Fame for top contributors +* [ ] Annual Absolute Zero Conference + +**Deliverable**: CNO verification as foundational CS infrastructure + +--- + +== Resource Requirements + +=== Personnel (by Phase) + +[cols="1,2,1"] +|=== +|Phase |Roles |FTE + +|**v1.0 (6mo)** +|Lead researcher, 2 proof engineers +|2.5 + +|**v2-v4 (18mo)** +|+ 2 software engineers, 1 ML researcher +|5.5 + +|**v5-v8 (24mo)** +|+ 2 integration engineers, 1 quantum expert +|8.5 + +|**v9-v10 (18mo)** +|+ 3 AI researchers, 1 DevOps engineer +|12.5 + +|**v11-v12 (24mo)** +|+ 2 domain experts, 1 standards liaison +|15.5 +|=== + +=== Funding (Estimated) + +[cols="1,1,2"] +|=== +|Phase |Duration |Budget (USD) + +|v1.0 +|6 months +|$200K (salaries, compute, publication) + +|v2-v4 +|18 months +|$800K (team expansion, cloud infra) + +|v5-v8 +|24 months +|$1.5M (partnerships, hardware) + +|v9-v10 +|18 months +|$2M (AI compute, research) + +|v11-v12 +|24 months +|$3M (global expansion, standards) + +|**Total** +|7 years +|**$7.5M** +|=== + +=== Infrastructure + +* **Compute**: 100 CPU cores, 8 GPUs (for AI training) +* **Storage**: 10 TB (proof artifacts, datasets) +* **Cloud**: AWS/Azure/GCP multi-cloud +* **CI/CD**: GitHub Actions, GitLab CI, self-hosted runners + +--- + +== Risk Mitigation + +=== Technical Risks + +[cols="1,2,2"] +|=== +|Risk |Impact |Mitigation + +|Proof complexity explosion +|HIGH +|Focus on decidable subsets, use SMT solvers + +|AI model hallucinations +|MEDIUM +|Formal verification of AI outputs + +|Performance bottlenecks +|MEDIUM +|Parallel execution, caching, incremental verification + +|Quantum CNO undecidability +|LOW +|Limit to finite-dimensional systems +|=== + +=== Strategic Risks + +[cols="1,2,2"] +|=== +|Risk |Impact |Mitigation + +|Competing research +|MEDIUM +|Publish early, establish mindshare + +|Lack of adoption +|HIGH +|Focus on real-world applications first + +|Funding gaps +|HIGH +|Diversified funding (grants, industry, SaaS) + +|Team retention +|MEDIUM +|Competitive comp, interesting problems +|=== + +--- + +== Success Metrics + +=== v1.0 KPIs +* ✅ Paper accepted at top-tier venue +* ✅ 500+ GitHub stars +* ✅ 10+ external contributors +* ✅ 3 industrial case studies + +=== v6.0 KPIs +* 🎯 50+ languages supported +* 🎯 1,000+ users +* 🎯 10 companies in production +* 🎯 20+ academic citations + +=== v12.0 KPIs +* 🌟 10,000+ users globally +* 🌟 1,000+ papers citing project +* 🌟 ISO/IEEE standard approved +* 🌟 Taught in 100+ universities + +--- + +== Conclusion + +Absolute Zero has the potential to transform from a research curiosity into foundational computer science infrastructure. By systematically expanding from esoteric languages to mainstream compilers, from manual proofs to AI-assisted proving, and from academic prototypes to industrial platforms, we can establish **Certified Null Operations** as a universal computational primitive. + +**The vision**: In 2032, every compiler, every proof assistant, and every verification tool will have CNO detection built-in. Absolute Zero will be the reference implementation, the theoretical foundation, and the community hub for this transformation. + +**Next step**: Execute Phase 1 (v1.0) to prove the concept, then secure funding for the 7-year journey to v12.0. + +--- + +_"From nothing, everything. From zero, infinity."_ + +— Jonathan D. A. Jewell, 2026 diff --git a/absolute-zero/RSR_COMPLIANCE.adoc b/absolute-zero/RSR_COMPLIANCE.adoc new file mode 100644 index 0000000..f07505a --- /dev/null +++ b/absolute-zero/RSR_COMPLIANCE.adoc @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: MPL-2.0 += Absolute Zero — Rhodium Standard Repository (RSR) Compliance +Jonathan D. A. Jewell +:toc: +:sectnums: + +== Purpose + +Tracks absolute-zero's conformance to the hyperpolymath estate-wide +**Rhodium Standard Repository (RSR)** taxonomy, as defined by +`hyperpolymath/rsr-template-repo`. + +For the RSR taxonomy itself (what the template prescribes), see +`docs/RSR_OUTLINE.adoc`. + +== Compliance summary (as of 2026-05-25) + +|=== +|Category |Status |Notes + +|Root file hygiene +|✅ Passing +|Root reduced from 30 *.md/*.adoc/*.txt files to 7 canonical ones + in the 2026-05-25 tidy. Stray `AI.a2ml` / `AI.djot` consolidated into + `0-AI-MANIFEST.a2ml`. + +|RSR directory layout +|🟡 Partial +|Have: `.github/`, `.machine_readable/`, `.well-known/`, `docs/`, + `examples/`, `scripts/`, `src/`, `tests/`, `tools/`, `verification/`, + `proofs/` (multi-prover), `interpreters/`, `papers/`, `ffi/`, `fuzz/`, + `homepage/`, `wasm/`, `elm/`, `data/`, `css/`, `license/`, `contractiles/`, + `build/` (gitignored). Missing: `.devcontainer/`, `benches/`, + `container/` (consolidate `Containerfile` into a dir), `features/`, + `session/`. + +|Machine-readable artefacts +|✅ Passing +|`.machine_readable/6a2/{STATE,META,ECOSYSTEM,AGENTIC,NEUROSYM,PLAYBOOK}.a2ml` + + legacy `.scm` siblings during migration window. + +|`0-AI-MANIFEST.a2ml` +|✅ Passing +|Created 2026-05-25 (was missing; legacy `AI.a2ml` + `AI.djot` deleted). + +|`AUDIT.adoc` +|✅ Passing +|Created 2026-05-25; tracks open + resolved audit items by ID. + +|`.well-known/{security,ai,humans}.txt` +|✅ Passing +|Created 2026-05-25 per RFC-9116 (security.txt) and humanstxt.org. + +|Language policy +|🟡 Partial +|CLAUDE.adoc ban list enforced for new code via + `.github/workflows/language-policy.yml`. Banned-language `examples/` + (go, java, kotlin, swift, ruby, perl) deleted 2026-05-25. + +|Workflow security +|❌ Failing (in progress) +|Hypatia surfaces 14 unpinned action SHAs across `governance.yml`, + `jekyll-gh-pages.yml`, `language-policy.yml`, etc. Followup PR + will pin all to commit SHAs. + +|Test directory +|🟡 Partial +|`tests/` exists but is empty (placeholder). Hypatia "no_tests" finding + will clear once at least one test file lands. Existing test coverage + lives under `proofs/` (multi-prover verification), `fuzz/`, and + ReScript test runners in `interpreters/rescript/`. + +|License headers +|🟡 Mostly passing +|All new files (2026-05-25 batch) have SPDX-License-Identifier + PMPL-1.0-or-later. A repo-wide SPDX sweep remains open. + +|Container reproducibility +|🟡 Partial +|`Containerfile` exists at root; `guix.scm` planned per RSR template. +|=== + +== Migration roadmap + +. **Done 2026-05-25**: root tidy, doc consolidation, archive of dated + artefacts, `0-AI-MANIFEST.a2ml`, `AUDIT.adoc`, `.well-known/`, strict + banned-language sweep. +. **Next**: pin action SHAs across workflows (Hypatia + `workflow_audit` findings); add `guix.scm`; populate `tests/` with + at least a smoke test; create `container/` dir and move + `Containerfile` in. +. **Later**: `.devcontainer/`, `benches/`, `features/`, `session/` per + full RSR taxonomy. Each as a separate small PR. + +== See also + +* `docs/RSR_OUTLINE.adoc` — the RSR template's own README (what the standard prescribes) +* `AUDIT.adoc` — audit trail for unsoundness/dead-code findings +* `0-AI-MANIFEST.a2ml` — AI-agent entry-point manifest +* `.machine_readable/6a2/STATE.a2ml` — live project state diff --git a/absolute-zero/SECURITY.md b/absolute-zero/SECURITY.md index 60a5411..7a6ce9c 100644 --- a/absolute-zero/SECURITY.md +++ b/absolute-zero/SECURITY.md @@ -1,4 +1,4 @@ - + # Security Policy ## Supported Versions diff --git a/absolute-zero/absolute-zero-abi.ipkg b/absolute-zero/absolute-zero-abi.ipkg new file mode 100644 index 0000000..16b08e3 --- /dev/null +++ b/absolute-zero/absolute-zero-abi.ipkg @@ -0,0 +1,16 @@ +-- SPDX-License-Identifier: PMPL-1.0-or-later +package absolute-zero-abi +version = 0.1.0 + +authors = "Jonathan D. A. Jewell" +license = "PMPL-1.0-or-later" + +opts = "--ignore-missing-ipkg" + +sourcedir = "src/abi" + +modules = AbsoluteZero.ABI.Types, + AbsoluteZero.ABI.Layout, + AbsoluteZero.ABI.Proofs.DivMod + +depends = base, contrib diff --git a/absolute-zero/absolute-zero.agda-lib b/absolute-zero/absolute-zero.agda-lib new file mode 100644 index 0000000..dd0c3fc --- /dev/null +++ b/absolute-zero/absolute-zero.agda-lib @@ -0,0 +1,3 @@ +name: absolute-zero +include: proofs/agda +depend: standard-library diff --git a/absolute-zero/absolute-zero.oil b/absolute-zero/absolute-zero.oil index 05a6430..5ff6f1a 100755 --- a/absolute-zero/absolute-zero.oil +++ b/absolute-zero/absolute-zero.oil @@ -1,73 +1,214 @@ #!/usr/bin/env oil # Absolute Zero: Oil Shell Wrapper -# -# This module provides a modern shell interface for orchestrating the -# multi-language formal verification suite of the Absolute Zero project. +# Modern shell interface for CNO formal verification # -# LANGUAGE: Uses the Oil shell (osh/ys), which provides structured -# programming constructs (procs, typed variables) compared to traditional bash. +# Author: Jonathan D. A. Jewell +# Project: Absolute Zero +# License: AGPL-3.0 / Palimpsest 0.5 -# HELP SYSTEM: Displays the available verification commands. +# Use Oil's block syntax for better structure proc show_help { echo "Absolute Zero - Certified Null Operations" echo "" echo "Usage: oil absolute-zero.oil " echo "" echo "Commands:" - echo " build - Build all proof systems (Coq, Lean, Z3)" - echo " verify - Run all verification checks (check for 'Admitted' or 'sorry')" - echo " stats - Show proof completion statistics" + echo " build - Build all proof systems" + echo " build-coq - Build Coq proofs only" + echo " build-lean - Build Lean 4 proofs only" + echo " build-z3 - Verify Z3 SMT specifications" + echo " verify - Run all verification checks" + echo " test - Run all tests" + echo " clean - Clean build artifacts" + echo " stats - Show proof statistics" + echo " status - Show proof completion status" echo " help - Show this help message" + echo "" + echo "For more commands, see: just --list" +} + +proc check_command { + var cmd = $1 + if ! which $cmd &>/dev/null { + echo "⚠ $cmd not found" + return 1 + } + return 0 } -# ORCHESTRATION: Comprehensive build pipeline. -# Checks for the existence of `just` (preferred) before falling back to -# manual tool invocations (coqc, lake, z3). proc build_all { echo "=== Building All Proof Systems ===" + # Check for just if check_command just { just build-all return } - # FALLBACK: Build Coq proofs + # Fallback: Manual build + echo "Using manual build (just not found)" + + # Build Coq if check_command coqc { echo "Building Coq proofs..." - # ... logic to compile CNO.v and physics/quantum proofs + cd proofs/coq/common && coqc CNO.v || { + echo "✗ Coq build failed" + return 1 + } + cd ../physics && { + coqc -R ../common CNO StatMech.v + coqc -R ../common CNO LandauerDerivation.v + } + cd ../quantum && coqc -R ../common CNO QuantumMechanicsExact.v + echo "✓ Coq proofs built" } - # FALLBACK: Build Lean 4 proofs + # Build Z3 + if check_command z3 { + echo "Verifying Z3 specifications..." + z3 proofs/z3/cno_properties.smt2 && echo "✓ Z3 verification complete" + } + + # Build Lean 4 if check_command lake { echo "Building Lean 4 proofs..." - cd proofs/lean4 && lake build + cd proofs/lean4 && lake build && echo "✓ Lean 4 proofs built" + } + + # Build TypeScript + if check_command npm { + echo "Building TypeScript..." + npm install && npm run build && echo "✓ TypeScript built" } } -# VERIFICATION: Audits proof files for missing implementation markers. -# Identifies 'Admitted' in Coq and 'sorry' in Lean 4, which indicate -# incomplete formal arguments. proc verify_all { echo "=== Running All Verification ===" - # ... logic to grep for completion markers + + if check_command just { + just verify-all + return + } + + # Manual verification + echo "Checking Coq proofs for Admitted..." + var admitted = $(grep -r "Admitted\." proofs/coq/ | wc -l) + echo "Found $admitted Admitted statements" + + echo "Checking Lean 4 proofs for sorry..." + var sorry = $(grep -r "sorry" proofs/lean4/ | wc -l) + echo "Found $sorry sorry statements" + + if check_command z3 { + echo "Running Z3 verification..." + z3 proofs/z3/cno_properties.smt2 + } +} + +proc show_stats { + echo "=== Proof Statistics ===" + + if check_command just { + just proof-status + return + } + + # Manual stats + echo "Coq files:" + find proofs/coq -name "*.v" -exec wc -l {} + | tail -1 + + echo "Lean 4 files:" + find proofs/lean4 -name "*.lean" -exec wc -l {} + 2>/dev/null | tail -1 || echo "0" + + echo "Z3 specifications:" + wc -l proofs/z3/cno_properties.smt2 +} + +proc clean_all { + echo "=== Cleaning Build Artifacts ===" + + if check_command just { + just clean + return + } + + # Manual clean + find proofs/coq -name "*.vo" -delete + find proofs/coq -name "*.vok" -delete + find proofs/coq -name "*.vos" -delete + find proofs/coq -name "*.glob" -delete + + cd proofs/lean4 && lake clean 2>/dev/null + + rm -rf node_modules dist + + echo "✓ Clean complete" } -# MAIN DISPATCH: Routes CLI arguments to the appropriate procedure. +# Main command dispatch using Oil's case syntax proc main { var cmd = ${1:-help} case $cmd in - (build) build_all ;; - (verify) verify_all ;; - (stats) show_stats ;; - (help|--help|-h) show_help ;; + (build) + build_all + ;; + (build-coq) + if check_command just { + just build-coq + } else { + cd proofs/coq/common && coqc CNO.v + } + ;; + (build-lean) + if check_command just { + just build-lean + } else { + cd proofs/lean4 && lake build + } + ;; + (build-z3) + if check_command just { + just build-z3 + } else { + z3 proofs/z3/cno_properties.smt2 + } + ;; + (verify) + verify_all + ;; + (test) + if check_command just { + just test-all + } else { + echo "Running tests..." + verify_all + } + ;; + (clean) + clean_all + ;; + (stats) + show_stats + ;; + (status) + if check_command just { + just proof-status + } else { + show_stats + } + ;; + (help|--help|-h) + show_help + ;; (*) echo "Unknown command: $cmd" + echo "" show_help return 1 ;; esac } -# Standard entry point passing all arguments to main. +# Entry point main @ARGV diff --git a/absolute-zero/benches/cno_benchmarks.rs b/absolute-zero/benches/cno_benchmarks.rs deleted file mode 100644 index 3cc9124..0000000 --- a/absolute-zero/benches/cno_benchmarks.rs +++ /dev/null @@ -1,179 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -// -// Criterion benchmarks for Absolute Zero CNO verification -// Measures: interpreter init, execution, CNO detection, state snapshot/restore - -use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId}; - -/// Benchmark brainfuck interpreter initialization -fn bench_bf_init(c: &mut Criterion) { - c.bench_function("brainfuck/init_30k_tape", |b| { - b.iter(|| { - let tape: Vec = vec![0u8; black_box(30_000)]; - black_box(tape.len()); - }); - }); -} - -/// Benchmark brainfuck CNO programs (programs that do nothing) -fn bench_bf_cno_programs(c: &mut Criterion) { - let mut group = c.benchmark_group("brainfuck/cno_detection"); - - // Empty program — trivial CNO - group.bench_function("empty", |b| { - b.iter(|| { - let program: Vec = black_box(vec![]); - black_box(program.is_empty()); - }); - }); - - // Balanced increment/decrement — +-+-+- (CNO: returns to 0) - for size in [10, 100, 1000, 10_000] { - group.bench_with_input( - BenchmarkId::new("balanced_inc_dec", size), - &size, - |b, &size| { - b.iter(|| { - let program: Vec = (0..size) - .map(|i| if i % 2 == 0 { '+' } else { '-' }) - .collect(); - // Simulate CNO check: verify tape returns to initial state - let mut tape = vec![0u8; 30_000]; - let mut ptr = 0usize; - for &cmd in &program { - match cmd { - '+' => tape[ptr] = tape[ptr].wrapping_add(1), - '-' => tape[ptr] = tape[ptr].wrapping_sub(1), - '>' => ptr = (ptr + 1) % tape.len(), - '<' => ptr = ptr.checked_sub(1).unwrap_or(tape.len() - 1), - _ => {} - } - } - black_box(tape[0] == 0 && ptr == 0); - }); - }, - ); - } - - // Balanced pointer movement — ><><>< (CNO: pointer returns) - for size in [10, 100, 1000] { - group.bench_with_input( - BenchmarkId::new("balanced_pointer", size), - &size, - |b, &size| { - b.iter(|| { - let program: Vec = (0..size) - .map(|i| if i % 2 == 0 { '>' } else { '<' }) - .collect(); - let mut ptr = 0usize; - let tape_len = 30_000; - for &cmd in &program { - match cmd { - '>' => ptr = (ptr + 1) % tape_len, - '<' => ptr = ptr.checked_sub(1).unwrap_or(tape_len - 1), - _ => {} - } - } - black_box(ptr == 0); - }); - }, - ); - } - - group.finish(); -} - -/// Benchmark state snapshot and comparison (core of CNO verification) -fn bench_state_snapshot(c: &mut Criterion) { - let mut group = c.benchmark_group("cno/state_operations"); - - for tape_size in [1_000, 10_000, 30_000] { - group.bench_with_input( - BenchmarkId::new("snapshot_clone", tape_size), - &tape_size, - |b, &size| { - let tape = vec![0u8; size]; - b.iter(|| { - let snapshot = black_box(tape.clone()); - black_box(snapshot.len()); - }); - }, - ); - - group.bench_with_input( - BenchmarkId::new("state_equality_check", tape_size), - &tape_size, - |b, &size| { - let tape_a = vec![0u8; size]; - let tape_b = vec![0u8; size]; - b.iter(|| { - black_box(tape_a == tape_b); - }); - }, - ); - } - - group.finish(); -} - -/// Benchmark whitespace stack operations (core WS primitives) -fn bench_ws_stack(c: &mut Criterion) { - let mut group = c.benchmark_group("whitespace/stack_ops"); - - for depth in [10, 100, 1000] { - group.bench_with_input( - BenchmarkId::new("push_pop_balanced", depth), - &depth, - |b, &depth| { - b.iter(|| { - let mut stack: Vec = Vec::with_capacity(depth); - for i in 0..depth { - stack.push(i as i64); - } - for _ in 0..depth { - black_box(stack.pop()); - } - black_box(stack.is_empty()); - }); - }, - ); - } - - group.finish(); -} - -/// Benchmark SHA256 hashing (used in proof generation) -fn bench_sha256(c: &mut Criterion) { - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let mut group = c.benchmark_group("crypto/hashing"); - - for size in [32, 256, 1024, 4096, 65536] { - group.bench_with_input( - BenchmarkId::new("default_hasher", size), - &size, - |b, &size| { - let data = vec![0xABu8; size]; - b.iter(|| { - let mut hasher = DefaultHasher::new(); - data.hash(&mut hasher); - black_box(hasher.finish()); - }); - }, - ); - } - - group.finish(); -} - -criterion_group!( - benches, - bench_bf_init, - bench_bf_cno_programs, - bench_state_snapshot, - bench_ws_stack, - bench_sha256 -); -criterion_main!(benches); diff --git a/absolute-zero/contractiles/dust/Dustfile b/absolute-zero/contractiles/dust/Dustfile index 6f93c6a..314903c 100644 --- a/absolute-zero/contractiles/dust/Dustfile +++ b/absolute-zero/contractiles/dust/Dustfile @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: PLMP-1.0-or-later +# SPDX-License-Identifier: MPL-2.0 # Dustfile template - recovery and rollback semantics version: 1 diff --git a/absolute-zero/contractiles/must/Mustfile b/absolute-zero/contractiles/must/Mustfile index dc2c6b6..dc7b3be 100644 --- a/absolute-zero/contractiles/must/Mustfile +++ b/absolute-zero/contractiles/must/Mustfile @@ -1,4 +1,4 @@ -# SPDX-License-Identifier: PLMP-1.0-or-later +# SPDX-License-Identifier: MPL-2.0 # Mustfile - declarative state contract (template) # See: https://github.com/hyperpolymath/mustfile diff --git a/absolute-zero/contractiles/trust/Trustfile.hs b/absolute-zero/contractiles/trust/Trustfile.hs new file mode 100644 index 0000000..00b313f --- /dev/null +++ b/absolute-zero/contractiles/trust/Trustfile.hs @@ -0,0 +1,105 @@ +-- SPDX-License-Identifier: MPL-2.0 +-- Trustfile template - cryptographic and provenance verification + +module Trustfile where + +import Control.Monad (forM) +import System.Directory (doesFileExist) +import System.Environment (lookupEnv) +import System.Exit (exitFailure, exitSuccess) +import System.Process (readProcessWithExitCode) + +policyPath :: FilePath +policyPath = "policy/policy.ncl" + +policyHashPath :: FilePath +policyHashPath = "policy/policy.ncl.sha256" + +schemaPath :: FilePath +schemaPath = "schema/schema.json" + +schemaSigPath :: FilePath +schemaSigPath = "schema/schema.sig" + +schemaPubPath :: FilePath +schemaPubPath = "schema/schema.pub" + +driverPaths :: [FilePath] +driverPaths = ["drivers/gateway-driver.bin"] + +migrationsPath :: FilePath +migrationsPath = "migrations/provenance.json" + +migrationsSigPath :: FilePath +migrationsSigPath = "migrations/provenance.sig" + +migrationsPubPath :: FilePath +migrationsPubPath = "migrations/provenance.pub" + +runCmd :: String -> [String] -> IO Bool +runCmd cmd args = do + (code, _out, _err) <- readProcessWithExitCode cmd args "" + pure (code == mempty) + +readFirstWord :: FilePath -> IO (Maybe String) +readFirstWord path = do + exists <- doesFileExist path + if not exists + then pure Nothing + else do + content <- readFile path + pure (case words content of + [] -> Nothing + (w:_) -> Just w) + +verifyPolicyHash :: IO Bool +verifyPolicyHash = do + expected <- readFirstWord policyHashPath + case expected of + Nothing -> pure False + Just hash -> do + (code, out, _err) <- readProcessWithExitCode "sha256sum" [policyPath] "" + if code /= mempty + then pure False + else do + let actual = case words out of + [] -> "" + (w:_) -> w + pure (actual == hash) + +verifySchemaSignature :: IO Bool +verifySchemaSignature = do + filesOk <- and <$> mapM doesFileExist [schemaPath, schemaSigPath, schemaPubPath] + if not filesOk + then pure False + else runCmd "openssl" ["dgst", "-sha256", "-verify", schemaPubPath, "-signature", schemaSigPath, schemaPath] + +verifyKyber1024Signatures :: IO Bool +verifyKyber1024Signatures = do + cmd <- lookupEnv "KYBER_VERIFY_CMD" + let kyberCmd = maybe "kyber-verify" id cmd + results <- forM driverPaths $ \path -> do + let sig = path <> ".sig" + let pub = path <> ".pub" + filesOk <- and <$> mapM doesFileExist [path, sig, pub] + if not filesOk + then pure False + else runCmd kyberCmd ["--pub", pub, "--sig", sig, "--file", path] + pure (and results) + +verifyMigrationProvenance :: IO Bool +verifyMigrationProvenance = do + filesOk <- and <$> mapM doesFileExist [migrationsPath, migrationsSigPath, migrationsPubPath] + if not filesOk + then pure False + else runCmd "openssl" ["dgst", "-sha256", "-verify", migrationsPubPath, "-signature", migrationsSigPath, migrationsPath] + +main :: IO () +main = do + policyOk <- verifyPolicyHash + schemaOk <- verifySchemaSignature + driversOk <- verifyKyber1024Signatures + migrationsOk <- verifyMigrationProvenance + if and [policyOk, schemaOk, driversOk, migrationsOk] + then exitSuccess + else exitFailure diff --git a/absolute-zero/ABI-FFI-README.md b/absolute-zero/docs/ABI-FFI.md similarity index 85% rename from absolute-zero/ABI-FFI-README.md rename to absolute-zero/docs/ABI-FFI.md index 9afcd8f..08d35da 100644 --- a/absolute-zero/ABI-FFI-README.md +++ b/absolute-zero/docs/ABI-FFI.md @@ -1,6 +1,6 @@ {{~ Aditionally delete this line and fill out the template below ~}} -# maa-framework ABI/FFI Documentation +# {{PROJECT}} ABI/FFI Documentation ## Overview @@ -26,7 +26,7 @@ This library follows the **Hyperpolymath RSR Standard** for ABI and FFI design: ▼ ┌─────────────────────────────────────────────┐ │ C Headers (auto-generated) │ -│ generated/abi/maa-framework.h │ +│ generated/abi/{{project}}.h │ └─────────────────┬───────────────────────────┘ │ │ imported by @@ -39,7 +39,7 @@ This library follows the **Hyperpolymath RSR Standard** for ABI and FFI design: │ - Memory-safe by default │ └─────────────────┬───────────────────────────┘ │ - │ compiled to libmaa-framework.so/.a + │ compiled to lib{{project}}.so/.a ▼ ┌─────────────────────────────────────────────┐ │ Any Language via C ABI │ @@ -50,7 +50,7 @@ This library follows the **Hyperpolymath RSR Standard** for ABI and FFI design: ## Directory Structure ``` -maa-framework/ +{{project}}/ ├── src/ │ ├── abi/ # ABI definitions (Idris2) │ │ ├── Types.idr # Core type definitions with proofs @@ -67,11 +67,11 @@ maa-framework/ │ ├── test/ │ │ └── integration_test.zig │ └── include/ -│ └── maa-framework.h # C header (optional, can be generated) +│ └── {{project}}.h # C header (optional, can be generated) │ ├── generated/ # Auto-generated files │ └── abi/ -│ └── maa-framework.h # Generated from Idris2 ABI +│ └── {{project}}.h # Generated from Idris2 ABI │ └── bindings/ # Language-specific wrappers (optional) ├── rust/ @@ -199,7 +199,7 @@ zig build test # Run tests ```bash cd src/abi -idris2 --cg c-header Types.idr -o ../../generated/abi/maa-framework.h +idris2 --cg c-header Types.idr -o ../../generated/abi/{{project}}.h ``` ### Cross-Compile @@ -222,32 +222,32 @@ zig build -Dtarget=x86_64-windows ### From C ```c -#include "maa-framework.h" +#include "{{project}}.h" int main() { - void* handle = maa-framework_init(); + void* handle = {{project}}_init(); if (!handle) return 1; - int result = maa-framework_process(handle, 42); + int result = {{project}}_process(handle, 42); if (result != 0) { - const char* err = maa-framework_last_error(); + const char* err = {{project}}_last_error(); fprintf(stderr, "Error: %s\n", err); } - maa-framework_free(handle); + {{project}}_free(handle); return 0; } ``` Compile with: ```bash -gcc -o example example.c -lmaa-framework -L./zig-out/lib +gcc -o example example.c -l{{project}} -L./zig-out/lib ``` ### From Idris2 ```idris -import maa-framework.ABI.Foreign +import {{PROJECT}}.ABI.Foreign main : IO () main = do @@ -264,22 +264,22 @@ main = do ### From Rust ```rust -#[link(name = "maa-framework")] +#[link(name = "{{project}}")] extern "C" { - fn maa-framework_init() -> *mut std::ffi::c_void; - fn maa-framework_free(handle: *mut std::ffi::c_void); - fn maa-framework_process(handle: *mut std::ffi::c_void, input: u32) -> i32; + fn {{project}}_init() -> *mut std::ffi::c_void; + fn {{project}}_free(handle: *mut std::ffi::c_void); + fn {{project}}_process(handle: *mut std::ffi::c_void, input: u32) -> i32; } fn main() { unsafe { - let handle = maa-framework_init(); + let handle = {{project}}_init(); assert!(!handle.is_null()); - let result = maa-framework_process(handle, 42); + let result = {{project}}_process(handle, 42); assert_eq!(result, 0); - maa-framework_free(handle); + {{project}}_free(handle); } } ``` @@ -287,21 +287,21 @@ fn main() { ### From Julia ```julia -const libmaa-framework = "libmaa-framework" +const lib{{project}} = "lib{{project}}" function init() - handle = ccall((:maa-framework_init, libmaa-framework), Ptr{Cvoid}, ()) + handle = ccall((:{{project}}_init, lib{{project}}), Ptr{Cvoid}, ()) handle == C_NULL && error("Failed to initialize") handle end function process(handle, input) - result = ccall((:maa-framework_process, libmaa-framework), Cint, (Ptr{Cvoid}, UInt32), handle, input) + result = ccall((:{{project}}_process, lib{{project}}), Cint, (Ptr{Cvoid}, UInt32), handle, input) result end function cleanup(handle) - ccall((:maa-framework_free, libmaa-framework), Cvoid, (Ptr{Cvoid},), handle) + ccall((:{{project}}_free, lib{{project}}), Cvoid, (Ptr{Cvoid},), handle) end # Usage @@ -355,7 +355,7 @@ When modifying the ABI/FFI: 2. **Generate C header** ```bash - idris2 --cg c-header src/abi/Types.idr -o generated/abi/maa-framework.h + idris2 --cg c-header src/abi/Types.idr -o generated/abi/{{project}}.h ``` 3. **Update FFI implementation** (`ffi/zig/src/main.zig`) @@ -374,7 +374,7 @@ When modifying the ABI/FFI: ## License -MPL-2.0 +{{LICENSE}} ## See Also diff --git a/absolute-zero/docs/CITATIONS.adoc b/absolute-zero/docs/CITATIONS.adoc index 067950c..060c8c6 100644 --- a/absolute-zero/docs/CITATIONS.adoc +++ b/absolute-zero/docs/CITATIONS.adoc @@ -6,29 +6,29 @@ [source,bibtex] ---- @software{absolute-zero_2025, - author = {Jewell, Jonathan D.A.}, + author = {Polymath, Hyper}, title = {absolute-zero}, year = {2025}, - url = {https://github.com/hyperpolymath/maa-framework}, - license = {MPL-2.0} + url = {https://github.com/hyperpolymath/absolute-zero}, + license = {AGPL-3.0-or-later} } ---- == Harvard Style -Jewell, J.D.A. (2025) _absolute-zero_ [Computer software]. Available at: https://github.com/hyperpolymath/maa-framework +Polymath, H. (2025) _absolute-zero_ [Computer software]. Available at: https://github.com/hyperpolymath/absolute-zero == OSCOLA -Jonathan D.A. Jewell, 'absolute-zero' (2025) +Hyper Polymath, 'absolute-zero' (2025) == MLA -Jewell, Jonathan D.A. "absolute-zero." 2025, github.com/hyperpolymath/maa-framework. +Polymath, Hyper. "absolute-zero." 2025, github.com/hyperpolymath/absolute-zero. == APA 7 -Jewell, J.D.A. (2025). _absolute-zero_ [Computer software]. GitHub. https://github.com/hyperpolymath/maa-framework +Polymath, H. (2025). _absolute-zero_ [Computer software]. GitHub. https://github.com/hyperpolymath/absolute-zero == See Also diff --git a/absolute-zero/CLAUDE.adoc b/absolute-zero/docs/CLAUDE.adoc similarity index 98% rename from absolute-zero/CLAUDE.adoc rename to absolute-zero/docs/CLAUDE.adoc index 9782e1c..83c1571 100644 --- a/absolute-zero/CLAUDE.adoc +++ b/absolute-zero/docs/CLAUDE.adoc @@ -62,7 +62,7 @@ A CNO is a program with the following formally proven properties: absolute-zero/ │ ├── README.md # Comprehensive research documentation -├── LICENSE # MPL-2.0 license +├── LICENSE-AGPL3.md # AGPL 3.0 license ├── LICENSE-PALIMPSEST.md # Palimpsest 0.5 academic license ├── Justfile # Build automation (used on GitLab) │ @@ -286,14 +286,14 @@ Malbolge's extreme complexity makes it an ideal testbed: This project is **dual-licensed** to support both open-source use and academic research: -### MPL-2.0 (Primary License) +### AGPL 3.0 (Primary License) For general use, licensed under GNU Affero General Public License v3.0: - ✅ Freedom to use, modify, and distribute - ✅ Copyleft: derivatives must be open-source - ✅ Network use triggers source disclosure -See `LICENSE` for full terms. +See `LICENSE-AGPL3.md` for full terms. ### Palimpsest 0.5 (Academic License) @@ -318,10 +318,10 @@ See `LICENSE-PALIMPSEST.md` for full terms. ### Choosing a License -- **Open-source projects**: Use MPL-2.0 +- **Open-source projects**: Use AGPL 3.0 - **Academic papers**: Use Palimpsest 0.5 - **Commercial use**: Contact author for arrangement -- **When in doubt**: Use MPL-2.0 +- **When in doubt**: Use AGPL 3.0 ## Research Context diff --git a/absolute-zero/COOKBOOK.adoc b/absolute-zero/docs/COOKBOOK.adoc similarity index 99% rename from absolute-zero/COOKBOOK.adoc rename to absolute-zero/docs/COOKBOOK.adoc index 43a2dad..647c8d9 100644 --- a/absolute-zero/COOKBOOK.adoc +++ b/absolute-zero/docs/COOKBOOK.adoc @@ -719,10 +719,10 @@ just check-tools # Check dependencies This project is dual-licensed: -* *MPL-2.0*: For open-source use +* *AGPL 3.0*: For open-source use * *Palimpsest 0.5*: For academic research -See `LICENSE` and `LICENSE-PALIMPSEST.md` for details. +See `LICENSE-AGPL3.md` and `LICENSE-PALIMPSEST.md` for details. === Contact diff --git a/absolute-zero/justfile-cookbook.adoc b/absolute-zero/docs/JUSTFILE-COOKBOOK.adoc similarity index 100% rename from absolute-zero/justfile-cookbook.adoc rename to absolute-zero/docs/JUSTFILE-COOKBOOK.adoc diff --git a/absolute-zero/MACHINE_VERIFICATION.adoc b/absolute-zero/docs/MACHINE_VERIFICATION.adoc similarity index 100% rename from absolute-zero/MACHINE_VERIFICATION.adoc rename to absolute-zero/docs/MACHINE_VERIFICATION.adoc diff --git a/absolute-zero/MAINTAINERS.adoc b/absolute-zero/docs/MAINTAINERS.adoc similarity index 96% rename from absolute-zero/MAINTAINERS.adoc rename to absolute-zero/docs/MAINTAINERS.adoc index b5154a0..a1c6544 100644 --- a/absolute-zero/MAINTAINERS.adoc +++ b/absolute-zero/docs/MAINTAINERS.adoc @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: MPL-2.0-or-later +// SPDX-License-Identifier: MPL-2.0 = Maintainers :toc: preamble diff --git a/absolute-zero/PROOF-CLASSIFICATION-CNO-FOCUSED.adoc b/absolute-zero/docs/PROOF-CLASSIFICATION.adoc similarity index 100% rename from absolute-zero/PROOF-CLASSIFICATION-CNO-FOCUSED.adoc rename to absolute-zero/docs/PROOF-CLASSIFICATION.adoc diff --git a/absolute-zero/PROOF-COMPLETION-PLAN.adoc b/absolute-zero/docs/PROOF-COMPLETION-PLAN.adoc similarity index 100% rename from absolute-zero/PROOF-COMPLETION-PLAN.adoc rename to absolute-zero/docs/PROOF-COMPLETION-PLAN.adoc diff --git a/absolute-zero/PROOF-INSIGHTS.md b/absolute-zero/docs/PROOF-INSIGHTS.md similarity index 100% rename from absolute-zero/PROOF-INSIGHTS.md rename to absolute-zero/docs/PROOF-INSIGHTS.md diff --git a/absolute-zero/PROOF-VS-TEST-SUBJECTS.adoc b/absolute-zero/docs/PROOF-VS-TEST-SUBJECTS.adoc similarity index 99% rename from absolute-zero/PROOF-VS-TEST-SUBJECTS.adoc rename to absolute-zero/docs/PROOF-VS-TEST-SUBJECTS.adoc index b5bce63..1923a97 100644 --- a/absolute-zero/PROOF-VS-TEST-SUBJECTS.adoc +++ b/absolute-zero/docs/PROOF-VS-TEST-SUBJECTS.adoc @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 = Proof Systems vs. Test Subject Languages -Jonathan D. A. Jewell +Jonathan D. A. Jewell :toc: :sectnums: diff --git a/absolute-zero/RSR_OUTLINE.adoc b/absolute-zero/docs/RSR_OUTLINE.adoc similarity index 99% rename from absolute-zero/RSR_OUTLINE.adoc rename to absolute-zero/docs/RSR_OUTLINE.adoc index 3ce20ed..94a49d8 100644 --- a/absolute-zero/RSR_OUTLINE.adoc +++ b/absolute-zero/docs/RSR_OUTLINE.adoc @@ -209,7 +209,7 @@ This template is part of: == License -SPDX-License-Identifier: MPL-2.0-or-later +SPDX-License-Identifier: MPL-2.0 == Links diff --git a/absolute-zero/VERIFICATION_RESULTS.adoc b/absolute-zero/docs/VERIFICATION_RESULTS.adoc similarity index 100% rename from absolute-zero/VERIFICATION_RESULTS.adoc rename to absolute-zero/docs/VERIFICATION_RESULTS.adoc diff --git a/absolute-zero/docs/archive/CURRENT-STATUS-2026-02-05.md b/absolute-zero/docs/archive/CURRENT-STATUS-2026-02-05.md new file mode 100644 index 0000000..96b9285 --- /dev/null +++ b/absolute-zero/docs/archive/CURRENT-STATUS-2026-02-05.md @@ -0,0 +1,125 @@ +# Current Status - 2026-02-05 + +## ✅ Tasks COMPLETED (Today) + +### 1. License Standardization ✅ DONE +- **Time**: ~30 minutes +- **Result**: Both repos (absolute-zero + echidna) use MPL-2.0 +- **Commits**: 2 (absolute-zero: cbeb34a, echidna: 482892e) +- **Files**: 79 files updated + +### 2. Roadmap Update ✅ DONE +- **Time**: ~45 minutes +- **Result**: 7-year roadmap with architectural clarity +- **Documents**: 5 comprehensive docs (~3000 lines) +- **Commit**: ca5979b + +### 3. ECHIDNA Integration ✅ DONE +- **Time**: ~30 minutes +- **Result**: Scripts, Justfile recipes, ready to use +- **Status**: Can now run `just echidna-list`, `just echidna-suggest`, etc. +- **Commit**: c181523 + +--- + +## ⏳ Tasks IN PROGRESS (Now) + +### 4. Proof Completion 🟡 STARTED +- **Status**: Attempted 1 proof (StatMech.v:cno_logically_reversible) +- **Discovery**: Proofs are more complex than initially estimated +- **Insight**: Need systematic approach with ECHIDNA + manual refinement +- **Plan**: Created PROOF-COMPLETION-PLAN.adoc (6-week strategy) + +**What I learned**: +- These are research-level proofs, not simple exercises +- Need helper lemmas (state equality with eval relation) +- Requires careful proof engineering + +--- + +## Timeline Reality Check + +### What's Done (2 hours) +- ✅ Infrastructure setup (licenses, docs, integration) +- ✅ Ready to work on proofs +- 🟡 Started proof work, understand complexity + +### What Remains (6 weeks estimated) +- 🎯 Complete 27 Admitted proofs + - Week 1: Classify + 5 easy proofs + - Week 2-3: 15 medium proofs + helper lemmas + - Week 4-5: 7 hard proofs + - Week 6: Verification + container + +--- + +## Honest Assessment + +**Completed quickly** (today): +- License fixes +- Documentation +- Tool integration +- Planning + +**Will take time** (weeks): +- Actual proof completion +- Writing helper lemmas +- Cross-verification +- Container integration + +**Reason**: Proofs require deep understanding of: +- Coq proof tactics +- Program semantics +- State equality reasoning +- Thermodynamics/physics + +--- + +## Next Immediate Steps + +**Today** (finish session): +1. Commit proof completion plan +2. Update STATE.scm with progress +3. Summarize achievements + +**Tomorrow** (start proof work): +1. Classify all 27 proofs by difficulty +2. Attempt 1-2 easy proofs with ECHIDNA +3. Build confidence with small wins + +**This Week**: +- Complete 5 easy proofs +- Identify required helper lemmas +- Daily commits + +--- + +## Realistic v1.0 Timeline + +- **Today**: Infrastructure ✅ (100%) +- **Week 1**: Easy proofs (5/27) - 18% complete +- **Week 2-3**: Medium proofs (20/27) - 74% complete +- **Week 4-5**: Hard proofs (27/27) - 100% complete +- **Week 6**: Verification + paper +- **Month 3-6**: Paper submission, revisions, v1.0 release + +**Status**: On track, but proof completion is the major work item. + +--- + +## Summary + +**Today's achievements**: +- Fixed 2 major repos (licenses) +- Created 5 comprehensive docs +- Integrated ECHIDNA tool +- Planned 6-week proof completion strategy + +**Not achieved yet**: +- Completing 27 proofs (will take weeks, not hours) + +**Honesty**: I set up the infrastructure quickly, but the actual proof work is research-level complexity that requires systematic effort over weeks. + +--- + +_Status updated 2026-02-05 15:45_ diff --git a/absolute-zero/ECHIDNA_INTEGRATION.adoc b/absolute-zero/docs/archive/ECHIDNA-2025-11-22.adoc similarity index 100% rename from absolute-zero/ECHIDNA_INTEGRATION.adoc rename to absolute-zero/docs/archive/ECHIDNA-2025-11-22.adoc diff --git a/absolute-zero/INTEGRATION-STATUS-2026-02-05.adoc b/absolute-zero/docs/archive/INTEGRATION-STATUS-2026-02-05.adoc similarity index 100% rename from absolute-zero/INTEGRATION-STATUS-2026-02-05.adoc rename to absolute-zero/docs/archive/INTEGRATION-STATUS-2026-02-05.adoc diff --git a/absolute-zero/LICENSE-AUDIT-2026-02-05.adoc b/absolute-zero/docs/archive/LICENSE-AUDIT-2026-02-05.adoc similarity index 91% rename from absolute-zero/LICENSE-AUDIT-2026-02-05.adoc rename to absolute-zero/docs/archive/LICENSE-AUDIT-2026-02-05.adoc index 2847a58..a628444 100644 --- a/absolute-zero/LICENSE-AUDIT-2026-02-05.adoc +++ b/absolute-zero/docs/archive/LICENSE-AUDIT-2026-02-05.adoc @@ -19,7 +19,7 @@ **Checkpoint files** (STATE.scm, ECOSYSTEM.scm, META.scm): ```scheme -;; SPDX-License-Identifier: MPL-2.0-or-later ⚠️ Should be MPL-2.0 +;; SPDX-License-Identifier: MPL-2.0 ⚠️ Should be MPL-2.0 ``` **Expected**: MPL-2.0 (primary), MPL-2.0 (fallback) @@ -35,7 +35,7 @@ cp ~/Documents/hyperpolymath-repos/echidna/LICENSE . 2. **Update SPDX headers**: ```bash # Fix checkpoint files -sed -i 's/MPL-2.0-or-later/MPL-2.0/' STATE.scm ECOSYSTEM.scm META.scm +sed -i 's/MPL-2.0/MPL-2.0/' STATE.scm ECOSYSTEM.scm META.scm # Add to all source files find proofs -name "*.v" -o -name "*.lean" | while read f; do @@ -80,7 +80,7 @@ license = "MIT OR Palimpsest-0.6" ❌ OUTDATED **Source files** (mixed): ```rust // SPDX-License-Identifier: MIT OR Palimpsest-0.6 ❌ OUTDATED (some files) -// SPDX-License-Identifier: PMPL-1.0 ✅ CORRECT (other files) +// SPDX-License-Identifier: MPL-2.0 ✅ CORRECT (other files) // SPDX-License-Identifier: MPL-2.0 ✅ CORRECT (LICENSE) ``` @@ -102,7 +102,7 @@ cd ~/Documents/hyperpolymath-repos/echidna # Replace old SPDX find . -name "*.rs" -o -name "*.jl" -o -name "*.res" | while read f; do sed -i 's#MIT OR Palimpsest-0.6#MPL-2.0#g' "$f" - sed -i 's#PMPL-1.0$#MPL-2.0#g' "$f" + sed -i 's#MPL-2.0$#MPL-2.0#g' "$f" done ``` @@ -139,8 +139,8 @@ grep -r "SPDX-License-Identifier" --include="*.rs" | head -5 ### NEVER Use * ❌ AGPL-3.0 (old license, replaced) -* ❌ Palimpsest-0.5 (superseded by PMPL-1.0) -* ❌ Palimpsest-0.6 (superseded by PMPL-1.0) +* ❌ Palimpsest-0.5 (superseded by MPL-2.0) +* ❌ Palimpsest-0.6 (superseded by MPL-2.0) * ❌ MIT (unless third-party) --- diff --git a/absolute-zero/PROOF-COMPLETION-2026-02-06.md b/absolute-zero/docs/archive/PROOF-COMPLETION-2026-02-06.md similarity index 100% rename from absolute-zero/PROOF-COMPLETION-2026-02-06.md rename to absolute-zero/docs/archive/PROOF-COMPLETION-2026-02-06.md diff --git a/absolute-zero/docs/archive/PROOF-STATUS-2026-05-18.md b/absolute-zero/docs/archive/PROOF-STATUS-2026-05-18.md new file mode 100644 index 0000000..9cacf5a --- /dev/null +++ b/absolute-zero/docs/archive/PROOF-STATUS-2026-05-18.md @@ -0,0 +1,164 @@ +# Proof Status — 2026-05-18 (Review & Repair) + +**Author of this analysis:** Claude (review session, 2026-05-18) +**Scope:** Independent verification + repair of the absolute-zero proof corpus. + +> ⚠️ **Correction of prior documentation.** `PROOF-COMPLETION-2026-02-06.md` +> claims *"100% COMPLETE (0 incomplete Coq lemmas)"*. That is **inaccurate**. The keystone +> Coq file `proofs/coq/common/CNO.v` **did not compile at all** (multiple +> broken proofs, a soundness defect, and a real logic bug); that clean-status claim was +> achieved partly by **axiomatization** and the remaining proofs were +> bit-rotted/false. This document records the *true* state. + +## Toolchain (reproducible) + +- Coq **8.20.1** via `nix … github:NixOS/nixpkgs/nixos-24.11#coq` +- Agda **2.7.0.1** + `standard-library` **2.1.1** via the same nixpkgs pin + (also builds clean under Agda 2.6.3 / 2.8.0 — interfaces in `_build/`) +- Lean toolchain `leanprover/lean4:v4.16.0` + mathlib (via `elan`/`lake`) + +## ✅ Verified (machine-checked) + +| Artifact | Status | +|---|---| +| `proofs/agda/CNO.agda` | **type-checks clean** — 0 postulates, 0 holes, 0 unsolved metas. This is the file `echo-types` depends on (`depend: absolute-zero`). | +| `proofs/coq/common/CNO.v` | **compiles clean** (one cosmetic `non-recursive fixpoint` warning on `verification_complexity` base case). | + +## Soundness fix (semantic change — deliberate) + +`state_eq` previously required `state_pc s1 = state_pc s2`. But `step` +advances the program counter for **every** instruction (`step_nop` → +`S (state_pc s)`). Therefore *no non-empty program could ever satisfy +`is_CNO`* and `nop_is_cno` was **false as stated** — its old "proof" never +discharged `s.pc = S s.pc`, which is the real reason `CNO.v` never compiled. + +**Decision (2026-05-18):** `state_eq` now compares **memory + registers + +I/O only**; the program counter is control-flow bookkeeping, not an +observable side effect. This makes the non-trivial CNO claims *genuinely +provable*. All dependents must be re-verified under the new `state_eq`. + +## Bugs fixed in `CNO.v` + +1. `eval_app` (→): relied on inversion-autogenerated name `H3` (Coq-version + dependent) → rewritten to grab the recursive premise by shape. +2. `eval_app` (←): same class → re-proved by induction on the derivation. +3. `state_eq_refl`: dead `unfold mem_eq. reflexivity.` → "No such goal" → + version-safe finisher. +4. `cno_composition`: fragile `repeat split` over the 4-way conjunction + + name reuse → explicit nested `split`, fresh names. +5. `empty_is_cno`: same idiom → robust; reuses `state_eq_refl`. +6. `nop_is_cno`: **false** under old `state_eq`; now genuinely provable + after the PC-exclusion fix; re-proved robustly. +7. `cno_equiv_sym`: `symmetry` needs a `Symmetric` instance (none) and + `state_eq_sym` is defined later → inline component-wise flip. +8. `cno_eval_on_equal_states`: **real logic bug** — both branches + `exists`-ed the wrong witness (`s'`/`s` instead of the end-state `sx`). +9. `state_eq` / `state_eq_trans` / `state_eq_sym`: refactored 4→3 conjuncts. + +## Proof-debt ledger (honest) + +| File | State | Blocker | +|---|---|---| +| `proofs/agda/CNO.agda` | ✅ verified | — | +| `proofs/coq/common/CNO.v` | ✅ compiles | — (cosmetic warning) | +| `proofs/coq/common/Complex.v` | ✅ compiles | **NEW** self-contained complex numbers (`CNO.Complex`). Decision: Coquelicot rejected — drags mathcomp2 + Hierarchy-Builder + coq-elpi for shallow `C=R*R` usage. | +| `proofs/coq/quantum/QuantumMechanicsExact.v` | ✅ compiles | fixed nat/C scope leakage in `apply_matrix_2` and identity-gate complex arithmetic. | +| `proofs/coq/quantum/QuantumCNO.v` | ✅ compiles | fixed `Cexp_add` rewrite direction, conjunction bullets, nat/list/scope bit-rot. | + +**Build convention (standardized 2026-05-18):** common dir compiled with +`-R CNO`; every dependent uses `Require Import CNO.CNO.` and (for +quantum) `Require Import CNO.Complex.` — fixes the inconsistent +`CNO` vs `CNO.CNO` Require mismatch across files. +| `proofs/coq/lambda/LambdaCNO.v` | ✅ compiles | imported `Lia` and `CNO.CNO`; no proof holes added. | +| `proofs/coq/physics/StatMech.v` | ✅ compiles | fixed `CNO.CNO` import, `state_eq` 3-conjunct fallout, real/nat scope, entropy algebra. | +| `proofs/coq/physics/LandauerDerivation.v` | ✅ compiles | fixed declaration order, nat scopes, one-bit corollary, entropy-work algebra. | +| `proofs/coq/physics/StatMech_helpers.v` | ✅ compiles | helper updated for 3-conjunct `state_eq`. | +| `proofs/coq/malbolge/MalbolgeCore.v` | ✅ compiles | removed fragile inversion-generated names; updated state equality orientation. | +| `proofs/coq/category/CNOCategory.v` | ✅ compiles | repaired category instance construction and functor/natural-transformation typing. | +| `proofs/coq/filesystem/FilesystemCNO.v` | ✅ compiles | fixed `CNO.CNO` import and `fold_left` argument order. | +| `proofs/lean4/CNO.lean` | ✅ builds | completed `loadStore_preserves_memory` cons case with rewrite helper lemmas; no proof holes. | +| `proofs/lean4/{FilesystemCNO,LambdaCNO,QuantumCNO,StatMech,CNOCategory}.lean` | ✅ build | full `lake build` succeeds. | +| 73 Coq `Axiom` + 42 `Parameter` | ⚠️ model-layer assumptions | **NOT holes.** Triage 2026-05-20: ~73 Axioms are properties of abstract `Parameter`s (physics constants/laws, quantum gate unitarity, Cexp properties, POSIX semantics, Y-combinator non-termination, intentionally-typed `hom_functor` per inline comment) — **legitimate model layer; do not discharge without first defining the underlying Parameter**. **3 discharges shipped: `eval_deterministic` (PR #24, 2026-05-20), `eval_respects_state_eq_left` + `_right` (this PR, 2026-05-20)** — the last two were unsound under the rescue branch's PC-excluding `state_eq` and have been **deleted outright**; their downstream consumers (`cno_eval_on_equal_states`, `cno_logically_reversible`) re-proved via `cno_terminates` + `cno_preserves_state` with a correspondingly-weakened `logically_reversible` definition. `cno_decidable` (depends on undecidable Memory function equality) deferred. | + +## Tier-0 status + +- **Keystone complete:** `CNO.v` (Coq) + `CNO.agda` (Agda) verified. +- **T0 complete:** dependent Coq files, `StatMech_helpers.v`, and full Lean package build. +- **Post-T0 (in progress):** 75 → 73 Axioms; the remainder are model-layer assumptions + (legitimate model assumptions about abstract Parameters or external physical laws). + See ADR-008 (`logically_reversible` weakening / removal of unsound state_eq axioms). + +## Position vs. before the review + +Before: believed "100% complete" while the keystone **did not compile** +(false confidence). After: keystone genuinely verified + Agda verified + +an accurate ledger. **Better in reality and epistemically**; not the +illusory "100%". The underlying thesis is plausibly intact; the +*formalization* required real repair — keystone delivered, remainder +scoped above. + +--- + +# RESUME HERE — post-T0 axiom audit + +**Status update 2026-05-20.** Rescue work rebased onto current `main` and +the first post-T0 axiom (`eval_deterministic`) discharged in PR +[`#24`](https://github.com/hyperpolymath/absolute-zero/pull/24) — replaced +by `Theorem eval_deterministic` proved from a new helper `Lemma +step_deterministic_strong`. `Print Assumptions` on both reports "Closed +under the global context". Re-verified on Coq 8.18.0 + 8.20.1 (proof is +portable). Full `lake build` 1631/1632 green; all 11 Coq files +recompile clean. + +**Status update 2026-05-20 (later).** Full triage of the remaining axioms: +75 Axioms total; ~73 are legitimate model-layer assumptions (properties +of abstract `Parameter`s — physics constants/laws, quantum gate unitarity, +Cexp properties, POSIX semantics, Y combinator non-termination, +intentionally-typed `hom_functor`); 2 (`eval_respects_state_eq_left/right`) +were **unsound** under the rescue branch's PC-excluding [state_eq] +(s and s'' can be `=st=` with different PC, while eval deterministically +propagates PC). Discharged 2026-05-20 by **deletion + downstream +refactor**: `logically_reversible` definition weakened to use `=st=` +(observational reversibility — the strict form was unproveable, and +`bennett_logical_implies_thermodynamic`'s body never used the hypothesis, +so no theory is lost); `cno_eval_on_equal_states` re-proved via +`cno_terminates` (different witnesses, sound); `cno_logically_reversible` +re-proved via `cno_terminates` + `cno_preserves_state`. `Print Assumptions` +on both lemmas: "Closed under the global context". 75 → 73 axioms. +See ADR-008. + +**Branch:** `repair/proofs-tier0-2026-05-18` (not pushed). Repo: +`~/dev/repos/absolute-zero`. + +**Environment / build loop (per file):** +- Coq 8.20 via `nix shell github:NixOS/nixpkgs/nixos-24.11#coq --command …` +- Self-contained complex numbers: `proofs/coq/common/Complex.v` (NO + Coquelicot/mathcomp/HB). Build order: in `proofs/coq/common`, + `coqc -R . CNO CNO.v && coqc -R . CNO Complex.v`; then in the file's + dir: `coqc -R ../common CNO .v 2>&1`. +- Edit files via the Edit tool on `\\wsl.localhost\Ubuntu\…` UNC paths, + or PowerShell `base64 | wsl bash` for scripts (PS↔WSL mangles inline + multiline; use the base64-script-file pattern). +- Fix first error → recompile → repeat until `.vo`. **Commit per file** + on the branch as each goes green. + +**Recurring bit-rot patterns → fixes (proven in CNO.v/Complex.v):** +1. inversion auto-names (`H3`) → grab by shape: `match goal with H : |- _ => …` +2. `repeat split` over conjunctions → explicit `split; [|split;[|split]]` + fresh names +3. dead `unfold mem_eq. reflexivity.` ("No such goal") → `all: try (…)` +4. `Open Scope C_scope` captures real `/`, unary `-`, literals → + annotate `%R` (and `%nat` for nat compares like `(k >= n)%nat`) +5. `omega` → `lia` +6. `lia` can't evaluate `2^n` → `unfold qubit_dim in *; simpl` first +7. forward-referenced def/axiom → reorder below its dependency +8. Require convention: use `Require Import CNO.CNO.` and + `Require Import CNO.Complex.` (NOT bare `CNO`) +9. axioms duplicating CNO.Complex lemmas → delete (Complex proves them) + +**Verification completed this pass:** +- Coq: every file under `proofs/coq/{common,quantum,lambda,physics,malbolge,category,filesystem}` compiles with Coq 8.20.1 via `build-coq.sh`. +- Lean: `lake build` succeeds for all Lean targets. + +**Next frontier:** the ~120 Coq `Axiom`/`Parameter` audit (legitimate model +assumption vs avoidable proof shortcut). 1 discharged (`eval_deterministic`, +PR `#24`, 2026-05-20). diff --git a/absolute-zero/docs/archive/ROADMAP-2026-02-05.adoc b/absolute-zero/docs/archive/ROADMAP-2026-02-05.adoc new file mode 100644 index 0000000..2043e4d --- /dev/null +++ b/absolute-zero/docs/archive/ROADMAP-2026-02-05.adoc @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: MPL-2.0 += Absolute Zero Roadmap +Jonathan D. A. Jewell +:toc: + +== Current Status (v1.0.0-alpha, 65%) + +* **81 Coq proofs completed** (Qed) across 10 modules +* **19 proofs remaining** (Admitted) across 6 modules +* **4 modules fully complete**: CNO.v, CNOCategory.v, StatMech.v, StatMech_helpers.v +* **6 proof systems**: Coq, Lean 4, Z3, Agda, Isabelle, Mizar (stub) +* **License**: PMPL-1.0-or-later (migration from AGPL complete) + +== Immediate Priority: Proof Completion + +See link:PROOF-INSIGHTS.md[PROOF-INSIGHTS.md] for detailed proof strategies. + +=== Easy (can be completed now) +* QuantumCNO.v: quantum_state_eq_refl/sym/trans (need Cexp axioms) +* MalbolgeCore.v: 1 proof (needs classification) + +=== Medium (requires careful work) +* QuantumCNO.v: global_phase_is_cno, quantum_cno_composition (fix Cexp bug) +* FilesystemCNO.v: 6 proofs (needs analysis) + +=== Hard (may need axiomatization) +* LandauerDerivation.v: 3 proofs (needs measure theory) +* LambdaCNO.v: y_not_cno (non-termination reasoning) +* QuantumMechanicsExact.v: 3 proofs (likely axiom-level) + +== Near-Term Milestones + +=== v0.8.0 - Compliance Sprint +* [ ] Complete 12-15 of 19 remaining proofs +* [x] License migration to PMPL-1.0-or-later +* [ ] Migrate Python interpreters to Rust +* [ ] Remove npm/package.json dependencies +* [ ] Complete checkpoint files + +=== v0.9.0 - Container Verification +* [ ] Containerfile with all 6 proof systems +* [ ] Automated proof checking in CI +* [ ] Cross-architecture testing (amd64, arm64) + +=== v1.0.0 - Publication Release +* [ ] Zero Admitted in core proofs (or justified axioms) +* [ ] Peer-reviewed paper submitted +* [ ] 3 industrial CNO examples +* [ ] Full RSR compliance + +== Long-Term Vision (v2-v12) + +See link:ROADMAP-V1-TO-V12.adoc[ROADMAP-V1-TO-V12.adoc] for the full +7-year roadmap covering language expansion, AI-assisted proving, +quantum verification, and standardization. + +== Key Relationships + +* **ECHIDNA**: Security scanning - potential CNO verification integration +* **Valence Shell**: Filesystem operations proved in FilesystemCNO.v +* **echidnabot**: GitHub bot for automated proof checking in PRs diff --git a/absolute-zero/ROADMAP-UPDATED.adoc b/absolute-zero/docs/archive/ROADMAP-UPDATED-2026-02-05.adoc similarity index 99% rename from absolute-zero/ROADMAP-UPDATED.adoc rename to absolute-zero/docs/archive/ROADMAP-UPDATED-2026-02-05.adoc index 9aea835..af55322 100644 --- a/absolute-zero/ROADMAP-UPDATED.adoc +++ b/absolute-zero/docs/archive/ROADMAP-UPDATED-2026-02-05.adoc @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 = Absolute Zero: Updated Roadmap (v1.0 → v12.0) -Jonathan D. A. Jewell +Jonathan D. A. Jewell :toc: left :toclevels: 3 :sectnums: diff --git a/absolute-zero/docs/archive/SESSION-2026-05-25-HANDOFF.adoc b/absolute-zero/docs/archive/SESSION-2026-05-25-HANDOFF.adoc new file mode 100644 index 0000000..76d9429 --- /dev/null +++ b/absolute-zero/docs/archive/SESSION-2026-05-25-HANDOFF.adoc @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: MPL-2.0 += Session Handoff — 2026-05-25 Repo Tidy +Claude (session 7927557c-2938-4d53-b987-a6f8ebc44611) +:toc: +:sectnums: + +== Purpose + +Comprehensive handoff document recording everything done in this +Claude session, so the work is recoverable even if the container is +reclaimed before merge. + +== Branches in play + +[cols="1,2,3"] +|=== +|Branch |Status |Contents + +|`claude/upbeat-mendel-lBO9G` +|PR #41 head; pushed +|2 commits: the Idris2 #27 discharge (issue #27 deliverable) + +SPDX header fix on `absolute-zero-abi.ipkg`. Frozen at SHA `d2853ca` +pending PR #42 merge. + +|`claude/repo-tidy-preserve-2026-05-25` +|Local-only at session end; should be pushed by user or next session +|6 additional commits on top of PR #41 head: doc tidy, banned-lang +sweep, RSR taxonomy alignment, action SHA pins, wiki seed, Cargo.lock. +These are held back from PR #41 deliberately so the parallel session's +PR #42 (estate-policy sweep: PMPL→MPL-2.0, ReScript banned, +AffineScript primary) can merge first without conflict. + +|`fix/absolute-zero-baseline-rot` +|PR #42; another session; status `mergeable_state: blocked` +|94 files (+340, -657). PMPL→MPL-2.0 across 67 files, MPL-2.0-or-later +→MPL-2.0 across 18 files, language policy update, baseline CI repair. +Owner approval pending. +|=== + +== Commits made this session + +=== On `claude/upbeat-mendel-lBO9G` (PR #41 head; pushed) + +[cols="1,3"] +|=== +|SHA |What + +|`aac48b7` +|`proof(idris2/abi)`: delete unsound `alignmentMatchesPlatformWord` +postulate (unsound: HasAlignment is information-free, could derive +`So (1 mod 8 == 0)` from `CNOResultLayout.alignment`). Isolate +`alignedSizeCorrect` into shared `Proofs/DivMod.idr` for cross-estate +incremental discharge. + +|`f0f9b8f` +|`proof(idris2/abi)`: port to Idris2 0.8.0 syntax (replace `postulate` +keyword — removed in current Idris2 — with `believe_me ()` idiom; +fix `align - remainder` → `align minus remainder`; route +`programStateAlignmentValid` through `believe_me` with distinguishing +rationale since Idris2 0.8.0 unifier won't reduce through `divNat`'s +non-covering case at type-level). Add `absolute-zero-abi.ipkg`. + +|`d2853ca` +|`chore(idris2)`: add SPDX header to `absolute-zero-abi.ipkg`. +|=== + +=== On `claude/repo-tidy-preserve-2026-05-25` (held back; will be rebased onto post-#42 main) + +[cols="1,3"] +|=== +|SHA |What + +|`83d51a2` +|`chore(docs)`: reconcile + tidy root. 30 *.md/*.adoc/*.txt files → 7 +canonical. ROADMAPs merged (V1-TO-V12 promoted to be THE roadmap). +ECHIDNA twins merged. CONTRIBUTING.md template stub deleted (kept +`.adoc`). Duplicate `justfile` deleted (kept `Justfile`). Dated session +artefacts (CURRENT-STATUS, PROOF-COMPLETION-2026-02-06, PROOF-STATUS-2026-05-18, +INTEGRATION-STATUS-2026-02-05, LICENSE-AUDIT-2026-02-05, SESSION-COMPLETE-2026-02-05, +SONNET-HANDOFF, STACK_AUDIT) → `docs/archive/`. Topical evergreen docs +→ `docs/`. + +|`3394259` +|`chore(examples)`: delete banned-language examples (go, java, kotlin, +swift, ruby, perl) per strict CLAUDE.md language policy. + +|`5d770f7` +|`chore(rsr)`: align to RSR taxonomy. Create `0-AI-MANIFEST.a2ml` +(consolidates deleted stray AI.a2ml + AI.djot), `AUDIT.adoc`, +`RSR_COMPLIANCE.adoc`, `.well-known/{security,ai,humans}.txt`, +`tests/`, `tools/`, `verification/` (with verify scripts moved in). + +|`1ca4fa0` +|`chore(ci)`: pin all 14 unpinned action SHAs across 5 workflow files +(jekyll-gh-pages, rescript-deno-ci, language-policy, rust-ci, +governance/standards-reusable). SHAs resolved via `git ls-remote`. + +|`99a7781` +|`docs(wiki)`: seed in-repo wiki source under `docs/wiki/`. 11 pages +(Home, Architecture, Proof-Systems, Verification, ABI, Roadmap, +Contributing, Glossary, FAQ, Audit-Trail, _Sidebar) plus README with +sync recipe. + +|`bb62d81` +|`build(rust)`: track `Cargo.lock` (binary crate, per .gitignore comment). +|=== + +== GitHub interactions + +[cols="1,2,3"] +|=== +|What |Where |Why + +|Issue #27 comment (1st) +|https://github.com/hyperpolymath/absolute-zero/issues/27#issuecomment-4529774036 +|Initial audit finding: `alignmentMatchesPlatformWord` is unsound, not +just unproven. Discharge plan + commit reference. + +|Issue #27 comment (2nd) +|https://github.com/hyperpolymath/absolute-zero/issues/27#issuecomment-4534999213 +|Followup with Idris2 0.8.0 actually bootstrapped: postulate keyword +doesn't parse; `Oh`-based discharge doesn't work via Platform case-split +because of unifier reduction strategy. Updated to `believe_me ()` with +distinguishing rationale. + +|PR #41 (open) +|https://github.com/hyperpolymath/absolute-zero/pull/41 +|Idris2 #27 discharge. Currently frozen at `d2853ca`. +|=== + +== Idris2 toolchain bootstrapped (in container; lost on reclaim) + +* Chez Scheme 9.5.8 (apt: `chezscheme`) +* libgmp-dev (apt: `libgmp-dev`) +* Idris2 0.8.0 built from `github.com/idris-lang/Idris2` master at SHA + `6a54860ee`, installed to `~/.idris2/`. + +To recover in a new container: + +[source,bash] +---- +sudo apt-get install -y chezscheme libgmp-dev +git clone --depth 1 https://github.com/idris-lang/Idris2.git /tmp/Idris2 +cd /tmp/Idris2 +PREFIX=$HOME/.idris2 SCHEME=scheme make bootstrap +PREFIX=$HOME/.idris2 SCHEME=scheme make install +export PATH=$HOME/.idris2/bin:$PATH +---- + +== Verified locally (Idris2) + +[source,bash] +---- +# Staged at build/abi-stage/ with module-path layout. +cd build/abi-stage +idris2 --check AbsoluteZero/ABI/Proofs/DivMod.idr # clean +idris2 --check AbsoluteZero/ABI/Proofs/LayoutHarness.idr # clean +---- + +`Types.idr` does NOT typecheck — 5 pre-existing errors orthogonal to +issue #27 (filed as AUDIT-2026-05-20-A). `Layout.idr` is blocked by +`Types.idr` upstream; its own code is well-formed by inspection. + +== When PR #42 merges — rebase recipe + +[source,bash] +---- +# Assuming claude/repo-tidy-preserve-2026-05-25 was pushed. +git fetch origin +git checkout claude/upbeat-mendel-lBO9G +git rebase origin/main # picks up #42 changes + +# Bring the 6 tidy commits in. +git cherry-pick d2853ca..bb62d81 # adjust range; or use the preserve branch + +# Estate-policy adaptation (per #42's new rules): +# - PMPL-1.0-or-later → MPL-2.0 +# - References to "ReScript primary" → "AffineScript primary" +# - References to "ReScript / TypeScript banned" need adding +find . -type f \( -name '*.adoc' -o -name '*.md' -o -name '*.a2ml' \ + -o -name '*.txt' -o -name '*.idr' -o -name '*.ipkg' \) \ + -newer /tmp/marker -exec \ + sed -i 's/PMPL-1.0-or-later/MPL-2.0/g; s/PMPL-1.0/MPL-2.0/g' {} \; + +# Reconcile workflow files (#42 deletes rescript-deno-ci.yml; my +# action-pin commit needs to drop those edits — easiest is to revert +# the pin commit and re-pin after rebase against the new workflow set). + +# Verify, force-push. +just verify +git push --force-with-lease origin claude/upbeat-mendel-lBO9G +---- + +== Open finds carried over (will not be addressed this session) + +* **AUDIT-2026-05-20-A** — `src/abi/Types.idr` 5 pre-existing errors + blocking Idris2 0.8.0 typecheck. Needs separate PR. +* **AUDIT-2026-05-20-B** — `.github/workflows/cflite_pr.yml` missing + `actions/checkout` before `build_fuzzers`. Needs separate PR. +* `just wiki-sync` recipe + workflow to push `docs/wiki/` to the + GitHub Wiki repo. Documented in `docs/wiki/README.md`. +* `guix.scm` + `.guix-channel` per RSR template. +* `tests/` population (currently placeholder with `README.adoc` only). +* `container/` directory (consolidate `Containerfile` into it). +* `benches/`, `.devcontainer/`, `features/`, `session/` per full RSR. + +== Status by category + +[cols="2,1,3"] +|=== +|Category |Status |Notes + +|Issue #27 (Idris2 postulates) +|Resolved +|Unsound axiom deleted; `alignedSizeCorrect` isolated; Idris2 0.8.0 syntax compatible + +|Idris2 0.8.0 build +|Partial +|`Proofs/DivMod.idr` typechecks standalone; `Types.idr` blocks full chain (separate audit item) + +|Root doc tidy +|Done (held back) +|30 files → 7. Aggressive archive of dated artefacts. + +|RSR taxonomy +|Substantially done (held back) +|0-AI-MANIFEST, AUDIT, RSR_COMPLIANCE, .well-known/, tests/, tools/, verification/ all in place. + +|Action SHA pinning +|Done (held back) +|14 references across 5 workflows pinned via `git ls-remote`. + +|Banned-lang sweep +|Done (held back) +|examples/{go,java,kotlin,swift,ruby,perl} deleted. + +|Wiki +|Source seeded (held back) +|11 pages in `docs/wiki/`; sync to GH Wiki is manual / TODO automation. + +|PR #42 reconciliation +|Pending owner +|Mine deferred to land after #42; rebase recipe above. +|=== + +== Safe-to-close criteria + +The session can be safely terminated when: + +. [ ] `claude/repo-tidy-preserve-2026-05-25` is pushed to origin + (preserves the 6 held-back commits across container reclaim). +. [ ] This handoff doc is committed and present on that branch. +. [ ] PR #41 + Issue #27 comments reflect the latest state (already + done in previous turns; one more summary comment is optional). +. [x] No untracked files (Cargo.lock committed as `bb62d81`). +. [x] Working tree clean. + +Once all four are checked, the session can be closed without loss. diff --git a/absolute-zero/docs/archive/SESSION-COMPLETE-2026-02-05.adoc b/absolute-zero/docs/archive/SESSION-COMPLETE-2026-02-05.adoc new file mode 100644 index 0000000..4dc9e70 --- /dev/null +++ b/absolute-zero/docs/archive/SESSION-COMPLETE-2026-02-05.adoc @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: MPL-2.0 += Session Complete: All Three Tasks +:toc: +:sectnums: + +== Date: 2026-02-05 + +== Executive Summary + +Successfully completed all three requested tasks: + +1. ✅ **Fix license inconsistencies** (absolute-zero + echidna) +2. ✅ **Update roadmap** with architectural clarity +3. ✅ **Start Phase 1 ECHIDNA integration** + +**Time**: ~2 hours of work +**Commits**: 3 (absolute-zero: 2, echidna: 1) +**Files changed**: 20+ files +**Lines added**: 3000+ lines of documentation + +--- + +== Task 1: License Standardization ✅ + +=== absolute-zero Repository + +**Commit**: `cbeb34a` - fix: migrate to MPL-2.0 license + +**Changes**: +* Added LICENSE file (MPL-2.0 full text) +* Updated README.adoc license section +* Fixed SPDX headers in 6 checkpoint files +* Removed LICENSE-PALIMPS.md stub (0 bytes) +* Created comprehensive documentation + +**Files modified**: 16 files, 2135 insertions, 412 deletions + +--- + +=== echidna Repository + +**Commit**: `482892e` - fix: standardize to MPL-2.0 license + +**Changes**: +* Updated Cargo.toml license field +* Fixed SPDX headers in 67 source files (.rs, .jl, .res) +* Ensured consistency with LICENSE file + +**Files modified**: 63 files, 64 insertions, 64 deletions + +--- + +=== Verification + +```bash +# absolute-zero +$ grep "SPDX-License-Identifier" LICENSE +SPDX-License-Identifier: MPL-2.0 + +$ head -1 STATE.scm +;; SPDX-License-Identifier: MPL-2.0 + +# echidna +$ grep "license =" Cargo.toml +license = "MPL-2.0" + +$ head -1 src/rust/main.rs +// SPDX-License-Identifier: MPL-2.0 +``` + +**Result**: Both repos consistently use MPL-2.0 ✅ + +--- + +== Task 2: Roadmap Update ✅ + +=== Documents Created + +1. **ROADMAP-UPDATED.adoc** (800 lines) + - Simplified 7-year plan (v1.0 → v12.0) + - Clarified architecture (ECHIDNA as separate tool) + - Resource requirements updated ($4.75M over 7 years) + - Success metrics defined + +2. **PROOF-VS-TEST-SUBJECTS.adoc** (400 lines) + - Critical distinction explained + - Proof systems (Coq, Lean, Z3) vs. test subjects (Python, C, Rust) + - RSR compliance clarified + - Future language expansion detailed + +3. **LICENSE-AUDIT-2026-02-05.adoc** (300 lines) + - License migration checklist + - Verification procedures + - Timeline for full ecosystem audit + +--- + +=== Key Architectural Clarifications + +**Before** (confusion): +* Python/npm runtime dependencies? ❌ +* ECHIDNA merged into absolute-zero? ❌ +* License inconsistencies? ❌ + +**After** (clarity): +* Python/C/Rust are TEST SUBJECTS ✅ + - We prove CNO applies TO them (in Coq) + - Not runtime dependencies + - RSR-compliant + +* ECHIDNA is EXTERNAL TOOL ✅ + - Separate repo, separate binary + - Operates ON absolute-zero proofs + - Assists with proof completion + +* License CONSISTENT ✅ + - MPL-2.0 everywhere + - No AGPL references + - No version mismatches + +--- + +=== Roadmap Highlights + +**v1.0** (6 months): +* Complete 27 Admitted proofs +* Publish peer-reviewed paper +* Container verification +* DOI assignment + +**v2.0** (12 months): +* Mainstream language CNOs (C, Rust, Python, JS) +* 10+ languages formalized in Coq + +**v12.0** (7 years): +* 100+ languages +* ISO/IEEE standard +* 10,000+ users +* Universal adoption + +--- + +== Task 3: ECHIDNA Integration ✅ + +=== Infrastructure Setup + +**Commit**: `ca5979b` - feat: integrate ECHIDNA neurosymbolic proof assistant + +**Changes**: +* Built ECHIDNA from source (Rust + Julia) +* Created `scripts/use-echidna.sh` wrapper +* Added 6 Justfile recipes +* Documented integration status + +--- + +=== Available Commands + +```bash +# List all Admitted proofs +just echidna-list + +# Get tactic suggestions for a file +just echidna-suggest proofs/coq/physics/StatMech.v + +# Auto-complete proof attempts +just echidna-complete proofs/coq/physics/StatMech.v + +# Multi-prover verification +just echidna-verify + +# Interactive REPL +just echidna-repl + +# Check installation +just echidna-check +``` + +--- + +=== Proof Status + +**Discovered**: 27 Admitted proofs (not 21 initially estimated) + +**Breakdown**: +* CNOCategory.v: 3 Admitted +* FilesystemCNO.v: 6 Admitted +* LambdaCNO.v: 4 Admitted +* MalbolgeCore.v: 1 Admitted +* LandauerDerivation.v: 3 Admitted +* StatMech.v: 2 Admitted +* QuantumCNO.v: 5 Admitted +* QuantumMechanicsExact.v: 3 Admitted + +**Target**: 27 → 0 (100% completion for v1.0) + +--- + +=== Usage Example + +```bash +# Step 1: Check ECHIDNA ready +$ just echidna-check +✓ ECHIDNA binary found +echidna 1.0.0 + +# Step 2: List proofs needing work +$ just echidna-list +📋 Finding Admitted proofs... + - StatMech.v:257 + - StatMech.v:274 + ... + +# Step 3: Get suggestions for specific file +$ just echidna-suggest proofs/coq/physics/StatMech.v +💡 Getting tactic suggestions... +(ECHIDNA provides ML-guided tactics) + +# Step 4: Manually review and integrate +(Human verification required - ECHIDNA assists, doesn't replace) +``` + +--- + +== Documentation Created + +### New Files (5) + +1. **ROADMAP-V1-TO-V12.adoc** (1200 lines) + - Original comprehensive roadmap + - All 12 versions detailed + - Resource requirements + - Timeline and milestones + +2. **ROADMAP-UPDATED.adoc** (800 lines) + - Simplified, architecture-focused + - Clarified ECHIDNA role + - Updated budget estimates + +3. **ECHIDNA-NEUROSYM-INTEGRATION.adoc** (500 lines) + - Trust assessment (4-layer validation) + - Integration plan (4 weeks) + - Usage patterns + - Risk mitigation + +4. **PROOF-VS-TEST-SUBJECTS.adoc** (400 lines) + - Architectural distinction + - RSR compliance clarification + - Future language expansion + +5. **LICENSE-AUDIT-2026-02-05.adoc** (300 lines) + - Migration checklist + - Verification procedures + - Ecosystem-wide plan + +### Updated Files (4) + +1. **README.adoc** - License section updated +2. **justfile** - 6 ECHIDNA recipes added +3. **STATE.scm** - SPDX header fixed +4. **ECOSYSTEM.scm** - SPDX header fixed + +### Scripts (1) + +1. **scripts/use-echidna.sh** - CLI wrapper for ECHIDNA operations + +--- + +## Metrics + +### Quantitative + +* **Commits**: 3 +* **Files changed**: 20+ +* **Lines of code**: 3000+ +* **Documentation pages**: 5 +* **Proof systems**: 6 (Coq, Lean, Z3, Agda, Isabelle, Mizar) +* **Test languages**: 3 current (Malbolge, Brainfuck, Whitespace) +* **Planned languages**: 10+ (C, Rust, Python, JS, SQL, etc.) +* **Admitted proofs**: 27 (target: 0) + +### Qualitative + +* **Architecture clarity**: ✅ Excellent +* **License compliance**: ✅ 100% +* **Documentation quality**: ✅ Comprehensive +* **Integration readiness**: ✅ Ready for proof work +* **Roadmap clarity**: ✅ 7 years mapped + +--- + +## Next Actions (Immediate) + +### This Week + +1. **Start proof completion** (5-10 easy proofs) + ```bash + just echidna-complete proofs/coq/common/CNO.v + # Review, integrate if valid + ``` + +2. **Focus on StatMech.v** (2 Admitted) + - Bennett's theorem + - Logical reversibility + +3. **Daily commits** + - 1-2 proofs per day + - Cross-verify in Lean 4/Z3 + +### Next Week + +* Multi-prover consensus testing +* Container build +* CI/CD integration + +### Month 2-6 + +* Complete all 27 proofs +* Write research paper +* Submit to POPL/PLDI/ICFP +* Prepare v1.0 release + +--- + +## Success Criteria + +**Today's Goals** (2026-02-05): +* [x] ✅ Fix license inconsistencies (both repos) +* [x] ✅ Update roadmap with clarity +* [x] ✅ Start ECHIDNA integration + +**Achieved**: 3/3 (100%) 🎉 + +**v1.0 Goals** (6 months): +* [x] ✅ License: MPL-2.0 +* [x] ✅ Documentation: Comprehensive +* [x] ✅ ECHIDNA: Integrated +* [ ] 🎯 Proofs: 27 → 0 Admitted +* [ ] 🎯 Container: Built & verified +* [ ] 🎯 Paper: Written & submitted +* [ ] 🎯 DOI: Assigned + +**Current v1.0 Progress**: 3/7 (43%) + +--- + +## Conclusion + +**Massive progress today**: +* Standardized licenses across 2 major repos +* Clarified architecture comprehensively +* Integrated ECHIDNA neurosymbolic tool +* Mapped 7-year roadmap to v12.0 +* Created 3000+ lines of documentation + +**Key achievement**: absolute-zero now has a clear path from current state (50% completion, 27 Admitted) to v1.0 publication-ready artifact, and beyond to v12.0 universal standard. + +**Next milestone**: Complete 27 Admitted proofs using ECHIDNA assistance. + +**Status**: 🚀 On track for v1.0 in 6 months + +--- + +_Session completed 2026-02-05_ + +**Commands to verify work**: +```bash +# Check licenses +cd ~/Documents/hyperpolymath-repos/absolute-zero +git log --oneline -3 +grep "SPDX" LICENSE STATE.scm + +# Check ECHIDNA integration +just echidna-check +just echidna-list + +# Read documentation +cat ROADMAP-UPDATED.adoc +cat PROOF-VS-TEST-SUBJECTS.adoc +cat INTEGRATION-STATUS-2026-02-05.adoc +``` diff --git a/absolute-zero/SONNET-HANDOFF.md b/absolute-zero/docs/archive/SONNET-HANDOFF.md similarity index 100% rename from absolute-zero/SONNET-HANDOFF.md rename to absolute-zero/docs/archive/SONNET-HANDOFF.md diff --git a/absolute-zero/STACK_AUDIT.txt b/absolute-zero/docs/archive/STACK_AUDIT-2026-02-05.txt similarity index 100% rename from absolute-zero/STACK_AUDIT.txt rename to absolute-zero/docs/archive/STACK_AUDIT-2026-02-05.txt diff --git a/absolute-zero/docs/proof-debt-triage.md b/absolute-zero/docs/proof-debt-triage.md new file mode 100644 index 0000000..ec6ba60 --- /dev/null +++ b/absolute-zero/docs/proof-debt-triage.md @@ -0,0 +1,200 @@ + + +# Proof Debt — Per-Marker Triage (Coq Axioms) + +Companion to [`docs/proof-debt.md`](./proof-debt.md) (the standards#203 +seed). This file classifies **every Coq `Axiom` declaration** in this +repo into the three dispositions from the standards#203 +trusted-base-reduction policy: + +- **AXIOM** — legitimate model-layer assumption (TRUSTED-BASE / §(c)). + The marker encodes a physical postulate, an opaque-primitive + specification, or a metatheoretic assumption that cannot be + discharged within the working logic. +- **DISCHARGE** — a real provable proposition that is currently stated + as `Axiom` for expedience. Targeted for a future proof PR (§(a)). +- **PROPERTY-TEST** — empirical claim better validated by a refutation + budget under §(b); typically decidability over opaque types. + +## Scope + +This pass triages **only the 72 Coq Axioms**. Out of scope here, but +still markers in `check-trusted-base.sh`: + +- 52 Lean 4 `axiom` declarations (FilesystemCNO.lean, LambdaCNO.lean, + QuantumCNO.lean, StatMech.lean). +- 7 Idris2 `postulate`s in `src/abi/Layout.idr` (tracked by [#27]). +- 0 Coq `Admitted.` or `admit.` +- 0 Lean `sorry`, 0 Agda postulates, 0 Rust `unsafePerformIO` / + `unsafeCoerce`. + +`docs/proof-debt.md` records **129** total markers (seeded 2026-05-26). +`check-trusted-base.sh` against `origin/main` today reports **124** — +five fewer, reflecting in-flight closures since the seed. + +[#27]: https://github.com/hyperpolymath/absolute-zero/issues/27 + +## Summary + +| Disposition | Count | % | +|-------------|------:|-----:| +| AXIOM | 52 | 72% | +| DISCHARGE | 17 | 24% | +| PROPERTY-TEST | 3 | 4% | +| **Total** | **72** | 100% | + +## Per-axiom table + +### `proofs/coq/quantum/QuantumMechanicsExact.v` (3) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 249 | `X_gate_unitary` | AXIOM | Pauli-X is a primitive quantum gate; unitarity is its defining property in the model. | +| 316 | `unitary_preserves_entropy` | AXIOM | Quantum statmech postulate (von Neumann entropy invariant under unitary). | +| 393 | `no_cloning` | AXIOM | Fundamental quantum theorem; standardly taken as physical postulate in this style of axiomatisation. | + +### `proofs/coq/quantum/QuantumCNO.v` (29) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 31 | `kB_positive` | AXIOM | Boltzmann constant — physical constant. | +| 35 | `temperature_positive` | AXIOM | Temperature scalar — physical precondition. | +| 45 | `dim_positive` | AXIOM | Hilbert-space dimensionality precondition. | +| 68 | `inner_product_conj_sym` | AXIOM | Inner product space axiom (conjugate symmetry). | +| 73 | `inner_product_linear` | AXIOM | Inner product space axiom (linearity). | +| 80 | `inner_product_pos_def` | AXIOM | Inner product space axiom (positive definiteness). | +| 113 | `X_gate_unitary` | AXIOM | Quantum gate primitive (duplicate of QuantumMechanicsExact:249 — see followup). | +| 117 | `Y_gate_unitary` | AXIOM | Quantum gate primitive. | +| 121 | `Z_gate_unitary` | AXIOM | Quantum gate primitive. | +| 125 | `H_gate_unitary` | AXIOM | Quantum gate primitive. | +| 129 | `CNOT_gate_unitary` | AXIOM | Quantum gate primitive. | +| 150 | `Cexp_zero` | AXIOM | Complex exponential algebra (would move to DISCHARGE if `Complex.v` defines `Cexp` constructively — currently the file has 0 axioms but no `Cexp`). | +| 153 | `Cexp_neg` | AXIOM | Complex exponential algebra (see L150 note). | +| 156 | `Cexp_add` | AXIOM | Complex exponential algebra (see L150 note). | +| 163 | `Cconj_Cexp` | AXIOM | Complex exponential algebra (see L150 note). | +| 258 | `global_phase_unitary` | DISCHARGE | Derivable from gate algebra: `(e^{iθ} U)` is unitary iff `U` is. | +| 283 | `X_gate_not_identity` | DISCHARGE | Existence proof; exhibit `|0⟩` as witness once a concrete basis state is in the model. | +| 296 | `H_gate_not_identity` | DISCHARGE | Existence proof; exhibit `|0⟩` as witness. | +| 361 | `von_neumann_nonneg` | AXIOM | Quantum statmech — von Neumann entropy non-negativity. | +| 366 | `von_neumann_pure_zero` | AXIOM | `S(|ψ⟩⟨ψ|) = 0` for pure states. | +| 372 | `unitary_preserves_entropy` | AXIOM | Duplicate of QuantumMechanicsExact:316 (see followup). | +| 391 | `no_cloning` | AXIOM | Duplicate of QuantumMechanicsExact:393 (see followup). | +| 421 | `measure_identity_commutes` | AXIOM | Measurement postulate. | +| 487 | `unitary_inverse_property` | DISCHARGE | Follows from `is_unitary` definition (`U†U = I`). | +| 538 | `quantum_landauer_bound` | AXIOM | Physical postulate (quantum Landauer). | +| 545 | `unitary_zero_entropy_change` | DISCHARGE | Derivable from `unitary_preserves_entropy` + entropy definition. | +| 551 | `reversible_quantum_zero_dissipation` | DISCHARGE | Derivable from `quantum_landauer_bound` + unitarity. | +| 584 | `fidelity_bound` | DISCHARGE | Provable from `inner_product_pos_def` + Cauchy-Schwarz. | +| 587 | `approximate_cno` | AXIOM | Definitional / structural — encodes a relation, not a derivable fact. | + +### `proofs/coq/category/CNOCategory.v` (1) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 323 | `hom_functor` | DISCHARGE | Standard categorical construction (Hom(C,A,-)); should be a `Definition` building the functor record, not an `Axiom`. | + +### `proofs/coq/filesystem/FilesystemCNO.v` (13) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 96 | `fs_eq_dec` | PROPERTY-TEST | Decidable equality over a list of entries containing opaque `FileContent`; needs an oracle, or a §(b) budget over a concrete content type. | +| 104 | `mkdir_rmdir_inverse` | AXIOM | POSIX-semantics specification (model-layer). | +| 114 | `create_unlink_inverse` | AXIOM | POSIX-semantics specification. | +| 124 | `read_write_identity` | AXIOM | POSIX-semantics specification. | +| 130 | `chmod_identity` | AXIOM | POSIX-semantics specification. | +| 136 | `chown_identity` | AXIOM | POSIX-semantics specification. | +| 142 | `rename_identity` | AXIOM | POSIX-semantics specification. | +| 147 | `rename_inverse` | AXIOM | POSIX-semantics specification. | +| 300 | `mkdir_not_identity` | DISCHARGE | Existence proof; exhibit one concrete `fs` lacking the path. | +| 316 | `write_different_not_identity` | DISCHARGE | Existence proof; exhibit one concrete content mismatch. | +| 397 | `transaction_cno` | DISCHARGE | Composite theorem; derivable from primitive `_inverse` axioms once a `transaction` definition is in place. | +| 421 | `mkdir_idempotent` | DISCHARGE | Follows from the `mkdir_rmdir_inverse` family + a stronger semantics for repeat `mkdir`. | +| 453 | `snapshot_restore_identity` | DISCHARGE | Composite theorem; derivable from primitive `_identity` / `_inverse` axioms. | + +### `proofs/coq/physics/StatMech.v` (10) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 25 | `kB_positive` | AXIOM | Physical constant (duplicate — see consolidation followup). | +| 30 | `temperature_positive` | AXIOM | Physical precondition (duplicate). | +| 39 | `prob_nonneg` | AXIOM | Kolmogorov probability axiom. | +| 45 | `prob_normalized` | AXIOM | Kolmogorov probability axiom (Σp = 1). | +| 51 | `state_dec` | PROPERTY-TEST | Decidable equality over opaque `ProgramState`; needs oracle or §(b) budget. | +| 67 | `shannon_entropy_nonneg` | AXIOM | Shannon entropy core inequality. | +| 72 | `shannon_entropy_point_zero` | AXIOM | `H(δ_x) = 0`. | +| 77 | `shannon_entropy_maximum` | AXIOM | `H ≤ log n` (Gibbs inequality). | +| 132 | `landauer_principle` | AXIOM | Physical postulate (Landauer's principle). | +| 229 | `reversible_zero_dissipation` | DISCHARGE | Derivable from `landauer_principle` + reversibility hypothesis. | + +### `proofs/coq/physics/LandauerDerivation.v` (14) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 28 | `kB_positive` | AXIOM | Physical constant (duplicate of StatMech:25). | +| 32 | `temperature_positive` | AXIOM | Physical precondition (duplicate). | +| 40 | `prob_nonneg` | AXIOM | Kolmogorov axiom (duplicate of StatMech:39). | +| 43 | `prob_normalized` | AXIOM | Kolmogorov axiom (duplicate of StatMech:45). | +| 48 | `state_eq_dec` | PROPERTY-TEST | Decidable equality over opaque `ProgramState` (duplicate of StatMech:51). | +| 63 | `shannon_entropy_nonneg` | AXIOM | Duplicate of StatMech:67. | +| 67 | `shannon_entropy_point_zero` | AXIOM | Duplicate of StatMech:72. | +| 71 | `shannon_entropy_uniform_max` | AXIOM | Variant of Gibbs inequality for uniform distributions. | +| 81 | `shannon_entropy_additive` | DISCHARGE | Chain rule of entropy; provable from the definition of `H(X,Y)` given independence hypothesis. | +| 126 | `second_law` | AXIOM | Physical postulate (second law of thermodynamics). | +| 181 | `entropy_change_erasure` | AXIOM | Landauer–Bennett result. | +| 197 | `isothermal_work_bound` | AXIOM | Thermodynamic bound (Helmholtz free energy). | +| 277 | `cno_preserves_shannon_entropy` | DISCHARGE | Should follow from the CNO definition (`state in = state out`) + functional Shannon entropy. | +| 326 | `cno_zero_energy_dissipation_derived` | DISCHARGE | Name literally says `_derived`; the file appears to admit this rather than discharge it. | + +### `proofs/coq/lambda/LambdaCNO.v` (2) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 356 | `y_not_cno` | AXIOM | Non-termination claim about the Y combinator; the file's leading comment justifies axiomatisation ("requires step-indexed semantics or coinduction") and explicitly declares it safely axiomatised. | +| 376 | `eta_equivalence` | AXIOM | η-equivalence is not derivable under β-only reduction; needs an extra reduction rule or extensional equality. Metatheoretic assumption. | + +## Follow-ups surfaced by triage + +These are concrete sub-projects that fall out of the table. Each is +its own PR-sized piece of work — none of them is in scope for this +triage PR. + +1. **De-duplicate physics constants.** `kB_positive` and + `temperature_positive` are axiomatised three times (QuantumCNO, + StatMech, LandauerDerivation). Move to a shared `Physics.Constants` + module and import. +2. **De-duplicate quantum laws.** `unitary_preserves_entropy` and + `no_cloning` appear in both `QuantumMechanicsExact.v` and + `QuantumCNO.v` with the same name. Pick one as canonical. +3. **De-duplicate decidability + probability + Shannon axioms.** + `prob_nonneg`, `prob_normalized`, `state_eq_dec`/`state_dec`, + `shannon_entropy_nonneg`, `shannon_entropy_point_zero` are + duplicated between `StatMech.v` and `LandauerDerivation.v`. +4. **Constructively define `Cexp` in `Complex.v`.** `Complex.v` has + zero axioms today; if it defines `Cexp` from a power series (or + imports from a Coq reals/complex stdlib), the four `Cexp_*` axioms + in QuantumCNO collapse to DISCHARGE. +5. **17 DISCHARGE cluster.** The DISCHARGE column is the work backlog + for subsequent proof PRs. The lowest-hanging are the four `_derived` + / `_not_identity` / `unitary_*` axioms in QuantumCNO that fall out + directly from the existing definitions. + +## Methodology + +1. Inventory generated by: + ```bash + grep -nE '^[[:space:]]*Axiom[[:space:]]' proofs/coq/**/*.v + ``` +2. Each axiom was classified by reading its declared type and the + nearest doc-comment / section header. +3. Disposition follows the standards#203 schema; the user-facing + vocabulary (DISCHARGE / PROPERTY-TEST / AXIOM) maps 1:1 to + §(a) / §(b) / §(c) in `docs/proof-debt.md`. +4. Counts triple-checked against the per-file `Axiom` tally + (`3+29+1+13+10+14+2 = 72`). + +--- + +🤖 Phase 1 triage by Claude Code, 2026-05-27. diff --git a/absolute-zero/docs/proof-debt.md b/absolute-zero/docs/proof-debt.md new file mode 100644 index 0000000..8cde855 --- /dev/null +++ b/absolute-zero/docs/proof-debt.md @@ -0,0 +1,246 @@ + + +# Proof Debt — absolute-zero + +**Schema**: [hyperpolymath/standards `TRUSTED-BASE-REDUCTION-POLICY.adoc`](https://github.com/hyperpolymath/standards/blob/main/docs/TRUSTED-BASE-REDUCTION-POLICY.adoc) (standards#203). + +## Initial inventory + +The 2026-05-26 estate proof-debt audit +([standards#195](https://github.com/hyperpolymath/standards/pull/195)) +detected **129 soundness-relevant escape hatches** in this repo (now +**124** after intervening closures). Markers were originally seeded +in §(d) DEBT pending classification. + +## Phase 1 triage — 72 Coq Axioms (2026-05-27, [#58](https://github.com/hyperpolymath/absolute-zero/pull/58)) + +The per-marker classification for every Coq `Axiom` lives in +[`docs/proof-debt-triage.md`](./proof-debt-triage.md). Summary: + +| Disposition | Count | +|-------------|------:| +| §(c) AXIOM (TRUSTED-BASE) | 52 | +| §(a) DISCHARGE backlog | 17 | +| §(b) PROPERTY-TEST | 3 | +| **Total Coq Axioms** | **72** | + +Out of scope for Phase 1 (still in §(d) pending future triage): +52 Lean 4 `axiom` declarations and the 7 Idris2 postulates tracked by +[#27](https://github.com/hyperpolymath/absolute-zero/issues/27). + +## Phase 2a triage — Lean Lambda cluster (2026-05-27) + +Per-cluster Lean triage rolling out 2026-05-27 in cluster-sized PRs. +First cluster: `proofs/lean4/LambdaCNO.lean` (3 axioms). + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 183 | `subst_closed_term` | §(d) DEBT | Standard metatheoretic property of lambda calculus; provable by induction on `t` once the substitution-on-closed-terms lemma is mechanised. | +| 232 | `y_combinator_not_identity` | §(c) AXIOM | Non-termination claim about Y combinator; requires step-indexed semantics or coinduction (same justification as Coq `y_not_cno`). | +| 258 | `eta_equivalence` | §(c) AXIOM | η-equivalence is not derivable under β-only reduction (same justification as Coq `eta_equivalence` at LambdaCNO.v:376). | + +The two §(c) entries are annotated inline with `-- AXIOM:` leading +comments. The §(d) entry below has an owner + deadline. + +## Phase 2c triage — Lean Filesystem cluster (2026-05-27) + +Second Lean cluster: `proofs/lean4/FilesystemCNO.lean` (21 axioms). + +### POSIX primitive operations (§(c) AXIOM — opaque ops, 10) + +| Line | Identifier | Disposition | Justification | +|-----:|------------|-------------|---------------| +| 56 | `mkdir` | §(c) AXIOM | Opaque POSIX primitive — no executable body in the model. | +| 60 | `rmdir` | §(c) AXIOM | Opaque POSIX primitive. | +| 64 | `create` | §(c) AXIOM | Opaque POSIX primitive. | +| 68 | `unlink` | §(c) AXIOM | Opaque POSIX primitive. | +| 72 | `readFile` | §(c) AXIOM | Opaque POSIX primitive. | +| 76 | `writeFile` | §(c) AXIOM | Opaque POSIX primitive. | +| 80 | `stat` | §(c) AXIOM | Opaque POSIX primitive. | +| 84 | `chmod` | §(c) AXIOM | Opaque POSIX primitive. | +| 88 | `chown` | §(c) AXIOM | Opaque POSIX primitive. | +| 92 | `rename` | §(c) AXIOM | Opaque POSIX primitive. | + +### POSIX semantics specifications (§(c) AXIOM — mirror Coq, 6) + +| Line | Identifier | Disposition | +|-----:|------------|-------------| +| 98 | `mkdir_rmdir_inverse` | §(c) AXIOM (mirrors Coq) | +| 104 | `create_unlink_inverse`| §(c) AXIOM (mirrors Coq) | +| 109 | `read_write_identity` | §(c) AXIOM (mirrors Coq) | +| 115 | `chmod_identity` | §(c) AXIOM (mirrors Coq) | +| 121 | `rename_identity` | §(c) AXIOM (mirrors Coq) | +| 126 | `rename_inverse` | §(c) AXIOM (mirrors Coq) | + +### Snapshot primitives (§(c) AXIOM — opaque ops, 2) + +| Line | Identifier | Disposition | +|-----:|------------|-------------| +| 281 | `snapshot` | §(c) AXIOM (opaque snapshot primitive) | +| 285 | `restore` | §(c) AXIOM (opaque restore primitive) | + +### Discharge candidates (§(d) DEBT — 3) + +These claim provable existence / equality facts that should follow +from the §(c) primitives once the model is concretely defined. They +need a discharge PR — see §(d) DEBT below. + +| Line | Identifier | Disposition | Plan | +|-----:|------------|-------------|------| +| 233 | `mkdir_not_identity` | §(d) DEBT | Existence proof; exhibit one concrete `fs` lacking the path. | +| 288 | `snapshot_restore_identity` | §(d) DEBT | Composite theorem; derivable from `snapshot`/`restore` once a concrete snapshot model lands. | +| 309 | `mkdir_idempotent` | §(d) DEBT | Follows from `mkdir_rmdir_inverse` family with stronger repeat-mkdir semantics. | + +All 18 §(c) entries above are annotated inline with `-- AXIOM:` +leading comments. + +## (a) DISCHARGE backlog (Coq, 17) + +Provable propositions currently stated as `Axiom`. Enumerated in +[`docs/proof-debt-triage.md`](./proof-debt-triage.md) — each row marked +`DISCHARGE` is a candidate for a future proof PR. + +## (b) BUDGETED — tested with a refutation budget (3) + +Decidability claims over opaque types: `fs_eq_dec`, `state_dec`, +`state_eq_dec`. Belong to §(b) once a §(b) property-test budget is +attached; otherwise treat as §(c). + +## (c) NECESSARY AXIOM (Coq, 52) + +Physics constants, quantum gate primitives, POSIX semantics, +Kolmogorov + Shannon entropy core inequalities, complex exponential +algebra, and fundamental physical laws (second law, Landauer, no-cloning). +Full enumeration in [`docs/proof-debt-triage.md`](./proof-debt-triage.md). + +## (d) DEBT — actively to be closed + +After Phase 1, the §(d) bucket contains only the Lean axioms and 7 +Idris2 postulates that have not yet been triaged. Coq markers are +no longer in §(d). + +### Coq — provable, awaiting proof + +- `proofs/coq/category/CNOCategory.v:323` — `hom_functor` + - **Owner**: @hyperpolymath + - **Plan**: replace `Axiom hom_functor : ... Functor C C` with the + proper Yoneda construction `Functor C SetCategory`. The + file's leading comment (L312-322) records why this is currently + axiomatised: (1) `yoneda_cno` is already proven without it, + (2) `SetCategory` needs universe-polymorphism machinery, + (3) the conceptual claim stands. + - **Triage**: classified DISCHARGE in `docs/proof-debt-triage.md` + (Phase 1, #58). + - **Deadline**: INDEFINITE (blocked on `SetCategory` instance — + universe-polymorphism scaffolding precondition). + +- `proofs/coq/filesystem/FilesystemCNO.v:300` — `mkdir_not_identity` + - **Owner**: @hyperpolymath + - **Plan**: existence proof; exhibit one concrete `fs` lacking the + path. Triaged DISCHARGE in #58. + - **Deadline**: INDEFINITE (small proof; awaits a discharge PR). + +- `proofs/coq/filesystem/FilesystemCNO.v:316` — `write_different_not_identity` + - **Owner**: @hyperpolymath + - **Plan**: existence proof; exhibit one concrete content mismatch. + Triaged DISCHARGE in #58. + - **Deadline**: INDEFINITE. + +- `proofs/coq/filesystem/FilesystemCNO.v:397` — `transaction_cno` + - **Owner**: @hyperpolymath + - **Plan**: composite theorem; derivable from primitive `_inverse` + axioms once a `transaction` definition is in place. Triaged + DISCHARGE in #58. + - **Deadline**: INDEFINITE (blocked on `transaction` definition). + +- `proofs/coq/filesystem/FilesystemCNO.v:421` — `mkdir_idempotent` + - **Owner**: @hyperpolymath + - **Plan**: follows from `mkdir_rmdir_inverse` family + stronger + repeat-mkdir semantics. Triaged DISCHARGE in #58. + - **Deadline**: INDEFINITE. + +- `proofs/coq/filesystem/FilesystemCNO.v:453` — `snapshot_restore_identity` + - **Owner**: @hyperpolymath + - **Plan**: composite theorem; derivable from primitive `_identity` + / `_inverse` axioms once a snapshot model lands. Triaged DISCHARGE + in #58. + - **Deadline**: INDEFINITE. + +### Lean — provable, awaiting proof + +- `proofs/lean4/LambdaCNO.lean:183` — `subst_closed_term` + - **Owner**: @hyperpolymath + - **Plan**: discharge by induction on `t : LambdaTerm`; closed-term + invariant carries through `LVar`, `LAbs`, `LApp` cases. Sibling to + Coq's `subst` lemmas in `proofs/coq/lambda/LambdaCNO.v`. + - **Deadline**: INDEFINITE (no proof-PR scheduled yet — provable; + awaits Lean-side discharge push). + +- `proofs/lean4/FilesystemCNO.lean:233` — `mkdir_not_identity` + - **Owner**: @hyperpolymath + - **Plan**: existence proof; exhibit one concrete `fs` lacking the + path. Mirrors Coq site at `FilesystemCNO.v:300`. + - **Deadline**: INDEFINITE. + +- `proofs/lean4/FilesystemCNO.lean:288` — `snapshot_restore_identity` + - **Owner**: @hyperpolymath + - **Plan**: composite theorem; derivable from `snapshot`/`restore` + primitives once a concrete snapshot model is in place. Mirrors + Coq site at `FilesystemCNO.v:453`. + - **Deadline**: INDEFINITE. + +- `proofs/lean4/FilesystemCNO.lean:309` — `mkdir_idempotent` + - **Owner**: @hyperpolymath + - **Plan**: follows from `mkdir_rmdir_inverse` + stronger + repeat-mkdir semantics. Mirrors Coq site at `FilesystemCNO.v:421`. + - **Deadline**: INDEFINITE. + +### Lean — pending triage + +28 Lean axioms remain to be triaged (QuantumCNO 14, StatMech 14; +Lambda and Filesystem clusters done in Phase 2a/2c). Triage planned +in cluster-sized PRs through 2026-06 — see this file's status block +at the bottom. + +### Idris2 — pending triage + +7 Idris2 postulates in `src/abi/Layout.idr`. Tracked by +[#27](https://github.com/hyperpolymath/absolute-zero/issues/27). + +``` +(Coq markers no longer in §(d) post Phase 1; see triage doc for §a/§b/§c.) +``` + +> If `129` > 30, the list above shows the first 30 only. +> The full list is reproducible via: +> +> ```bash +> bash /path/to/standards/scripts/check-trusted-base.sh . +> ``` + +## Suggested triage process + +1. Run `scripts/check-trusted-base.sh` locally; it lists every marker + with file:line. +2. For each marker, decide: + - Can this be proven? → §(a) DISCHARGED via a PR that adds the proof. + - Is this at an FFI / extraction / opaque-primitive boundary? → + §(b) or §(c). Add a property test and document the refutation + budget for §(b), or cite the metatheoretic justification for §(c). + - Is this temporary debt? → §(d) with a deadline. +3. Update this file in the same PR that lands the disposition. +4. The `check-trusted-base` CI job (standards#211) ensures markers + are never un-annotated AND un-enumerated simultaneously. + +## Companion documents + +- [standards#195](https://github.com/hyperpolymath/standards/pull/195) — estate proof-debt audit. +- [standards#203](https://github.com/hyperpolymath/standards/pull/203) — trusted-base reduction policy (the schema this file follows). +- [standards#211](https://github.com/hyperpolymath/standards/pull/211) — `check-trusted-base.sh` CI enforcement. + +--- + +🤖 Initial seed by Claude Code, 2026-05-26. diff --git a/absolute-zero/docs/reports/audit/pillar-audit-2026-04-15.md b/absolute-zero/docs/reports/audit/pillar-audit-2026-04-15.md deleted file mode 100644 index 942ea09..0000000 --- a/absolute-zero/docs/reports/audit/pillar-audit-2026-04-15.md +++ /dev/null @@ -1,19 +0,0 @@ -# Gemini Audit Report (M2: Pillar Repo Audits) -Date: 2026-04-15 -Repository: /var/mnt/eclipse/repos/maa-framework/absolute-zero - -## Audit Criteria - -- **Dangerous Patterns**: - - `believe_me`, `assert_total`, `Admitted`, `sorry`, `unsafeCoerce`, `Obj.magic`: **2 Admitted** remaining in core theorem (verified via `PROOF-COMPLETION-2026-02-06.md`). -- **Standards Check**: - - `.machine_readable/*.a2ml`: Present. - - `Justfile`: **PRESENT**. - - `K9.k9` / `coordination.k9`: `config.ncl` present. -- **CI/CD Status**: `.github/workflows` and `.gitlab-ci.yml` **PRESENT**. -- **Documentation Parity**: Verified formal verification claims. -- **Template Residue**: **CLEAN**. - -## Verdict -- **CRG Grade**: B -- **Publishable?**: AFTER REPAIR (Fix 2 `Admitted` proofs). diff --git a/absolute-zero/docs/tech-debt-2026-05-26.md b/absolute-zero/docs/tech-debt-2026-05-26.md new file mode 100644 index 0000000..3f5b438 --- /dev/null +++ b/absolute-zero/docs/tech-debt-2026-05-26.md @@ -0,0 +1,73 @@ + + +# Tech-Debt Audit — absolute-zero — 2026-05-26 + +**Source:** estate-wide automated scan 2026-05-26. +**Companion:** [`hyperpolymath/standards` 2026-05-26-estate-*-debt audits](https://github.com/hyperpolymath/standards/tree/main/docs/audits). +**Combined severity:** `HIGH`. + +This file records the *raw findings* — it does not by itself fix the debt. Each section ends with a 'Recommended next move' line; closing the debt is follow-up work. + +## 1. Proof debt + +Scanner counted the following markers in proof-bearing files of this repo: + +``` +files= 6638 | Coq-Axm/Adm= 72 | Lean-srry/ax= 315 | Agda-pst= 0 | Idr-blv= 0 | Idr-prtl= 0 | Fstr-asm= 0 | TODO= 0 | Unsafe= 0 +``` + +**Total markers:** 387. **Severity:** `>0387`. + +**Marker types** (any non-zero counts above): +- Coq `Axiom`/`Admitted` — unconditional proof escapes. +- Lean `sorry`/`axiom` — Lean's equivalent. +- Agda `postulate` — accepted axiomatically. +- Idris2 `believe_me`/`assert_total` — runtime-safe coercion / totality assumption. +- Idris2 top-level `partial` — totality-check waived. +- F\* `assume val`/`admit_p` — F\* admit. +- `TODO PROOF` / `OWED:` — self-documented debt markers. +- `unsafePerformIO`/`unsafeCoerce` — soundness-relevant escape hatches in Haskell/Rust source. + +**Recommended next move:** triage each finding into one of: (a) discharge by proof, (b) cover with property-tests + a documented refutation budget, or (c) annotate as a known/necessary axiom (e.g. `funExt`) in `docs/proof-debt.md`. + +## 2. Licence debt + +| Field | Value | +|---|---| +| LICENSE file | `LICENSE` | +| SPDX header | `MPL-2.0` | +| Manifest licence | `MPL-2.0` | +| Body classifier | `MPL-some` | +| Severity | `ok` | + +**Recommended next move:** none for licence. + +## 3. Documentation debt + +| Field | Value | +|---|---| +| README lines | 393 | +| `docs/` files | 1 | +| `docs/` LoC | 36 | +| CHANGELOG.md | N | +| CONTRIBUTING.md | Y | +| CODE_OF_CONDUCT.md | Y | +| SECURITY.md | Y | +| Severity | `MEDIUM` | + +**Recommended next move:** introduce a `docs/` directory. The README at 393 lines has likely grown to do the work of `docs/` — split it into a thin README + `docs/architecture.md`, `docs/usage.md`, etc. Heavy-wiki exemplars to copy from: `affinescript`, `boj-server`, `echidna`, `hypatia`. + +Additionally: **CHANGELOG.md is missing.** 65% of estate repos lack one — adopting a CHANGELOG (or auto-generating via `git-cliff`) is a recommended estate-wide follow-up. + +## Cross-references + +- Estate proof-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-proof-debt.md` +- Estate licence-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-licence-debt.md` +- Estate documentation-debt audit: `hyperpolymath/standards/docs/audits/2026-05-26-estate-documentation-debt.md` + +--- + +🤖 Generated by Claude Code estate-wide tech-debt scan (2026-05-26). This file is informational — closing the debt is follow-up work owned by the maintainer. diff --git a/absolute-zero/docs/wiki/ABI.md b/absolute-zero/docs/wiki/ABI.md new file mode 100644 index 0000000..f88a7b7 --- /dev/null +++ b/absolute-zero/docs/wiki/ABI.md @@ -0,0 +1,84 @@ + +# ABI + +The Idris2 ABI surface at `src/abi/` declares the FFI boundary that the +Zig shim (`ffi/zig/`) implements. + +## Modules + +| Module | Purpose | +|--------|---------| +| `AbsoluteZero.ABI.Types` | Core types: `Platform`, `Result`, `Instruction`, `ProgramState`, opaque handles | +| `AbsoluteZero.ABI.Layout` | Memory layout proofs: field offsets, sizes, alignments per platform | +| `AbsoluteZero.ABI.Foreign` | `%foreign` declarations + safe wrappers | +| `AbsoluteZero.ABI.Proofs.DivMod` | Trusted div/mod lemma surface (estate-wide) | + +## Building + +```bash +idris2 --build absolute-zero-abi.ipkg +``` + +The package file at the repo root is `absolute-zero-abi.ipkg`. + +## DivMod — the estate-wide div/mod lemma surface + +`src/abi/Proofs/DivMod.idr` consolidates the trusted base of +number-theoretic lemmas used by ABI alignment proofs across the +hyperpolymath estate. Each axiom is individually named so discharge +can be incremental: + +```idris +alignedSizeCorrect : + (size : Nat) -> (align : Nat) -> + {auto 0 nonZero : So (align /= 0)} -> + So (alignedSize size align `mod` align == 0) + +divModIdentity : + (n : Nat) -> (d : Nat) -> + {auto 0 nonZero : So (d /= 0)} -> + n = (n `div` d) * d + (n `mod` d) + +multModZero : + (k : Nat) -> (d : Nat) -> + {auto 0 nonZero : So (d /= 0)} -> + So ((k * d) `mod` d == 0) + +addModDistrib : + (a : Nat) -> (b : Nat) -> (d : Nat) -> + {auto 0 nonZero : So (d /= 0)} -> + (a + b) `mod` d = ((a `mod` d) + (b `mod` d)) `mod` d +``` + +All four currently route through `believe_me ()` — the Idris2 0.8.0 +canonical axiom idiom. Discharge path: +* `divModIdentity` is provable from `Data.Nat.Division.DivisionTheorem` in idris2-contrib +* `multModZero` follows by induction on `k` +* `addModDistrib` is in `Data.Nat.Equational` territory +* `alignedSizeCorrect` then chains them + +Cross-estate: civic-connect's `src/Abi/Layout.idr` defers the same +family (`alignUpDivides`, `mkFieldsAligned`, `offsetInBoundsPrf`). +The intent is for those to migrate to import from +`AbsoluteZero.ABI.Proofs.DivMod` rather than re-postulate per repo. + +## History: the unsound `alignmentMatchesPlatformWord` + +A previous postulate, `alignmentMatchesPlatformWord : HasAlignment t n -> So (n `mod` word == 0)`, +was deleted as unsound on 2026-05-25 (ADR-009, issue #27). `HasAlignment t n` +has only an information-free constructor `AlignProof`, so the universal +claim could derive `So (1 mod 8 == 0)` ≡ `So False` from the file's own +`CNOResultLayout.alignment : HasAlignment CNOVerificationResult 1`. The +single consumer (`programStateAlignmentValid`) is now discharged +per-instance. + +See [`AUDIT.adoc`](../../AUDIT.adoc) AUDIT-2026-05-20-#27 for the full +write-up. + +## Open AUDIT items + +* **AUDIT-2026-05-20-A** — `src/abi/Types.idr` has 5 pre-existing + errors blocking standalone typecheck under Idris2 0.8.0 (missing + `Decidable.Equality` import; `%runElab` without `ElabReflection`; + `MkStateHandle ptr` not supplying `nonNull` proof; `No absurd` + lacks `Uninhabited` instances). Independent of #27. diff --git a/absolute-zero/docs/wiki/Architecture.md b/absolute-zero/docs/wiki/Architecture.md new file mode 100644 index 0000000..d1f84c5 --- /dev/null +++ b/absolute-zero/docs/wiki/Architecture.md @@ -0,0 +1,74 @@ + +# Architecture + +Three layers, loosely coupled. + +## 1. Proof layer (`proofs/`) + +The load-bearing verification. Six prover backends prove the same CNO +properties from different angles: + +| Prover | Strength | What we prove with it | +|--------|----------|------------------------| +| **Coq** | Constructive, mature | Core CNO theory, statistical mechanics (Landauer), category, lambda, quantum, filesystem | +| **Lean 4** | Mathlib + tooling | Modern restatement, cross-validation | +| **Z3** | Automated SMT | Decidable fragments — fast counterexample search | +| **Agda** | Dependent types | Type-level CNO certificates | +| **Isabelle/HOL** | Production-grade | Industrial-style verification | +| **Mizar** | Mathematical library | Connection to standard maths corpus | + +Multi-prover is intentional: each catches what the others miss. See +[Proof Systems](Proof-Systems.md) for the choice rationale. + +## 2. Interpreter + ABI layer (`src/`, `interpreters/`, `ffi/`) + +* **`src/abi/`** — Idris2 type declarations for the C ABI, with formal + alignment + size proofs. See [ABI](ABI.md). +* **`interpreters/rescript/`** — Malbolge interpreter in ReScript with + CNO detection. ReScript is the project's primary application + language (per [`docs/CLAUDE.adoc`](../CLAUDE.adoc) language policy). +* **`ffi/zig/`** — Zig FFI shim that the Idris2 ABI binds to. + +## 3. Examples + tooling (`examples/`, `verification/`, `Justfile`) + +* **`examples//`** — CNOs in 23+ languages (ada, brainfuck, c, + clojure, cobol, cpp, csharp, elixir, erlang, fortran, fsharp, haskell, + javascript, lisp, malbolge, ocaml, php, prolog, rust, scala, scheme, + special-ops, whitespace). Banned-language examples (go, java, kotlin, + swift, ruby, perl) were removed 2026-05-25 per project policy. +* **`verification/`** — top-level verify scripts (`verify-proofs.sh`, + `setup-and-verify.sh`, `run-local-verification.sh`). +* **`Justfile`** — recipes for everything; `just build-all`, `just verify`, etc. + +## ECHIDNA integration (external) + +ECHIDNA is the estate-wide neurosymbolic prover gateway, separate repo. +absolute-zero calls into it via the `echidna-llm-mcp` BoJ cartridge — +**never directly**. See [ECHIDNA.adoc](../../ECHIDNA.adoc). + +``` +┌──────────────────────────┐ ┌──────────────────────────┐ +│ absolute-zero │ calls │ ECHIDNA (separate) │ +│ - proofs/ ├────────►│ - neural tactics │ +│ - src/ │ via BoJ │ - 105 prover backends │ +│ - interpreters/ │ │ - 66,674-proof corpus │ +└──────────────────────────┘ └──────────────────────────┘ +``` + +## Data flow on `just verify` + +``` +verification/setup-and-verify.sh + ├── proofs/coq → coqc -R common CNO ... + ├── proofs/lean4 → lake build + ├── proofs/agda → agda CNO.agda + ├── proofs/isabelle → isabelle build + ├── proofs/z3 → z3 *.smt2 + ├── src/abi → idris2 --build absolute-zero-abi.ipkg + └── cargo build --release +``` + +## Why this taxonomy + +The directory layout follows the [RSR-template-repo](../RSR_OUTLINE.adoc) +convention. Compliance state is tracked in [RSR_COMPLIANCE.adoc](../../RSR_COMPLIANCE.adoc). diff --git a/absolute-zero/docs/wiki/Audit-Trail.md b/absolute-zero/docs/wiki/Audit-Trail.md new file mode 100644 index 0000000..248b29b --- /dev/null +++ b/absolute-zero/docs/wiki/Audit-Trail.md @@ -0,0 +1,56 @@ + +# Audit Trail + +Short summary; the authoritative ledger is [`AUDIT.adoc`](../../AUDIT.adoc). + +## Resolved + +| ID | Date | What | Where | +|----|------|------|-------| +| AUDIT-2026-05-20-#27 | 2026-05-25 | Unsound `alignmentMatchesPlatformWord` Idris2 postulate deleted; `alignedSizeCorrect` isolated into shared `Proofs/DivMod.idr` | PR #41, ADR-009 | +| AUDIT-2026-05-20-#32 | 2026-05-20 | Deleted unsound `eval_respects_state_eq_{left,right}` axioms; observational reversibility (`=st=`) | PR #32, ADR-008 | +| AUDIT-2026-05-20-#24 | 2026-05-20 | `eval_deterministic`: Axiom → Theorem via `step_deterministic_strong` | PR #24, ADR-007 | +| AUDIT-2026-02-05 | 2026-02-05 | License canonicalisation to PMPL-1.0-or-later (79 files) | [archived](../archive/LICENSE-AUDIT-2026-02-05.adoc) | + +## Open + +| ID | Severity | What | Status | +|----|---------|------|--------| +| AUDIT-2026-05-20-A | Medium | `src/abi/Types.idr` has 5 pre-existing errors blocking Idris2 0.8.0 typecheck | Filed, needs separate PR | +| AUDIT-2026-05-20-B | Low | `cflite_pr.yml` missing `actions/checkout` before fuzzer | Filed, needs separate PR | + +## Axiom classification + +The 73 Coq Axioms + 42 Parameters in `proofs/coq/` are model-layer +assumptions: + +* **Physics**: thermodynamic laws, Landauer bound, statistical mechanics +* **Quantum**: Hilbert-space axioms, unitarity +* **POSIX**: filesystem semantics +* **Computational complexity**: standard model assumptions + +These are *intentional* axiomatisations of the external world, not +verification gaps for the CNO claim itself. + +Tracked under [`hyperpolymath/standards`#133](https://github.com/hyperpolymath/standards/issues/133). + +## Discharge mechanism + +To turn an axiom into a theorem: + +1. Identify the axiom in `proofs//.` +2. Find or write a helper that lets you derive it from less-trusted + axioms (ideally Prelude-only) +3. Replace `Axiom name : ...` / `axiom name : ...` / `name = believe_me ()` + with the proven theorem +4. Add an ADR-NNN entry to `META.scm` +5. Add an AUDIT-YYYY-MM-DD-#PR row to `AUDIT.adoc` + +See ADR-007 (#24) for a worked example. + +## Trust-escape inventory + +Estate-wide cross-trust-escape sweeps are run periodically. Most recent: +2026-05-20 (the sweep that surfaced #27). All findings either: +* land in `AUDIT.adoc` if absolute-zero-local, or +* land in [`hyperpolymath/standards`#133](https://github.com/hyperpolymath/standards/issues/133) for model-layer. diff --git a/absolute-zero/docs/wiki/Contributing.md b/absolute-zero/docs/wiki/Contributing.md new file mode 100644 index 0000000..3502f01 --- /dev/null +++ b/absolute-zero/docs/wiki/Contributing.md @@ -0,0 +1,55 @@ + +# Contributing + +Short summary; the authoritative version is [`CONTRIBUTING.adoc`](../../CONTRIBUTING.adoc) at the root. + +## Language policy (hard rule) + +Read [`docs/CLAUDE.adoc`](../CLAUDE.adoc) Language Policy section first. +TL;DR: + +* **Allowed**: ReScript, Deno, Rust, Tauri, Dioxus, Gleam, Bash, JavaScript + (where ReScript cannot reach), Nickel, Guile Scheme, Julia, OCaml, Ada, Idris2 +* **Banned**: TypeScript, Node.js, npm/Bun/pnpm/yarn, Go, Python, Java/Kotlin, + Swift, React Native, Flutter/Dart, Ruby, Perl + +`.github/workflows/language-policy.yml` blocks new banned-language files at CI. + +## Commit conventions + +Conventional commits. Examples: + +``` +proof(coq): discharge eval_deterministic via step_deterministic_strong +proof(idris2/abi): port to Idris2 0.8.0 syntax (#27) +chore(docs): reconcile and tidy root +fix(licence): canonicalise to PMPL-1.0-or-later (#133) +``` + +* Never amend published commits. +* Hook bypass (`--no-verify`, `--no-gpg-sign`) only with explicit owner approval. + +## Verify before pushing + +```bash +just verify # full suite +just lint +just fmt +``` + +## ADR / Audit trail + +* If your change is an **architectural decision** going forward, add an ADR + entry to [`.machine_readable/META.scm`](../../.machine_readable/META.scm) + (next ADR-NNN). +* If your change **discharges a postulate / deletes unsound code**, add an + AUDIT entry to [`AUDIT.adoc`](../../AUDIT.adoc). + +## PR checklist + +* [ ] SPDX-License-Identifier on all new files (`PMPL-1.0-or-later` unless reason otherwise) +* [ ] No new banned-language files +* [ ] Tests / proofs updated where relevant +* [ ] If you touched workflows, all `uses:` references pinned to commit SHAs +* [ ] If you added a new top-level dir, it's listed in + [`RSR_COMPLIANCE.adoc`](../../RSR_COMPLIANCE.adoc) diff --git a/absolute-zero/docs/wiki/FAQ.md b/absolute-zero/docs/wiki/FAQ.md new file mode 100644 index 0000000..3110eea --- /dev/null +++ b/absolute-zero/docs/wiki/FAQ.md @@ -0,0 +1,69 @@ + +# FAQ + +### Why prove that a program does nothing? + +Because the universe of "no-op" candidates is huge and most of them +aren't no-ops. A `for i in 1..1e9` loop that increments and decrements +a counter looks like a no-op until you notice it heats the CPU. Formal +verification draws the line: a program is a CNO iff a machine-checkable +proof says so, in a model that captures the side-effects you care about +(state, I/O, *and* entropy). + +### Why six proof systems? + +Each catches what the others miss. A property proved in Coq + Lean + +Agda + Isabelle + Mizar + Z3 doesn't depend on any single backend's +foundational quirks. When something is provable only in some, that +tells you something about the foundational dependency. See +[Proof Systems](Proof-Systems.md). + +### Why is Idris2 here separately from `proofs/`? + +`src/abi/` is the FFI surface, not a proof system in its own right — +it carries formal alignment + size proofs for the C ABI used by the +Zig shim. See [ABI](ABI.md). + +### What's the difference between an Axiom and an Admitted? + +* **Axiom** (Coq) / `axiom` (Lean) / `believe_me ()` (Idris2 0.8.0): an + asserted proposition. Permanent unless discharged. +* **Admitted** (Coq) / `sorry` (Lean) / `?hole` (Idris2): a placeholder + in a proof, marking incomplete work. Should not ship. + +absolute-zero core: **0 Admitted**, 73 Axioms + 42 Parameters, all +owner-classified. + +### Why is `examples/python` / `examples/go` / `examples/java` missing? + +Deleted 2026-05-25 per the strict CLAUDE.md language policy. See +[Contributing](Contributing.md). The CNO concept generalises across +languages; the demonstrations now cover the 23 still-allowed ones. + +### Where do I file issues? + +`hyperpolymath/absolute-zero/issues`. For audit / trust-escape findings, +use the existing [`AUDIT.adoc`](../../AUDIT.adoc) issue template; for +proof discharges, the regular issue template + an ADR plan. + +### How do I talk to ECHIDNA from a script? + +Through the `echidna-llm-mcp` BoJ cartridge — never directly. See the +ECHIDNA tool table in [`0-AI-MANIFEST.a2ml`](../../0-AI-MANIFEST.a2ml). + +### Is the Coq proof complete? + +Core theory: yes (11/11 files compile, 0 Admitted). Model-layer +assumptions (Parameters about abstract physics, quantum, POSIX) are +owner-classified — these are *intended* axiomatisations of the +external world, not gaps in the verification of the computational claim. + +### Where's the live state? + +`.machine_readable/6a2/STATE.a2ml`. Updated on every meaningful change. + +### Why "Absolute Zero"? + +The thermodynamic analogy: at 0 K, a system has no entropy to release. +A CNO is a program at "computational absolute zero" — it has no +side-effect entropy to release into the world. diff --git a/absolute-zero/docs/wiki/Glossary.md b/absolute-zero/docs/wiki/Glossary.md new file mode 100644 index 0000000..4291bb9 --- /dev/null +++ b/absolute-zero/docs/wiki/Glossary.md @@ -0,0 +1,20 @@ + +# Glossary + +| Term | Definition | +|------|------------| +| **CNO** | Certified Null Operation. A program that compiles + runs and is formally proven to have zero net computational effect — no state change, no I/O, no entropy. | +| **Identity morphism** | In category theory, the morphism `id_X : X → X` that leaves `X` unchanged. CNOs are identity morphisms in the category of computational states (ADR-001). | +| **Observational reversibility (`=st=`)** | The weakened reversibility property used after ADR-008. State equality modulo program-counter bookkeeping; PC is not observable, so two states with different PC but same observable content are `=st=`. | +| **Landauer bound** | Lower thermodynamic cost of erasing one bit (`kT ln 2`). CNOs erase nothing, so any logically-reversible CNO can in principle be thermodynamically reversible too. Formalised in `StatMech.v` (axiom) + derived in `LandauerDerivation.v` (ADR-002). | +| **Postulate / Axiom** | Asserted, unproven proposition. In Coq: `Axiom`. In Lean: `axiom`. In Idris2 0.8.0: `name = believe_me ()` (the `postulate` keyword was removed). Every estate-wide axiom is tracked in [`AUDIT.adoc`](../../AUDIT.adoc) or [`META.scm`](../../.machine_readable/META.scm). | +| **HasAlignment t n** | Idris2 type asserting that type `t` has byte alignment `n`. The constructor `AlignProof` is information-free — the obligation sits on the producer to construct it only for the genuinely-correct `n`. | +| **alignedSize** | `(size, align) ↦` smallest multiple of `align` that is ≥ `size`. Core ABI primitive; correctness proved (via `believe_me`, pending discharge) in `Proofs.DivMod`. | +| **BoJ** | Brain of Jonathan — the estate's cross-repo automation cartridge layer. ECHIDNA invocations route through `echidna-llm-mcp` BoJ. | +| **ECHIDNA** | Estate-wide neurosymbolic prover gateway. 105 prover backends, 66,674-proof corpus, ML tactic suggestion. Lives in a separate repo; called via BoJ. | +| **PMPL-1.0** | Palimpsest-MPL 1.0. The project's licence. MPL-2.0 is the OSI-fallback. | +| **RSR** | Rhodium Standard Repository — the estate-wide taxonomy convention defined by [`hyperpolymath/rsr-template-repo`](https://github.com/hyperpolymath/rsr-template-repo). Conformance tracked in [`RSR_COMPLIANCE.adoc`](../../RSR_COMPLIANCE.adoc). | +| **ADR** | Architectural Decision Record. Forward-looking design choice. Recorded in [`META.scm`](../../.machine_readable/META.scm). | +| **AUDIT-ID** | Backward-looking trust event (discharged axiom, deleted unsound code, license correction). Format `AUDIT-YYYY-MM-DD-`. Recorded in [`AUDIT.adoc`](../../AUDIT.adoc). | +| **6a2** | The `.a2ml` machine-readable format under `.machine_readable/6a2/`. Successor to the older `.scm` (Guile Scheme) format which is kept side-by-side during the migration window. | +| **Trust escape** | An axiom or `believe_me` use that lets you bypass the type system. Hunted by the estate-wide cross-trust-escape sweep. | diff --git a/absolute-zero/docs/wiki/Home.md b/absolute-zero/docs/wiki/Home.md new file mode 100644 index 0000000..98f98d1 --- /dev/null +++ b/absolute-zero/docs/wiki/Home.md @@ -0,0 +1,67 @@ + +# Absolute Zero — Wiki + +> **Formal Verification of Certified Null Operations: When Doing Nothing Is Everything.** + +Welcome to the **absolute-zero** project wiki. This wiki is the human-facing entry +point; the machine-facing entry point is [`0-AI-MANIFEST.a2ml`](../../0-AI-MANIFEST.a2ml). + +## What is a CNO? + +A **Certified Null Operation** is a program that: +* compiles + executes without error, +* and is *formally proven* to have zero net computational effect — no + observable side effect on state, I/O, or thermodynamic entropy. + +The interesting question is not "can we write a no-op?" (trivially yes), but +"can we prove that an arbitrary candidate program is a no-op, in a +machine-checkable way, across multiple semantic models?". Absolute Zero +formalises this across six proof systems and verifies it for interpreters +of 23+ languages. + +## Navigate + +| Page | Purpose | +|------|---------| +| [Architecture](Architecture.md) | How the pieces fit together: proofs, interpreters, ABI, ECHIDNA | +| [Proof Systems](Proof-Systems.md) | Coq / Lean 4 / Z3 / Agda / Isabelle / Mizar — what each proves and why six | +| [Verification](Verification.md) | How to build and verify locally; CI matrix | +| [ABI](ABI.md) | Idris2 FFI surface; alignment + size invariants | +| [Roadmap](Roadmap.md) | v1.0 → v12.0 trajectory | +| [Contributing](Contributing.md) | How to send a PR, conventions, sign-off | +| [Glossary](Glossary.md) | CNO, observational reversibility, =st=, Landauer bound, etc. | +| [FAQ](FAQ.md) | Common questions | +| [Audit Trail](Audit-Trail.md) | Discharged axioms, deleted unsound code, open findings | + +## Status (live) + +* **Phase**: proof-completion (~65%) +* **Coq**: 11/11 files compile, 0 Admitted, 73 Axioms + 42 Parameters (model-layer) +* **Lean 4**: `lake build` 1631/1632 green +* **Idris2 ABI**: typechecks under 0.8.0; `Proofs/DivMod.idr` consolidates the trusted div/mod base +* For the authoritative live state, read [`.machine_readable/6a2/STATE.a2ml`](../../.machine_readable/6a2/STATE.a2ml) + +## Project layout (RSR-aligned) + +``` +absolute-zero/ +├── 0-AI-MANIFEST.a2ml ← machine entry point +├── README.adoc ← short pitch +├── ROADMAP.adoc ← v1.0 → v12.0 +├── AUDIT.adoc ← discharged axioms + open findings +├── RSR_COMPLIANCE.adoc ← Rhodium Standard conformance +├── ECHIDNA.adoc ← integration with the prover gateway +├── docs/ ← evergreen topical docs; wiki/ subdir +├── proofs/ ← coq, lean4, z3, agda, isabelle, mizar +├── src/ ← Idris2 ABI + Rust core +├── interpreters/ ← language interpreters (ReScript) +├── examples/ ← CNOs in 23+ languages +├── verification/ ← top-level verify scripts +├── tests/, tools/ ← RSR-conventional placeholders +├── .well-known/ ← security.txt, ai.txt, humans.txt +└── .machine_readable/ ← STATE / META / ECOSYSTEM / AGENTIC / NEUROSYM / PLAYBOOK +``` + +## License + +PMPL-1.0-or-later (Palimpsest-MPL 1.0). MPL-2.0 fallback where platform requires OSI-approved licence. diff --git a/absolute-zero/docs/wiki/Proof-Systems.md b/absolute-zero/docs/wiki/Proof-Systems.md new file mode 100644 index 0000000..52f427a --- /dev/null +++ b/absolute-zero/docs/wiki/Proof-Systems.md @@ -0,0 +1,85 @@ + +# Proof Systems + +## Why six? + +Each prover trades off three axes: + +| | Constructive | Automated | Mathlib | +|---|---|---|---| +| Coq | ✅ | ⚪ | ⚪ | +| Lean 4 | ✅ | ⚪ | ✅ | +| Agda | ✅ | ⚪ | ⚪ | +| Isabelle | ⚪ | ⚪ | ✅ | +| Mizar | ⚪ | ⚪ | ✅ | +| Z3 | ⚪ | ✅ | ⚪ | + +A property proved in **all six** is robust against any single backend's +foundational quirks. A property proved in *some but not others* +flags a foundational dependency worth understanding. + +## What lives where + +### `proofs/coq/` (the load-bearing system) +* `common/CNO.v` — core CNO definitions and properties +* `physics/StatMech.v` — Landauer bound axiomatised +* `physics/LandauerDerivation.v` — Landauer bound derived (the two + together form ADR-002's "dual formalisation") +* `category/CNOCategory.v` — CNOs as identity morphisms +* `lambda/LambdaCNO.v` — lambda calculus CNOs +* `quantum/QuantumCNO.v` — quantum CNOs +* `quantum/QuantumMechanicsExact.v` — exact QM formulation +* `malbolge/MalbolgeCore.v` — Malbolge VM semantics +* `filesystem/FilesystemCNO.v` — filesystem CNOs + +Status: 11/11 files compile, 0 Admitted (post 2026-05-18 rescue). +73 Axioms + 42 Parameters, all owner-classified as legitimate +model-layer assumptions. See [`docs/PROOF-CLASSIFICATION.adoc`](../PROOF-CLASSIFICATION.adoc). + +### `proofs/lean4/` +* `CNO.lean`, `StatMech.lean`, `CNOCategory.lean`, `LambdaCNO.lean`, + `QuantumCNO.lean`, `FilesystemCNO.lean` +* Built with `lake build`; mathlib + 6 lean_lib targets; + 1631/1632 green (verified 2026-05-20). + +### `proofs/z3/` +SMT proofs of decidable fragments. Fast counterexample search for +candidate CNO claims before committing to a constructive proof. + +### `proofs/agda/` +Type-level CNO certificates exploiting dependent types. + +### `proofs/isabelle/`, `proofs/mizar/` +Cross-validation. Catches Coq-specific tactic quirks; connects +Mizar's standard maths library. + +## Reproducible build + +```bash +just build-coq # coqc -R common CNO physics/StatMech.v ... +just build-lean # cd proofs/lean4 && lake build +just build-agda # agda CNO.agda +just build-isabelle # isabelle build +just build-z3 # z3 *.smt2 (when present) +just verify # all of the above + ABI + Rust +``` + +## Discharged axioms (recent) + +* **ADR-007** (2026-05-20, PR #24): `eval_deterministic` + Axiom → Theorem via `step_deterministic_strong` +* **ADR-008** (2026-05-20, PR #32): deleted unsound + `eval_respects_state_eq_{left,right}` axioms; weakened + `logically_reversible` to observational reversibility (`=st=`) +* **ADR-009** (2026-05-25, PR #41 / #40): + deleted unsound Idris2 `alignmentMatchesPlatformWord` postulate; + consolidated div/mod axioms into shared + `AbsoluteZero.ABI.Proofs.DivMod` + +See [Audit Trail](Audit-Trail.md) for the full ledger. + +## Idris2 ABI (the seventh) + +The Idris2 surface in `src/abi/` isn't a proof system per se, but +carries formal alignment + size proofs for the C FFI boundary. See +[ABI](ABI.md). diff --git a/absolute-zero/docs/wiki/README.md b/absolute-zero/docs/wiki/README.md new file mode 100644 index 0000000..8cd7028 --- /dev/null +++ b/absolute-zero/docs/wiki/README.md @@ -0,0 +1,53 @@ + +# docs/wiki — In-repo source for the GitHub Wiki + +These markdown pages are the canonical source for +. + +## Why in-repo? + +* Wiki pages get reviewed in PRs like any other code. +* The wiki history is recoverable from `git log` even if GitHub Wiki + goes away. +* AI agents read this directory directly without needing wiki access. + +## Sync to GitHub Wiki + +The GitHub Wiki is itself a git repo at +`https://github.com/hyperpolymath/absolute-zero.wiki.git`. + +To push these pages: + +```bash +# Clone the wiki repo alongside the main repo +git clone https://github.com/hyperpolymath/absolute-zero.wiki.git ../absolute-zero.wiki + +# Copy the in-repo pages over +cp docs/wiki/*.md ../absolute-zero.wiki/ + +# Commit + push to the wiki +cd ../absolute-zero.wiki +git add . +git commit -m "Sync from absolute-zero/docs/wiki@$(cd ../absolute-zero && git rev-parse --short HEAD)" +git push +``` + +(Automation TODO: a `Justfile` recipe `just wiki-sync` plus a workflow +that runs the above on every push to main. Tracked in +`RSR_COMPLIANCE.adoc`.) + +## Page index + +| Page | Status | +|------|--------| +| `Home.md` | Landing | +| `Architecture.md` | Three-layer architecture | +| `Proof-Systems.md` | Why six provers; what each covers | +| `Verification.md` | Build + CI matrix | +| `ABI.md` | Idris2 ABI + DivMod lemma surface | +| `Roadmap.md` | Short; cross-links to ROADMAP.adoc | +| `Contributing.md` | Short; cross-links to CONTRIBUTING.adoc | +| `Glossary.md` | CNO, =st=, postulate, etc. | +| `FAQ.md` | Common questions | +| `Audit-Trail.md` | Resolved + open audit items | +| `_Sidebar.md` | Persistent sidebar (rendered on every wiki page) | diff --git a/absolute-zero/docs/wiki/Roadmap.md b/absolute-zero/docs/wiki/Roadmap.md new file mode 100644 index 0000000..d2dd47a --- /dev/null +++ b/absolute-zero/docs/wiki/Roadmap.md @@ -0,0 +1,31 @@ + +# Roadmap + +Short summary; the authoritative version is [`ROADMAP.adoc`](../../ROADMAP.adoc) at the root. + +## Now (v1.0.0-alpha → v1.0.0) + +* Discharge remaining Coq Admitteds (currently 0 in core, 19→0 historic) +* Complete Idris2 ABI typecheck (unblock `Types.idr` pre-existing errors) +* Wire `idris2 --build absolute-zero-abi.ipkg` into CI matrix +* Strict language-policy compliance (banned-lang examples removed 2026-05-25) +* RSR-template-repo conformance (see [RSR_COMPLIANCE.adoc](../../RSR_COMPLIANCE.adoc)) + +## Next (v0.8 → v0.9 milestones) + +* `v0.8.0` — Compliance Sprint: complete checkpoint files, remove npm +* `v0.9.0` — Container Verification: Containerfile with all 6 provers, cross-arch CI +* `v1.0.0` — Publication: zero Admitted, paper submitted, 3 industrial CNO examples + +## Long horizon (v2 → v12) + +7-year vision: language expansion, AI-assisted proving, quantum verification, +standardisation. Detailed phase decomposition in [`ROADMAP.adoc`](../../ROADMAP.adoc). + +## How decisions are recorded + +* Forward-looking architectural choices → ADRs in + [`.machine_readable/META.scm`](../../.machine_readable/META.scm) + `architecture-decisions` section +* Backward-looking audit events → [`AUDIT.adoc`](../../AUDIT.adoc) +* Live phase / progress → [`.machine_readable/6a2/STATE.a2ml`](../../.machine_readable/6a2/STATE.a2ml) diff --git a/absolute-zero/docs/wiki/Verification.md b/absolute-zero/docs/wiki/Verification.md new file mode 100644 index 0000000..8c9a0d2 --- /dev/null +++ b/absolute-zero/docs/wiki/Verification.md @@ -0,0 +1,97 @@ + +# Verification + +How to verify locally and what CI does. + +## Local + +The `verification/` directory contains the top-level scripts. + +```bash +# One-shot: install deps + run full verification +./verification/setup-and-verify.sh + +# After deps are installed +./verification/run-local-verification.sh + +# Just the proof suite +./verification/verify-proofs.sh +``` + +Or via `Justfile` recipes (more granular): + +```bash +just build-all # everything +just build-coq # Coq only +just build-lean # Lean 4 only +just build-agda +just build-isabelle +just build-rescript +just verify # build + check +``` + +## Per-prover commands + +### Coq +```bash +cd proofs/coq/common && coqc CNO.v +cd ../physics && coqc -R ../common CNO StatMech.v + coqc -R ../common CNO LandauerDerivation.v +cd ../quantum && coqc -R ../common CNO QuantumMechanicsExact.v +cd ../malbolge && coqc -R ../common CNO MalbolgeCore.v +``` + +### Lean 4 +```bash +cd proofs/lean4 && lake build +``` + +### Agda +```bash +cd proofs/agda && agda CNO.agda +``` + +### Idris2 ABI +```bash +idris2 --build absolute-zero-abi.ipkg +``` + +(Standalone DivMod check, useful for the issue #27 surface:) +```bash +idris2 --check src/abi/Proofs/DivMod.idr +``` + +## CI matrix + +| Workflow | What it does | Status check name | +|----------|--------------|--------------------| +| `rust-ci.yml` | `cargo build --release`, `cargo audit`, coverage | `build`, `security`, `coverage` | +| `rescript-deno-ci.yml` | `deno lint`, `deno fmt --check`, `deno test`, `rescript build` | `build` | +| `codeql.yml` | CodeQL static analysis | `check` | +| `secret-scanner.yml` | trufflehog + gitleaks | `secrets` | +| `language-policy.yml` | Block new banned-language files | `check` | +| `governance.yml` | Estate-wide reusable governance bundle | `governance / *` | +| `hypatia-scan.yml` | Neurosymbolic CI/CD scan | (comment-only) | +| `cflite_pr.yml` | ClusterFuzzLite (address sanitizer) | `PR (address)` | +| `scorecard.yml` | OpenSSF Scorecard | (badge) | +| `jekyll-gh-pages.yml` | Deploy homepage | (deploy) | +| `publish-container.yml` | Build + push container image | (release) | + +## Reproducible container + +`Containerfile` at root pins toolchain versions. Build: + +```bash +podman build -t absolute-zero:verify -f Containerfile . +podman run --rm absolute-zero:verify just verify +``` + +(Or `docker` in place of `podman`.) + +## Status as of 2026-05-25 + +See [`.machine_readable/6a2/STATE.a2ml`](../../.machine_readable/6a2/STATE.a2ml) +for live status. Summary: Coq 11/11, Lean 4 1631/1632, Idris2 ABI +typechecks (DivMod standalone; Layout blocked by pre-existing +`Types.idr` errors — tracked as AUDIT-2026-05-20-A in +[AUDIT.adoc](../../AUDIT.adoc)). diff --git a/absolute-zero/docs/wiki/_Sidebar.md b/absolute-zero/docs/wiki/_Sidebar.md new file mode 100644 index 0000000..addbd51 --- /dev/null +++ b/absolute-zero/docs/wiki/_Sidebar.md @@ -0,0 +1,25 @@ + +**[Home](Home)** + +**Project** +* [Architecture](Architecture) +* [Roadmap](Roadmap) +* [Audit Trail](Audit-Trail) + +**Verification** +* [Proof Systems](Proof-Systems) +* [Verification](Verification) +* [ABI](ABI) + +**Reference** +* [Contributing](Contributing) +* [Glossary](Glossary) +* [FAQ](FAQ) + +--- + +**Live state** +[`STATE.a2ml`](https://github.com/hyperpolymath/absolute-zero/blob/main/.machine_readable/6a2/STATE.a2ml) + +**AI manifest** +[`0-AI-MANIFEST.a2ml`](https://github.com/hyperpolymath/absolute-zero/blob/main/0-AI-MANIFEST.a2ml) diff --git a/absolute-zero/eclexiaiser.toml b/absolute-zero/eclexiaiser.toml deleted file mode 100644 index 134fcab..0000000 --- a/absolute-zero/eclexiaiser.toml +++ /dev/null @@ -1,26 +0,0 @@ -# eclexiaiser manifest — energy/carbon resource budgets -# SPDX-License-Identifier: MPL-2.0 - -[project] -name = "absolute-zero" - -[[functions]] -name = "test_cno" -source = "src/brainfuck/src/main.rs" -energy-budget-mj = 30.0 -carbon-budget-mg = 6.0 - -[[functions]] -name = "annotateAudits" -source = "src/AuditTrail.res" -energy-budget-mj = 10.0 -carbon-budget-mg = 2.0 - -[carbon] -provider = "static" -region = "GB" -static-intensity = 200.0 - -[report] -format = "text" -include-recommendations = true diff --git a/absolute-zero/examples/SafeDOMExample.res b/absolute-zero/examples/SafeDOMExample.res deleted file mode 100644 index e5c9046..0000000 --- a/absolute-zero/examples/SafeDOMExample.res +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Example: Using SafeDOM for formally verified DOM mounting - -open SafeDOM - -// Example 1: Basic mounting with error handling -let mountApp = () => { - mountSafe( - "#app", - "

Hello, World!

Mounted safely with proofs.

", - ~onSuccess=el => { - Console.log("✓ App mounted successfully!") - Console.log("Element:", el) - }, - ~onError=err => { - Console.error("✗ Mount failed:", err) - } - ) -} - -// Example 2: Wait for DOM ready before mounting -let mountWhenDOMReady = () => { - mountWhenReady( - "#app", - "

App Title

", - ~onSuccess=_ => Console.log("✓ Mounted after DOM ready"), - ~onError=err => Console.error("✗ Failed:", err) - ) -} - -// Example 3: Batch mounting (atomic - all or nothing) -let mountMultiple = () => { - let specs = [ - {selector: "#header", html: "

Site Title

"}, - {selector: "#nav", html: ""}, - {selector: "#main", html: "

Content here

"}, - {selector: "#footer", html: "
© 2026
"} - ] - - switch mountBatch(specs) { - | Ok(elements) => { - Console.log(`✓ Successfully mounted ${Array.length(elements)} elements`) - elements->Array.forEach(el => Console.log(" -", el)) - } - | Error(err) => { - Console.error("✗ Batch mount failed:", err) - Console.error(" (None were mounted - atomic operation)") - } - } -} - -// Example 4: Explicit validation before mounting -let mountWithValidation = () => { - // Validate selector first - switch ProvenSelector.validate("#my-app") { - | Error(e) => Console.error(`Invalid selector: ${e}`) - | Ok(validSelector) => { - // Validate HTML - switch ProvenHTML.validate("
Content
") { - | Error(e) => Console.error(`Invalid HTML: ${e}`) - | Ok(validHtml) => { - // Now mount with proven safety - switch mount(validSelector, validHtml) { - | Mounted(el) => Console.log("✓ Mounted with validated inputs:", el) - | MountPointNotFound(s) => Console.error(`✗ Element not found: ${s}`) - | InvalidSelector(_) => Console.error("Impossible - already validated") - | InvalidHTML(_) => Console.error("Impossible - already validated") - } - } - } - } -} - -// Example 5: Integration with TEA -module MyApp = { - type model = {message: string} - type msg = NoOp - - let init = () => {message: "Hello from TEA"} - let update = (model, _msg) => model - let view = model => `

${model.message}

` -} - -let mountTEAApp = () => { - let model = MyApp.init() - let html = MyApp.view(model) - - mountWhenReady( - "#tea-app", - html, - ~onSuccess=el => { - Console.log("✓ TEA app mounted") - // Set up event handlers, subscriptions here - }, - ~onError=err => Console.error(`✗ TEA mount failed: ${err}`) - ) -} - -// Entry point -let main = () => { - Console.log("SafeDOM Examples") - Console.log("================\n") - - // Choose which example to run - mountWhenDOMReady() // Run on DOM ready -} - -// Auto-execute when module loads -main() diff --git a/absolute-zero/examples/go/nop.go b/absolute-zero/examples/go/nop.go deleted file mode 100644 index 79011e8..0000000 --- a/absolute-zero/examples/go/nop.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Certified Null Operation in Go - * - * A program that does absolutely nothing at the application level. - * Exits with code 0 (success) without any observable side effects. - * - * Properties: - * - Terminates immediately - * - No I/O operations - * - No goroutines spawned - * - No channel operations - * - Exit code 0 - * - * Build: go build nop.go - * Run: ./nop - */ - -package main - -func main() { - // Empty main - the minimal CNO in Go - // The Go runtime handles initialization and cleanup, - // but at the application level, this computes nothing observable. -} - -/* - * Verification notes: - * - Go runtime initializes (scheduler, garbage collector, etc.) - * - Goroutine for main() is created - * - Memory allocator is initialized - * - At application level: CNO - * - At runtime level: goroutine scheduling occurs - * - * This demonstrates the gap between application logic and - * the concurrent runtime that Go provides. - * - * Interestingly, even this empty program benefits from Go's - * concurrent runtime infrastructure, though no concurrency is used. - */ diff --git a/absolute-zero/examples/java/BalancedOps.java b/absolute-zero/examples/java/BalancedOps.java deleted file mode 100644 index c3d3b69..0000000 --- a/absolute-zero/examples/java/BalancedOps.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Balanced Operations CNO in Java - * - * Performs operations that cancel out, resulting in no net effect. - * Demonstrates computational work with zero net result. - */ - -public class BalancedOps { - public static void main(String[] args) { - // All operations cancel out - int x = 0; - - // Increment then decrement - x = x + 1; - x = x - 1; - - // Multiply then divide - x = x * 2; - x = x / 2; - - // XOR with self (always 0) - x = x ^ x; - - // Bitwise NOT twice - x = ~(~x); - - // String operations that cancel - String s = "test"; - s = s.toUpperCase(); - s = s.toLowerCase(); - - // Final values: x == 0, s == "test" (unchanged) - } -} - -/* - * JVM-specific CNO considerations: - * - * Garbage Collection: - * - String operations create temporary objects - * - These become garbage immediately - * - GC may or may not run during execution - * - CNO at application level despite heap churn - * - * JIT Compilation: - * - HotSpot may optimize away dead code - * - Use -XX:+PrintCompilation to observe - * - Even optimized code has JVM overhead - * - * Memory Barriers: - * - Operations involve memory reads/writes - * - Cache coherency protocols engaged - * - CNO doesn't mean zero memory operations - * - * At semantic level: operations cancel perfectly - * At runtime level: significant computational work performed - */ diff --git a/absolute-zero/examples/java/Nop.java b/absolute-zero/examples/java/Nop.java deleted file mode 100644 index ecf700e..0000000 --- a/absolute-zero/examples/java/Nop.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Certified Null Operation in Java - * - * A program that does absolutely nothing at the application level. - * Exits successfully without any side effects. - * - * Properties: - * - Terminates immediately - * - No I/O operations - * - No object allocations (beyond JVM startup) - * - Exit code 0 - */ - -public class Nop { - public static void main(String[] args) { - // Intentionally empty - } -} - -/* - * Verification notes: - * - JVM startup involves significant work: - * - Class loading and verification - * - JIT compilation - * - Garbage collector initialization - * - Thread pool creation - * - At application level: CNO - * - At JVM level: thousands of operations - * - At OS level: process creation, memory mapping - * - * This demonstrates multiple abstraction layers between logical and physical computation. - * The "null operation" exists only at the application semantic level. - */ diff --git a/absolute-zero/examples/kotlin/BalancedOps.kt b/absolute-zero/examples/kotlin/BalancedOps.kt deleted file mode 100644 index c687d90..0000000 --- a/absolute-zero/examples/kotlin/BalancedOps.kt +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Balanced Operations CNO in Kotlin - * - * Performs operations that cancel out, resulting in no net effect. - * Demonstrates Kotlin idioms with zero net result. - */ - -fun main() { - // All operations cancel out - var x = 0 - - // Increment then decrement - x += 1 - x -= 1 - - // Multiply then divide - x *= 2 - x /= 2 - - // XOR with self (always 0) - x = x xor x - - // Collection transformations that cancel - val list = listOf(1, 2, 3) - val reversed = list.reversed().reversed() - - // Map operations that cancel - val doubled = list.map { it * 2 }.map { it / 2 } - - // Scope functions that cancel - val result = 42.let { it + 10 }.let { it - 10 } - - // Nullable operations - val nullable: Int? = 42 - val transformed = nullable?.let { it + 10 }?.let { it - 10 } - - // String operations - var s = "test" - s = s.uppercase() - s = s.lowercase() - - // Final values unchanged: x == 0, reversed == list, doubled == list, - // result == 42, transformed == 42, s == "test" -} - -/* - * Kotlin-specific CNO considerations: - * - * Null Safety: - * - Runtime checks for nullable operations - * - Safe call operator (?.) adds branching - * - CNO maintained even with null safety overhead - * - * Extension Functions: - * - reversed(), uppercase(), etc. are extensions - * - Compiled to static method calls - * - No performance penalty vs Java - * - * Lambda Expressions: - * - map { } and let { } use lambdas - * - May be inlined by compiler - * - Creates synthetic classes if not inlined - * - GC impact from lambda objects - * - * Immutable Collections: - * - listOf() creates immutable list - * - Each transformation creates new collection - * - Heavy allocation despite CNO result - * - * Coroutines: - * - Not used here, but runtime available - * - suspend functions would add continuation overhead - * - CNO achievable even with async operations - * - * Inline Classes: - * - Could use inline classes for zero-overhead wrappers - * - Still CNO with type safety benefits - * - * At semantic level: identity transformations - * At runtime level: object creation, method dispatch, null checks - * At JVM level: same overhead as Java plus Kotlin runtime - */ diff --git a/absolute-zero/examples/kotlin/Nop.kt b/absolute-zero/examples/kotlin/Nop.kt deleted file mode 100644 index 5c3d26c..0000000 --- a/absolute-zero/examples/kotlin/Nop.kt +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Certified Null Operation in Kotlin - * - * A program that does absolutely nothing at the application level. - * Exits successfully without any side effects. - * - * Properties: - * - Terminates immediately - * - No I/O operations - * - No computations performed - * - Exit code 0 - */ - -fun main() { - // Intentionally empty -} - -/* - * Verification notes: - * - Kotlin compiles to JVM bytecode (or JS/Native) - * - Kotlin stdlib loaded and initialized - * - Coroutine infrastructure available (even if unused) - * - Reflection metadata loaded - * - Null safety runtime checks initialized - * - * At application level: CNO - * At Kotlin runtime level: stdlib initialization - * At JVM level: full startup sequence - * - * Kotlin's modern features (null safety, coroutines, extension functions) - * all require runtime support structures, even for CNO. - * - * The Unit return type (implicit here) represents side-effecting - * computation with no meaningful value - a form of computational CNO. - * - * Note: Kotlin allows top-level main() without class wrapper, - * but compiler generates synthetic class anyway. - */ diff --git a/absolute-zero/examples/perl/nop.pl b/absolute-zero/examples/perl/nop.pl deleted file mode 100755 index 8539396..0000000 --- a/absolute-zero/examples/perl/nop.pl +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env perl -use strict; -use warnings; - -# Perl CNO (Code with No Output) - Absolute Zero Example -# -# This program executes successfully without producing any output. -# Demonstrates the minimal Perl program that does nothing observably. -# -# INTERPRETER BEHAVIOR: -# - Perl interpreter (typically perl5) initialization -# - Script compilation to internal opcodes -# - @INC constructed from system and environment paths -# - Symbol table setup for main:: package -# - Runtime overhead: ~5-20ms for Perl startup -# -# RUNTIME OVERHEAD: -# - Core Perl runtime loaded (~2-5 MB baseline) -# - Built-in variables initialized: $0, @ARGV, %ENV, etc. -# - Special variables: $/, $\, $", $;, etc. all set to defaults -# - UNIVERSAL package methods available -# - DynaLoader for loading XS modules initialized -# - Approximate cost: 5-10 MB memory footprint minimum -# -# SIDE EFFECTS: -# - Exit code 0 set implicitly -# - STDIN, STDOUT, STDERR filehandles opened -# - Current working directory cached ($ENV{PWD}) -# - @INC populated with library search paths -# - %INC tracks loaded modules (empty if no use/require) -# - Signal handlers set to defaults -# - $^T (program start time) set -# - $$ (process ID) available -# -# VERIFICATION: -# - No stdout/stderr output -# - Exit code 0 -# - No warnings or errors (with use strict; use warnings;) -# - No files modified -# - $? is 0 (child process status) -# -# EXECUTION: -# perl nop.pl -# echo $? # Should output 0 -# -# LANGUAGE SEMANTICS: -# - Empty program block after pragmas is valid -# - undef is implicit return value -# - 'use strict' and 'use warnings' compile-time directives -# - No main() function needed (unlike C) -# - exit(0) is implicit; explicit exit unnecessary -# -# PERL-SPECIFIC NOTES: -# - BEGIN blocks would execute at compile time -# - END blocks would execute at exit -# - CHECK/INIT blocks for special phase execution -# - Taint mode (-T) would be enforced if enabled -# - No .plc compiled cache (unlike Python/Ruby bytecode) - -# Explicit no-operation (uncomment to demonstrate): -# 1; - -# Alternative explicit no-ops in Perl: -# (); -# {}; -# undef; -# sub nop {} -# package Nop; -# BEGIN {} -# END {} - -# Note: Perl modules conventionally end with '1;' to indicate -# successful loading, but scripts do not require this. - -__END__ - -# Everything after __END__ is ignored by Perl -# This is a valid way to add documentation or data sections -# that won't be executed. diff --git a/absolute-zero/examples/ruby/nop.rb b/absolute-zero/examples/ruby/nop.rb deleted file mode 100755 index 0561845..0000000 --- a/absolute-zero/examples/ruby/nop.rb +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env ruby -# frozen_string_literal: true - -# Ruby CNO (Code with No Output) - Absolute Zero Example -# -# This program executes successfully without producing any output. -# Demonstrates the minimal Ruby program that does nothing observably. -# -# INTERPRETER BEHAVIOR: -# - MRI (Matz's Ruby Interpreter) performs environment setup -# - YARV bytecode compilation (Ruby 1.9+) -# - Standard library autoload triggers are registered -# - Runtime overhead: ~20-50ms for interpreter startup -# -# RUNTIME OVERHEAD: -# - Object space initialization -# - Core classes loaded (Object, Class, Module, etc.) -# - $LOAD_PATH constructed from gem paths -# - Encoding tables initialized (UTF-8 default in Ruby 2.0+) -# - Approximate cost: 10-20 MB memory footprint minimum -# -# SIDE EFFECTS: -# - Global variables populated: $PROGRAM_NAME, $0, ARGV, etc. -# - File descriptors opened: STDIN, STDOUT, STDERR -# - Process exit code 0 set implicitly -# - Signal handlers initialized -# - ObjectSpace contains all core objects -# - No .rbc files created (unlike Python's .pyc) -# -# VERIFICATION: -# - No stdout/stderr output -# - Exit code 0 -# - No exceptions raised -# - No files modified -# -# EXECUTION: -# ruby nop.rb -# echo $? # Should output 0 -# -# LANGUAGE SEMANTICS: -# - Empty file is valid Ruby program -# - nil is implicit return value -# - Comments-only file is valid -# - No explicit 'exit 0' needed - -# Explicit no-operation (uncomment to demonstrate): -# nil - -# Alternative explicit no-ops in Ruby: -# -> {} -# proc {} -# begin; end -# if false; end diff --git a/absolute-zero/examples/swift/Nop.swift b/absolute-zero/examples/swift/Nop.swift deleted file mode 100644 index 8b2a7ec..0000000 --- a/absolute-zero/examples/swift/Nop.swift +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Certified Null Operation in Swift - * - * A program that does absolutely nothing at the application level. - * Exits with code 0 (success) without any observable side effects. - * - * Properties: - * - Terminates immediately - * - No I/O operations - * - No memory allocation beyond runtime overhead - * - Exit code 0 - * - * Compile: swiftc Nop.swift -o nop - * Run: ./nop - */ - -// Empty file - the minimal CNO in Swift -// Swift allows top-level code, so an empty file is a valid program -// that does nothing and exits with code 0. - -/* - * Verification notes: - * - Swift runtime initializes (ARC, standard library, etc.) - * - No explicit main function required in scripts - * - For compiled programs, an implicit main is generated - * - At application level: CNO - * - At runtime level: memory management initialization - * - * This demonstrates Swift's dual nature as both a scripting - * and compiled systems language. An empty file is valid in both contexts. - * - * Alternative explicit form: - * - * @main - * struct NopProgram { - * static func main() { - * // Empty main - * } - * } - * - * Both forms are equally valid CNOs. - */ diff --git a/absolute-zero/examples/web-project-deno.json b/absolute-zero/examples/web-project-deno.json index 5ddd3bd..eaa39d9 100644 --- a/absolute-zero/examples/web-project-deno.json +++ b/absolute-zero/examples/web-project-deno.json @@ -8,7 +8,7 @@ "test": "deno test --allow-all" }, "imports": { - "rescript": "^12.0.0", + "rescript": "npm:rescript@^12.1.0", "@rescript/core": "npm:@rescript/core@^1.6.0", "safe-dom/": "https://raw.githubusercontent.com/hyperpolymath/rescript-dom-mounter/main/src/", "proven/": "../proven/bindings/rescript/src/" diff --git a/absolute-zero/ffi/zig/build.zig b/absolute-zero/ffi/zig/build.zig index 3c9daca..fe27f5e 100644 --- a/absolute-zero/ffi/zig/build.zig +++ b/absolute-zero/ffi/zig/build.zig @@ -1,6 +1,5 @@ -// Absolute Zero FFI Build Configuration -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell +// {{PROJECT}} FFI Build Configuration +// SPDX-License-Identifier: AGPL-3.0-or-later const std = @import("std"); @@ -8,21 +7,88 @@ pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - const root_mod = b.createModule(.{ + // Shared library (.so, .dylib, .dll) + const lib = b.addSharedLibrary(.{ + .name = "{{project}}", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); - // Unit tests — link libc since FFI uses c_allocator - root_mod.link_libc = true; + // Set version + lib.version = .{ .major = 0, .minor = 1, .patch = 0 }; + // Static library (.a) + const lib_static = b.addStaticLibrary(.{ + .name = "{{project}}", + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, + }); + + // Install artifacts + b.installArtifact(lib); + b.installArtifact(lib_static); + + // Generate header file for C compatibility + const header = b.addInstallHeader( + b.path("include/{{project}}.h"), + "{{project}}.h", + ); + b.getInstallStep().dependOn(&header.step); + + // Unit tests const lib_tests = b.addTest(.{ - .root_module = root_mod, + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = optimize, }); const run_lib_tests = b.addRunArtifact(lib_tests); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&run_lib_tests.step); + + // Integration tests + const integration_tests = b.addTest(.{ + .root_source_file = b.path("test/integration_test.zig"), + .target = target, + .optimize = optimize, + }); + + integration_tests.linkLibrary(lib); + + const run_integration_tests = b.addRunArtifact(integration_tests); + + const integration_test_step = b.step("test-integration", "Run integration tests"); + integration_test_step.dependOn(&run_integration_tests.step); + + // Documentation + const docs = b.addTest(.{ + .root_source_file = b.path("src/main.zig"), + .target = target, + .optimize = .Debug, + }); + + const docs_step = b.step("docs", "Generate documentation"); + docs_step.dependOn(&b.addInstallDirectory(.{ + .source_dir = docs.getEmittedDocs(), + .install_dir = .prefix, + .install_subdir = "docs", + }).step); + + // Benchmark (if needed) + const bench = b.addExecutable(.{ + .name = "{{project}}-bench", + .root_source_file = b.path("bench/bench.zig"), + .target = target, + .optimize = .ReleaseFast, + }); + + bench.linkLibrary(lib); + + const run_bench = b.addRunArtifact(bench); + + const bench_step = b.step("bench", "Run benchmarks"); + bench_step.dependOn(&run_bench.step); } diff --git a/absolute-zero/ffi/zig/src/main.zig b/absolute-zero/ffi/zig/src/main.zig index 2ebad10..8f897a2 100644 --- a/absolute-zero/ffi/zig/src/main.zig +++ b/absolute-zero/ffi/zig/src/main.zig @@ -1,26 +1,25 @@ -// Absolute Zero FFI Implementation +// {{PROJECT}} FFI Implementation // -// This module implements the C-compatible FFI declared in src/abi/Foreign.idr. +// This module implements the C-compatible FFI declared in src/abi/Foreign.idr // All types and layouts must match the Idris2 ABI definitions. // -// The FFI provides a pure Zig implementation of the Brainfuck CNO verification -// engine, callable from any language that supports the C ABI. -// -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell +// SPDX-License-Identifier: AGPL-3.0-or-later const std = @import("std"); -const VERSION = "1.0.0"; -const BUILD_INFO = "absolute-zero built with Zig " ++ @import("builtin").zig_version_string; +// Version information (keep in sync with project) +const VERSION = "0.1.0"; +const BUILD_INFO = "{{PROJECT}} 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; } @@ -29,324 +28,247 @@ fn clearError() void { // Core Types (must match src/abi/Types.idr) //============================================================================== -/// Result codes (matches Idris2 Result type: Ok=0..NotCNO=7) +/// Result codes (must match Idris2 Result type) pub const Result = enum(c_int) { ok = 0, - err = 1, + @"error" = 1, invalid_param = 2, out_of_memory = 3, null_pointer = 4, - non_terminating = 5, - has_side_effects = 6, - not_cno = 7, }; -/// CNO verification result (matches Idris2 CNOVerificationResult) -/// Layout: 5 bools packed as u8, total 5 bytes -pub const CnoResult = extern struct { - is_cno: u8, - terminates: u8, - preserves_state: u8, - is_pure: u8, - is_reversible: u8, +/// Library handle (opaque to prevent direct access) +pub const Handle = opaque { + // Internal state hidden from C + allocator: std.mem.Allocator, + initialized: bool, + // Add your fields here }; -const MEMORY_SIZE: usize = 30_000; -const DEFAULT_MAX_CYCLES: usize = 1_000_000; - //============================================================================== -// Brainfuck VM (matches Rust BrainfuckInterpreter) +// Library Lifecycle //============================================================================== -/// Brainfuck interpreter state -const BfInterpreter = struct { - program: []const u8, - bracket_map: []usize, - memory: [MEMORY_SIZE]u8, - pointer: usize, - pc: usize, - output_len: usize, - halted: bool, - cycles: usize, - max_cycles: usize, - allocator: std.mem.Allocator, - - fn init(allocator: std.mem.Allocator, program: []const u8, max_cycles: usize) !*BfInterpreter { - const self = try allocator.create(BfInterpreter); - self.* = .{ - .program = program, - .bracket_map = try buildBracketMap(allocator, program), - .memory = [_]u8{0} ** MEMORY_SIZE, - .pointer = 0, - .pc = 0, - .output_len = 0, - .halted = false, - .cycles = 0, - .max_cycles = max_cycles, - .allocator = allocator, - }; - return self; - } - - fn deinit(self: *BfInterpreter) void { - self.allocator.free(self.bracket_map); - self.allocator.destroy(self); - } +/// Initialize the library +/// Returns a handle, or null on failure +export fn {{project}}_init() ?*Handle { + const allocator = std.heap.c_allocator; - fn step(self: *BfInterpreter) void { - if (self.halted or self.pc >= self.program.len) { - self.halted = true; - return; - } - if (self.cycles >= self.max_cycles) { - self.halted = true; - return; - } - - self.cycles += 1; - const inst = self.program[self.pc]; - - switch (inst) { - '>' => self.pointer = (self.pointer + 1) % MEMORY_SIZE, - '<' => self.pointer = if (self.pointer == 0) MEMORY_SIZE - 1 else self.pointer - 1, - '+' => self.memory[self.pointer] +%= 1, - '-' => self.memory[self.pointer] -%= 1, - '.' => self.output_len += 1, - ',' => self.memory[self.pointer] = 0, // no input in verification - '[' => { - if (self.memory[self.pointer] == 0) { - self.pc = self.bracket_map[self.pc]; - } - }, - ']' => { - if (self.memory[self.pointer] != 0) { - self.pc = self.bracket_map[self.pc]; - } - }, - else => {}, - } - self.pc += 1; - } + const handle = allocator.create(Handle) catch { + setError("Failed to allocate handle"); + return null; + }; - fn run(self: *BfInterpreter) void { - while (!self.halted and self.pc < self.program.len) { - self.step(); - } - self.halted = true; - } + // Initialize handle + handle.* = .{ + .allocator = allocator, + .initialized = true, + }; - fn verifyCno(self: *BfInterpreter) CnoResult { - var initial_memory: [MEMORY_SIZE]u8 = undefined; - @memcpy(&initial_memory, &self.memory); - const initial_pointer = self.pointer; - - self.run(); - - const terminates = self.cycles < self.max_cycles; - const is_pure = self.output_len == 0; - const mem_preserved = std.mem.eql(u8, &self.memory, &initial_memory); - const ptr_preserved = self.pointer == initial_pointer; - const preserves_state = mem_preserved and ptr_preserved; - const is_reversible = preserves_state; - const is_cno = terminates and is_pure and preserves_state; - - return .{ - .is_cno = if (is_cno) 1 else 0, - .terminates = if (terminates) 1 else 0, - .preserves_state = if (preserves_state) 1 else 0, - .is_pure = if (is_pure) 1 else 0, - .is_reversible = if (is_reversible) 1 else 0, - }; - } + clearError(); + return handle; +} - fn reset(self: *BfInterpreter) void { - @memset(&self.memory, 0); - self.pointer = 0; - self.pc = 0; - self.output_len = 0; - self.halted = false; - self.cycles = 0; - } -}; +/// Free the library handle +export fn {{project}}_free(handle: ?*Handle) void { + const h = handle orelse return; + const allocator = h.allocator; -fn buildBracketMap(allocator: std.mem.Allocator, program: []const u8) ![]usize { - const map = try allocator.alloc(usize, program.len); - @memset(map, 0); - - var stack_buf: [1024]usize = undefined; - var stack_len: usize = 0; - - for (program, 0..) |ch, i| { - if (ch == '[') { - if (stack_len >= stack_buf.len) return error.NestingTooDeep; - stack_buf[stack_len] = i; - stack_len += 1; - } else if (ch == ']') { - if (stack_len > 0) { - stack_len -= 1; - const open = stack_buf[stack_len]; - map[open] = i; - map[i] = open; - } - } - } + // Clean up resources + h.initialized = false; - return map; + allocator.destroy(h); + clearError(); } //============================================================================== -// C ABI Exports (matches src/abi/Foreign.idr declarations) +// Core Operations //============================================================================== -/// Initialize the library. Returns opaque handle. -export fn absolute_zero_init() ?*anyopaque { - const allocator = std.heap.c_allocator; - _ = allocator; - clearError(); - // Library-level init (stateless for now) - return @ptrFromInt(@as(usize, 1)); // Sentinel non-null -} +/// Process data (example operation) +export fn {{project}}_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; -/// Free library resources. -export fn absolute_zero_free(_: ?*anyopaque) void { clearError(); + return .ok; } -/// Create a Brainfuck interpreter for CNO verification. -/// program_ptr: pointer to program bytes -/// program_len: length of program -/// max_cycles: cycle limit (0 = default 1M) -/// Returns opaque interpreter handle, or null on failure. -export fn az_bf_create( - program_ptr: ?[*]const u8, - program_len: u32, - max_cycles: u32, -) ?*anyopaque { - const prog = program_ptr orelse { - setError("Null program pointer"); +//============================================================================== +// String Operations +//============================================================================== + +/// Get a string result (example) +/// Caller must free the returned string +export fn {{project}}_get_string(handle: ?*Handle) ?[*:0]const u8 { + const h = handle orelse { + setError("Null handle"); return null; }; - const allocator = std.heap.c_allocator; - const cycles: usize = if (max_cycles == 0) DEFAULT_MAX_CYCLES else @intCast(max_cycles); - const program = prog[0..@intCast(program_len)]; + if (!h.initialized) { + setError("Handle not initialized"); + return null; + } - const interp = BfInterpreter.init(allocator, program, cycles) catch { - setError("Failed to create interpreter"); + // Example: allocate and return a string + const result = h.allocator.dupeZ(u8, "Example result") catch { + setError("Failed to allocate string"); return null; }; clearError(); - return @ptrCast(interp); + return result.ptr; } -/// Destroy a Brainfuck interpreter. -export fn az_bf_destroy(handle: ?*anyopaque) void { - const interp: *BfInterpreter = @ptrCast(@alignCast(handle orelse return)); - interp.deinit(); - clearError(); -} - -/// Run CNO verification on a Brainfuck program. -/// Returns CnoResult struct (matches Idris2 CNOVerificationResult). -export fn az_bf_verify_cno(handle: ?*anyopaque) CnoResult { - const interp: *BfInterpreter = @ptrCast(@alignCast(handle orelse { - setError("Null interpreter handle"); - return .{ .is_cno = 0, .terminates = 0, .preserves_state = 0, .is_pure = 0, .is_reversible = 0 }; - })); +/// Free a string allocated by the library +export fn {{project}}_free_string(str: ?[*:0]const u8) void { + const s = str orelse return; + const allocator = std.heap.c_allocator; - clearError(); - return interp.verifyCno(); + const slice = std.mem.span(s); + allocator.free(slice); } -/// Reset interpreter for re-verification. -export fn az_bf_reset(handle: ?*anyopaque) Result { - const interp: *BfInterpreter = @ptrCast(@alignCast(handle orelse { +//============================================================================== +// Array/Buffer Operations +//============================================================================== + +/// Process an array of data +export fn {{project}}_process_array( + handle: ?*Handle, + buffer: ?[*]const u8, + len: u32, +) Result { + const h = handle orelse { setError("Null handle"); return .null_pointer; - })); - interp.reset(); + }; + + 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 & Version +// Error Handling //============================================================================== -/// Get the last error message. Returns null if no error. -export fn absolute_zero_last_error() ?[*:0]const u8 { +/// Get the last error message +/// Returns null if no error +export fn {{project}}_last_error() ?[*:0]const u8 { const err = last_error orelse return null; + + // Return C string (static storage, no need to free) const allocator = std.heap.c_allocator; const c_str = allocator.dupeZ(u8, err) catch return null; return c_str.ptr; } -/// Get the library version string. -export fn absolute_zero_version() [*:0]const u8 { - return VERSION; +//============================================================================== +// Version Information +//============================================================================== + +/// Get the library version +export fn {{project}}_version() [*:0]const u8 { + return VERSION.ptr; } -/// Get build information. -export fn absolute_zero_build_info() [*:0]const u8 { - return BUILD_INFO; +/// Get build information +export fn {{project}}_build_info() [*:0]const u8 { + return BUILD_INFO.ptr; } //============================================================================== -// Tests +// Callback Support //============================================================================== -test "empty program is CNO" { - const allocator = std.testing.allocator; - const interp = try BfInterpreter.init(allocator, "", DEFAULT_MAX_CYCLES); - defer interp.deinit(); +/// Callback function type (C ABI) +pub const Callback = *const fn (u64, u32) callconv(.C) u32; - const result = interp.verifyCno(); - try std.testing.expectEqual(@as(u8, 1), result.is_cno); - try std.testing.expectEqual(@as(u8, 1), result.terminates); - try std.testing.expectEqual(@as(u8, 1), result.is_pure); - try std.testing.expectEqual(@as(u8, 1), result.preserves_state); -} +/// Register a callback +export fn {{project}}_register_callback( + handle: ?*Handle, + callback: ?Callback, +) Result { + const h = handle orelse { + setError("Null handle"); + return .null_pointer; + }; -test "balanced move is CNO" { - const allocator = std.testing.allocator; - const interp = try BfInterpreter.init(allocator, "><", DEFAULT_MAX_CYCLES); - defer interp.deinit(); + const cb = callback orelse { + setError("Null callback"); + return .null_pointer; + }; + + if (!h.initialized) { + setError("Handle not initialized"); + return .@"error"; + } - const result = interp.verifyCno(); - try std.testing.expectEqual(@as(u8, 1), result.is_cno); + // Store callback for later use + _ = cb; + + clearError(); + return .ok; } -test "balanced inc/dec is CNO" { - const allocator = std.testing.allocator; - const interp = try BfInterpreter.init(allocator, "+-", DEFAULT_MAX_CYCLES); - defer interp.deinit(); +//============================================================================== +// Utility Functions +//============================================================================== - const result = interp.verifyCno(); - try std.testing.expectEqual(@as(u8, 1), result.is_cno); +/// Check if handle is initialized +export fn {{project}}_is_initialized(handle: ?*Handle) u32 { + const h = handle orelse return 0; + return if (h.initialized) 1 else 0; } -test "unbalanced increment is NOT CNO" { - const allocator = std.testing.allocator; - const interp = try BfInterpreter.init(allocator, "+", DEFAULT_MAX_CYCLES); - defer interp.deinit(); +//============================================================================== +// Tests +//============================================================================== + +test "lifecycle" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); - const result = interp.verifyCno(); - try std.testing.expectEqual(@as(u8, 0), result.is_cno); - try std.testing.expectEqual(@as(u8, 0), result.preserves_state); + try std.testing.expect({{project}}_is_initialized(handle) == 1); } -test "output is NOT CNO" { - const allocator = std.testing.allocator; - const interp = try BfInterpreter.init(allocator, ".", DEFAULT_MAX_CYCLES); - defer interp.deinit(); +test "error handling" { + const result = {{project}}_process(null, 0); + try std.testing.expectEqual(Result.null_pointer, result); - const result = interp.verifyCno(); - try std.testing.expectEqual(@as(u8, 0), result.is_cno); - try std.testing.expectEqual(@as(u8, 0), result.is_pure); + const err = {{project}}_last_error(); + try std.testing.expect(err != null); } -test "CnoResult layout matches Idris2" { - // CNOVerificationResult in Types.idr has size 5 - try std.testing.expectEqual(@as(usize, 5), @sizeOf(CnoResult)); +test "version" { + const ver = {{project}}_version(); + const ver_str = std.mem.span(ver); + try std.testing.expectEqualStrings(VERSION, ver_str); } diff --git a/absolute-zero/ffi/zig/test/integration_test.zig b/absolute-zero/ffi/zig/test/integration_test.zig index 3deecbc..e5ba919 100644 --- a/absolute-zero/ffi/zig/test/integration_test.zig +++ b/absolute-zero/ffi/zig/test/integration_test.zig @@ -1,118 +1,182 @@ -// Absolute Zero FFI Integration Tests -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell +// {{PROJECT}} Integration Tests +// SPDX-License-Identifier: AGPL-3.0-or-later // -// These tests verify that the Zig FFI correctly implements the Idris2 ABI. -// They call through the C ABI exports and verify CNO verification results. +// These tests verify that the Zig FFI correctly implements the Idris2 ABI const std = @import("std"); const testing = std.testing; -// Import FFI functions via C ABI -extern fn absolute_zero_init() ?*anyopaque; -extern fn absolute_zero_free(?*anyopaque) void; -extern fn absolute_zero_version() [*:0]const u8; -extern fn absolute_zero_last_error() ?[*:0]const u8; - -const CnoResult = extern struct { - is_cno: u8, - terminates: u8, - preserves_state: u8, - is_pure: u8, - is_reversible: u8, -}; - -extern fn az_bf_create(?[*]const u8, u32, u32) ?*anyopaque; -extern fn az_bf_destroy(?*anyopaque) void; -extern fn az_bf_verify_cno(?*anyopaque) CnoResult; -extern fn az_bf_reset(?*anyopaque) c_int; +// Import FFI functions +extern fn {{project}}_init() ?*opaque {}; +extern fn {{project}}_free(?*opaque {}) void; +extern fn {{project}}_process(?*opaque {}, u32) c_int; +extern fn {{project}}_get_string(?*opaque {}) ?[*:0]const u8; +extern fn {{project}}_free_string(?[*:0]const u8) void; +extern fn {{project}}_last_error() ?[*:0]const u8; +extern fn {{project}}_version() [*:0]const u8; +extern fn {{project}}_is_initialized(?*opaque {}) u32; //============================================================================== // Lifecycle Tests //============================================================================== -test "library init and free" { - const handle = absolute_zero_init(); +test "create and destroy handle" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); + try testing.expect(handle != null); - absolute_zero_free(handle); } -test "version string" { - const ver = absolute_zero_version(); - const ver_str = std.mem.span(ver); - try testing.expectEqualStrings("1.0.0", ver_str); +test "handle is initialized" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); + + const initialized = {{project}}_is_initialized(handle); + try testing.expectEqual(@as(u32, 1), initialized); +} + +test "null handle is not initialized" { + const initialized = {{project}}_is_initialized(null); + try testing.expectEqual(@as(u32, 0), initialized); +} + +//============================================================================== +// Operation Tests +//============================================================================== + +test "process with valid handle" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); + + const result = {{project}}_process(handle, 42); + try testing.expectEqual(@as(c_int, 0), result); // 0 = ok +} + +test "process with null handle returns error" { + const result = {{project}}_process(null, 42); + try testing.expectEqual(@as(c_int, 4), result); // 4 = null_pointer +} + +//============================================================================== +// String Tests +//============================================================================== + +test "get string result" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); + + const str = {{project}}_get_string(handle); + defer if (str) |s| {{project}}_free_string(s); + + try testing.expect(str != null); +} + +test "get string with null handle" { + const str = {{project}}_get_string(null); + try testing.expect(str == null); } //============================================================================== -// Brainfuck CNO Verification via C ABI +// Error Handling Tests //============================================================================== -test "empty program is CNO via FFI" { - const program = ""; - const interp = az_bf_create(program.ptr, program.len, 0); - try testing.expect(interp != null); - defer az_bf_destroy(interp); - - const result = az_bf_verify_cno(interp); - try testing.expectEqual(@as(u8, 1), result.is_cno); - try testing.expectEqual(@as(u8, 1), result.terminates); - try testing.expectEqual(@as(u8, 1), result.is_pure); - try testing.expectEqual(@as(u8, 1), result.preserves_state); +test "last error after null handle operation" { + _ = {{project}}_process(null, 0); + + const err = {{project}}_last_error(); + try testing.expect(err != null); + + if (err) |e| { + const err_str = std.mem.span(e); + try testing.expect(err_str.len > 0); + } } -test "balanced move is CNO via FFI" { - const program = "><"; - const interp = az_bf_create(program.ptr, program.len, 0); - defer az_bf_destroy(interp); +test "no error after successful operation" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); + + _ = {{project}}_process(handle, 0); - const result = az_bf_verify_cno(interp); - try testing.expectEqual(@as(u8, 1), result.is_cno); + // Error should be cleared after successful operation + // (This depends on implementation) } -test "unbalanced increment is NOT CNO via FFI" { - const program = "+"; - const interp = az_bf_create(program.ptr, program.len, 0); - defer az_bf_destroy(interp); +//============================================================================== +// Version Tests +//============================================================================== + +test "version string is not empty" { + const ver = {{project}}_version(); + const ver_str = std.mem.span(ver); - const result = az_bf_verify_cno(interp); - try testing.expectEqual(@as(u8, 0), result.is_cno); - try testing.expectEqual(@as(u8, 0), result.preserves_state); + try testing.expect(ver_str.len > 0); } -test "output is NOT pure via FFI" { - const program = "."; - const interp = az_bf_create(program.ptr, program.len, 0); - defer az_bf_destroy(interp); +test "version string is semantic version format" { + const ver = {{project}}_version(); + const ver_str = std.mem.span(ver); - const result = az_bf_verify_cno(interp); - try testing.expectEqual(@as(u8, 0), result.is_cno); - try testing.expectEqual(@as(u8, 0), result.is_pure); + // Should be in format X.Y.Z + try testing.expect(std.mem.count(u8, ver_str, ".") >= 1); } -test "reset allows re-verification" { - const program = "+-"; - const interp = az_bf_create(program.ptr, program.len, 0); - defer az_bf_destroy(interp); +//============================================================================== +// Memory Safety Tests +//============================================================================== - const r1 = az_bf_verify_cno(interp); - try testing.expectEqual(@as(u8, 1), r1.is_cno); +test "multiple handles are independent" { + const h1 = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(h1); + + const h2 = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(h2); + + try testing.expect(h1 != h2); + + // Operations on h1 should not affect h2 + _ = {{project}}_process(h1, 1); + _ = {{project}}_process(h2, 2); +} - const reset_result = az_bf_reset(interp); - try testing.expectEqual(@as(c_int, 0), reset_result); // ok = 0 +test "double free is safe" { + const handle = {{project}}_init() orelse return error.InitFailed; - const r2 = az_bf_verify_cno(interp); - try testing.expectEqual(@as(u8, 1), r2.is_cno); + {{project}}_free(handle); + {{project}}_free(handle); // Should not crash } -test "null handle returns zero result" { - const result = az_bf_verify_cno(null); - try testing.expectEqual(@as(u8, 0), result.is_cno); +test "free null is safe" { + {{project}}_free(null); // Should not crash } //============================================================================== -// CnoResult ABI Layout +// Thread Safety Tests (if applicable) //============================================================================== -test "CnoResult size matches Idris2 CNOVerificationResult" { - try testing.expectEqual(@as(usize, 5), @sizeOf(CnoResult)); +test "concurrent operations" { + const handle = {{project}}_init() orelse return error.InitFailed; + defer {{project}}_free(handle); + + const ThreadContext = struct { + h: *opaque {}, + id: u32, + }; + + const thread_fn = struct { + fn run(ctx: ThreadContext) void { + _ = {{project}}_process(ctx.h, ctx.id); + } + }.run; + + var threads: [4]std.Thread = undefined; + for (&threads, 0..) |*thread, i| { + thread.* = try std.Thread.spawn(.{}, thread_fn, .{ + ThreadContext{ .h = handle, .id = @intCast(i) }, + }); + } + + for (threads) |thread| { + thread.join(); + } } diff --git a/absolute-zero/fuzz/Cargo.lock b/absolute-zero/fuzz/Cargo.lock new file mode 100644 index 0000000..432f2fe --- /dev/null +++ b/absolute-zero/fuzz/Cargo.lock @@ -0,0 +1,155 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "absolute_zero-fuzz" +version = "0.0.0" +dependencies = [ + "arbitrary", + "libfuzzer-sys", +] + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "cc" +version = "1.2.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f12a681b7dd8ce12bff52488013ba614b869148d54dd79836ab85aafdd53f08d" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "wasip2" +version = "1.0.3+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" diff --git a/absolute-zero/fuzz/Cargo.toml b/absolute-zero/fuzz/Cargo.toml index 4816899..6486cc5 100644 --- a/absolute-zero/fuzz/Cargo.toml +++ b/absolute-zero/fuzz/Cargo.toml @@ -1,8 +1,8 @@ -# SPDX-License-Identifier: MPL-2.0-or-later +# SPDX-License-Identifier: MPL-2.0 [package] name = "absolute_zero-fuzz" version = "0.0.0" -authors = ["Jonathan D.A. Jewell "] +authors = ["hyperpolymath"] publish = false edition = "2021" @@ -13,9 +13,6 @@ cargo-fuzz = true libfuzzer-sys = "0.4" arbitrary = { version = "1", features = ["derive"] } -[dependencies.absolute_zero] -path = ".." - [[bin]] name = "fuzz_input" path = "fuzz_targets/fuzz_input.rs" diff --git a/absolute-zero/fuzz/fuzz_targets/fuzz_input.rs b/absolute-zero/fuzz/fuzz_targets/fuzz_input.rs index f824c82..aefae70 100644 --- a/absolute-zero/fuzz/fuzz_targets/fuzz_input.rs +++ b/absolute-zero/fuzz/fuzz_targets/fuzz_input.rs @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: PMPL-1.0 +// SPDX-License-Identifier: MPL-2.0 //! Generic fuzz target for arbitrary input processing #![no_main] diff --git a/absolute-zero/interpreters/rescript/malbolgeInterpreter.res b/absolute-zero/interpreters/rescript/malbolgeInterpreter.res deleted file mode 100644 index c5a9f54..0000000 --- a/absolute-zero/interpreters/rescript/malbolgeInterpreter.res +++ /dev/null @@ -1,256 +0,0 @@ -// Malbolge Interpreter in ReScript -// -// Malbolge is one of the hardest programming languages to use. -// This interpreter implements the Malbolge specification for CNO verification. -// -// Author: Jonathan D. A. Jewell -// Project: Absolute Zero -// License: AGPL-3.0 / Palimpsest 0.5 - -type ternary = int // Base-3 numbers - -// Malbolge constants -let memorySize = 59049 // 3^10 -let maxCycles = 1000000 - -// Malbolge operations -type operation = - | Jmp - | Out - | In - | Rot - | Mov - | Crz // Crazy operation - | Nop - | Hlt - -// Malbolge state -type state = { - memory: array, - a: int, // Accumulator - c: int, // Code pointer - d: int, // Data pointer - input: list, - output: list, - halted: bool, - cycles: int, -} - -// Create initial state -let makeState = (~program: string): state => { - let memory = Array.make(memorySize, 0) - - // Load program into memory - String.toArray(program)->Array.forEachWithIndex((i, char) => { - memory[i] = Char.code(char) - }) - - { - memory: memory, - a: 0, - c: 0, - d: 0, - input: list{}, - output: list{}, - halted: false, - cycles: 0, - } -} - -// Crazy operation lookup table (simplified) -// In real Malbolge, this is a complex ternary operation -let crazyOp = (a: int, b: int): int => { - // Simplified implementation - // Real Malbolge uses: [i]'th element of crz table where i = (a - b) mod 3^10 - mod(a + b, 3) -} - -// Rotation in ternary -let rotateRight = (n: int): int => { - // Simplified: rotate 10-trit ternary number right - let lower = mod(n, 3) - let upper = n / 3 - lower * 19683 + upper // 19683 = 3^9 -} - -// Decode operation at position c -let decodeOp = (mem: array, c: int): option => { - let opCode = mod(mem[c] - c, 94) - - switch opCode { - | 4 => Some(Jmp) - | 5 => Some(Out) - | 23 => Some(In) - | 39 => Some(Rot) - | 40 => Some(Mov) - | 62 => Some(Crz) - | 68 => Some(Nop) - | 81 => Some(Hlt) - | _ => None // Invalid instruction - } -} - -// Encrypt (modify) instruction after execution -let encrypt = (mem: array, c: int): unit => { - // Malbolge self-modifies by encrypting executed instructions - // Simplified encryption: rotate the value - mem[c] = mod(mem[c] + 1, 256) -} - -// Execute single step -let step = (state: state): state => { - if state.halted || state.cycles >= maxCycles { - {...state, halted: true} - } else { - let {memory, a, c, d, input, output, cycles} = state - - switch decodeOp(memory, c) { - | None => {...state, halted: true} // Invalid instruction - - | Some(Hlt) => {...state, halted: true} - - | Some(Nop) => { - encrypt(memory, c) - {...state, c: mod(c + 1, memorySize), cycles: cycles + 1} - } - - | Some(Jmp) => { - encrypt(memory, c) - {...state, c: memory[d], cycles: cycles + 1} - } - - | Some(Out) => { - encrypt(memory, c) - let char = mod(a, 256) - { - ...state, - c: mod(c + 1, memorySize), - output: list{char, ...output}, - cycles: cycles + 1, - } - } - - | Some(In) => { - encrypt(memory, c) - switch input { - | list{} => {...state, a: 0, c: mod(c + 1, memorySize), cycles: cycles + 1} - | list{val, ...rest} => { - {...state, a: val, input: rest, c: mod(c + 1, memorySize), cycles: cycles + 1} - } - } - } - - | Some(Rot) => { - encrypt(memory, c) - { - ...state, - a: rotateRight(a), - c: mod(c + 1, memorySize), - d: mod(d + 1, memorySize), - cycles: cycles + 1, - } - } - - | Some(Mov) => { - encrypt(memory, c) - { - ...state, - a: memory[d], - c: mod(c + 1, memorySize), - d: mod(d + 1, memorySize), - cycles: cycles + 1, - } - } - - | Some(Crz) => { - encrypt(memory, c) - let result = crazyOp(a, memory[d]) - memory[d] = result - { - ...state, - a: result, - c: mod(c + 1, memorySize), - d: mod(d + 1, memorySize), - cycles: cycles + 1, - } - } - } - } -} - -// Run program until halt or max cycles -let rec run = (state: state): state => { - if state.halted || state.cycles >= maxCycles { - state - } else { - run(step(state)) - } -} - -// Execute program and return output -let execute = (program: string): string => { - let initialState = makeState(~program) - let finalState = run(initialState) - - // Convert output list to string - finalState.output - ->List.reverse - ->List.map(Char.chr) - ->List.toArray - ->String.fromCharArray -} - -// Check if program is a CNO -let isCNO = (program: string): bool => { - let initialState = makeState(~program) - let finalState = run(initialState) - - // A program is a CNO if: - // 1. It terminates (not at max cycles) - // 2. No output produced - // 3. Memory unchanged (difficult to check due to encryption) - - finalState.cycles < maxCycles && - List.length(finalState.output) == 0 -} - -// CNO Examples - -// Empty program - the simplest CNO -let emptyProgram = "" - -// Single Nop (if we could encode it properly) -// Note: Actual Malbolge encoding is complex -let nopProgram = " " // Simplified - -// Test function -let testCNO = (program: string, name: string): unit => { - let result = if isCNO(program) { - "is a CNO ✓" - } else { - "is NOT a CNO ✗" - } - - Console.log(`${name}: ${result}`) -} - -// Run tests -testCNO(emptyProgram, "Empty program") -testCNO(nopProgram, "Nop program") - -// Export for external use -type exports = { - execute: string => string, - isCNO: string => bool, - makeState: (~program: string) => state, - run: state => state, - step: state => state, -} - -let exports: exports = { - execute: execute, - isCNO: isCNO, - makeState: makeState, - run: run, - step: step, -} diff --git a/absolute-zero/license/PMPL-1.0.txt b/absolute-zero/license/PMPL-1.0.txt index 13d072a..711e372 100644 --- a/absolute-zero/license/PMPL-1.0.txt +++ b/absolute-zero/license/PMPL-1.0.txt @@ -1,4 +1,4 @@ -SPDX-License-Identifier: MPL-2.0-or-later +SPDX-License-Identifier: MPL-2.0 SPDX-FileCopyrightText: 2025 Palimpsest Stewardship Council ================================================================================ diff --git a/absolute-zero/malbolge_test.mb b/absolute-zero/malbolge_test.mb deleted file mode 100644 index 418a90f..0000000 --- a/absolute-zero/malbolge_test.mb +++ /dev/null @@ -1 +0,0 @@ -(=<`#9]~6ZY32Vx/4Rs+0No-&Jk)"Fh}|Bcy?`=_wz]Kw%oE4UUS0/@-ejc(:'8dc \ No newline at end of file diff --git a/absolute-zero/proofs/agda/CNO.agda b/absolute-zero/proofs/agda/CNO.agda index 2e79406..5b52d65 100644 --- a/absolute-zero/proofs/agda/CNO.agda +++ b/absolute-zero/proofs/agda/CNO.agda @@ -1,3 +1,5 @@ +{-# OPTIONS --safe --without-K #-} + {- Certified Null Operations: Agda Formalization This file provides an Agda formalization of CNO theory. @@ -10,20 +12,15 @@ module CNO where -open import Data.Nat using (ℕ; zero; suc; _+_; _*_; nonZero) -open import Data.Nat.Base using (NonZero) -open import Data.Nat.DivMod using (_%_) +open import Data.Nat using (ℕ; zero; suc; _+_; _*_) open import Data.List using (List; []; _∷_; _++_; length) open import Data.Product using (_×_; _,_; proj₁; proj₂; Σ; ∃) -open import Relation.Binary.PropositionalEquality using (_≡_; refl; sym; trans; cong) +open import Relation.Binary.PropositionalEquality + using (_≡_; refl; sym; trans; cong; subst) open import Data.Bool using (Bool; true; false; if_then_else_) open import Data.Maybe using (Maybe; just; nothing) open import Function using (_∘_; id) -instance - nonZero3 : NonZero 3 - nonZero3 = nonZero - ---------------------------------------------------------------------------- -- Memory Model ---------------------------------------------------------------------------- @@ -299,23 +296,36 @@ state-eq-trans (m₁ , r₁ , i₁ , p₁) (m₂ , r₂ , i₂ , p₂) = trans i₁ i₂ , trans p₁ p₂ -state-eq-cong-left : ∀ {s₁ s₂ s₃} → s₁ ≡ s₂ → state-eq s₂ s₃ → state-eq s₁ s₃ -state-eq-cong-left refl eq = eq - --- Composition of CNOs is a CNO +-- Pointwise-transitive purity: agree on I/O and on memory. +-- Uses `proj₁`/`proj₂` rather than pattern-matching on `_,_` +-- because `pure` is a definitional `_×_` and the unifier sometimes +-- declines to unfold it in pattern positions. +pure-trans : ∀ {s₁ s₂ s₃} → pure s₁ s₂ → pure s₂ s₃ → pure s₁ s₃ +pure-trans p₁₂ p₂₃ = + trans (proj₁ p₁₂) (proj₁ p₂₃) , + (λ addr → trans (proj₂ p₁₂ addr) (proj₂ p₂₃ addr)) + +-- Composition of CNOs is a CNO. The two non-trivial fields +-- (`cno-identity`, `cno-pure`) chain the per-program lemmas +-- through `eval p₁ s` and transport along `eval-seq-comp` to the +-- composite evaluation. cno-composition : ∀ {p₁ p₂} → IsCNO p₁ → IsCNO p₂ → IsCNO (seq-comp p₁ p₂) cno-composition {p₁} {p₂} cno₁ cno₂ = record { cno-terminates = λ s → terminates-always (seq-comp p₁ p₂) s ; cno-identity = λ s → let eq₁ = IsCNO.cno-identity cno₁ s eq₂ = IsCNO.cno-identity cno₂ (eval p₁ s) - in state-eq-cong-left (eval-seq-comp p₁ p₂ s) (state-eq-trans eq₂ eq₁) + in subst (λ x → state-eq x s) (sym (eval-seq-comp p₁ p₂ s)) + (state-eq-trans eq₂ eq₁) ; cno-pure = λ s → - let eq₁ = IsCNO.cno-identity cno₁ s - eq₂ = IsCNO.cno-identity cno₂ (eval p₁ s) - eq = state-eq-cong-left (eval-seq-comp p₁ p₂ s) (state-eq-trans eq₂ eq₁) - (m , _ , i , _) = eq - in sym i , (λ addr → sym (m addr)) + let pu₁ : pure s (eval p₁ s) + pu₁ = IsCNO.cno-pure cno₁ s + pu₂ : pure (eval p₁ s) (eval p₂ (eval p₁ s)) + pu₂ = IsCNO.cno-pure cno₂ (eval p₁ s) + composed : pure s (eval p₂ (eval p₁ s)) + composed = pure-trans {s₁ = s} {s₂ = eval p₁ s} + {s₃ = eval p₂ (eval p₁ s)} pu₁ pu₂ + in subst (pure s) (sym (eval-seq-comp p₁ p₂ s)) composed ; cno-reversible = λ s → refl } @@ -323,13 +333,23 @@ cno-composition {p₁} {p₂} cno₁ cno₂ = record -- Malbolge-Specific ---------------------------------------------------------------------------- --- Ternary operations +-- Ternary operations: addition mod 3 (Malbolge-flavoured). +-- Local `mod3` is structural-recursive on its argument, so it +-- terminates and stays inside `--safe --without-K` without pulling +-- in `Data.Nat.DivMod._%_` (whose `NonZero` instance lookup adds +-- noise that this helper does not need). +mod3 : ℕ → ℕ +mod3 zero = zero +mod3 (suc zero) = suc zero +mod3 (suc (suc zero)) = suc (suc zero) +mod3 (suc (suc (suc n))) = mod3 n + ternary-add : ℕ → ℕ → ℕ -ternary-add a b = (a + b) % 3 +ternary-add a b = mod3 (a + b) --- Crazy operation +-- Crazy operation (Malbolge crazy op surface; placeholder semantics) crazy-op : ℕ → ℕ → ℕ -crazy-op a b = (a + b) % 3 +crazy-op a b = mod3 (a + b) ---------------------------------------------------------------------------- -- Absolute Zero diff --git a/absolute-zero/proofs/coq/category/CNOCategory.v b/absolute-zero/proofs/coq/category/CNOCategory.v index a7b2068..d3d569e 100644 --- a/absolute-zero/proofs/coq/category/CNOCategory.v +++ b/absolute-zero/proofs/coq/category/CNOCategory.v @@ -21,7 +21,7 @@ Require Import Coq.Logic.ProofIrrelevance. Require Import Coq.Program.Equality. Require Import Coq.Lists.List. Import ListNotations. -Require Import CNO. +Require Import CNO.CNO. (** ** Category Definition *) @@ -99,18 +99,19 @@ Proof. Qed. (** Programs form a category *) -Instance ProgramCategory : Category := { - Obj := ProgramState; - Hom := ProgramMorphism; - compose := @compose_morphisms; - id := id_morphism; -}. +Instance ProgramCategory : Category. Proof. + refine {| + Obj := ProgramState; + Hom := ProgramMorphism; + compose := @compose_morphisms; + id := id_morphism + |}. - (* compose_assoc: (f ++ g) ++ h = f ++ (g ++ h) *) intros A B C D h g f. apply morph_eq_ext. destruct f as [pf Hf], g as [pg Hg], h as [ph Hh]. - simpl. apply app_assoc. + simpl. symmetry. apply app_assoc. - (* compose_id_left: p ++ [] = p *) intros A B f. apply morph_eq_ext. @@ -157,20 +158,22 @@ Proof. - (* <- direction: Construct full CNO from termination + identity *) destruct H as [H_term H_id]. unfold is_CNO. - repeat split. + split. + (* Termination *) exact H_term. - + (* Identity *) - exact H_id. - + (* Purity: follows from state equality *) - intros s s' H_eval. - assert (H_eq : s =st= s') by (apply H_id; assumption). - destruct H_eq as [H_mem [H_reg [H_io H_pc]]]. - unfold pure, no_io, no_memory_alloc. - split; assumption. - + (* Thermodynamic reversibility: trivially true *) - unfold thermodynamically_reversible, energy_dissipated. - intros. reflexivity. + + split. + * (* Identity *) + exact H_id. + * split. + -- (* Purity: follows from state equality *) + intros s s' H_eval. + assert (H_eq : s =st= s') by (apply H_id; assumption). + destruct H_eq as [H_mem [H_reg H_io]]. + unfold pure, no_io, no_memory_alloc. + split; assumption. + -- (* Thermodynamic reversibility: trivially true *) + unfold thermodynamically_reversible, energy_dissipated. + intros. reflexivity. Qed. (** ** Universal Property *) @@ -200,12 +203,13 @@ Qed. (** A functor maps between categories, preserving structure *) Class Functor (C D : Category) := { - fobj : Obj -> Obj; - fmap : forall {A B : Obj}, Hom A B -> Hom (fobj A) (fobj B); + fobj : @Obj C -> @Obj D; + fmap : forall {A B : @Obj C}, @Hom C A B -> @Hom D (fobj A) (fobj B); - fmap_id : forall {A : Obj}, fmap (@id C A) = @id D (fobj A); - fmap_compose : forall {A B C : Obj} (g : Hom B C) (f : Hom A B), - fmap (g ∘ f) = fmap g ∘ fmap f; + fmap_id : forall {A : @Obj C}, fmap (@id C A) = @id D (fobj A); + fmap_compose : forall {A B E : @Obj C} (g : @Hom C B E) (f : @Hom C A B), + fmap (@compose C A B E g f) = + @compose D (fobj A) (fobj B) (fobj E) (fmap g) (fmap f); }. (** CNOs are preserved by functors *) @@ -228,17 +232,19 @@ Qed. (** A natural transformation between functors *) Class NaturalTransformation (C D : Category) (F G : Functor C D) := { - component : forall (A : @Obj C), @Hom D (fobj A) (fobj A); + component : forall (A : @Obj C), @Hom D (@fobj C D F A) (@fobj C D G A); naturality : forall (A B : @Obj C) (f : @Hom C A B), - component B ∘ fmap f = fmap f ∘ component A; + @compose D _ _ _ (component B) (@fmap C D F A B f) = + @compose D _ _ _ (@fmap C D G A B f) (component A); }. (** Identity natural transformation *) Definition id_nat_trans (C D : Category) (F : Functor C D) : NaturalTransformation C D F F. Proof. - apply Build_NaturalTransformation with (component := fun A => id). + apply Build_NaturalTransformation with + (component := fun A => @id D (@fobj C D F A)). - intros A B f. rewrite compose_id_left. rewrite compose_id_right. @@ -247,11 +253,11 @@ Defined. (** CNOs as natural transformations *) Theorem cno_as_nat_trans : - forall (C : Category) (F : Functor C C), - (forall A : @Obj C, @id C A = component A) -> + forall (C : Category) (F : Functor C C) (η : NaturalTransformation C C F F), + (forall A : @Obj C, @id C (@fobj C C F A) = @component C C F F η A) -> F = F. (* Identity functor *) Proof. - intros C F H. + intros C F η H. (* CNOs correspond to identity natural transformations *) reflexivity. Qed. @@ -265,7 +271,7 @@ Definition CNO_equivalent (C D : Category) : Prop := exists (F : Functor C D) (G : Functor D C), forall (s : @Obj C) (m : @Hom C s s), is_CNO_categorical m <-> - is_CNO_categorical (fmap (fmap m)). + is_CNO_categorical (@fmap D C G _ _ (@fmap C D F _ _ m)). (** Main Universal Theorem: CNO property is model-independent *) Theorem cno_model_independent : @@ -273,11 +279,12 @@ Theorem cno_model_independent : CNO_equivalent C D -> forall (s : @Obj C) (m : @Hom C s s), is_CNO_categorical m -> - exists (m' : @Hom D (fobj s) (fobj s)), + exists (s' : @Obj D) (m' : @Hom D s' s'), is_CNO_categorical m'. Proof. intros C D [F [G H_equiv]] s m H_cno. - exists (fmap m). + exists (@fobj C D F s). + exists (@fmap C D F _ _ m). apply functor_preserves_cno. assumption. Qed. @@ -332,10 +339,10 @@ Proof. apply compose_id_left. - (* Right identity for all morphisms implies CNO *) (* Take f = id, then m ∘ id = id *) + unfold is_CNO_categorical. specialize (H A id). rewrite compose_id_right in H. - symmetry. - assumption. + exact H. Qed. (** ** Summary *) diff --git a/absolute-zero/proofs/coq/common/CNO.v b/absolute-zero/proofs/coq/common/CNO.v index d4905a0..312512f 100644 --- a/absolute-zero/proofs/coq/common/CNO.v +++ b/absolute-zero/proofs/coq/common/CNO.v @@ -5,7 +5,7 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import Coq.Init.Nat. @@ -61,10 +61,14 @@ Record ProgramState : Type := mkState { (** State equality *) Definition state_eq (s1 s2 : ProgramState) : Prop := + (* NOTE (2026-05-18): state_pc is deliberately EXCLUDED. The program + counter is control-flow bookkeeping, not an observable side effect; + `step` advances it for every instruction, so requiring PC-equality + made `nop_is_cno` (and every non-empty CNO claim) FALSE. Observable + state = memory + registers + I/O. *) s1.(state_memory) =mem= s2.(state_memory) /\ s1.(state_registers) = s2.(state_registers) /\ - s1.(state_io) = s2.(state_io) /\ - s1.(state_pc) = s2.(state_pc). + s1.(state_io) = s2.(state_io). Notation "s1 '=st=' s2" := (state_eq s1 s2) (at level 70). @@ -268,27 +272,28 @@ Proof. + (* p1 = i :: p1' *) simpl in H. inversion H; subst. - apply IH in H3. - destruct H3 as [sm [H3a H3b]]. + (* Grab the recursive `eval (p1' ++ p2)` premise by shape, not by the + inversion-autogenerated name (which is Coq-version dependent — the + old `H3` broke under Coq 8.20). *) + match goal with + | [ Hrec : eval (p1' ++ p2) _ _ |- _ ] => + apply IH in Hrec; destruct Hrec as [sm [H3a H3b]] + end. exists sm. split; try assumption. eapply eval_step; eassumption. - - (* <- direction *) + - (* <- direction: induct on the derivation `eval p1 s sm` (robust; no + reliance on inversion-autogenerated hypothesis names, which broke + under Coq 8.20). *) intros [sm [H1 H2]]. - generalize dependent s'. - generalize dependent sm. - generalize dependent s. - induction p1 as [| i p1' IH]; intros s sm s' H1 H2. - + (* p1 = [] *) - simpl. - inversion H1; subst. - assumption. - + (* p1 = i :: p1' *) - simpl. - inversion H1; subst. - eapply eval_step. - * eassumption. - * apply IH; eassumption. + revert s' H2. + induction H1 as [ s0 | i is s1 s2 s3 Hstep Hev IH ]; intros s' H2. + + (* eval_empty: p1 = [], s0 = sm *) + simpl. exact H2. + + (* eval_step: eval (i :: is) s1 s3 *) + simpl. eapply eval_step. + * exact Hstep. + * apply IH. exact H2. Qed. (** State equality is reflexive *) @@ -297,16 +302,19 @@ Proof. intros s. unfold state_eq. repeat split; try reflexivity. - unfold mem_eq. reflexivity. + (* Coq 8.20: `reflexivity` already discharges the mem_eq goal (function + equality), so the old explicit `unfold mem_eq. reflexivity.` now raises + "No such goal". Make the finisher no-op-safe across Coq versions. *) + all: try (unfold mem_eq; reflexivity). Qed. (** State equality is transitive *) Lemma state_eq_trans : forall s1 s2 s3, s1 =st= s2 -> s2 =st= s3 -> s1 =st= s3. Proof. - intros s1 s2 s3 [Hm1 [Hr1 [Hi1 Hp1]]] [Hm2 [Hr2 [Hi2 Hp2]]]. - unfold state_eq. - repeat split. + intros s1 s2 s3 [Hm1 [Hr1 Hi1]] [Hm2 [Hr2 Hi2]]. + unfold state_eq in *. + split; [ | split ]. - (* Memory *) unfold mem_eq in *. intros addr. @@ -315,8 +323,6 @@ Proof. transitivity (s2.(state_registers)); auto. - (* I/O *) transitivity (s2.(state_io)); auto. - - (* PC *) - transitivity (s2.(state_pc)); auto. Qed. (** Purity is transitive *) @@ -342,30 +348,29 @@ Proof. unfold is_CNO in *. destruct H1 as [T1 [I1 [P1 R1]]]. destruct H2 as [T2 [I2 [P2 R2]]]. - repeat split. + (* Robust: explicit nested split (not `repeat split`, which mis-structured + the 4-way is_CNO conjunction under Coq 8.20), seq_comp unfolded up front, + and fresh intro names (`s0`) that cannot clash with earlier hypotheses. *) + unfold seq_comp in *. + split; [ | split; [ | split ] ]. - (* Termination *) - intros s. + intros s0. unfold terminates in *. - destruct (T1 s) as [s1 E1]. + destruct (T1 s0) as [s1 E1]. destruct (T2 s1) as [s2 E2]. exists s2. - unfold seq_comp. apply eval_app. exists s1. split; assumption. - (* Identity *) - intros s s' Heval. - unfold seq_comp in Heval. + intros s0 s' Heval. apply eval_app in Heval. destruct Heval as [sm [E1 E2]]. - (* p1 maps s to itself, so sm = s *) - (* p2 maps sm to itself, so s' = sm = s *) apply I1 in E1. apply I2 in E2. eapply state_eq_trans; eassumption. - (* Purity *) - intros s s' Heval. - unfold seq_comp in Heval. + intros s0 s' Heval. apply eval_app in Heval. destruct Heval as [sm [E1 E2]]. apply P1 in E1. @@ -383,23 +388,18 @@ Qed. Theorem empty_is_cno : is_CNO []. Proof. unfold is_CNO. - repeat split. + split; [ | split; [ | split ] ]. - (* Termination *) - intros s. - exists s. - constructor. - - (* Identity *) - intros s s' Heval. + intros s0. exists s0. constructor. + - (* Identity: eval [] s0 s' forces s' = s0, so reuse state_eq_refl *) + intros s0 s' Heval. inversion Heval; subst. - unfold state_eq. - repeat split; try reflexivity. - unfold mem_eq. reflexivity. + apply state_eq_refl. - (* Purity *) - intros s s' Heval. + intros s0 s' Heval. inversion Heval; subst. - unfold pure, no_io, no_memory_alloc. - split; try reflexivity. - unfold mem_eq. reflexivity. + unfold pure, no_io, no_memory_alloc, mem_eq. + split; [ reflexivity | intros addr; reflexivity ]. - (* Thermodynamic reversibility *) unfold thermodynamically_reversible. intros s1 s2 Heval. @@ -412,27 +412,30 @@ Qed. Theorem nop_is_cno : is_CNO [Nop]. Proof. unfold is_CNO. - repeat split. + (* Robust: explicit nested split, fresh names, and inversion hypotheses + grabbed by shape (match goal) so Coq-version autonaming can't break it. + With PC excluded from state_eq, [Nop] is genuinely a CNO. *) + split; [ | split; [ | split ] ]. - (* Termination *) - intros s. - exists (mkState s.(state_memory) s.(state_registers) s.(state_io) (S s.(state_pc))). - apply eval_step with (s2 := mkState s.(state_memory) s.(state_registers) s.(state_io) (S s.(state_pc))). - + constructor. - + constructor. - - (* Identity - modulo PC increment *) - intros s s' Heval. + intros s0. + eexists. + eapply eval_step. + + apply step_nop. + + apply eval_empty. + - (* Identity *) + intros s0 s' Heval. inversion Heval; subst. - inversion H; subst. - inversion H0; subst. - unfold state_eq. - repeat split; try reflexivity. - unfold mem_eq. reflexivity. + match goal with H : step _ Nop _ |- _ => inversion H; subst end. + match goal with H : eval [] _ _ |- _ => inversion H; subst end. + unfold state_eq, mem_eq. + split; [ intros addr; reflexivity | split; reflexivity ]. - (* Purity *) - intros s s' Heval. + intros s0 s' Heval. inversion Heval; subst. - inversion H; subst. - unfold pure, no_io, no_memory_alloc. - split; reflexivity. + match goal with H : step _ Nop _ |- _ => inversion H; subst end. + match goal with H : eval [] _ _ |- _ => inversion H; subst end. + unfold pure, no_io, no_memory_alloc, mem_eq. + split; [ reflexivity | intros addr; reflexivity ]. - (* Thermodynamic reversibility *) unfold thermodynamically_reversible. intros s1 s2 Heval. @@ -441,15 +444,57 @@ Qed. (** ** CNO Equivalence *) -(** Evaluation is deterministic *) -Axiom eval_deterministic : - forall p s s1 s2, - eval p s s1 -> eval p s s2 -> s1 =st= s2. +(** Single-step evaluation is fully deterministic: same start state and + instruction force a syntactically identical result state. The result + of `step` is always `mkState …` whose components are functions of the + instruction and the start state (`state_memory`, `get_reg`, + `set_reg`, `mem_update`); the auxiliary witnesses in [step_load] / + [step_store] / [step_add] are pinned by their hypotheses. *) +Lemma step_deterministic_strong : forall s i s1 s2, + step s i s1 -> step s i s2 -> s1 = s2. +Proof. + intros s i s1 s2 H1 H2. + destruct i; inversion H1; subst; inversion H2; subst; try reflexivity. + - (* Store: two get_reg results agree by functional dependence. *) + match goal with + | [ Ha : get_reg _ _ = Some ?v1, + Hb : get_reg _ _ = Some ?v2 |- _ ] => + rewrite Ha in Hb; injection Hb as -> + end. + reflexivity. + - (* Add: two pairs of get_reg results. *) + repeat match goal with + | [ Ha : get_reg ?regs ?r = Some ?v1, + Hb : get_reg ?regs ?r = Some ?v2 |- _ ] => + rewrite Ha in Hb; injection Hb as ->; clear Ha + end. + reflexivity. +Qed. -(** Note: This could be proven by induction on the evaluation relation, - but would require showing that the step relation is deterministic. - For now, we axiomatize it as a reasonable assumption for our - simple instruction set. *) +(** Evaluation is deterministic. Discharged 2026-05-20 from + [step_deterministic_strong] by induction on the eval derivation — + [Print Assumptions] reports "Closed under the global context". + Was previously an [Axiom] (see PROOF-STATUS-2026-05-18.md + "post-T0 axiom audit"). *) +Theorem eval_deterministic : forall p s s1 s2, + eval p s s1 -> eval p s s2 -> s1 =st= s2. +Proof. + intros p s s1 s2 H1. + generalize dependent s2. + induction H1 as [ s0 | i is sA sB sC Hstep Hev IH ]; intros s2 H2. + - (* eval_empty: inversion forces s2 = s0. *) + inversion H2; subst. apply state_eq_refl. + - (* eval_step: inversion gives step sA i sB' and eval is sB' s2. + step_deterministic_strong then forces sB = sB' (syntactic), so the + induction hypothesis closes the tail. *) + inversion H2; subst. + match goal with + | [ Hs : step sA i ?sBp, He : eval is ?sBp s2 |- _ ] => + pose proof (step_deterministic_strong _ _ _ _ Hstep Hs) as Heq; + subst sBp; + apply IH; exact He + end. +Qed. (** Two programs are CNO-equivalent if they produce the same state transformations *) Definition cno_equiv (p1 p2 : Program) : Prop := @@ -469,17 +514,26 @@ Theorem cno_equiv_sym : forall p1 p2, cno_equiv p1 p2 -> cno_equiv p2 p1. Proof. unfold cno_equiv. intros p1 p2 H s s1 s2 H1 H2. - symmetry. - apply H; assumption. + (* `symmetry` needs a registered Symmetric instance for =st= (none), and + state_eq_sym is defined later in this file. Derive s2 =st= s1 from H + and flip each observable component by hand. *) + destruct (H s s2 s1 H2 H1) as [Hm [Hr Hi]]. + unfold state_eq, mem_eq in *. + split; [ | split ]. + - intros addr; symmetry; apply Hm. + - symmetry; exact Hr. + - symmetry; exact Hi. Qed. (** State equality is symmetric *) Lemma state_eq_sym : forall s1 s2, s1 =st= s2 -> s2 =st= s1. Proof. - intros s1 s2 [Hm [Hr [Hi Hp]]]. + intros s1 s2 [Hm [Hr Hi]]. unfold state_eq, mem_eq in *. - repeat split; auto. - intros addr. symmetry. apply Hm. + split; [ | split ]. + - intros addr. symmetry. apply Hm. + - symmetry. exact Hr. + - symmetry. exact Hi. Qed. Theorem cno_equiv_trans : @@ -518,9 +572,21 @@ Qed. (** ** Decidability *) (** Question: Is CNO verification decidable? *) -(** This is a major research question *) -Axiom cno_decidable : forall p, {is_CNO p} + {~ is_CNO p}. +(** Universal decidability of [is_CNO] over arbitrary programs was + previously asserted as an [Axiom] [cno_decidable]. That axiom has + been dropped (owner ruling, Stage 3 of standards#157): the + universal form asks for a constructive decision procedure over an + unbounded state space ([Memory : nat -> nat], unbounded + registers, unbounded I/O traces), and [is_CNO]'s + universally-quantified clauses range over all of them. This is + essentially the Rice's-theorem situation: deciding a non-trivial + semantic property of an arbitrary program is undecidable, so the + universal-decidability claim is not constructively achievable in + Coq and any client that wants decidability must work in a + restricted syntactic fragment of [Program] (which the current + development does not formalise). No theorem in this file depended + on it. *) (** ** Complexity *) @@ -577,51 +643,35 @@ Conjecture cno_verification_overhead : (** ** State Equality and Evaluation *) -(** CRITICAL LEMMA: Evaluation respects state equality on the right - - This lemma is essential for proving CNO reversibility. - It states that if we can evaluate p from s to s', and s' is - state-equal to s'', then we can also evaluate p from s to s''. - - This is needed because the eval relation is defined inductively - on specific states, but CNO theory works with state equality (=st=). -*) -Axiom eval_respects_state_eq_right : - forall p s s' s'', - eval p s s' -> - s' =st= s'' -> - eval p s s''. - -(** TODO: Prove this axiom by induction on eval structure. - This requires showing that each step constructor respects state equality. - For now, we axiomatize it to unblock cno_logically_reversible proof. -*) - -(** Similarly for the left side *) -Axiom eval_respects_state_eq_left : - forall p s s' s'', - eval p s s'' -> - s =st= s' -> - eval p s' s''. - -(** For CNOs specifically, if s =st= s', then eval p s s evaluates the same as eval p s' s' *) +(** UNSOUND-AS-STATED axioms previously declared here + (`eval_respects_state_eq_right` and `_left`) have been REMOVED + (2026-05-20). The rescue branch's PC-excluding [state_eq] (memory + + registers + I/O, not [state_pc]) means two `=st=` states can carry + different PCs, while the eval relation deterministically propagates + PC through every step constructor. So [eval p s s'] forces a unique + [s'] (cf. [eval_deterministic]) — replacing [s'] by an [=st=]-equal + [s''] is generally unsound (different PC). + + The only consumer that needed the strong form ([cno_logically_reversible] + in StatMech.v) has been refactored to use [cno_terminates] + + [cno_preserves_state] directly, with a correspondingly-weakened + [logically_reversible] definition. See ADR-008. *) + +(** For CNOs specifically, termination from one state is equivalent to + termination from any state-equal state — both can be witnessed by + [cno_terminates] (the witnesses need not coincide). *) Lemma cno_eval_on_equal_states : forall p s s', is_CNO p -> s =st= s' -> (exists s1, eval p s s1) <-> (exists s2, eval p s' s2). Proof. - intros p s s' H_cno H_eq. - split; intros [sx H_eval]. - - (* Forward direction *) - exists s'. - eapply eval_respects_state_eq_left. - + eassumption. - + assumption. - - (* Backward direction *) - exists s. - eapply eval_respects_state_eq_left. - + eassumption. - + apply state_eq_sym. assumption. + intros p s s' H_cno _. + split; intros _. + - (* termination from s' is direct from is_CNO p *) + destruct (cno_terminates p H_cno s') as [s2 Heval2]. + exists s2; exact Heval2. + - destruct (cno_terminates p H_cno s) as [s1 Heval1]. + exists s1; exact Heval1. Qed. diff --git a/absolute-zero/proofs/coq/common/Complex.v b/absolute-zero/proofs/coq/common/Complex.v new file mode 100644 index 0000000..bd7ae7d --- /dev/null +++ b/absolute-zero/proofs/coq/common/Complex.v @@ -0,0 +1,82 @@ +(** * Complex.v — self-contained complex numbers (no external deps) + + Replaces the non-existent `Coq.Complex.Complex` and avoids the + Coquelicot -> mathcomp2 -> Hierarchy-Builder -> coq-elpi dependency + chain. The quantum proofs use only shallow field arithmetic on + C = R*R (Cplus, Cmult, Cconj, RtoC, Cinv, Re/Im), so a small + self-contained module is the right call. + + Decision recorded in PROOF-STATUS-2026-05-18.md. *) + +Require Import Coq.Reals.Reals. +Require Import Coq.micromega.Lra. +Open Scope R_scope. + +Definition C : Type := (R * R)%type. + +Definition Re (z : C) : R := fst z. +Definition Im (z : C) : R := snd z. + +Definition RtoC (r : R) : C := (r, 0). +Coercion RtoC : R >-> C. + +Definition C0 : C := (0, 0). +Definition C1 : C := (1, 0). +Definition Ci : C := (0, 1). + +Definition Cplus (a b : C) : C := (fst a + fst b, snd a + snd b). +Definition Copp (a : C) : C := (- fst a, - snd a). +Definition Cminus (a b : C) : C := Cplus a (Copp b). +Definition Cmult (a b : C) : C := + (fst a * fst b - snd a * snd b, fst a * snd b + snd a * fst b). +Definition Cconj (z : C) : C := (fst z, - snd z). + +Definition Cnorm2 (z : C) : R := fst z * fst z + snd z * snd z. +Definition Cinv (z : C) : C := + (fst z / Cnorm2 z, - snd z / Cnorm2 z). +Definition Cdiv (a b : C) : C := Cmult a (Cinv b). + +Declare Scope C_scope. +Delimit Scope C_scope with C. +Bind Scope C_scope with C. +Infix "+" := Cplus : C_scope. +Infix "-" := Cminus : C_scope. +Infix "*" := Cmult : C_scope. +Infix "/" := Cdiv : C_scope. +Notation "- x" := (Copp x) : C_scope. + +(** A complex pair is determined by its components. *) +Lemma Cpair_eq : forall a b : C, fst a = fst b -> snd a = snd b -> a = b. +Proof. + intros [a1 a2] [b1 b2] H1 H2; simpl in *; subst; reflexivity. +Qed. + +Ltac Csolve := apply Cpair_eq; simpl; lra. + +Lemma Cplus_comm : forall a b, Cplus a b = Cplus b a. Proof. intros; Csolve. Qed. +Lemma Cplus_assoc : forall a b c, Cplus a (Cplus b c) = Cplus (Cplus a b) c. Proof. intros; Csolve. Qed. +Lemma Cplus_0_l : forall a, Cplus C0 a = a. Proof. intros [??]; Csolve. Qed. +Lemma Cplus_0_r : forall a, Cplus a C0 = a. Proof. intros [??]; Csolve. Qed. +Lemma Cmult_comm : forall a b, Cmult a b = Cmult b a. Proof. intros; Csolve. Qed. +Lemma Cmult_assoc : forall a b c, Cmult a (Cmult b c) = Cmult (Cmult a b) c. Proof. intros; Csolve. Qed. +Lemma Cmult_1_l : forall a, Cmult C1 a = a. Proof. intros [??]; Csolve. Qed. +Lemma Cmult_1_r : forall a, Cmult a C1 = a. Proof. intros [??]; Csolve. Qed. +Lemma Cmult_0_l : forall a, Cmult C0 a = C0. Proof. intros [??]; Csolve. Qed. +Lemma Cmult_plus_distr_l : + forall a b c, Cmult a (Cplus b c) = Cplus (Cmult a b) (Cmult a c). +Proof. intros; Csolve. Qed. + +Lemma Cconj_involutive : forall z, Cconj (Cconj z) = z. +Proof. intros [??]; Csolve. Qed. +Lemma Cconj_plus : forall a b, Cconj (Cplus a b) = Cplus (Cconj a) (Cconj b). +Proof. intros; Csolve. Qed. +Lemma Cconj_mult : forall a b, Cconj (Cmult a b) = Cmult (Cconj a) (Cconj b). +Proof. intros; Csolve. Qed. +Lemma Cconj_RtoC : forall r : R, Cconj (RtoC r) = RtoC r. +Proof. intros; unfold Cconj, RtoC; Csolve. Qed. +Lemma RtoC_plus : forall r s : R, RtoC (r + s) = Cplus (RtoC r) (RtoC s). +Proof. intros; unfold RtoC; Csolve. Qed. +Lemma RtoC_mult : forall r s : R, RtoC (r * s) = Cmult (RtoC r) (RtoC s). +Proof. intros; unfold RtoC; Csolve. Qed. +Lemma RtoC_opp : forall r : R, RtoC (- r) = Copp (RtoC r). +Proof. intros; unfold RtoC; Csolve. Qed. diff --git a/absolute-zero/proofs/coq/filesystem/FilesystemCNO.v b/absolute-zero/proofs/coq/filesystem/FilesystemCNO.v index 684d4e1..19e2f8e 100644 --- a/absolute-zero/proofs/coq/filesystem/FilesystemCNO.v +++ b/absolute-zero/proofs/coq/filesystem/FilesystemCNO.v @@ -15,13 +15,13 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero (integrating Valence Shell) - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import Coq.Lists.List. Require Import Coq.Strings.String. Require Import Coq.Arith.Arith. -Require Import CNO. +Require Import CNO.CNO. Import ListNotations. @@ -93,6 +93,10 @@ Parameter rename : Path -> Path -> Filesystem -> Filesystem. (** ** Filesystem State Equality *) (** Two filesystems are equal if they have the same structure and content *) +(* AXIOM: fs_eq_dec; decidable equality over opaque FileContent — currently + §(c) NECESSARY AXIOM; promote to §(b) TRUSTED with property-test budget + when a concrete FileContent type lands. See docs/proof-debt.md and + docs/proof-debt-triage.md row FilesystemCNO.v:96. *) Axiom fs_eq_dec : forall (fs1 fs2 : Filesystem), {fs1 = fs2} + {fs1 <> fs2}. (** Filesystem equality is an equivalence relation *) @@ -101,6 +105,8 @@ Notation "fs1 =fs= fs2" := (fs1 = fs2) (at level 70). (** ** Operation Axioms *) (** mkdir followed by rmdir is identity (if directory doesn't exist initially) *) +(* AXIOM: mkdir_rmdir_inverse; POSIX-semantics specification (model-layer); + §(c) per docs/proof-debt.md. *) Axiom mkdir_rmdir_inverse : forall (p : Path) (fs : Filesystem), (* Precondition: p doesn't exist *) @@ -111,6 +117,7 @@ Axiom mkdir_rmdir_inverse : rmdir p (mkdir p fs) =fs= fs. (** create followed by unlink is identity (if file doesn't exist initially) *) +(* AXIOM: create_unlink_inverse; POSIX-semantics specification; §(c) per docs/proof-debt.md. *) Axiom create_unlink_inverse : forall (p : Path) (fs : Filesystem), (* Precondition: p doesn't exist *) @@ -121,29 +128,34 @@ Axiom create_unlink_inverse : unlink p (create p fs) =fs= fs. (** read followed by write is identity (preserves filesystem) *) +(* AXIOM: read_write_identity; POSIX-semantics specification; §(c) per docs/proof-debt.md. *) Axiom read_write_identity : forall (p : Path) (fs : Filesystem) (content : FileContent), read_file p fs = Some content -> write_file p content fs =fs= fs. (** chmod to current permissions is identity *) +(* AXIOM: chmod_identity; POSIX-semantics specification; §(c) per docs/proof-debt.md. *) Axiom chmod_identity : forall (p : Path) (fs : Filesystem) (meta : FileMetadata), stat p fs = Some meta -> chmod p (permissions meta) fs =fs= fs. (** chown to current owner is identity *) +(* AXIOM: chown_identity; POSIX-semantics specification; §(c) per docs/proof-debt.md. *) Axiom chown_identity : forall (p : Path) (fs : Filesystem) (meta : FileMetadata), stat p fs = Some meta -> chown p (owner meta) fs =fs= fs. (** rename to same path is identity *) +(* AXIOM: rename_identity; POSIX-semantics specification; §(c) per docs/proof-debt.md. *) Axiom rename_identity : forall (p : Path) (fs : Filesystem), rename p p fs =fs= fs. (** rename A to B followed by rename B to A is identity *) +(* AXIOM: rename_inverse; POSIX-semantics specification; §(c) per docs/proof-debt.md. *) Axiom rename_inverse : forall (p1 p2 : Path) (fs : Filesystem), p1 <> p2 -> @@ -380,7 +392,7 @@ Qed. Definition transaction_rollback (ops : list fs_op) (rollback_ops : list fs_op) : Prop := forall fs, fold_right (fun op acc => op acc) fs rollback_ops =fs= - fold_left (fun acc op => op acc) fs ops. + fold_left (fun acc op => op acc) ops fs. (** If each operation has an inverse, transaction is a CNO @@ -398,7 +410,7 @@ Axiom transaction_cno : forall (ops rollback_ops : list fs_op), (forall i, valence_reversible (nth i ops fs_nop) (nth i rollback_ops fs_nop)) -> is_fs_CNO (fun fs => - fold_right (fun op acc => op acc) (fold_left (fun acc op => op acc) fs ops) rollback_ops). + fold_right (fun op acc => op acc) (fold_left (fun acc op => op acc) ops fs) rollback_ops). (** ** Connection to Classical CNOs *) diff --git a/absolute-zero/proofs/coq/lambda/LambdaCNO.v b/absolute-zero/proofs/coq/lambda/LambdaCNO.v index ebe81a5..c931a52 100644 --- a/absolute-zero/proofs/coq/lambda/LambdaCNO.v +++ b/absolute-zero/proofs/coq/lambda/LambdaCNO.v @@ -14,6 +14,8 @@ Require Import Coq.Lists.List. Require Import Coq.Arith.Arith. Require Import Coq.Bool.Bool. +Require Import Lia. +Require Import CNO.CNO. Import ListNotations. (** ** Lambda Calculus Syntax *) @@ -351,6 +353,10 @@ Definition y_combinator : LambdaTerm := This is a fundamental result in lambda calculus and is safely axiomatized. *) +(* AXIOM: y_not_cno; non-termination claim about the Y combinator — + requires step-indexed semantics or coinduction to discharge within + the working logic. §(c) NECESSARY AXIOM per docs/proof-debt.md + (triage: docs/proof-debt-triage.md row LambdaCNO.v:356). *) Axiom y_not_cno : ~ is_lambda_CNO y_combinator. (** ** Practical Examples *) @@ -371,6 +377,10 @@ Definition snd : LambdaTerm := (** ** Eta Equivalence *) (** Eta reduction: (λx. f x) ≡ f *) +(* AXIOM: eta_equivalence; η-equivalence is not derivable under β-only + reduction — requires an extra reduction rule or extensional equality. + §(c) NECESSARY AXIOM per docs/proof-debt.md (triage: + docs/proof-debt-triage.md row LambdaCNO.v:376). *) Axiom eta_equivalence : forall f : LambdaTerm, beta_reduce_star (LAbs (LApp f (LVar 0))) f. @@ -403,6 +413,7 @@ Proof. Qed. (** ** Summary *) + (** This module proves: 1. Lambda calculus has CNOs (identity function) [lambda_id_is_cno: Qed] @@ -411,13 +422,14 @@ Qed. 4. Connection to Church encodings 5. Eta equivalence expands CNO class [eta_expanded_id_is_cno: Qed] - Proof status: 3 of 4 theorems fully proven (1 Axiom). + Proof status: 3 of 4 theorems fully proven (1 explicit axiom). - The Axiom (y_not_cno) represents a well-established result in - lambda calculus theory (Y f diverges for all f). + The remaining axiomatized result (y_not_cno) requires formal + non-termination reasoning, which is inherently difficult + in constructive type theory. The result itself is well-established + in lambda calculus theory (Y f diverges for all f). CONCLUSION: CNO theory is model-independent. -*) The same mathematical structure appears in: - Imperative programs (our original model) - Functional programs (lambda calculus) diff --git a/absolute-zero/proofs/coq/malbolge/MalbolgeCore.v b/absolute-zero/proofs/coq/malbolge/MalbolgeCore.v index b155f19..b9d0638 100644 --- a/absolute-zero/proofs/coq/malbolge/MalbolgeCore.v +++ b/absolute-zero/proofs/coq/malbolge/MalbolgeCore.v @@ -7,7 +7,7 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import CNO.CNO. @@ -190,8 +190,14 @@ Theorem malbolge_nop_preserves_state : Proof. intros ms ms' H. inversion H; subst. - inversion H2; subst. - inversion H3; subst. + match goal with + | Hstep : malbolge_step _ MNop _ |- _ => + inversion Hstep; subst; clear Hstep + end. + match goal with + | Hrest : malbolge_eval [] _ _ |- _ => + inversion Hrest; subst; clear Hrest + end. repeat split; reflexivity. Qed. @@ -207,8 +213,14 @@ Theorem malbolge_halt_is_cno : Proof. intros ms ms' H. inversion H; subst. - inversion H2; subst. - inversion H3; subst. + match goal with + | Hstep : malbolge_step _ MHlt _ |- _ => + inversion Hstep; subst; clear Hstep + end. + match goal with + | Hrest : malbolge_eval [] _ _ |- _ => + inversion Hrest; subst; clear Hrest + end. reflexivity. Qed. @@ -265,7 +277,7 @@ Proof. - constructor. } specialize (H ms ms' H0). - destruct H as [_ [_ [_ HIO]]]. + destruct H as [_ [_ [_ [_ HIO]]]]. simpl in HIO. discriminate HIO. Qed. @@ -297,12 +309,7 @@ Proof. rewrite HA, HC, HD. reflexivity. - (* I/O *) - apply HIO. - - (* PC *) - simpl. - (* C register is PC and is now preserved by strengthened CNO definition *) - rewrite HC. - reflexivity. + symmetry. apply HIO. Qed. (** ** The "Absolute Zero" Program *) diff --git a/absolute-zero/proofs/coq/physics/LandauerDerivation.v b/absolute-zero/proofs/coq/physics/LandauerDerivation.v index 9699228..06866c6 100644 --- a/absolute-zero/proofs/coq/physics/LandauerDerivation.v +++ b/absolute-zero/proofs/coq/physics/LandauerDerivation.v @@ -7,13 +7,16 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - Phase 1 Complete Derivation - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import Coq.Reals.Reals. Require Import Coq.Reals.RIneq. Require Import Coq.micromega.Psatz. -Require Import CNO. +Require Import Coq.Lists.List. +Require Import Lia. +Require Import CNO.CNO. +Import ListNotations. Open Scope R_scope. @@ -42,18 +45,20 @@ Axiom prob_normalized : exists (states : list ProgramState), fold_right (fun s acc => acc + P s) 0 states = 1. +Axiom state_eq_dec : forall s1 s2 : ProgramState, {s1 = s2} + {s1 <> s2}. + (** Point distribution (Dirac delta) *) Definition point_dist (s0 : ProgramState) : StateDistribution := fun s => if state_eq_dec s s0 then 1 else 0. -Axiom state_eq_dec : forall s1 s2 : ProgramState, {s1 = s2} + {s1 <> s2}. - (** ** Shannon Entropy: Information-Theoretic Foundation *) (** Shannon entropy: H(P) = -Σ p_i log_2(p_i) Measured in bits *) Parameter shannon_entropy : StateDistribution -> R. +Definition log2 (x : R) : R := ln x / ln 2. + (** Shannon entropy axioms (from information theory) *) Axiom shannon_entropy_nonneg : forall P : StateDistribution, shannon_entropy P >= 0. @@ -69,6 +74,9 @@ Axiom shannon_entropy_uniform_max : (forall s, In s states -> P s = 1 / INR n) -> shannon_entropy P = log2 (INR n). +(** Product distribution (for independence) *) +Parameter product_dist : StateDistribution -> StateDistribution -> StateDistribution. + (** Entropy is additive for independent distributions *) Axiom shannon_entropy_additive : forall P Q : StateDistribution, @@ -76,9 +84,6 @@ Axiom shannon_entropy_additive : shannon_entropy (product_dist P Q) = shannon_entropy P + shannon_entropy Q. -(** Product distribution (for independence) *) -Parameter product_dist : StateDistribution -> StateDistribution -> StateDistribution. - (** ** Boltzmann Entropy: Thermodynamic Foundation *) (** Boltzmann entropy: S = k_B ln(W) where W is number of microstates @@ -96,11 +101,20 @@ Theorem boltzmann_entropy_nonneg : Proof. intro P. unfold boltzmann_entropy. - apply Rmult_le_pos. - - apply Rmult_le_pos. - + apply Rlt_le. apply kB_positive. - + apply Rlt_le. apply ln_2_pos. - - apply shannon_entropy_nonneg. + pose proof kB_positive as HkB. + pose proof ln_lt_2 as Hln_half. + assert (Hln : ln 2 > 0) by lra. + pose proof (shannon_entropy_nonneg P) as Hentropy. + unfold Rge in Hentropy. + unfold Rge. + destruct Hentropy as [Hentropy_pos | Hentropy_zero]. + - left. + replace (kB * ln 2 * shannon_entropy P)%R + with ((kB * ln 2) * shannon_entropy P)%R by ring. + apply Rmult_lt_0_compat. + + apply Rmult_lt_0_compat; assumption. + + exact Hentropy_pos. + - right. rewrite Hentropy_zero. ring. Qed. (** ** Second Law of Thermodynamics *) @@ -166,7 +180,7 @@ Definition erasure_final (s_final : ProgramState) : StateDistribution := *) Axiom entropy_change_erasure : forall (n : nat) (s_final : ProgramState), - n > 0 -> + (n > 0)%nat -> boltzmann_entropy (erasure_initial n) - boltzmann_entropy (erasure_final s_final) = kB * ln 2 * INR n. @@ -189,7 +203,7 @@ Axiom isothermal_work_bound : Theorem landauer_principle_derived : forall (n : nat) (s_final : ProgramState), - n > 0 -> + (n > 0)%nat -> work_dissipated (erasure_initial n) (erasure_final s_final) >= kB * temperature * ln 2 * INR n. Proof. @@ -202,7 +216,10 @@ Proof. (* work ≥ T * ΔS *) (* work ≥ T * (k_B ln(2) * n) *) (* work ≥ k_B * T * ln(2) * n *) - lra. + rewrite H_entropy in H_work. + replace (kB * temperature * ln 2 * INR n)%R + with (temperature * (kB * ln 2 * INR n))%R by ring. + exact H_work. Qed. (** For erasing one bit (n = 1): *) @@ -212,11 +229,10 @@ Corollary landauer_one_bit : kB * temperature * ln 2. Proof. intro s_final. - assert (H := landauer_principle_derived 1 s_final). - replace (INR 1) with 1 by (simpl; lra). - ring_simplify in H. - apply H. - omega. + replace (kB * temperature * ln 2)%R + with (kB * temperature * ln 2 * INR 1)%R by (simpl; ring). + apply landauer_principle_derived. + lia. Qed. (** At room temperature (300K): *) @@ -224,6 +240,10 @@ Qed. (** ** Application to CNOs *) +(** Finite-state carrier used by the simplified distribution model. *) +Parameter all_states : list ProgramState. +Parameter eval_to_dec : forall p s s', {eval p s s'} + {~ eval p s s'}. + (** Distribution after program execution *) Definition post_execution_dist (p : Program) (P : StateDistribution) : StateDistribution := fun s' => @@ -231,9 +251,6 @@ Definition post_execution_dist (p : Program) (P : StateDistribution) : StateDist fold_right Rplus 0 (map (fun s => if eval_to_dec p s s' then P s else 0) all_states). -Parameter all_states : list ProgramState. -Parameter eval_to_dec : forall p s s', {eval p s s'} + {~ eval p s s'}. - (** CNOs preserve Shannon entropy (key property) A CNO is an identity transformation: for all states s, eval p s s implies s' = s. diff --git a/absolute-zero/proofs/coq/physics/StatMech.v b/absolute-zero/proofs/coq/physics/StatMech.v index bd75fe7..159a175 100644 --- a/absolute-zero/proofs/coq/physics/StatMech.v +++ b/absolute-zero/proofs/coq/physics/StatMech.v @@ -6,12 +6,15 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import Coq.Reals.Reals. Require Import Coq.Logic.FunctionalExtensionality. -Require Import CNO. +Require Import Coq.Lists.List. +Require Import Coq.micromega.Psatz. +Require Import CNO.CNO. +Import ListNotations. Open Scope R_scope. @@ -44,14 +47,14 @@ Axiom prob_normalized : exists (states : list ProgramState), fold_right Rplus 0 (map P states) = 1. -(** Point distribution (all probability on one state) *) -Definition point_dist (s0 : ProgramState) : StateDistribution := - fun s => if state_dec s s0 then 1 else 0. - (** State decidability *) Axiom state_dec : forall s1 s2 : ProgramState, {s1 = s2} + {s1 <> s2}. +(** Point distribution (all probability on one state) *) +Definition point_dist (s0 : ProgramState) : StateDistribution := + fun s => if state_dec s s0 then 1 else 0. + (** ** Information-Theoretic Entropy *) (** Shannon entropy: H(P) = -Σ p(s) log₂ p(s) @@ -95,11 +98,20 @@ Theorem boltzmann_entropy_nonneg : Proof. intros P. unfold boltzmann_entropy. - apply Rmult_le_pos. - - apply Rmult_le_pos. - + left. apply kB_positive. - + apply Rlt_le. apply ln_lt_2. lra. - - apply shannon_entropy_nonneg. + pose proof kB_positive as HkB. + pose proof (shannon_entropy_nonneg P) as Hentropy. + unfold Rge in Hentropy. + pose proof ln_lt_2 as Hln_half. + assert (Hln : ln 2 > 0) by lra. + unfold Rge. + destruct Hentropy as [Hentropy_pos | Hentropy_zero]. + - left. + replace (kB * ln 2 * shannon_entropy P)%R + with ((kB * ln 2) * shannon_entropy P)%R by ring. + apply Rmult_lt_0_compat. + + apply Rmult_lt_0_compat; assumption. + + exact Hentropy_pos. + - right. rewrite Hentropy_zero. ring. Qed. (** ** Landauer's Principle *) @@ -134,7 +146,7 @@ Proof. - apply Rmult_lt_0_compat. + apply kB_positive. + apply temperature_positive. - - apply ln_lt_2. lra. + - pose proof ln_lt_2 as Hln_half. lra. Qed. (** At room temperature (300K): E_min ≈ 2.85 × 10⁻²¹ J per bit *) @@ -229,8 +241,9 @@ Proof. (* Apply the axiom that reversible processes (ΔS = 0) dissipate no energy *) apply reversible_zero_dissipation. (* CNOs preserve entropy *) + symmetry. apply cno_preserves_shannon_entropy. - assumption. + exact H_cno. Qed. (** ** Bennett's Reversible Computing *) @@ -238,12 +251,23 @@ Qed. (** Bennett (1973): Computation can be made thermodynamically reversible by never erasing information, only permuting it. *) -(** A program is logically reversible if it's bijective *) +(** A program is logically reversible up to observational equivalence: + there exists an inverse program that, run on the post-execution state, + recovers a state observationally equal ([=st=]) to the input. + + Stating reversibility up to [=st=] (rather than strict [=]) is forced + by the rescue branch's PC-excluding [state_eq]: [eval p s s'] uniquely + determines [s'] (cf. [eval_deterministic_strong]) including its PC, + so re-running [p] on a different start state cannot in general produce + a PC-identical result. Observational reversibility is what the + thermodynamic argument actually needs (memory + registers + I/O are + the bits of physical record; the PC is bookkeeping). See ADR-008 + (2026-05-20). *) Definition logically_reversible (p : Program) : Prop := exists p_inv : Program, forall s s', eval p s s' -> - eval p_inv s' s. + exists s'', eval p_inv s' s'' /\ s'' =st= s. (** Logical reversibility implies thermodynamic reversibility *) @@ -303,8 +327,8 @@ Proof. (* Step 2: By termination, eval p s' s'' for some s'' *) destruct (cno_terminates p H_cno s') as [s'' H_eval']. - (* Step 3: By CNO identity property, s'' =st= s' *) - assert (s'' =st= s') as H_s''_eq_s'. + (* Step 3: By CNO identity property, s' =st= s'' *) + assert (s' =st= s'') as H_s'_eq_s''. { apply cno_preserves_state with (p := p) (s := s') (s' := s''). - assumption. - assumption. } @@ -312,14 +336,16 @@ Proof. (* Step 4: By transitivity, s'' =st= s *) assert (s'' =st= s) as H_s''_eq_s. { apply state_eq_trans with (s2 := s'). - - apply state_eq_sym. assumption. - - apply state_eq_sym. assumption. } - - (* Step 5: We have eval p s' s'' and s'' =st= s - Apply eval_respects_state_eq_right to get eval p s' s *) - apply eval_respects_state_eq_right with (s' := s''). - - exact H_eval'. - - exact H_s''_eq_s. + - apply state_eq_sym. exact H_s'_eq_s''. + - apply state_eq_sym. exact H_state_eq. } + + (* Step 5: We have eval p s' s'' and s'' =st= s. + The (now weakened) definition of [logically_reversible] only requires + a witness end-state observationally equal to s — H_eval' + H_s''_eq_s + supply it directly. The previous proof used the unsound + [eval_respects_state_eq_right] axiom; that axiom has been removed + (see CNO.v / ADR-008). *) + exists s''. split; [ exact H_eval' | exact H_s''_eq_s ]. Qed. (** ** Physical Implications *) @@ -345,8 +371,7 @@ Proof. rewrite cno_preserves_shannon_entropy; auto. simpl. (* ΔS = 0, so we're in the else branch *) - destruct Rlt_dec; try lra. - reflexivity. + destruct Rlt_dec; [lra | reflexivity]. Qed. (** ** Connection to Original CNO Definition *) @@ -358,8 +383,8 @@ Theorem symbolic_energy_matches_physical : forall (p : Program) (s1 s2 : ProgramState), eval p s1 s2 -> is_CNO p -> - CNO.energy_dissipated p s1 s2 = 0 <-> - energy_dissipated_phys (point_dist s1) (point_dist s2) = 0. + CNO.energy_dissipated p s1 s2 = 0%nat <-> + energy_dissipated_phys (point_dist s1) (post_execution_dist p (point_dist s1)) = 0. Proof. intros p s1 s2 H_eval H_cno. split; intros H. diff --git a/absolute-zero/proofs/coq/physics/StatMech_helpers.v b/absolute-zero/proofs/coq/physics/StatMech_helpers.v index d09e813..2aec05f 100644 --- a/absolute-zero/proofs/coq/physics/StatMech_helpers.v +++ b/absolute-zero/proofs/coq/physics/StatMech_helpers.v @@ -2,6 +2,10 @@ Auxiliary lemmas needed for thermodynamic CNO proofs. These should eventually be integrated into CNO.v. + + Author: Jonathan D. A. Jewell + Project: Absolute Zero + License: MPL-2.0 *) Require Import CNO. @@ -11,13 +15,12 @@ Lemma state_eq_sym : forall s1 s2 : ProgramState, s1 =st= s2 -> s2 =st= s1. Proof. - intros s1 s2 [H_mem [H_reg [H_io H_pc]]]. + intros s1 s2 [H_mem [H_reg H_io]]. unfold state_eq. repeat split. - unfold mem_eq in *. intro addr. symmetry. apply H_mem. - symmetry. assumption. - symmetry. assumption. - - symmetry. assumption. Qed. (** State equality is transitive *) @@ -25,14 +28,13 @@ Lemma state_eq_trans : forall s1 s2 s3 : ProgramState, s1 =st= s2 -> s2 =st= s3 -> s1 =st= s3. Proof. - intros s1 s2 s3 [H_mem12 [H_reg12 [H_io12 H_pc12]]] [H_mem23 [H_reg23 [H_io23 H_pc23]]]. + intros s1 s2 s3 [H_mem12 [H_reg12 H_io12]] [H_mem23 [H_reg23 H_io23]]. unfold state_eq. repeat split. - unfold mem_eq in *. intro addr. transitivity (state_memory s2 addr); [apply H_mem12 | apply H_mem23]. - transitivity (state_registers s2); assumption. - transitivity (state_io s2); assumption. - - transitivity (state_pc s2); assumption. Qed. (** For CNOs, evaluation from any state leads back to that state *) diff --git a/absolute-zero/proofs/coq/quantum/QuantumCNO.v b/absolute-zero/proofs/coq/quantum/QuantumCNO.v index 19ca555..890f99b 100644 --- a/absolute-zero/proofs/coq/quantum/QuantumCNO.v +++ b/absolute-zero/proofs/coq/quantum/QuantumCNO.v @@ -12,13 +12,14 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import Coq.Reals.Reals. -Require Import Coq.Complex.Complex. +(* Self-contained complex numbers (proofs/coq/common/Complex.v). *) +Require Import CNO.Complex. Require Import Coq.Logic.FunctionalExtensionality. -Require Import CNO. +Require Import CNO.CNO. Open Scope R_scope. Open Scope C_scope. @@ -41,7 +42,7 @@ Axiom temperature_positive : temperature > 0. (** Dimension of Hilbert space (2^n for n qubits) *) Parameter dim : nat. -Axiom dim_positive : dim > 0. +Axiom dim_positive : (dim > 0)%nat. (** Complex vector representing quantum state *) Definition QuantumState : Type := nat -> C. @@ -129,6 +130,12 @@ Axiom CNOT_gate_unitary : is_unitary CNOT_gate. (** ** Quantum State Equality *) +(** Complex exponential. The quantum proofs use it abstractly via the + axioms below (Cexp_zero/neg/add, Cconj_Cexp). Declared as a parameter + so it is in scope before first use. Recorded as an assumption in + PROOF-STATUS-2026-05-18.md (post-T0 axiom audit). *) +Parameter Cexp : C -> C. + (** Two quantum states are equal up to global phase *) Definition quantum_state_eq (ψ φ : QuantumState) : Prop := exists θ : R, forall n, ψ n = Cexp (RtoC θ) * φ n. @@ -148,24 +155,15 @@ Axiom Cexp_neg : forall x : R, Cexp (RtoC (-x)) = Cinv (Cexp (RtoC x)). (** e^x × e^y = e^{x+y} *) Axiom Cexp_add : forall x y : R, Cexp (RtoC x) * Cexp (RtoC y) = Cexp (RtoC (x + y)). -(** 1 × z = z *) -Axiom Cmult_1_l : forall z : C, C1 * z = z. - -(** Complex multiplication associativity *) -Axiom Cmult_assoc : forall a b c : C, a * (b * c) = (a * b) * c. +(* Cmult_1_l, Cmult_assoc, Cconj_RtoC, Cconj_mult are now PROVED lemmas + in CNO.Complex — no longer axioms (strengthens the development and + removes the redeclaration clash). *) (** Complex conjugate of exponential: (e^x)* = e^{x*} *) Axiom Cconj_Cexp : forall x : C, Cconj (Cexp x) = Cexp (Cconj x). -(** Conjugate of real is identity: (r)* = r *) -Axiom Cconj_RtoC : forall r : R, Cconj (RtoC r) = RtoC r. - -(** (a × b)* = a* × b* *) -Axiom Cconj_mult : forall a b : C, Cconj (a * b) = Cconj a * Cconj b. - -(** Global phase gates are unitary (standard quantum mechanics result) *) -Axiom global_phase_unitary : - forall θ : R, is_unitary (global_phase_gate θ). +(* `global_phase_unitary` axiom moved below, after `global_phase_gate` + is defined (it referenced the gate before its definition). *) (** Reflexivity, symmetry, transitivity *) Lemma quantum_state_eq_refl : forall ψ, ψ =q= ψ. @@ -183,17 +181,16 @@ Qed. Lemma quantum_state_eq_sym : forall ψ φ, ψ =q= φ -> φ =q= ψ. Proof. intros ψ φ [θ H]. - exists (-θ). + exists (-θ)%R. intros n. (* ψ_n = e^θ × φ_n, so φ_n = e^{-θ} × ψ_n *) specialize (H n). rewrite H. - rewrite Cexp_neg. (* e^{-θ} × (e^θ × φ_n) = (e^{-θ} × e^θ) × φ_n *) rewrite Cmult_assoc. (* e^{-θ} × e^θ = e^{-θ + θ} = e^0 = 1 *) assert (Cexp (RtoC (-θ)) * Cexp (RtoC θ) = C1) as Hinv. - { rewrite <- Cexp_add. + { rewrite Cexp_add. replace (-θ + θ)%R with 0%R by ring. apply Cexp_zero. } rewrite Hinv. @@ -205,7 +202,7 @@ Lemma quantum_state_eq_trans : forall ψ φ χ, ψ =q= φ -> φ =q= χ -> ψ =q= χ. Proof. intros ψ φ χ [θ1 H1] [θ2 H2]. - exists (θ1 + θ2). + exists (θ1 + θ2)%R. intros n. (* ψ_n = e^{θ1} × φ_n and φ_n = e^{θ2} × χ_n *) (* So ψ_n = e^{θ1} × (e^{θ2} × χ_n) = e^{θ1 + θ2} × χ_n *) @@ -213,8 +210,8 @@ Proof. specialize (H2 n). rewrite H1. rewrite H2. - rewrite <- Cmult_assoc. - rewrite <- Cexp_add. + rewrite Cmult_assoc. + rewrite Cexp_add. reflexivity. Qed. @@ -242,12 +239,12 @@ Proof. split. - (* Unitary *) apply I_gate_unitary. - split. - - (* Identity *) - intros ψ. - apply quantum_state_eq_refl. - - (* No measurement *) - trivial. + - split. + + (* Identity *) + intros ψ. + apply quantum_state_eq_refl. + + (* No measurement *) + trivial. Qed. (** ** Trivial Global Phase Gates *) @@ -256,6 +253,11 @@ Qed. Definition global_phase_gate (θ : R) : QuantumGate := fun ψ n => Cexp (RtoC θ) * ψ n. +(** Global phase gates are unitary (standard QM result). Assumption — + see PROOF-STATUS-2026-05-18.md (post-T0 axiom audit). *) +Axiom global_phase_unitary : + forall θ : R, is_unitary (global_phase_gate θ). + Theorem global_phase_is_cno : forall θ : R, is_quantum_CNO (global_phase_gate θ). Proof. @@ -264,15 +266,15 @@ Proof. split. - (* Unitary *) apply global_phase_unitary. - split. - - (* Identity up to phase *) - intros ψ. - unfold quantum_state_eq. - exists θ. - intros n. - unfold global_phase_gate. - reflexivity. - - trivial. + - split. + + (* Identity up to phase *) + intros ψ. + unfold quantum_state_eq. + exists θ. + intros n. + unfold global_phase_gate. + reflexivity. + + trivial. Qed. (** ** Non-CNO Gates *) @@ -337,18 +339,18 @@ Proof. split. - (* Unitary *) apply unitary_compose; assumption. - split. - - (* Identity *) - intros ψ. - unfold gate_compose. - (* U(V ψ) =q= ψ via transitivity through V ψ *) - (* U(V ψ) =q= V ψ (by HU_id) and V ψ =q= ψ (by HV_id) *) - apply quantum_state_eq_trans with (V ψ). - + (* U(V ψ) =q= V ψ *) - apply HU_id. - + (* V ψ =q= ψ *) - apply HV_id. - - trivial. + - split. + + (* Identity *) + intros ψ. + unfold gate_compose. + (* U(V ψ) =q= ψ via transitivity through V ψ *) + (* U(V ψ) =q= V ψ (by HU_id) and V ψ =q= ψ (by HV_id) *) + apply quantum_state_eq_trans with (V ψ). + * (* U(V ψ) =q= V ψ *) + apply HU_id. + * (* V ψ =q= ψ *) + apply HV_id. + + trivial. Qed. (** ** Quantum Information Theory *) @@ -389,7 +391,7 @@ Qed. Axiom no_cloning : ~ exists (U : QuantumGate), forall ψ : QuantumState, - exists basis, + exists basis : nat, U ψ = ψ /\ U ψ = ψ. (* Simplified statement *) (** CNOs respect no-cloning (they don't clone, they preserve) *) @@ -438,7 +440,7 @@ Definition quantum_to_classical (U : QuantumGate) : Program := 3. Classical program does nothing to measurement statistics 4. Empty program [] is the minimal classical CNO *) - []. + nil. (** Theorem: Quantum CNOs induce classical CNOs via measurement *) Theorem quantum_cno_induces_classical : @@ -535,7 +537,7 @@ Parameter quantum_energy_dissipated : QuantumGate -> QuantumState -> R. (** Landauer bound for quantum operations *) Axiom quantum_landauer_bound : forall (U : QuantumGate) (ψ : QuantumState), - let ΔS := von_neumann_entropy (U ψ) - von_neumann_entropy ψ in + let ΔS := (von_neumann_entropy (U ψ) - von_neumann_entropy ψ)%R in (ΔS <= 0)%R -> (* Entropy decreased (information erased) *) (quantum_energy_dissipated U ψ >= kB * temperature * (-ΔS))%R. diff --git a/absolute-zero/proofs/coq/quantum/QuantumMechanicsExact.v b/absolute-zero/proofs/coq/quantum/QuantumMechanicsExact.v index 2e25e30..b5cca3a 100644 --- a/absolute-zero/proofs/coq/quantum/QuantumMechanicsExact.v +++ b/absolute-zero/proofs/coq/quantum/QuantumMechanicsExact.v @@ -8,14 +8,17 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - Exact Quantum Formulation - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 *) Require Import Coq.Reals.Reals. Require Import Coq.Reals.RIneq. -Require Import Coq.Complex.Complex. +(* Self-contained complex numbers — see proofs/coq/common/Complex.v and + PROOF-STATUS-2026-05-18.md. Replaces the non-existent + `Coq.Complex.Complex`; Coquelicot rejected (mathcomp2/HB/elpi weight). *) +Require Import CNO.Complex. Require Import Coq.micromega.Psatz. -Require Import CNO. +Require Import CNO.CNO. Open Scope R_scope. Open Scope C_scope. @@ -25,9 +28,8 @@ Open Scope C_scope. (** Complex numbers are already defined in Coq.Complex.Complex *) (** C = R + iR, with Cplus, Cmult, etc. *) -(** Complex conjugate *) -Definition Cconj (z : C) : C := - (fst z, - snd z). +(** Complex conjugate is provided by CNO.Complex (identical definition); + the previous local redefinition would clash. *) (** Complex modulus squared *) Definition Cmod2 (z : C) : R := @@ -53,7 +55,7 @@ Definition qubit_dim (n : nat) : nat := 2 ^ n. (** A quantum state is a vector in C^(2^n) *) (** We represent it as a function from basis indices to complex amplitudes *) Definition QuantumState (n : nat) : Type := - {ψ : nat -> C | forall k, k >= qubit_dim n -> ψ k = C0}. + {ψ : nat -> C | forall k, (k >= qubit_dim n)%nat -> ψ k = C0}. (** Extract the amplitude function *) Definition amplitude {n : nat} (ψ : QuantumState n) : nat -> C := @@ -85,14 +87,16 @@ Definition is_normalized {n : nat} (ψ : QuantumState n) : Prop := Definition ket_0 : QuantumState 1. Proof. exists (fun k => match k with 0 => C1 | _ => C0 end). - intros k Hk. destruct k. omega. destruct k. omega. reflexivity. + intros k Hk. unfold qubit_dim in Hk; simpl in Hk. + destruct k as [|[|k]]; [ lia | lia | reflexivity ]. Defined. (** |1⟩ = (0, 1) *) Definition ket_1 : QuantumState 1. Proof. exists (fun k => match k with 1 => C1 | _ => C0 end). - intros k Hk. destruct k. omega. destruct k. omega. reflexivity. + intros k Hk. unfold qubit_dim in Hk; simpl in Hk. + destruct k as [|[|k]]; [ lia | lia | reflexivity ]. Defined. (** ** Pauli Matrices (Exact 2x2 Matrices) *) @@ -146,10 +150,10 @@ Definition identity_2 : Matrix2 := [1 -1] *) Definition hadamard : Matrix2 := fun i j => match i, j with - | 0, 0 => (1 / sqrt 2, 0) - | 0, 1 => (1 / sqrt 2, 0) - | 1, 0 => (1 / sqrt 2, 0) - | 1, 1 => (-1 / sqrt 2, 0) + | 0, 0 => ((1 / sqrt 2)%R, 0%R) + | 0, 1 => ((1 / sqrt 2)%R, 0%R) + | 1, 0 => ((1 / sqrt 2)%R, 0%R) + | 1, 1 => ((-1 / sqrt 2)%R, 0%R) | _, _ => C0 end. @@ -160,13 +164,14 @@ Definition apply_matrix_2 (M : Matrix2) (ψ : QuantumState 1) : QuantumState 1. Proof. exists (fun k => match k with - | 0 => Cplus (Cmult (M 0 0) (amplitude ψ 0)) - (Cmult (M 0 1) (amplitude ψ 1)) - | 1 => Cplus (Cmult (M 1 0) (amplitude ψ 0)) - (Cmult (M 1 1) (amplitude ψ 1)) + | O => Cplus (Cmult (M 0%nat 0%nat) (amplitude ψ 0%nat)) + (Cmult (M 0%nat 1%nat) (amplitude ψ 1%nat)) + | S O => Cplus (Cmult (M 1%nat 0%nat) (amplitude ψ 0%nat)) + (Cmult (M 1%nat 1%nat) (amplitude ψ 1%nat)) | _ => C0 end). - intros k Hk. destruct k. omega. destruct k. omega. + intros k Hk. unfold qubit_dim in Hk; simpl in Hk. + destruct k as [|[|k]]; [ lia | lia | ]. simpl. reflexivity. Defined. @@ -340,7 +345,7 @@ Proof. replace (sin 0) with 0 by (rewrite sin_0; reflexivity). unfold Cmult. simpl. destruct (amplitude ψ k) as [r i]. - simpl. ring_simplify. reflexivity. + simpl. apply Cpair_eq; simpl; ring. Qed. (** ** Measurement and No-Cloning Theorem *) diff --git a/absolute-zero/proofs/lean4/CNO.lean b/absolute-zero/proofs/lean4/CNO.lean index 53578e7..117a08d 100644 --- a/absolute-zero/proofs/lean4/CNO.lean +++ b/absolute-zero/proofs/lean4/CNO.lean @@ -5,18 +5,22 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 -/ -import Std.Data.List.Basic -import Std.Data.Nat.Basic +-- Std.Data.{List,Nat}.Basic were vestigial: Std was renamed to Batteries +-- around Lean 4.5, and the List/Nat APIs used here (`++`, `foldl`, `get?`, +-- `Repr`, `BEq`) are all in core Lean 4. No external imports required. namespace CNO /-! ## Memory Model -/ -/-- Memory is modeled as a function from addresses to values -/ -def Memory : Type := Nat → Nat +/-- Memory is modeled as a function from addresses to values. + `abbrev` (rather than `def`) makes the definition reducible, so any + typeclass instance for `Nat → Nat` (none in core, but consistent with + sibling aliases below) is available on `Memory`. -/ +abbrev Memory : Type := Nat → Nat /-- Empty memory (all zeros) -/ def Memory.empty : Memory := fun _ => 0 @@ -34,8 +38,9 @@ instance : BEq Memory where /-! ## Program State -/ -/-- Registers are a list of natural numbers -/ -def Registers : Type := List Nat +/-- Registers are a list of natural numbers. + `abbrev` so List's HAppend / Repr / BEq instances propagate. -/ +abbrev Registers : Type := List Nat /-- I/O operations -/ inductive IOOp where @@ -44,16 +49,21 @@ inductive IOOp where | write : Nat → IOOp deriving Repr, BEq -/-- I/O state is a list of operations -/ -def IOState : Type := List IOOp +/-- I/O state is a list of operations. `abbrev` so List instances propagate. -/ +abbrev IOState : Type := List IOOp -/-- Complete program state -/ +/-- Complete program state. + No `deriving Repr`: `Memory` is `Nat → Nat`, which has no canonical + `Repr` instance (functions are not displayable). + `deriving BEq` works via the trivial `BEq Memory` instance above + plus core BEq for the other fields, and is required by downstream + distributions like `StatMech.pointDist` that branch on `s == s0`. -/ structure ProgramState where memory : Memory registers : Registers ioState : IOState pc : Nat -- Program counter - deriving Repr + deriving BEq /-- State equality -/ def ProgramState.eq (s1 s2 : ProgramState) : Prop := @@ -74,8 +84,10 @@ inductive Instruction where | jump : Nat → Instruction deriving Repr, BEq -/-- A program is a list of instructions -/ -def Program : Type := List Instruction +/-- A program is a list of instructions. + `abbrev` (not `def`) so List's `++` / `HAppend` instance is available + on `Program`. With `def`, `seqComp` below would fail to elaborate. -/ +abbrev Program : Type := List Instruction /-! ## Helper Functions -/ @@ -210,24 +222,33 @@ theorem nop_preserves_most_state (s : ProgramState) : Memory.eq s.memory s'.memory ∧ s.registers = s'.registers ∧ s.ioState = s'.ioState := by - unfold eval step - simp [Memory.eq] + -- eval [.nop] s = eval [] (step s .nop) = step s .nop = {s with pc := s.pc+1} + -- So memory, registers, ioState are all syntactically unchanged. + refine ⟨?_, rfl, rfl⟩ + intro addr + rfl -/-- Halt is a perfect CNO -/ +/-- Halt is a perfect CNO. + `eval [.halt] s` reduces definitionally to `s` (halt's step returns the + state unchanged, then `eval []` is identity), so each conjunct is + discharged by `rfl`-style reasoning. -/ theorem halt_is_cno : isCNO [.halt] := by - unfold isCNO - constructor + refine ⟨?_, ?_, ?_, ?_⟩ · intro s; exact terminates_always [.halt] s - constructor · intro s - unfold ProgramState.eq eval step - simp [Memory.eq] - constructor + -- ProgramState.eq (eval [.halt] s) s ≡ Memory.eq ∧ regs= ∧ io= ∧ pc= + refine ⟨?_, rfl, rfl, rfl⟩ + intro addr + rfl · intro s - unfold pure noIO noMemoryAlloc eval step - simp [Memory.eq] - · unfold thermodynamicallyReversible energyDissipated - intro s; rfl + -- pure s (eval [.halt] s) = noIO ∧ noMemoryAlloc + refine ⟨rfl, ?_⟩ + intro addr + rfl + · -- thermodynamicallyReversible: ∀ s, energyDissipated _ _ _ = 0, and + -- energyDissipated is defined as the constant 0. + intro s + rfl /-! ## CNO Properties -/ @@ -253,17 +274,27 @@ theorem cno_reversible (p : Program) (h : isCNO p) : /-! ## Composition -/ -/-- Sequential composition of programs -/ -def seqComp (p1 p2 : Program) : Program := p1 ++ p2 - -/-- Evaluation of composition -/ +/-- Sequential composition of programs. + `abbrev` (not `def`) so that `eval_seqComp` rewrites also fire when + the goal mentions the underlying `++` directly (downstream callers + in `CNOCategory.composeMorphisms` build the program with `++` and + rely on this transparency). -/ +abbrev seqComp (p1 p2 : Program) : Program := p1 ++ p2 + +/-- Evaluation of composition. + `unfold eval` unfolds the LHS one step but leaves the RHS in its + folded form, producing an apparent type mismatch. Use `show` to put + both sides into the same canonical shape, then the induction + hypothesis applies directly. -/ theorem eval_seqComp (p1 p2 : Program) (s : ProgramState) : eval (seqComp p1 p2) s = eval p2 (eval p1 s) := by unfold seqComp induction p1 generalizing s with | nil => rfl | cons i is ih => - unfold eval + -- LHS = eval (i :: is ++ p2) s = eval (is ++ p2) (step s i) + -- RHS = eval p2 (eval (i :: is) s) = eval p2 (eval is (step s i)) + show eval (is ++ p2) (step s i) = eval p2 (eval is (step s i)) exact ih (step s i) /-- State equality is transitive -/ @@ -308,9 +339,10 @@ theorem cno_composition (p1 p2 : Program) (h1 : isCNO p1) (h2 : isCNO p2) : -- p1 maps s to itself, so eval p1 s = s (by i1) -- p2 maps (eval p1 s) to itself, so eval p2 (eval p1 s) = eval p1 s (by i2) -- Therefore eval p2 (eval p1 s) = s by transitivity - have h1_eq := i1 s - have h2_eq := i2 (eval p1 s) - exact state_eq_trans s (eval p1 s) (eval p2 (eval p1 s)) h1_eq h2_eq + have h1_eq := i1 s -- ProgramState.eq (eval p1 s) s + have h2_eq := i2 (eval p1 s) -- ProgramState.eq (eval p2 (eval p1 s)) (eval p1 s) + -- Want: ProgramState.eq (eval p2 (eval p1 s)) s. Chain h2_eq then h1_eq. + exact state_eq_trans (eval p2 (eval p1 s)) (eval p1 s) s h2_eq h1_eq constructor · intro s rw [eval_seqComp] @@ -350,22 +382,127 @@ theorem triple_rotation_identity (n : Nat) : def loadStoreSame (addr : Nat) : Program := [.load addr 0, .store addr 0] -/-- This preserves memory -/ +/- ── Helper lemmas for loadStore_preserves_memory ────────────────────────── + + These three private theorems establish the round-trip property of + `setReg`/`getReg` for register index 0 and the no-op character of + `Memory.update m addr (m addr)`. They are the rewrite-lemma layer + mentioned in the DEFERRED comment below. + + `setReg_cons_zero` and `getReg_cons_zero` make `simp` able to compute + through the match chains in `setReg`/`getReg` (which are `def`, not + `abbrev`, so are otherwise opaque to the simp normal-form engine). + + `Memory.update_same_pointwise` is the key identity-update fact: writing + the value already stored at an address is a no-op, point-wise. -/ + +private theorem setReg_cons_zero (r val : Nat) (rs : List Nat) : + setReg (r :: rs) 0 val = val :: rs := by + unfold setReg + rfl + +private theorem getReg_cons_zero (val : Nat) (rs : List Nat) : + getReg (val :: rs) 0 = some val := by + unfold getReg + rfl + +/-- Writing the value already at `addr` back to `addr` is a pointwise no-op. -/ +private theorem Memory.update_same_pointwise (m : Memory) (addr a : Nat) : + Memory.update m addr (m addr) a = m a := by + unfold Memory.update + -- The branch condition is `a == addr : Bool`. We case-split on whether + -- `a` and `addr` are propositionally equal, then close each sub-goal. + by_cases h : a = addr + · -- Equal branch: write m addr back → still m addr = m a (since a = addr). + subst h + -- After substitution: `(if addr == addr then m addr else m addr) = m addr`. + simp + · -- Unequal branch: the if-branch is skipped, result is m a. + have hne : (a == addr) = false := by simp [h] + simp [hne] + +/-- This preserves memory. + + Proof strategy (rewrite-lemma layer): + - `load addr 0` puts `s.memory addr` into register 0; because + `loadStoreSame` only executes on a concrete two-instruction list, + we can `show` the definitionally-equal fully-reduced form of + `eval (loadStoreSame addr) s` and work on that directly. + - We then case-split on `s.registers`: + nil → `setReg [] 0 _ = []`, `getReg [] 0 = none`, so the + store instruction takes the `none` branch and leaves + memory untouched. + cons → `setReg_cons_zero` + `getReg_cons_zero` give the round-trip + `getReg (setReg (r :: rs) 0 v) 0 = some v`; the store + then writes `Memory.update s.memory addr (s.memory addr)`, + which equals `s.memory` pointwise by + `Memory.update_same_pointwise`. + - No proof holes. -/ theorem loadStore_preserves_memory (addr : Nat) (s : ProgramState) : let s' := eval (loadStoreSame addr) s Memory.eq s.memory s'.memory := by - unfold loadStoreSame eval step - simp [Memory.eq, Memory.update, setReg, getReg] - intro a - by_cases h : a = addr - · simp [h] - · simp [h] - -/-! ## Decidability and Complexity -/ - -/-- Question: Is CNO verification decidable? -/ -/-- For finite programs with bounded execution, yes. -/ -/-- For arbitrary programs, this reduces to the halting problem. -/ + -- Reduce `eval (loadStoreSame addr) s` to its fully-computed form. + -- `loadStoreSame addr = [.load addr 0, .store addr 0]` and `eval` on a + -- concrete two-instruction list is definitionally: + -- eval [l, st] s = step (step s l) st + -- so `show` restates the goal at that fully-reduced type. + show Memory.eq s.memory + (step (step s (.load addr 0)) (.store addr 0)).memory + -- Unfold both steps explicitly. + -- step s (.load addr 0) + -- = { s with registers := setReg s.registers 0 (s.memory addr), + -- pc := s.pc + 1 } [call this s_mid] + -- step s_mid (.store addr 0) + -- = match getReg s_mid.registers 0 with + -- | some v => { s_mid with memory := Memory.update s_mid.memory addr v, + -- pc := s_mid.pc + 1 } + -- | none => s_mid + -- s_mid.registers = setReg s.registers 0 (s.memory addr) + -- s_mid.memory = s.memory + -- Unfolding `step` leaves struct-literal field projections. + -- `simp only []` applies pure definitional (ι) reductions — specifically, + -- it reduces struct-literal field accesses like + -- `{ s with registers := X }.registers ↝ X` + -- without unfolding any user-defined `def`. + unfold step + simp only [] + -- Now case-split on s.registers to concretise setReg/getReg. + cases s.registers with + | nil => + -- s.registers = [] + -- setReg [] 0 _ = [] (nil case of setReg's definition, reduces by ι) + -- getReg [] 0 = [].get? 0 = none (idem, plus List.get? on nil) + -- ⟹ the store instruction takes the `none` error branch → leaves + -- memory and registers unchanged. + -- `unfold setReg getReg` expands both defs by their match clauses. + -- ι-reductions then collapse the goal: `[].get? 0 ↝ none`, + -- `match none with ... | none => X ↝ X`, and `.memory` projection + -- happen by definitional equality, so `rfl` closes after `intro a`. + unfold setReg getReg + intro a + rfl + | cons r rs => + -- s.registers = r :: rs + -- setReg (r :: rs) 0 v = v :: rs (setReg_cons_zero) + -- getReg (v :: rs) 0 = some v (getReg_cons_zero) + -- ⟹ store writes Memory.update s.memory addr (s.memory addr), + -- which equals s.memory pointwise (Memory.update_same_pointwise). + -- + -- After the two rewrites the match scrutinee is `some (s.memory addr)`. + -- `simp only []` applies the ι (constructor-match) reduction to resolve + -- it to the `some` arm, and then reduces the resulting struct-literal + -- `.memory` field access. The goal is then: + -- Memory.eq s.memory (Memory.update s.memory addr (s.memory addr)) + rw [setReg_cons_zero, getReg_cons_zero] + simp only [] + intro a + exact (Memory.update_same_pointwise s.memory addr a).symm + +/-! ## Decidability and Complexity + + Question: Is CNO verification decidable? + For finite programs with bounded execution, yes. + For arbitrary programs, this reduces to the halting problem. -/ /-- Complexity measure -/ def complexity (i : Instruction) : Nat := diff --git a/absolute-zero/proofs/lean4/CNOCategory.lean b/absolute-zero/proofs/lean4/CNOCategory.lean index 79c6d85..9331378 100644 --- a/absolute-zero/proofs/lean4/CNOCategory.lean +++ b/absolute-zero/proofs/lean4/CNOCategory.lean @@ -5,7 +5,7 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 -/ import CNO @@ -65,39 +65,58 @@ def idMorphism (s : CNO.ProgramState) : ProgramMorphism s s := evaluates := by unfold CNO.eval; rfl } -/-- Extensional equality for ProgramMorphism -/ -theorem ProgramMorphism.ext {s1 s2 : CNO.ProgramState} - (m1 m2 : ProgramMorphism s1 s2) - (h : m1.program = m2.program) : m1 = m2 := by - cases m1; cases m2 - simp at h - subst h - rfl - -/-- Programs form a category -/ +/-- Programs form a category. + + `id := fun {A} => idMorphism A`: the class field expects a function + with an *implicit* binder `∀ {A}, Hom A A`, but `idMorphism` takes + an *explicit* `(s : ProgramState)`. The implicit-lambda wrapper + bridges the two; bare `id := idMorphism` triggers + "implicit-lambda introduced A✝" and then a type mismatch under v4.16. + + The three category laws reduce, via the structure projections, to + laws on `List Instruction` (`++`): + - `compose_assoc` ↦ `List.append_assoc` + - `compose_id_left` ↦ `List.append_nil` (right-id of ++) + - `compose_id_right` ↦ `List.nil_append` (left-id of ++) + The proofs are in Prop and proof-irrelevant, so structural equality + of the morphism records reduces to equality of the program field. -/ instance ProgramCategory : Category where Obj := CNO.ProgramState Hom := ProgramMorphism compose := @composeMorphisms - id := idMorphism + id := fun {A} => idMorphism A compose_assoc := by intro A B C D h g f - apply ProgramMorphism.ext - show (f.program ++ g.program) ++ h.program = f.program ++ (g.program ++ h.program) - exact List.append_assoc f.program g.program h.program + -- LHS.program = (f.program ++ g.program) ++ h.program + -- RHS.program = f.program ++ (g.program ++ h.program) + cases h with | mk hp he => + cases g with | mk gp ge => + cases f with | mk fp fe => + show composeMorphisms ⟨hp, he⟩ (composeMorphisms ⟨gp, ge⟩ ⟨fp, fe⟩) = + composeMorphisms (composeMorphisms ⟨hp, he⟩ ⟨gp, ge⟩) ⟨fp, fe⟩ + simp only [composeMorphisms] + congr 1 + exact List.append_assoc fp gp hp compose_id_left := by intro A B f - apply ProgramMorphism.ext - show f.program ++ [] = f.program - exact List.append_nil f.program + -- composeMorphisms id f has program := f.program ++ [].program = f.program ++ [] + cases f with | mk fp fe => + show composeMorphisms (idMorphism B) ⟨fp, fe⟩ = ⟨fp, fe⟩ + simp only [composeMorphisms, idMorphism] + congr 1 + exact List.append_nil fp compose_id_right := by intro A B f - apply ProgramMorphism.ext - show [] ++ f.program = f.program - exact List.nil_append f.program + -- composeMorphisms f id has program := [].program ++ f.program = [] ++ f.program + -- which reduces to f.program by the cons-recursion of ++ + cases f with | mk fp fe => + show composeMorphisms ⟨fp, fe⟩ (idMorphism A) = ⟨fp, fe⟩ + simp only [composeMorphisms, idMorphism] + -- [] ++ fp ≡ fp definitionally + rfl /-! ## Categorical CNO Definition -/ @@ -113,7 +132,17 @@ def programIsCNOCategorical (p : CNO.Program) (s : CNO.ProgramState) : Prop := /-! ## Equivalence of Definitions -/ -/-- Categorical CNO definition is equivalent to our original -/ +/-- Categorical CNO definition is equivalent to our original. + + Reverse direction: from `∀ s s', eval p s = s' → ProgramState.eq s' s` + we recover the four conjuncts of `CNO.isCNO`: + - `terminates p s` is unconditional (`terminates_always`). + - state preservation is the hypothesis specialised at `eval p s`. + - `pure s (eval p s)` follows because `ProgramState.eq` includes + equality of `ioState` and `Memory.eq` of `memory` — exactly what + `noIO` and `noMemoryAlloc` need (.symm to flip direction). + - `thermodynamicallyReversible` reduces to `0 = 0` (the model's + `energyDissipated` is the constant 0). -/ theorem cno_categorical_equiv (p : CNO.Program) : CNO.isCNO p ↔ (∀ s s', CNO.eval p s = s' → CNO.ProgramState.eq s' s) := by constructor @@ -122,33 +151,50 @@ theorem cno_categorical_equiv (p : CNO.Program) : rw [← h_eval] exact h_id · intro h - unfold CNO.isCNO - constructor + refine ⟨?_, ?_, ?_, ?_⟩ · intro s; exact CNO.terminates_always p s - constructor - · intro s - exact h s (CNO.eval p s) rfl - constructor + · intro s; exact h s (CNO.eval p s) rfl · intro s - have h_eq := h s (CNO.eval p s) rfl - unfold CNO.pure CNO.noIO CNO.noMemoryAlloc - exact ⟨h_eq.2.2.1, h_eq.1⟩ + have hs := h s (CNO.eval p s) rfl + -- hs : ProgramState.eq (eval p s) s, decomposed as (mem, regs, io, pc) + refine ⟨?_, ?_⟩ + · -- noIO s (eval p s) := s.ioState = (eval p s).ioState + unfold CNO.noIO + exact hs.2.2.1.symm + · -- noMemoryAlloc s (eval p s) := Memory.eq s.memory (eval p s).memory + unfold CNO.noMemoryAlloc CNO.Memory.eq + intro addr + exact (hs.1 addr).symm · unfold CNO.thermodynamicallyReversible CNO.energyDissipated intro s; rfl /-! ## Functors -/ -/-- A functor maps between categories, preserving structure -/ -class Functor (C D : Category) where +/-- A functor maps between categories, preserving structure. + + Renamed from `Functor` to `CatFunctor` because Lean's core + `Init.Functor` (`class Functor (f : Type u → Type v)`) shadows our + binding when we apply it to a `Category` term — Lean tries to + unify `Category : Type 1` with `Type u → Type v` and fails. + + The third parameter binder is `{X Y Z}` rather than `{A B C}` to + avoid shadowing the outer Category-typed `C` (the original + `{A B C : C.Obj}` binding silently re-binds `C` inside the type + `C.Hom B C`, breaking field resolution). -/ +class CatFunctor (C D : Category) where fobj : C.Obj → D.Obj fmap : ∀ {A B : C.Obj}, C.Hom A B → D.Hom (fobj A) (fobj B) fmap_id : ∀ {A : C.Obj}, fmap (@Category.id C A) = @Category.id D (fobj A) - fmap_compose : ∀ {A B C : C.Obj} (g : C.Hom B C) (f : C.Hom A B), - fmap (g ∘ f) = fmap g ∘ fmap f + -- The `∘` notation routes through `Category.compose` via instance + -- resolution, but `C`/`D` here are bound *terms* of type Category, + -- not class instances — so `g ∘ f` cannot find them. Spell the + -- composition explicitly through field projections. + fmap_compose : ∀ {X Y Z : C.Obj} (g : C.Hom Y Z) (f : C.Hom X Y), + fmap (C.compose g f) = D.compose (fmap g) (fmap f) /-- CNOs are preserved by functors -/ -theorem functor_preserves_cno (C D : Category) (F : Functor C D) +theorem functor_preserves_cno (C D : Category) (F : CatFunctor C D) (s : C.Obj) (m : C.Hom s s) : isCNOCategorical m → isCNOCategorical (F.fmap m) := by @@ -159,37 +205,58 @@ theorem functor_preserves_cno (C D : Category) (F : Functor C D) /-! ## Model Independence -/ -/-- Different computational models can be categories -/ +/-- Different computational models can be categories. + + Pre-existing direction bug: original wrote `F.fmap (G.fmap m)` for + `m : C.Hom s s`, but `G : D ⟶ C` so `G.fmap` consumes `D.Hom`, not + `C.Hom`. The round-trip that respects the types is + `G.fmap (F.fmap m)`: push `m` through `F` to land in `D`, then + pull back through `G` to land in `C` again. -/ def CNOEquivalent (C D : Category) : Prop := - ∃ (F : Functor C D) (G : Functor D C), + ∃ (F : CatFunctor C D) (G : CatFunctor D C), ∀ (s : C.Obj) (m : C.Hom s s), isCNOCategorical m ↔ - isCNOCategorical (F.fmap (G.fmap m)) - -/-- Main Universal Theorem: CNO property is model-independent - For any CNO in C, the functor F maps it to a CNO in D -/ -theorem cno_model_independent (C D : Category) (F : Functor C D) : - ∀ (s : C.Obj) (m : C.Hom s s), - isCNOCategorical m → - isCNOCategorical (F.fmap m) := by - intro s m h_cno - exact functor_preserves_cno C D F s m h_cno + isCNOCategorical (G.fmap (F.fmap m)) + +/-- Main Universal Theorem: CNO property is model-independent. + + The original statement was type-incorrect: it took `s : C.Obj` and + then quantified `m' : D.Hom s s`, but `D.Hom` requires `D.Obj`. The + fix is to existentially produce both the carrier `s' : D.Obj` and + the morphism `m' : D.Hom s' s'` — set `s' := F.fobj s` and + `m' := F.fmap m`. Functoriality (`fmap_id`) then transports the + identity property: `m = C.id` ⟹ `F.fmap m = F.fmap C.id = D.id`. -/ +theorem cno_model_independent (C D : Category) (h_eq : CNOEquivalent C D) + (s : C.Obj) (m : C.Hom s s) (h_cno : isCNOCategorical m) : + ∃ (s' : D.Obj) (m' : D.Hom s' s'), isCNOCategorical m' := by + obtain ⟨F, _G, _h_equiv⟩ := h_eq + refine ⟨F.fobj s, F.fmap m, ?_⟩ + unfold isCNOCategorical at * + rw [h_cno] + exact F.fmap_id /-! ## Yoneda Perspective -/ /-- CNOs are precisely those elements that correspond to identity - under the Yoneda embedding -/ + under the Yoneda embedding. + + The body uses `C.compose m f` directly: as in `CatFunctor`, the + `∘` notation cannot resolve `Category.compose` against a term-level + `(C : Category)`. -/ theorem yoneda_cno (C : Category) (A : C.Obj) (m : C.Hom A A) : - isCNOCategorical m ↔ ∀ (B : C.Obj) (f : C.Hom B A), m ∘ f = f := by + isCNOCategorical m ↔ (∀ (B : C.Obj) (f : C.Hom B A), C.compose m f = f) := by constructor · intro h_cno B f rw [h_cno] exact C.compose_id_left f · intro h unfold isCNOCategorical - -- Take f = id, then m ∘ id = id + -- Take f = id: `C.compose m C.id = C.id`. Then `compose_id_right` + -- rewrites the LHS to `m`, leaving `this : m = C.id` — exactly + -- the goal (no `.symm` — original code had it because the + -- pre-paren parsing was equating the wrong way around). have := h A C.id rw [C.compose_id_right] at this - exact this.symm + exact this end CNOCategory diff --git a/absolute-zero/proofs/lean4/FilesystemCNO.lean b/absolute-zero/proofs/lean4/FilesystemCNO.lean index 40b7648..122c700 100644 --- a/absolute-zero/proofs/lean4/FilesystemCNO.lean +++ b/absolute-zero/proofs/lean4/FilesystemCNO.lean @@ -5,17 +5,18 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero (integrating Valence Shell) - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 -/ -import Std.Data.List.Basic +-- Std.Data.List.Basic was vestigial in pre-Batteries layouts. The List +-- type used here comes from core Lean 4's Init; no external imports required. namespace FilesystemCNO /-! ## Filesystem Model -/ -/-- File paths -/ -def Path : Type := String +/-- File paths. `abbrev` so String's Repr/BEq propagate. -/ +abbrev Path : Type := String /-- File permissions (simplified) -/ inductive Permission where @@ -24,10 +25,11 @@ inductive Permission where | Execute : Permission deriving Repr, BEq -def PermSet : Type := List Permission +/-- Set of permissions on a file. `abbrev` so List instances propagate. -/ +abbrev PermSet : Type := List Permission -/-- File content -/ -def FileContent : Type := List Nat -- Byte array +/-- File content (byte array). `abbrev` so List instances propagate. -/ +abbrev FileContent : Type := List Nat /-- Filesystem metadata -/ structure FileMetadata where @@ -44,75 +46,91 @@ inductive FileEntry where | Symlink : Path → Path → FileMetadata → FileEntry deriving Repr -/-- Filesystem state -/ -def Filesystem : Type := List FileEntry +/-- Filesystem state. `abbrev` so List instances propagate. -/ +abbrev Filesystem : Type := List FileEntry /-! ## Filesystem Operations -/ /-- Create directory -/ +-- AXIOM: mkdir; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom mkdir : Path → Filesystem → Filesystem /-- Remove directory -/ +-- AXIOM: rmdir; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom rmdir : Path → Filesystem → Filesystem /-- Create file -/ +-- AXIOM: create; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom create : Path → Filesystem → Filesystem /-- Delete file -/ +-- AXIOM: unlink; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom unlink : Path → Filesystem → Filesystem /-- Read file content -/ +-- AXIOM: readFile; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom readFile : Path → Filesystem → Option FileContent /-- Write file content -/ +-- AXIOM: writeFile; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom writeFile : Path → FileContent → Filesystem → Filesystem /-- Get file metadata -/ +-- AXIOM: stat; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom stat : Path → Filesystem → Option FileMetadata /-- Change permissions -/ +-- AXIOM: chmod; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom chmod : Path → PermSet → Filesystem → Filesystem /-- Change owner -/ +-- AXIOM: chown; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom chown : Path → Nat → Filesystem → Filesystem /-- Rename/move file -/ +-- AXIOM: rename; opaque POSIX primitive op; §(c) per docs/proof-debt.md. axiom rename : Path → Path → Filesystem → Filesystem /-! ## Operation Axioms -/ /-- mkdir followed by rmdir is identity -/ +-- AXIOM: mkdir_rmdir_inverse; POSIX-semantics specification (mirrors Coq); §(c) per docs/proof-debt.md. axiom mkdir_rmdir_inverse (p : Path) (fs : Filesystem) : -- Precondition: p doesn't exist rmdir p (mkdir p fs) = fs /-- create followed by unlink is identity -/ +-- AXIOM: create_unlink_inverse; POSIX-semantics specification (mirrors Coq); §(c) per docs/proof-debt.md. axiom create_unlink_inverse (p : Path) (fs : Filesystem) : unlink p (create p fs) = fs /-- read followed by write is identity -/ +-- AXIOM: read_write_identity; POSIX-semantics specification (mirrors Coq); §(c) per docs/proof-debt.md. axiom read_write_identity (p : Path) (fs : Filesystem) (content : FileContent) : readFile p fs = some content → writeFile p content fs = fs /-- chmod to current permissions is identity -/ +-- AXIOM: chmod_identity; POSIX-semantics specification (mirrors Coq); §(c) per docs/proof-debt.md. axiom chmod_identity (p : Path) (fs : Filesystem) (meta : FileMetadata) : stat p fs = some meta → chmod p meta.permissions fs = fs /-- rename to same path is identity -/ +-- AXIOM: rename_identity; POSIX-semantics specification (mirrors Coq); §(c) per docs/proof-debt.md. axiom rename_identity (p : Path) (fs : Filesystem) : rename p p fs = fs /-- rename A to B followed by rename B to A is identity -/ +-- AXIOM: rename_inverse; POSIX-semantics specification (mirrors Coq); §(c) per docs/proof-debt.md. axiom rename_inverse (p1 p2 : Path) (fs : Filesystem) : p1 ≠ p2 → rename p2 p1 (rename p1 p2 fs) = fs /-! ## Filesystem CNO Definition -/ -/-- A filesystem operation -/ -def FsOp : Type := Filesystem → Filesystem +/-- A filesystem operation. `abbrev` so HAppend / fn instances propagate. -/ +abbrev FsOp : Type := Filesystem → Filesystem /-- A filesystem operation is a CNO if it leaves filesystem unchanged -/ def isFsCNO (op : FsOp) : Prop := @@ -128,8 +146,8 @@ theorem fs_nop_is_cno : isFsCNO fs_nop := by intro fs rfl -/-- mkdir followed by rmdir -/ -def mkdirRmdirOp (p : Path) : FsOp := +/-- mkdir followed by rmdir. `noncomputable` — calls axioms `mkdir`/`rmdir`. -/ +noncomputable def mkdirRmdirOp (p : Path) : FsOp := fun fs => rmdir p (mkdir p fs) theorem mkdir_rmdir_is_cno (p : Path) : @@ -138,8 +156,8 @@ theorem mkdir_rmdir_is_cno (p : Path) : intro fs exact mkdir_rmdir_inverse p fs -/-- create followed by unlink -/ -def createUnlinkOp (p : Path) : FsOp := +/-- create followed by unlink. `noncomputable` — wraps axioms. -/ +noncomputable def createUnlinkOp (p : Path) : FsOp := fun fs => unlink p (create p fs) theorem create_unlink_is_cno (p : Path) : @@ -148,8 +166,8 @@ theorem create_unlink_is_cno (p : Path) : intro fs exact create_unlink_inverse p fs -/-- read followed by write -/ -def readWriteOp (p : Path) : FsOp := +/-- read followed by write. `noncomputable` — wraps axioms. -/ +noncomputable def readWriteOp (p : Path) : FsOp := fun fs => match readFile p fs with | some content => writeFile p content fs @@ -164,8 +182,8 @@ theorem read_write_is_cno (p : Path) : | some content => exact read_write_identity p fs content h -/-- chmod to current permissions -/ -def chmodNopOp (p : Path) : FsOp := +/-- chmod to current permissions. `noncomputable` — wraps axioms. -/ +noncomputable def chmodNopOp (p : Path) : FsOp := fun fs => match stat p fs with | some meta => chmod p meta.permissions fs @@ -180,8 +198,8 @@ theorem chmod_nop_is_cno (p : Path) : | some meta => exact chmod_identity p fs meta h -/-- rename to same path -/ -def renameNopOp (p : Path) : FsOp := +/-- rename to same path. `noncomputable` — wraps axiom. -/ +noncomputable def renameNopOp (p : Path) : FsOp := fun fs => rename p p fs theorem rename_nop_is_cno (p : Path) : @@ -214,9 +232,6 @@ theorem fs_cno_composition (op1 op2 : FsOp) : /-- mkdir alone is NOT a CNO -/ axiom mkdir_not_identity : ∃ (p : Path) (fs : Filesystem), mkdir p fs ≠ fs -/-- mkdir with a specific path is not identity -/ -axiom mkdir_test_not_identity : ∃ (fs : Filesystem), mkdir "test" fs ≠ fs - theorem mkdir_alone_not_cno : ¬ (∀ p, isFsCNO (fun fs => mkdir p fs)) := by intro h @@ -262,16 +277,20 @@ example (p : Path) : /-! ## Snapshot and Restore -/ /-- Snapshot operation -/ +-- AXIOM: snapshot; opaque snapshot primitive; §(c) per docs/proof-debt.md. axiom snapshot : Filesystem → Filesystem /-- Restore from snapshot -/ +-- AXIOM: restore; opaque restore primitive; §(c) per docs/proof-debt.md. axiom restore : Filesystem → Filesystem → Filesystem /-- snapshot followed by restore is identity -/ axiom snapshot_restore_identity (fs : Filesystem) : restore (snapshot fs) fs = fs -def snapshotRestoreOp : FsOp := +-- `noncomputable` because `restore` and `snapshot` are axioms with no +-- executable body; without this Lean 4.16 refuses to emit code for `def`. +noncomputable def snapshotRestoreOp : FsOp := fun fs => restore (snapshot fs) fs theorem snapshot_restore_is_cno : @@ -290,14 +309,18 @@ def isIdempotent (op : FsOp) : Prop := axiom mkdir_idempotent (p : Path) : isIdempotent (fun fs => mkdir p fs) -/-- Idempotent does NOT imply CNO -/ +/-- Idempotent does NOT imply CNO. + Proof: destructure mkdir_not_identity to get a specific (p, fs) where + mkdir p fs ≠ fs, then exhibit `fun fs => mkdir p fs` as the witness. + It is idempotent (mkdir_idempotent), but it cannot be a CNO: if it were, + applying it to fs would leave fs unchanged, contradicting h_neq. -/ example : ∃ op : FsOp, isIdempotent op ∧ ¬ isFsCNO op := by - exists (fun fs => mkdir "test" fs) + obtain ⟨p, fs, h_neq⟩ := mkdir_not_identity + exists (fun fs' => mkdir p fs') constructor - · exact mkdir_idempotent "test" + · exact mkdir_idempotent p · intro h unfold isFsCNO at h - obtain ⟨fs, h_neq⟩ := mkdir_test_not_identity exact h_neq (h fs) end FilesystemCNO diff --git a/absolute-zero/proofs/lean4/LambdaCNO.lean b/absolute-zero/proofs/lean4/LambdaCNO.lean index cf62929..066c61e 100644 --- a/absolute-zero/proofs/lean4/LambdaCNO.lean +++ b/absolute-zero/proofs/lean4/LambdaCNO.lean @@ -7,7 +7,7 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 -/ namespace LambdaCNO @@ -123,7 +123,7 @@ theorem lambda_id_normal_form : isNormalForm lambda_id := by | beta_abs _ _ h' => cases h' /-- lambda_id is a CNO: for arguments in normal form, it terminates and acts as identity -/ -theorem lambda_id_is_cno_on_values : isLambdaCNO lambda_id := by +theorem lambda_id_is_cno : isLambdaCNO lambda_id := by unfold isLambdaCNO lambda_id intro arg h_nf constructor @@ -190,25 +190,6 @@ axiom subst_closed_term (t s : LambdaTerm) (n : Nat) : def lambda_compose (f g : LambdaTerm) : LambdaTerm := LAbs (LApp f (LApp g (LVar 0))) -/-- Composition of weak lambda CNOs yields a weak CNO. - Requires f and g to be closed (standard for combinators). -/ -theorem lambda_cno_composition_weak (f g : LambdaTerm) - (hf_closed : Closed f 0) (hg_closed : Closed g 0) : - isLambdaCNOWeak f → - isLambdaCNOWeak g → - isLambdaCNOWeak (lambda_compose f g) := by - intro hf hg - unfold isLambdaCNOWeak at * - intro arg - -- (λx. f (g x)) arg →β subst 0 arg (f (g (LVar 0))) = f (g arg) - apply BetaReduceStar.beta_step - · apply BetaReduce.beta_app - · simp [subst, subst_closed_term f arg 0 hf_closed, subst_closed_term g arg 0 hg_closed] - have hg_arg := hg arg - have h_congr := BetaReduceStar_app_right f (LApp g arg) arg hg_arg - have hf_arg := hf arg - exact BetaReduceStar_trans _ _ _ h_congr hf_arg - /-- Composition of lambda CNOs yields a CNO. For arguments in normal form: compose applies g then f, both of which terminate and return the original argument. -/ @@ -248,6 +229,9 @@ def y_combinator : LambdaTerm := /-- Y is NOT a CNO because it doesn't act as identity. Y f reduces to f (Y f), not back to f. -/ +-- AXIOM: y_combinator_not_identity; non-termination claim about the Y combinator — +-- requires step-indexed semantics or coinduction to discharge. +-- §(c) NECESSARY AXIOM per docs/proof-debt.md (Lean Lambda triage 2026-05-27). axiom y_combinator_not_identity : ¬ BetaReduceStar (LApp y_combinator lambda_id) lambda_id @@ -274,23 +258,12 @@ example : BetaReduceStar (LApp church_zero church_zero) (LAbs (LVar 0)) := by /-! ## Eta Equivalence -/ /-- Eta reduction: (λx. f x) ≡ f -/ +-- AXIOM: eta_equivalence; η-equivalence is not derivable under β-only reduction — +-- requires an extra reduction rule or extensional equality. +-- §(c) NECESSARY AXIOM per docs/proof-debt.md (Lean Lambda triage 2026-05-27). axiom eta_equivalence (f : LambdaTerm) : BetaReduceStar (LAbs (LApp f (LVar 0))) f -/-- Eta-expanded identity acts as identity (weak version) -/ -theorem eta_expanded_id_is_cno_weak : - isLambdaCNOWeak (LAbs (LApp lambda_id (LVar 0))) := by - unfold isLambdaCNOWeak - intro arg - -- (λx. (λy.y) x) arg →β (λy.y) arg →β arg - apply BetaReduceStar.beta_step - · apply BetaReduce.beta_app - · simp [subst] - apply BetaReduceStar.beta_step - · apply BetaReduce.beta_app - · simp [subst, lambda_id] - apply BetaReduceStar.beta_refl - /-- Eta-expanded identity is a CNO: for arguments in normal form, it terminates and acts as identity -/ theorem eta_expanded_id_is_cno : diff --git a/absolute-zero/proofs/lean4/QuantumCNO.lean b/absolute-zero/proofs/lean4/QuantumCNO.lean index ae28082..8e7322c 100644 --- a/absolute-zero/proofs/lean4/QuantumCNO.lean +++ b/absolute-zero/proofs/lean4/QuantumCNO.lean @@ -5,7 +5,7 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 -/ import Mathlib.Data.Real.Basic @@ -67,19 +67,24 @@ theorem quantum_state_eq_refl (ψ : QuantumState) : ψ =q= ψ := by intro n rfl +/-- Symmetry of the (simplified) quantum-state equality. + + The simplified `quantumStateEq` definition discards `θ`; equality is + purely pointwise on amplitudes. So `(-θ)` is just a placeholder phase + and what we actually need is `(h n).symm` for each component. -/ theorem quantum_state_eq_sym (ψ φ : QuantumState) : - ψ =q= φ → φ =q= ψ := by + (ψ =q= φ) → (φ =q= ψ) := by intro ⟨θ, h⟩ - exists (-θ) - intro n - exact (h n).symm + exact ⟨-θ, fun n => (h n).symm⟩ +/-- Transitivity of the (simplified) quantum-state equality. + + With the placeholder phase, the transitive phase is just the sum and + the pointwise equalities chain via `Eq.trans`. -/ theorem quantum_state_eq_trans (ψ φ χ : QuantumState) : - ψ =q= φ → φ =q= χ → ψ =q= χ := by + (ψ =q= φ) → (φ =q= χ) → (ψ =q= χ) := by intro ⟨θ1, h1⟩ ⟨θ2, h2⟩ - exists (θ1 + θ2) - intro n - rw [h1 n, h2 n] + exact ⟨θ1 + θ2, fun n => (h1 n).trans (h2 n)⟩ /-! ## Quantum CNO Definition -/ @@ -113,19 +118,15 @@ def globalPhaseGate (θ : ℝ) : QuantumGate := theorem global_phase_is_cno (θ : ℝ) : isQuantumCNO (globalPhaseGate θ) := by unfold isQuantumCNO globalPhaseGate - constructor - · -- globalPhaseGate θ is definitionally the identity function, - -- so it trivially preserves inner products - unfold isUnitary + refine ⟨?_, ?_, trivial⟩ + · -- isUnitary: in the simplified spec `globalPhaseGate θ` η-reduces to + -- the identity function `fun ψ => ψ`, so its image under + -- `innerProduct` matches `innerProduct ψ φ` definitionally. intro ψ φ rfl - constructor · intro ψ unfold quantumStateEq - exists θ - intro n - rfl - · trivial + exact ⟨θ, fun _ => rfl⟩ /-! ## Non-CNO Gates -/ @@ -178,12 +179,11 @@ theorem quantum_cno_composition (U V : QuantumGate) : constructor · intro ψ unfold gateCompose - -- V ψ =q= ψ means ∀ n, V ψ n = ψ n, so V ψ = ψ by funext - have hV_eq : V ψ = ψ := by - funext n - exact (hV_id ψ).choose_spec n - rw [hV_eq] - exact hU_id ψ + -- Goal: U (V ψ) =q= ψ. Chain U(Vψ)=q=Vψ (hU_id (V ψ)) with Vψ=q=ψ (hV_id ψ). + -- The original proof-hole comment misdiagnosed the second goal: after + -- `apply quantum_state_eq_trans`, transitivity routes via `V ψ`, so + -- the second leg is just `hV_id ψ`, not a U-rewrite under =q=. + exact quantum_state_eq_trans (U (V ψ)) (V ψ) ψ (hU_id (V ψ)) (hV_id ψ) · trivial /-! ## Quantum Information Theory -/ diff --git a/absolute-zero/proofs/lean4/StatMech.lean b/absolute-zero/proofs/lean4/StatMech.lean index 8fc6d5a..e0f489a 100644 --- a/absolute-zero/proofs/lean4/StatMech.lean +++ b/absolute-zero/proofs/lean4/StatMech.lean @@ -5,7 +5,7 @@ Author: Jonathan D. A. Jewell Project: Absolute Zero - License: AGPL-3.0 / Palimpsest 0.5 + License: MPL-2.0 -/ import CNO @@ -58,27 +58,32 @@ axiom shannon_entropy_nonneg (P : StateDistribution) : axiom shannon_entropy_point_zero (s : CNO.ProgramState) : shannonEntropy (pointDist s) = 0 -/-- Change in entropy -/ -def entropyChange (P_initial P_final : StateDistribution) : ℝ := +/-- Change in entropy. + `noncomputable` because `shannonEntropy` is an axiom of type ℝ; Lean + cannot extract executable code for any definition that touches it. -/ +noncomputable def entropyChange (P_initial P_final : StateDistribution) : ℝ := shannonEntropy P_final - shannonEntropy P_initial /-! ## Thermodynamic Entropy -/ -/-- Boltzmann entropy: S = kB ln(2) H -/ -def boltzmannEntropy (P : StateDistribution) : ℝ := +/-- Boltzmann entropy: S = kB ln(2) H. + `noncomputable` — uses `Real.log` (no executable code). -/ +noncomputable def boltzmannEntropy (P : StateDistribution) : ℝ := kB * log 2 * shannonEntropy P -/-- Boltzmann entropy is non-negative -/ +/-- Boltzmann entropy is non-negative. + + `kB * log 2 * shannonEntropy P` is a product of three non-negative + reals: `kB > 0` (axiom), `log 2 > 0` (`Real.log_pos` since 1 < 2), + `shannonEntropy P ≥ 0` (axiom). -/ theorem boltzmann_entropy_nonneg (P : StateDistribution) : boltzmannEntropy P ≥ 0 := by unfold boltzmannEntropy - -- kB > 0, log 2 > 0, shannonEntropy P >= 0 - -- Product of non-negatives is non-negative - apply mul_nonneg - · apply mul_nonneg - · exact le_of_lt kB_positive - · exact le_of_lt (Real.log_pos (by norm_num : (1 : ℝ) < 2)) - · exact shannon_entropy_nonneg P + have h_kB : (0 : ℝ) ≤ kB := le_of_lt kB_positive + have h_log2 : (0 : ℝ) ≤ Real.log 2 := + le_of_lt (Real.log_pos (by norm_num : (1 : ℝ) < 2)) + have h_H : (0 : ℝ) ≤ shannonEntropy P := shannon_entropy_nonneg P + exact mul_nonneg (mul_nonneg h_kB h_log2) h_H /-! ## Landauer's Principle -/ @@ -92,25 +97,37 @@ axiom landauer_principle (P_initial P_final : StateDistribution) : ΔS < 0 → energyDissipatedPhys P_initial P_final ≥ kB * temperature * log 2 * (-ΔS) -/-- Landauer limit (energy per bit erased) -/ -def landauer_limit : ℝ := kB * temperature * log 2 +/-- Landauer limit (energy per bit erased). + `noncomputable` — `kB` and `temperature` are real-valued axioms. -/ +noncomputable def landauer_limit : ℝ := kB * temperature * log 2 /-! ## CNO Thermodynamics -/ /-- Distribution after program execution -/ axiom postExecutionDist : CNO.Program → StateDistribution → StateDistribution -/-- State-preserving programs preserve distributions -/ -axiom state_preserving_dist (p : CNO.Program) (P : StateDistribution) : - (∀ s, CNO.ProgramState.eq (CNO.eval p s) s) → +/-- The mechanism connecting `postExecutionDist` to per-state semantics. + `postExecutionDist` is an axiom in this model — without an axiom + that ties it to actual program behaviour, no result of the form + "running a state-preserving program leaves the distribution alone" + can be proved. This axiom states the minimum required link: + a program that pointwise preserves states leaves the distribution + fixed. -/ +axiom postExecutionDist_id_of_state_preserving + (p : CNO.Program) (P : StateDistribution) + (h : ∀ s, CNO.ProgramState.eq (CNO.eval p s) s) : postExecutionDist p P = P -/-- CNOs preserve Shannon entropy -/ +/-- CNOs preserve Shannon entropy. + + With the `postExecutionDist_id_of_state_preserving` axiom, this is + a trivial rewrite: a CNO is state-preserving by definition, so the + distribution is unchanged, so its entropy is unchanged. -/ theorem cno_preserves_shannon_entropy (p : CNO.Program) (P : StateDistribution) : CNO.isCNO p → shannonEntropy (postExecutionDist p P) = shannonEntropy P := by intro h_cno - rw [state_preserving_dist p P h_cno.2.1] + rw [postExecutionDist_id_of_state_preserving p P h_cno.2.1] /-- Corollary: CNOs have zero entropy change -/ theorem cno_zero_entropy_change (p : CNO.Program) (P : StateDistribution) : @@ -126,13 +143,16 @@ axiom reversible_zero_dissipation (P_initial P_final : StateDistribution) : shannonEntropy P_initial = shannonEntropy P_final → energyDissipatedPhys P_initial P_final = 0 -/-- Main Theorem: CNOs dissipate zero energy -/ +/-- Main Theorem: CNOs dissipate zero energy. + `reversible_zero_dissipation` wants `H P_initial = H P_final`; + `cno_preserves_shannon_entropy` gives the symmetric direction + `H (postExecutionDist p P) = H P`, so `.symm` flips it. -/ theorem cno_zero_energy_dissipation (p : CNO.Program) (P : StateDistribution) : CNO.isCNO p → energyDissipatedPhys P (postExecutionDist p P) = 0 := by intro h_cno apply reversible_zero_dissipation - exact cno_preserves_shannon_entropy p P h_cno + exact (cno_preserves_shannon_entropy p P h_cno).symm /-! ## Bennett's Reversible Computing -/ @@ -142,21 +162,34 @@ def logicallyReversible (p : CNO.Program) : Prop := ∀ s s', CNO.eval p s = s' → CNO.eval p_inv s' = s -/-- ProgramState.eq with eval identity implies eval fixpoint -/ -axiom programState_eq_eval_fixpoint (p : CNO.Program) (s : CNO.ProgramState) : - CNO.ProgramState.eq (CNO.eval p s) s → CNO.eval p s = s - -/-- CNOs are trivially logically reversible -/ +/-- Lift `ProgramState.eq` (componentwise; uses `Memory.eq` pointwise on + the function field) to propositional equality on `ProgramState`. + Memory equality requires `funext` (Lean 4 admits it). -/ +theorem ProgramState_eq_of_state_eq (s1 s2 : CNO.ProgramState) + (h : CNO.ProgramState.eq s1 s2) : s1 = s2 := by + obtain ⟨hmem, hregs, hio, hpc⟩ := h + have hmem_fn : s1.memory = s2.memory := funext hmem + cases s1; cases s2 + congr + +/-- CNOs are trivially logically reversible. + + From `isCNO p` we have `ProgramState.eq (eval p s) s` for every `s`. + Lifting to propositional equality (via `funext` on the memory + function field) gives `eval p s = s`. Then + `eval p s' = eval p (eval p s) = eval p s = s`. -/ theorem cno_logically_reversible (p : CNO.Program) : CNO.isCNO p → logicallyReversible p := by intro h_cno - unfold logicallyReversible - exists p + refine ⟨p, ?_⟩ intro s s' h_eval - -- Since p is a CNO, eval p s = s - have h_id := programState_eq_eval_fixpoint p s (h_cno.2.1 s) - -- s' = eval p s = s, so eval p s' = eval p s = s = s' - rw [← h_eval, h_id] + -- Goal: eval p s' = s + rw [← h_eval] + -- Goal: eval p (eval p s) = s + have h_eq : CNO.eval p s = s := + ProgramState_eq_of_state_eq _ _ (h_cno.2.1 s) + rw [h_eq] + exact h_eq /-! ## Thermodynamic Efficiency -/ diff --git a/absolute-zero/proofs/lean4/lake-manifest.json b/absolute-zero/proofs/lean4/lake-manifest.json new file mode 100644 index 0000000..99c452f --- /dev/null +++ b/absolute-zero/proofs/lean4/lake-manifest.json @@ -0,0 +1,95 @@ +{"version": "1.1.0", + "packagesDir": ".lake/packages", + "packages": + [{"url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "a6276f4c6097675b1cf5ebd49b1146b735f38c02", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.16.0", + "inherited": false, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "1622a8693b31523c8f82db48e01b14c74bc1f155", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.16.0-rc1", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "003ff459cdd85de551f4dcf95cdfeefe10f20531", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "1a6613663c3eb08c401ce0fd1a408412f2c2321e", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "07f60e90998dfd6592688a14cd67bd4e384b77b2", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "v0.0.50", + "inherited": true, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "79402ad9ab4be9a2286701a9880697e2351e4955", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.16.0-rc1", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f0c584bcb14c5adfb53079781eeea75b26ebbd32", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.15.0", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "01006c9e86bf9e397c026fef4190478dd1fd897e", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "0c8ea32a15a4f74143e4e1e107ba2c412adb90fd", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}], + "name": "cno", + "lakeDir": ".lake"} diff --git a/absolute-zero/proofs/lean4/lakefile.lean b/absolute-zero/proofs/lean4/lakefile.lean index f30a7ae..7c8f2fe 100644 --- a/absolute-zero/proofs/lean4/lakefile.lean +++ b/absolute-zero/proofs/lean4/lakefile.lean @@ -2,14 +2,29 @@ import Lake open Lake DSL package cno where - version := "0.1.0" + version := v!"0.1.0" require mathlib from git - "https://github.com/leanprover-community/mathlib4.git" + "https://github.com/leanprover-community/mathlib4.git" @ "v4.16.0" -lean_lib CNO where - -- Core CNO library +-- Each proof file is exposed as its own library so `lake build` covers them +-- all. The `lean_exe absolute_zero` target was dropped — CNO.lean defines no +-- `main`, and the project's surface is theorem verification, not a binary. @[default_target] -lean_exe absolute_zero where - root := `CNO +lean_lib CNO + +@[default_target] +lean_lib CNOCategory + +@[default_target] +lean_lib FilesystemCNO + +@[default_target] +lean_lib LambdaCNO + +@[default_target] +lean_lib QuantumCNO + +@[default_target] +lean_lib StatMech diff --git a/absolute-zero/proofs/lean4/lean-toolchain b/absolute-zero/proofs/lean4/lean-toolchain index 2586f88..8b4f470 100644 --- a/absolute-zero/proofs/lean4/lean-toolchain +++ b/absolute-zero/proofs/lean4/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:v4.16.0 +leanprover/lean4:v4.16.0 \ No newline at end of file diff --git a/absolute-zero/src/AuditTrail.res b/absolute-zero/src/AuditTrail.res deleted file mode 100644 index 39ebc54..0000000 --- a/absolute-zero/src/AuditTrail.res +++ /dev/null @@ -1,49 +0,0 @@ -// AuditTrail.res - DOM annotation for debugging -// Injects data-audit paths into the DOM - -@val @scope("document") -external querySelectorAll: string => array = "querySelectorAll" - -@val @scope("document") -external createElement: string => Dom.element = "createElement" - -@set external setTextContent: (Dom.element, string) => unit = "textContent" -@set external setCssText: ({..}, string) => unit = "cssText" -@get external getStyle: Dom.element => {..} = "style" -@get external getDataset: Dom.element => {..} = "dataset" -@get external getAudit: {..} => Js.nullable = "audit" -@send external appendChild: (Dom.element, Dom.element) => unit = "appendChild" -@set external setPosition: ({..}, string) => unit = "position" - -let annotateAudits = () => { - let elements = querySelectorAll("[data-audit]") - - elements->Array.forEach(el => { - let dataset = el->getDataset - let auditValue = dataset->getAudit - - switch auditValue->Js.Nullable.toOption { - | Some(audit) => { - let tag = createElement("span") - tag->setTextContent(audit) - - let tagStyle = tag->getStyle - tagStyle->setCssText( - "position:absolute; top:0; right:0; font-size:0.6rem; opacity:0.3;", - ) - - let elStyle = el->getStyle - elStyle->setPosition("relative") - - el->appendChild(tag) - } - | None => () - } - }) -} - -// Initialize on DOMContentLoaded -@val @scope("window") -external addEventListener: (string, unit => unit) => unit = "addEventListener" - -let () = addEventListener("DOMContentLoaded", annotateAudits) diff --git a/absolute-zero/src/abi/Layout.idr b/absolute-zero/src/abi/Layout.idr index d033f55..994ed35 100644 --- a/absolute-zero/src/abi/Layout.idr +++ b/absolute-zero/src/abi/Layout.idr @@ -14,6 +14,7 @@ import Data.Bits import Data.So import Data.Vect import AbsoluteZero.ABI.Types +import AbsoluteZero.ABI.Proofs.DivMod %default total @@ -238,27 +239,33 @@ instructionCrossPlatform = InvariantProof -- Alignment Verification -------------------------------------------------------------------------------- -||| Verify that a type's alignment is correct for the platform -public export -verifyAlignment : (p : Platform) -> (t : Type) -> - HasAlignment t n -> So (n `mod` (ptrSize p `div` 8) == 0) --- PROOF_TODO: Replace cast with actual proof -verifyAlignment Linux t (AlignProof {n}) = cast Oh --- PROOF_TODO: Replace cast with actual proof -verifyAlignment Windows t (AlignProof {n}) = cast Oh --- PROOF_TODO: Replace cast with actual proof -verifyAlignment MacOS t (AlignProof {n}) = cast Oh --- PROOF_TODO: Replace cast with actual proof -verifyAlignment BSD t (AlignProof {n}) = cast Oh --- PROOF_TODO: Replace cast with actual proof -verifyAlignment WASM t (AlignProof {n}) = cast Oh - -||| ProgramState alignment is valid on all platforms +-- Historical note (absolute-zero#27): a universally-quantified postulate +-- `alignmentMatchesPlatformWord : HasAlignment t n -> So (n `mod` word == 0)` +-- previously lived here. It was unsound: `AlignProof` carries no evidence +-- about `n`, so the postulate would derive `So (1 `mod` 8 == 0)` from +-- `CNOResultLayout.alignment : HasAlignment CNOVerificationResult 1`. It was +-- removed in favour of per-type decidable claims at each call site. +-- +-- Reduction note: `8 `mod` (ptrSize p `div` 8) == 0` is concretely True +-- on every supported platform (Linux/Windows/MacOS/BSD: 64/8=8, 8 mod 8=0; +-- WASM: 32/8=4, 8 mod 4=0). However, Idris2 0.8.0 will not reduce +-- through `divNat`'s non-covering case at type-level, so a direct `Oh` +-- proof fails to unify. The discharge below uses `believe_me` — +-- distinguished from the deleted unsound postulate in two ways: +-- 1. It is a per-instance claim (n=8 only), not a universal claim; +-- no further consumer can pivot from it to a false proposition. +-- 2. The claim is computationally true; the gap is the typechecker's +-- reduction strategy, not the proposition itself. +-- A clean discharge becomes available once `AbsoluteZero.ABI.Proofs.DivMod` +-- supplies an explicit rewrite from `ptrSize p` to its concrete value. + +||| ProgramState alignment is valid on all platforms. +||| See the note above on why this currently routes through `believe_me` +||| (typechecker reduction, not an axiom about an abstract proposition). public export programStateAlignmentValid : (p : Platform) -> So (8 `mod` (ptrSize p `div` 8) == 0) -programStateAlignmentValid p = - verifyAlignment p ProgramState ProgramStateLayout.alignment +programStateAlignmentValid _ = believe_me () -------------------------------------------------------------------------------- -- Size Calculation Utilities @@ -269,21 +276,12 @@ public export arraySize : HasSize t elemSize -> (n : Nat) -> Nat arraySize _ n = elemSize * n -||| Calculate aligned size (round up to alignment boundary) -public export -alignedSize : (size : Nat) -> (alignment : Nat) -> Nat -alignedSize size align = - let remainder = size `mod` align - in if remainder == 0 - then size - else size + (align - remainder) - -||| Prove that aligned size is a multiple of alignment +||| Calculate aligned size (round up to alignment boundary). +||| Definition and correctness lemma live in `AbsoluteZero.ABI.Proofs.DivMod` +||| (re-exported here for API compatibility). See absolute-zero#27. public export -alignedSizeCorrect : (size : Nat) -> (align : Nat) -> {auto 0 nonZero : So (align /= 0)} -> - So (alignedSize size align `mod` align == 0) --- PROOF_TODO: Replace cast with actual proof -alignedSizeCorrect size align = cast Oh +alignedSize : (size : Nat) -> (align : Nat) -> Nat +alignedSize = DivMod.alignedSize -------------------------------------------------------------------------------- -- Compile-Time Verification diff --git a/absolute-zero/src/abi/Proofs/DivMod.idr b/absolute-zero/src/abi/Proofs/DivMod.idr new file mode 100644 index 0000000..f00cb2f --- /dev/null +++ b/absolute-zero/src/abi/Proofs/DivMod.idr @@ -0,0 +1,119 @@ +||| Div/mod lemma library for ABI alignment proofs. +||| +||| Consolidates the trusted base of number-theoretic lemmas used by ABI +||| layout modules across the hyperpolymath estate (absolute-zero, +||| civic-connect, and any future Idris2 ABI consumers). +||| +||| Design goals: +||| * Single shared module — each estate repo imports the same lemmas +||| rather than re-postulating per file. +||| * Each lemma is an individually-named declaration so it can be +||| discharged incrementally (one proof per audit pass) without +||| touching consumers. +||| * Definitions of the functions the lemmas talk about live here too, +||| so the lemma statements don't drift from their referent. +||| +||| Discharge tracker: absolute-zero#27. +||| +||| Notes on Idris2 0.8.0: +||| * The `postulate` keyword used in older Idris/Agda style code does +||| not parse in current Idris2. The canonical axiom idiom is +||| `name = believe_me ()` — semantically equivalent (asserts a term +||| of the target type with no proof) but explicit at the term level, +||| so every axiom is grep-able as a `believe_me` occurrence in the +||| trusted base. +||| +||| @see https://github.com/hyperpolymath/absolute-zero/issues/27 + +-- SPDX-License-Identifier: MPL-2.0 + +module AbsoluteZero.ABI.Proofs.DivMod + +import Data.So +import Data.Nat + +%default total + +-------------------------------------------------------------------------------- +-- Aligned size +-------------------------------------------------------------------------------- + +||| Round `size` up to the next multiple of `align`. +||| If `size` is already aligned, returns `size` unchanged. +public export +alignedSize : (size : Nat) -> (align : Nat) -> Nat +alignedSize size align = + let remainder = size `mod` align + in if remainder == 0 + then size + else size + (align `minus` remainder) + +-------------------------------------------------------------------------------- +-- Trusted lemma surface +-- +-- Each `believe_me`-based axiom below is an individually-audit-trackable +-- item. Discharge one at a time by replacing the RHS with a real proof; +-- the lemma name and type signature stay stable so consumers don't break. +-- +-- Estate cross-reference (as of 2026-05-20): +-- * civic-connect/src/Abi/Layout.idr defers the same family under +-- `alignUpDivides`, `mkFieldsAligned`, `offsetInBoundsPrf`. Those +-- should migrate to import these names. +-- +-- Discharge path to stdlib: +-- * `divModIdentity` is provable from +-- `Data.Nat.Division.DivisionTheorem` (idris2-contrib): converts +-- `So (d /= 0)` to `NonZero d`, then rewrites between +-- `mod`/`div` (Prelude binary ops) and `modNatNZ`/`divNatNZ`. +-- * `multModZero` follows by induction on `k`. +-- * `addModDistrib` is in `Data.Nat.Equational` territory. +-- * `alignedSizeCorrect` then chains them. +-------------------------------------------------------------------------------- + +||| `alignedSize size align` is always a multiple of `align`. +||| +||| Proof outline (currently asserted; see discharge path above): +||| Let r = size `mod` align. +||| Case r == 0: alignedSize = size, divisible by hypothesis. +||| Case r /= 0: alignedSize = size + (align - r) +||| = ((size `div` align) * align + r) + (align - r) +||| [by divModIdentity] +||| = ((size `div` align) + 1) * align +||| [by Nat ring rewriting] +||| and (k * align) `mod` align = 0 +||| [by multModZero]. +export +alignedSizeCorrect : + (size : Nat) -> (align : Nat) -> + {auto 0 nonZero : So (align /= 0)} -> + So (alignedSize size align `mod` align == 0) +alignedSizeCorrect _ _ = believe_me () + +||| Euclidean division identity: every Nat decomposes as q*d + r. +||| Provable from `Data.Nat.Division.DivisionTheorem` — the conversion +||| between `So (d /= 0)` and `NonZero d`, plus the rewrite between +||| Prelude `mod`/`div` and `modNatNZ`/`divNatNZ`, is the only real work. +export +divModIdentity : + (n : Nat) -> (d : Nat) -> + {auto 0 nonZero : So (d /= 0)} -> + n = (n `div` d) * d + (n `mod` d) +divModIdentity _ _ = believe_me () + +||| Any multiple of `d` is congruent to zero mod `d`. +||| Provable by induction on `k`. +export +multModZero : + (k : Nat) -> (d : Nat) -> + {auto 0 nonZero : So (d /= 0)} -> + So ((k * d) `mod` d == 0) +multModZero _ _ = believe_me () + +||| Mod distributes over addition (in the sense that `(a + b) mod d` is +||| determined by `a mod d` and `b mod d`). +export +addModDistrib : + (a : Nat) -> (b : Nat) -> (d : Nat) -> + {auto 0 nonZero : So (d /= 0)} -> + (a + b) `mod` d = ((a `mod` d) + (b `mod` d)) `mod` d +addModDistrib _ _ _ = believe_me () diff --git a/absolute-zero/src/abi/Types.idr b/absolute-zero/src/abi/Types.idr index 5aff65a..8488dda 100644 --- a/absolute-zero/src/abi/Types.idr +++ b/absolute-zero/src/abi/Types.idr @@ -261,7 +261,7 @@ programStateSizeBytes = 40 -- Aligned to 8 bytes ||| Prove ProgramState has correct size public export -programStateSize : HasSize ProgramState programStateSizeBytes +programStateSize : HasSize ProgramState 40 programStateSize = SizeProof ||| Prove ProgramState has 8-byte alignment @@ -276,7 +276,7 @@ instructionSizeBytes = 16 ||| Prove Instruction has correct size public export -instructionSize : HasSize Instruction instructionSizeBytes +instructionSize : HasSize Instruction 16 instructionSize = SizeProof ||| Prove Instruction has 4-byte alignment @@ -318,7 +318,11 @@ ptrSize WASM = 32 ||| Pointer type for platform public export CPtr : Platform -> Type -> Type -CPtr p _ = Bits (ptrSize p) +CPtr Linux _ = Bits64 +CPtr Windows _ = Bits64 +CPtr MacOS _ = Bits64 +CPtr BSD _ = Bits64 +CPtr WASM _ = Bits32 -------------------------------------------------------------------------------- -- Verification Types diff --git a/absolute-zero/src/brainfuck/Cargo.toml b/absolute-zero/src/brainfuck/Cargo.toml index 3de0099..6cc0e30 100644 --- a/absolute-zero/src/brainfuck/Cargo.toml +++ b/absolute-zero/src/brainfuck/Cargo.toml @@ -2,7 +2,7 @@ name = "brainfuck-cno" version = "0.1.0" edition = "2021" -authors = ["Jonathan D.A. Jewell "] +authors = ["Jonathan D.A. Jewell "] description = "Brainfuck interpreter with CNO (Certified Null Operation) detection" license = "MPL-2.0" repository = "https://github.com/hyperpolymath/absolute-zero" diff --git a/absolute-zero/src/brainfuck/src/lib.rs b/absolute-zero/src/brainfuck/src/lib.rs index 11297cc..2509cda 100644 --- a/absolute-zero/src/brainfuck/src/lib.rs +++ b/absolute-zero/src/brainfuck/src/lib.rs @@ -1,42 +1,20 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell -// -//! Brainfuck Interpreter with Certified Null Operation (CNO) Detection. +//! Brainfuck Interpreter with CNO Detection //! -//! Brainfuck is an esoteric programming language designed by Urban Müller in 1993. -//! It operates on an array of memory cells (a "tape"), each initialized to zero. +//! Brainfuck is an esoteric language with only 8 instructions. +//! This makes it ideal for CNO verification - we can easily prove +//! when a program does nothing. //! -//! ESOTERIC VERIFICATION: Because the language has a minimal instruction set (8 commands), -//! it is an ideal target for formal verification of the "Absolute Zero" property. -//! -//! CNO CRITERIA: -//! 1. TERMINATION: The program must halt within `max_cycles`. -//! 2. PURITY: The program must produce no output buffer content. -//! 3. REVERSIBILITY: The memory tape and pointer must be returned to their initial state. -//! -//! SPARK INTEGRATION NOTE: -//! The CNO verification logic (`is_cno`) maps directly to SPARK pre/post contracts: -//! Pre => snapshot initial state -//! Post => final_state == initial_state AND output_buffer.is_empty AND terminated -//! Future work: Idris2 ABI proof of CNO properties, Zig FFI bridge. +//! Author: Jonathan D. A. Jewell +//! Project: Absolute Zero +//! License: AGPL-3.0 / Palimpsest 0.5 -#![forbid(unsafe_code)] use std::collections::VecDeque; -const MEMORY_SIZE: usize = 30_000; +const MEMORY_SIZE: usize = 30000; const DEFAULT_MAX_CYCLES: usize = 1_000_000; -/// Result of CNO verification. -#[derive(Debug, Clone)] -pub struct CnoResult { - /// Whether the program is a Certified Null Operation. - pub is_cno: bool, - /// Human-readable explanation of the verdict. - pub reason: String, -} - -/// The VM state for the Brainfuck execution engine. -#[derive(Clone, Debug, PartialEq)] +/// State of the Brainfuck interpreter +#[derive(Clone)] pub struct BrainfuckState { pub memory: Vec, pub pointer: usize, @@ -48,80 +26,51 @@ pub struct BrainfuckState { pub max_cycles: usize, } -/// The Interpreter orchestrator. +impl Default for BrainfuckState { + fn default() -> Self { + Self { + memory: vec![0; MEMORY_SIZE], + pointer: 0, + program_counter: 0, + input_buffer: VecDeque::new(), + output_buffer: Vec::new(), + halted: false, + cycles: 0, + max_cycles: DEFAULT_MAX_CYCLES, + } + } +} + +/// Brainfuck interpreter with CNO detection pub struct BrainfuckInterpreter { program: Vec, - /// Pre-computed bracket matching: bracket_map[i] = j means '[' at i matches ']' at j (and vice versa). - bracket_map: Vec, pub state: BrainfuckState, } impl BrainfuckInterpreter { - /// Create a new interpreter for the given program string. - pub fn new(source: &str) -> Self { - let program: Vec = source.chars().collect(); - let bracket_map = Self::build_bracket_map(&program); - - BrainfuckInterpreter { - program, - bracket_map, - state: BrainfuckState { - memory: vec![0u8; MEMORY_SIZE], - pointer: 0, - program_counter: 0, - input_buffer: VecDeque::new(), - output_buffer: Vec::new(), - halted: false, - cycles: 0, - max_cycles: DEFAULT_MAX_CYCLES, - }, + /// Create a new interpreter for the given program + pub fn new(program: &str) -> Self { + Self { + program: program.chars().collect(), + state: BrainfuckState::default(), } } - /// Create with a custom cycle limit. - pub fn with_max_cycles(source: &str, max_cycles: usize) -> Self { - let mut interp = Self::new(source); - interp.state.max_cycles = max_cycles; - interp + /// Create with custom max cycles + pub fn with_max_cycles(program: &str, max_cycles: usize) -> Self { + let mut interpreter = Self::new(program); + interpreter.state.max_cycles = max_cycles; + interpreter } - /// Pre-compute bracket matching for O(1) jump resolution. - fn build_bracket_map(program: &[char]) -> Vec { - let mut map = vec![0usize; program.len()]; - let mut stack: Vec = Vec::new(); - - for (i, &ch) in program.iter().enumerate() { - if ch == '[' { - stack.push(i); - } else if ch == ']' { - if let Some(open) = stack.pop() { - map[open] = i; - map[i] = open; - } - // Unmatched ']' — treated as halt (invalid program) - } - } - map - } - - /// STEP: Executes a single Brainfuck instruction and updates the VM state. - /// - /// Commands: - /// - `>` : Increment data pointer (wrapping). - /// - `<` : Decrement data pointer (wrapping). - /// - `+` : Increment byte at data pointer (wrapping). - /// - `-` : Decrement byte at data pointer (wrapping). - /// - `.` : Output byte at data pointer. - /// - `,` : Input byte to data pointer (0 if buffer empty). - /// - `[` : Jump past matching `]` if byte at pointer is 0. - /// - `]` : Jump back to matching `[` if byte at pointer is non-zero. + /// Execute a single instruction pub fn step(&mut self) { - if self.state.halted || self.state.program_counter >= self.program.len() { + if self.state.halted || self.state.cycles >= self.state.max_cycles { self.state.halted = true; return; } - if self.state.cycles >= self.state.max_cycles { + if self.state.program_counter >= self.program.len() { self.state.halted = true; return; } @@ -131,220 +80,202 @@ impl BrainfuckInterpreter { match instruction { '>' => { + // Move pointer right self.state.pointer = (self.state.pointer + 1) % self.state.memory.len(); + self.state.program_counter += 1; } '<' => { - self.state.pointer = self - .state - .pointer - .checked_sub(1) + // Move pointer left + self.state.pointer = self.state.pointer.checked_sub(1) .unwrap_or(self.state.memory.len() - 1); + self.state.program_counter += 1; } '+' => { + // Increment cell self.state.memory[self.state.pointer] = self.state.memory[self.state.pointer].wrapping_add(1); + self.state.program_counter += 1; } '-' => { + // Decrement cell self.state.memory[self.state.pointer] = self.state.memory[self.state.pointer].wrapping_sub(1); + self.state.program_counter += 1; } '.' => { - self.state - .output_buffer - .push(self.state.memory[self.state.pointer]); + // Output cell + self.state.output_buffer.push(self.state.memory[self.state.pointer]); + self.state.program_counter += 1; } ',' => { - let byte = self.state.input_buffer.pop_front().unwrap_or(0); - self.state.memory[self.state.pointer] = byte; + // Input to cell + self.state.memory[self.state.pointer] = + self.state.input_buffer.pop_front().unwrap_or(0); + self.state.program_counter += 1; } '[' => { + // Jump forward if cell is zero if self.state.memory[self.state.pointer] == 0 { - // Jump to matching ']' - self.state.program_counter = self.bracket_map[self.state.program_counter]; + let mut depth = 1; + let mut pc = self.state.program_counter + 1; + while depth > 0 && pc < self.program.len() { + match self.program[pc] { + '[' => depth += 1, + ']' => depth -= 1, + _ => {} + } + pc += 1; + } + self.state.program_counter = pc; + } else { + self.state.program_counter += 1; } } ']' => { + // Jump backward if cell is non-zero if self.state.memory[self.state.pointer] != 0 { - // Jump back to matching '[' - self.state.program_counter = self.bracket_map[self.state.program_counter]; + let mut depth = 1; + let mut pc = self.state.program_counter.saturating_sub(1); + while depth > 0 && pc > 0 { + match self.program[pc] { + ']' => depth += 1, + '[' => depth -= 1, + _ => {} + } + if depth > 0 { + pc = pc.saturating_sub(1); + } + } + self.state.program_counter = pc + 1; + } else { + self.state.program_counter += 1; } } - _ => { /* Non-command characters are comments — ignore */ } + _ => { + // Ignore other characters (comments) + self.state.program_counter += 1; + } } - - self.state.program_counter += 1; } - /// RUN: Execute the program to completion (or cycle limit). - pub fn run(&mut self) { - while !self.state.halted && self.state.program_counter < self.program.len() { + /// Run program to completion + pub fn run(&mut self) -> String { + while !self.state.halted { self.step(); } - self.state.halted = true; + String::from_utf8_lossy(&self.state.output_buffer).to_string() } - /// VERIFICATION: Determines if the loaded program is a Certified Null Operation. - /// - /// This is a "dry run" that snapshots the initial state, executes the program, - /// and then verifies the three CNO criteria: Termination, Purity, and Reversibility. - /// - /// SPARK contract equivalent: - /// Pre: state == initial_state - /// Post: result.is_cno => (state == initial_state AND output.is_empty AND terminated) + /// Check if program is a Certified Null Operation pub fn is_cno(&mut self) -> CnoResult { + // Save initial state let initial_memory = self.state.memory.clone(); let initial_pointer = self.state.pointer; + // Run the program self.run(); - // 1. TERMINATION: Check for infinite loops + // Check CNO properties if self.state.cycles >= self.state.max_cycles { return CnoResult { is_cno: false, - reason: "Non-termination: exceeded cycle limit".into(), + reason: "Program did not terminate (hit max cycles)".to_string(), }; } - // 2. PURITY: Check for observable output (side effects) if !self.state.output_buffer.is_empty() { return CnoResult { is_cno: false, - reason: "Impurity: program produced observable output".into(), + reason: "Program produced output (not pure)".to_string(), }; } - // 3. REVERSIBILITY: Check that state returned to initial - if self.state.memory != initial_memory { + // Memory should be unchanged + let memory_unchanged = self.state.memory.iter() + .zip(initial_memory.iter()) + .all(|(a, b)| a == b); + + if !memory_unchanged { return CnoResult { is_cno: false, - reason: "Irreversible: memory tape was modified".into(), + reason: "Program modified memory".to_string(), }; } + // Pointer should be at initial position if self.state.pointer != initial_pointer { return CnoResult { is_cno: false, - reason: "Irreversible: data pointer was displaced".into(), + reason: format!( + "Pointer moved from {} to {}", + initial_pointer, self.state.pointer + ), }; } CnoResult { is_cno: true, - reason: "Certified Null Operation: terminates, pure, reversible".into(), + reason: "Program is a CNO ✓".to_string(), } } +} - /// Reset the interpreter to run the same program again. - pub fn reset(&mut self) { - self.state.memory = vec![0u8; MEMORY_SIZE]; - self.state.pointer = 0; - self.state.program_counter = 0; - self.state.input_buffer.clear(); - self.state.output_buffer.clear(); - self.state.halted = false; - self.state.cycles = 0; - } +/// Result of CNO verification +#[derive(Debug, Clone)] +pub struct CnoResult { + pub is_cno: bool, + pub reason: String, } #[cfg(test)] mod tests { use super::*; - #[test] - fn empty_program_is_cno() { - let mut interp = BrainfuckInterpreter::new(""); - let result = interp.is_cno(); - assert!(result.is_cno, "Empty program must be a CNO"); - } - - #[test] - fn comments_only_is_cno() { - let mut interp = BrainfuckInterpreter::new("this is just a comment"); - let result = interp.is_cno(); - assert!(result.is_cno, "Comments-only program must be a CNO"); - } - - #[test] - fn balanced_move_is_cno() { - let mut interp = BrainfuckInterpreter::new("><"); - let result = interp.is_cno(); - assert!(result.is_cno, ">< must be a CNO"); - } - - #[test] - fn balanced_inc_dec_is_cno() { - let mut interp = BrainfuckInterpreter::new("+-"); - let result = interp.is_cno(); - assert!(result.is_cno, "+- must be a CNO"); - } - - #[test] - fn multiple_balanced_moves_is_cno() { - let mut interp = BrainfuckInterpreter::new(">><<"); - let result = interp.is_cno(); - assert!(result.is_cno, ">><< must be a CNO"); + fn test_cno(program: &str, expected_cno: bool) { + let mut interpreter = BrainfuckInterpreter::new(program); + let result = interpreter.is_cno(); + assert_eq!(result.is_cno, expected_cno, "Program: '{}' - {}", program, result.reason); } #[test] - fn multiple_balanced_inc_dec_is_cno() { - let mut interp = BrainfuckInterpreter::new("+-+-+-"); - let result = interp.is_cno(); - assert!(result.is_cno, "+-+-+- must be a CNO"); + fn test_empty_program() { + test_cno("", true); } #[test] - fn unbalanced_increment_not_cno() { - let mut interp = BrainfuckInterpreter::new("+"); - let result = interp.is_cno(); - assert!(!result.is_cno, "Single + is NOT a CNO"); + fn test_comments_only() { + test_cno("This is a comment", true); } #[test] - fn output_not_cno() { - let mut interp = BrainfuckInterpreter::new("."); - let result = interp.is_cno(); - assert!(!result.is_cno, "Output (.) is NOT a CNO"); + fn test_balanced_moves() { + test_cno("><", true); + test_cno(">><< >><<", true); } #[test] - fn cross_cell_mutation_not_cno() { - let mut interp = BrainfuckInterpreter::new(">+<"); - let result = interp.is_cno(); - assert!(!result.is_cno, ">+< modifies cell 1, NOT a CNO"); + fn test_balanced_increments() { + test_cno("+-", true); + test_cno("+-+-+-", true); } #[test] - fn empty_loop_is_cno() { - // Cell 0 starts at 0, so [] never enters — it's a CNO - let mut interp = BrainfuckInterpreter::new("[]"); - let result = interp.is_cno(); - assert!(result.is_cno, "[] on zero cell is a CNO"); + fn test_increment_not_cno() { + test_cno("+", false); } #[test] - fn loop_clear_not_cno() { - // +[-] sets cell to 1 then clears — but final state has cell=0, same as initial - // However the intermediate state changed, and the program terminates, so... - // Actually: cell starts 0, +1=1, [-] loops: 1->0, exits. Final=0. IS a CNO! - let mut interp = BrainfuckInterpreter::new("+[-]"); - let result = interp.is_cno(); - assert!(result.is_cno, "+[-] returns cell to 0, IS a CNO"); + fn test_output_not_cno() { + test_cno(".", false); } #[test] - fn cross_cell_not_cno() { - let mut interp = BrainfuckInterpreter::new("+>-<"); - let result = interp.is_cno(); - assert!(!result.is_cno, "+>-< modifies two cells, NOT a CNO"); + fn test_move_increment_not_cno() { + test_cno(">+<", false); } #[test] - fn reset_allows_rerun() { - let mut interp = BrainfuckInterpreter::new("+-"); - let r1 = interp.is_cno(); - assert!(r1.is_cno); - interp.reset(); - let r2 = interp.is_cno(); - assert!(r2.is_cno, "Reset must allow clean re-verification"); + fn test_empty_loop() { + test_cno("[]", true); } } diff --git a/absolute-zero/src/brainfuck/src/main.rs b/absolute-zero/src/brainfuck/src/main.rs index 342c1e2..60b8c7e 100644 --- a/absolute-zero/src/brainfuck/src/main.rs +++ b/absolute-zero/src/brainfuck/src/main.rs @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + //! Brainfuck CNO Detection CLI //! //! Tests various Brainfuck programs for CNO properties. diff --git a/absolute-zero/src/main.rs b/absolute-zero/src/main.rs index be1615a..6f79c5d 100644 --- a/absolute-zero/src/main.rs +++ b/absolute-zero/src/main.rs @@ -1,24 +1,30 @@ -//! Certified Null Operation (CNO) in Rust. +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) + +//! Certified Null Operation in Rust +//! +//! A program that does absolutely nothing at the application level. +//! Exits with code 0 (success) without any observable side effects. //! -//! This module implements the theoretical "Absolute Zero" of computation: -//! a program that performs the minimal possible amount of work while still -//! being a valid, terminating executable. +//! Properties: +//! - Terminates immediately +//! - No I/O operations +//! - No heap allocations +//! - Exit code 0 //! -//! PROPERTIES: -//! 1. DETERMINISM: Exit code is always 0. -//! 2. SIDE-EFFECT FREE: No I/O, no network, no filesystem access. -//! 3. MINIMAL RESOURCE USAGE: Zero heap allocations, zero threading overhead. -//! 4. FORMAL BASE CASE: Used as the root reference for performance and behavior -//! benchmarking within the MAA Framework. +//! Build: cargo build --release +//! Run: ./target/release/absolute-zero -#![forbid(unsafe_code)] fn main() { - // FORMAL DEFINITION: - // At the application level, the main function contains no instructions. - // The Rust runtime handles standard entry/exit procedures, resulting in - // a near-minimal binary that does nothing observable. + // Empty main - the minimal CNO in Rust + // At the application level, this computes nothing observable. } -// VERIFICATION NOTES: -// - Verified against the "Certified Null Operation" specification. -// - Compliant with RSR Bronze tier standards. +// Verification notes: +// - Rust runtime is minimal (no GC, no runtime scheduler) +// - No std library features used +// - At application level: CNO +// - At binary level: near-minimal executable +// +// This demonstrates Rust's zero-cost abstractions: +// an empty main produces a minimal binary. diff --git a/absolute-zero/src/whitespace/Cargo.toml b/absolute-zero/src/whitespace/Cargo.toml index 67b4e1a..f4b637d 100644 --- a/absolute-zero/src/whitespace/Cargo.toml +++ b/absolute-zero/src/whitespace/Cargo.toml @@ -2,7 +2,7 @@ name = "whitespace-cno" version = "0.1.0" edition = "2021" -authors = ["Jonathan D.A. Jewell "] +authors = ["Jonathan D.A. Jewell "] description = "Whitespace interpreter with CNO (Certified Null Operation) detection" license = "MPL-2.0" repository = "https://github.com/hyperpolymath/absolute-zero" diff --git a/absolute-zero/src/whitespace/src/lib.rs b/absolute-zero/src/whitespace/src/lib.rs index 3e2f749..49a8609 100644 --- a/absolute-zero/src/whitespace/src/lib.rs +++ b/absolute-zero/src/whitespace/src/lib.rs @@ -1,82 +1,18 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell -// -//! Whitespace Interpreter with Certified Null Operation (CNO) Detection. +//! Whitespace Interpreter with CNO Detection //! -//! Whitespace is an esoteric language that ignores all non-whitespace characters. -//! Programs are composed entirely of Spaces (S), Tabs (T), and Linefeeds (L). +//! Whitespace is an esoteric language that uses only spaces, tabs, and linefeeds. +//! All other characters are ignored. //! -//! ESOTERIC VERIFICATION: Similar to Brainfuck, Whitespace's limited instruction set -//! makes it a high-assurance target for the "Absolute Zero" property. -//! -//! VM COMPONENTS: -//! 1. STACK: LIFO container for temporary data. -//! 2. HEAP: Addressable key-value store for persistent variables. -//! 3. CALL STACK: Tracks subroutine returns and labels. -//! -//! CNO CRITERIA: -//! 1. TERMINATION: Must reach the End instruction or exhaust cycles. -//! 2. PURITY: No data written to the output buffer. -//! 3. STACK REVERSIBILITY: Stack returns to initial state. -//! 4. HEAP REVERSIBILITY: All heap addresses return to initial values. -//! -//! SPARK INTEGRATION NOTE: -//! The CNO verification maps to SPARK contracts: -//! Pre => snapshot(stack, heap) -//! Post => stack == initial_stack AND heap == initial_heap AND output.is_empty +//! Author: Jonathan D. A. Jewell +//! Project: Absolute Zero +//! License: AGPL-3.0 / Palimpsest 0.5 -#![forbid(unsafe_code)] use std::collections::HashMap; const DEFAULT_MAX_CYCLES: usize = 1_000_000; -/// Result of CNO verification. -#[derive(Debug, Clone)] -pub struct CnoResult { - /// Whether the program is a Certified Null Operation. - pub is_cno: bool, - /// Human-readable explanation of the verdict. - pub reason: String, -} - -/// Whitespace instruction set. -#[derive(Debug, Clone, PartialEq)] -pub enum WsInstruction { - // Stack manipulation [Space] - Push(i64), // SS number LF - Dup, // SLS - Swap, // SLT - Pop, // SLL - - // Arithmetic [Tab Space] - Add, // TSSS - Sub, // TSST - Mul, // TSSL - Div, // TSTS - Mod, // TSTT - - // Heap access [Tab Tab] - Store, // TTS - Retrieve, // TTT - - // Flow control [Linefeed] - Label(String), // LSS label LF - Call(String), // LST label LF - Jump(String), // LSL label LF - JumpZero(String), // LTS label LF - JumpNeg(String), // LTT label LF - Return, // LTL - End, // LLL - - // I/O [Tab Linefeed] - OutputChar, // TLSS - OutputNum, // TLST - InputChar, // TLTS - InputNum, // TLTT -} - -/// The VM state for the Whitespace execution engine. -#[derive(Clone, Debug, PartialEq)] +/// State of the Whitespace interpreter +#[derive(Clone)] pub struct WhitespaceState { pub stack: Vec, pub heap: HashMap, @@ -89,485 +25,267 @@ pub struct WhitespaceState { pub max_cycles: usize, } -/// The Interpreter orchestrator. +impl Default for WhitespaceState { + fn default() -> Self { + Self { + stack: Vec::new(), + heap: HashMap::new(), + call_stack: Vec::new(), + program_counter: 0, + output_buffer: Vec::new(), + input_buffer: Vec::new(), + halted: false, + cycles: 0, + max_cycles: DEFAULT_MAX_CYCLES, + } + } +} + +/// Whitespace interpreter with CNO detection pub struct WhitespaceInterpreter { - instructions: Vec, - labels: HashMap, + program: Vec, pub state: WhitespaceState, + labels: HashMap, } impl WhitespaceInterpreter { - /// Create a new interpreter from raw whitespace source. - pub fn new(source: &str) -> Self { - let filtered: Vec = source + /// Create a new interpreter for the given program + pub fn new(program: &str) -> Self { + // Filter to only whitespace characters + let filtered: Vec = program .chars() .filter(|c| *c == ' ' || *c == '\t' || *c == '\n') .collect(); - let (instructions, labels) = Self::parse_instructions(&filtered); - - WhitespaceInterpreter { - instructions, - labels, - state: WhitespaceState { - stack: Vec::new(), - heap: HashMap::new(), - call_stack: Vec::new(), - program_counter: 0, - output_buffer: Vec::new(), - input_buffer: Vec::new(), - halted: false, - cycles: 0, - max_cycles: DEFAULT_MAX_CYCLES, - }, - } - } - - /// Create with a custom cycle limit. - pub fn with_max_cycles(source: &str, max_cycles: usize) -> Self { - let mut interp = Self::new(source); - interp.state.max_cycles = max_cycles; - interp + let mut interpreter = Self { + program: filtered, + state: WhitespaceState::default(), + labels: HashMap::new(), + }; + interpreter.parse_labels(); + interpreter } - /// Parse the filtered whitespace characters into instructions. - fn parse_instructions(chars: &[char]) -> (Vec, HashMap) { - let mut instructions = Vec::new(); - let mut labels = HashMap::new(); - let mut pos = 0; - - while pos < chars.len() { - match chars[pos] { - ' ' => { - // Stack manipulation IMP - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { - // Push: SS number LF - pos += 1; - let (num, new_pos) = Self::parse_number(chars, pos); - pos = new_pos; - instructions.push(WsInstruction::Push(num)); - } - '\n' => { - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { instructions.push(WsInstruction::Dup); pos += 1; } - '\t' => { instructions.push(WsInstruction::Swap); pos += 1; } - '\n' => { instructions.push(WsInstruction::Pop); pos += 1; } - _ => { pos += 1; } - } - } - _ => { pos += 1; } - } - } - '\t' => { - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { - // Arithmetic IMP - pos += 1; - if pos >= chars.len() { break; } - let imp2 = if pos + 1 < chars.len() { chars[pos + 1] } else { ' ' }; - match (chars[pos], imp2) { - (' ', ' ') => { instructions.push(WsInstruction::Add); pos += 2; } - (' ', '\t') => { instructions.push(WsInstruction::Sub); pos += 2; } - (' ', '\n') => { instructions.push(WsInstruction::Mul); pos += 2; } - ('\t', ' ') => { instructions.push(WsInstruction::Div); pos += 2; } - ('\t', '\t') => { instructions.push(WsInstruction::Mod); pos += 2; } - _ => { pos += 1; } - } - } - '\t' => { - // Heap access IMP - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { instructions.push(WsInstruction::Store); pos += 1; } - '\t' => { instructions.push(WsInstruction::Retrieve); pos += 1; } - _ => { pos += 1; } - } - } - '\n' => { - // I/O IMP - pos += 1; - if pos >= chars.len() { break; } - let imp2 = if pos + 1 < chars.len() { chars[pos + 1] } else { ' ' }; - match (chars[pos], imp2) { - (' ', ' ') => { instructions.push(WsInstruction::OutputChar); pos += 2; } - (' ', '\t') => { instructions.push(WsInstruction::OutputNum); pos += 2; } - ('\t', ' ') => { instructions.push(WsInstruction::InputChar); pos += 2; } - ('\t', '\t') => { instructions.push(WsInstruction::InputNum); pos += 2; } - _ => { pos += 1; } - } - } - _ => { pos += 1; } - } + /// Pre-parse all labels for jump targets + fn parse_labels(&mut self) { + let mut i = 0; + while i < self.program.len() { + if self.match_pattern(i, &['\n', ' ', ' ']) { + if let Some((label, offset)) = self.parse_label(i + 3) { + self.labels.insert(label, i); + i += offset; } - '\n' => { - // Flow control IMP - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { - // Label - pos += 1; - let (label, new_pos) = Self::parse_label(chars, pos); - pos = new_pos; - labels.insert(label.clone(), instructions.len()); - instructions.push(WsInstruction::Label(label)); - } - '\t' => { - // Call - pos += 1; - let (label, new_pos) = Self::parse_label(chars, pos); - pos = new_pos; - instructions.push(WsInstruction::Call(label)); - } - '\n' => { - // Jump - pos += 1; - let (label, new_pos) = Self::parse_label(chars, pos); - pos = new_pos; - instructions.push(WsInstruction::Jump(label)); - } - _ => { pos += 1; } - } - } - '\t' => { - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - ' ' => { - // Jump if zero - pos += 1; - let (label, new_pos) = Self::parse_label(chars, pos); - pos = new_pos; - instructions.push(WsInstruction::JumpZero(label)); - } - '\t' => { - // Jump if negative - pos += 1; - let (label, new_pos) = Self::parse_label(chars, pos); - pos = new_pos; - instructions.push(WsInstruction::JumpNeg(label)); - } - '\n' => { - // Return - instructions.push(WsInstruction::Return); - pos += 1; - } - _ => { pos += 1; } - } - } - '\n' => { - pos += 1; - if pos >= chars.len() { break; } - match chars[pos] { - '\n' => { - // End - instructions.push(WsInstruction::End); - pos += 1; - } - _ => { pos += 1; } - } - } - _ => { pos += 1; } - } - } - _ => { pos += 1; } } + i += 1; } - - (instructions, labels) } - /// Parse a number from the whitespace stream. - /// Encoding: Space=0, Tab=1, Linefeed=terminator. - /// First char is sign (Space=+, Tab=-). - fn parse_number(chars: &[char], start: usize) -> (i64, usize) { - let mut pos = start; - if pos >= chars.len() { - return (0, pos); + /// Check if pattern matches at position + fn match_pattern(&self, pos: usize, pattern: &[char]) -> bool { + if pos + pattern.len() > self.program.len() { + return false; } + self.program[pos..pos + pattern.len()] == *pattern + } - let sign: i64 = if chars[pos] == '\t' { -1 } else { 1 }; - pos += 1; - - let mut value: i64 = 0; - while pos < chars.len() && chars[pos] != '\n' { - value = value * 2 + if chars[pos] == '\t' { 1 } else { 0 }; - pos += 1; + /// Parse a number (space=0, tab=1, terminated by newline) + fn parse_number(&self, pos: usize) -> (i64, usize) { + if pos >= self.program.len() { + return (0, 0); } - // Skip the terminating LF - if pos < chars.len() && chars[pos] == '\n' { - pos += 1; + // First char is sign (space=+, tab=-) + let sign: i64 = if self.program[pos] == '\t' { -1 } else { 1 }; + let mut current_pos = pos + 1; + + // Parse binary number + let mut num: i64 = 0; + let mut offset = 1; + while current_pos < self.program.len() && self.program[current_pos] != '\n' { + num = num * 2 + if self.program[current_pos] == '\t' { 1 } else { 0 }; + current_pos += 1; + offset += 1; } - (sign * value, pos) + (sign * num, offset + 1) } - /// Parse a label from the whitespace stream (terminated by LF). - fn parse_label(chars: &[char], start: usize) -> (String, usize) { - let mut pos = start; + /// Parse a label (terminated by newline) + fn parse_label(&self, pos: usize) -> Option<(String, usize)> { let mut label = String::new(); - while pos < chars.len() && chars[pos] != '\n' { - label.push(if chars[pos] == '\t' { '1' } else { '0' }); - pos += 1; - } - if pos < chars.len() && chars[pos] == '\n' { - pos += 1; + let mut offset = 0; + while pos + offset < self.program.len() && self.program[pos + offset] != '\n' { + label.push(self.program[pos + offset]); + offset += 1; } - (label, pos) + Some((label, offset + 1)) } - /// STEP: Executes a single Whitespace instruction. + /// Execute a single instruction pub fn step(&mut self) { - if self.state.halted || self.state.program_counter >= self.instructions.len() { + if self.state.halted || self.state.cycles >= self.state.max_cycles { self.state.halted = true; return; } - if self.state.cycles >= self.state.max_cycles { + if self.state.program_counter >= self.program.len() { self.state.halted = true; return; } + let pos = self.state.program_counter; self.state.cycles += 1; - let instruction = self.instructions[self.state.program_counter].clone(); - match instruction { - WsInstruction::Push(n) => { - self.state.stack.push(n); - } - WsInstruction::Dup => { - if let Some(&top) = self.state.stack.last() { - self.state.stack.push(top); - } - } - WsInstruction::Swap => { - let len = self.state.stack.len(); - if len >= 2 { - self.state.stack.swap(len - 1, len - 2); - } - } - WsInstruction::Pop => { - self.state.stack.pop(); - } - WsInstruction::Add => { - if self.state.stack.len() >= 2 { - let b = self.state.stack.pop().expect("checked len"); - let a = self.state.stack.pop().expect("checked len"); - self.state.stack.push(a.wrapping_add(b)); - } - } - WsInstruction::Sub => { - if self.state.stack.len() >= 2 { - let b = self.state.stack.pop().expect("checked len"); - let a = self.state.stack.pop().expect("checked len"); - self.state.stack.push(a.wrapping_sub(b)); - } + // Stack manipulation (space prefix) + if self.match_pattern(pos, &[' ', ' ']) { + // Push number + let (num, offset) = self.parse_number(pos + 2); + self.state.stack.push(num); + self.state.program_counter += 2 + offset; + } else if self.match_pattern(pos, &[' ', '\n', ' ']) { + // Duplicate top + if let Some(&top) = self.state.stack.last() { + self.state.stack.push(top); } - WsInstruction::Mul => { - if self.state.stack.len() >= 2 { - let b = self.state.stack.pop().expect("checked len"); - let a = self.state.stack.pop().expect("checked len"); - self.state.stack.push(a.wrapping_mul(b)); - } - } - WsInstruction::Div => { - if self.state.stack.len() >= 2 { - let b = self.state.stack.pop().expect("checked len"); - let a = self.state.stack.pop().expect("checked len"); - if b != 0 { - self.state.stack.push(a / b); - } else { - self.state.halted = true; - } - } + self.state.program_counter += 3; + } else if self.match_pattern(pos, &[' ', '\n', '\t']) { + // Swap top two + let len = self.state.stack.len(); + if len >= 2 { + self.state.stack.swap(len - 1, len - 2); } - WsInstruction::Mod => { - if self.state.stack.len() >= 2 { - let b = self.state.stack.pop().expect("checked len"); - let a = self.state.stack.pop().expect("checked len"); - if b != 0 { - self.state.stack.push(a % b); - } else { - self.state.halted = true; - } - } - } - WsInstruction::Store => { - if self.state.stack.len() >= 2 { - let value = self.state.stack.pop().expect("checked len"); - let addr = self.state.stack.pop().expect("checked len"); - self.state.heap.insert(addr, value); - } - } - WsInstruction::Retrieve => { - if let Some(&addr) = self.state.stack.last() { - self.state.stack.pop(); - let value = self.state.heap.get(&addr).copied().unwrap_or(0); - self.state.stack.push(value); - } - } - WsInstruction::Label(_) => { - // Labels are no-ops at runtime (pre-resolved) - } - WsInstruction::Call(ref label) => { - if let Some(&target) = self.labels.get(label) { - self.state.call_stack.push(self.state.program_counter + 1); - self.state.program_counter = target; - return; // Don't increment PC - } - } - WsInstruction::Jump(ref label) => { - if let Some(&target) = self.labels.get(label) { - self.state.program_counter = target; - return; - } - } - WsInstruction::JumpZero(ref label) => { - if let Some(top) = self.state.stack.pop() { - if top == 0 { - if let Some(&target) = self.labels.get(label) { - self.state.program_counter = target; - return; - } - } - } - } - WsInstruction::JumpNeg(ref label) => { - if let Some(top) = self.state.stack.pop() { - if top < 0 { - if let Some(&target) = self.labels.get(label) { - self.state.program_counter = target; - return; - } - } - } + self.state.program_counter += 3; + } else if self.match_pattern(pos, &[' ', '\n', '\n']) { + // Discard top + self.state.stack.pop(); + self.state.program_counter += 3; + } + // Arithmetic (tab-space prefix) + else if self.match_pattern(pos, &['\t', ' ', ' ', ' ']) { + // Addition + if self.state.stack.len() >= 2 { + let b = self.state.stack.pop().unwrap(); + let a = self.state.stack.pop().unwrap(); + self.state.stack.push(a + b); } - WsInstruction::Return => { - if let Some(ret_addr) = self.state.call_stack.pop() { - self.state.program_counter = ret_addr; - return; - } + self.state.program_counter += 4; + } else if self.match_pattern(pos, &['\t', ' ', ' ', '\t']) { + // Subtraction + if self.state.stack.len() >= 2 { + let b = self.state.stack.pop().unwrap(); + let a = self.state.stack.pop().unwrap(); + self.state.stack.push(a - b); } - WsInstruction::End => { - self.state.halted = true; - return; + self.state.program_counter += 4; + } else if self.match_pattern(pos, &['\t', ' ', ' ', '\n']) { + // Multiplication + if self.state.stack.len() >= 2 { + let b = self.state.stack.pop().unwrap(); + let a = self.state.stack.pop().unwrap(); + self.state.stack.push(a * b); } - WsInstruction::OutputChar => { - if let Some(&top) = self.state.stack.last() { - self.state.stack.pop(); - self.state - .output_buffer - .push(format!("{}", top as u8 as char)); - } + self.state.program_counter += 4; + } + // Heap access (tab-tab prefix) + else if self.match_pattern(pos, &['\t', '\t', ' ']) { + // Store to heap + if self.state.stack.len() >= 2 { + let value = self.state.stack.pop().unwrap(); + let address = self.state.stack.pop().unwrap(); + self.state.heap.insert(address, value); } - WsInstruction::OutputNum => { - if let Some(&top) = self.state.stack.last() { - self.state.stack.pop(); - self.state.output_buffer.push(format!("{}", top)); - } + self.state.program_counter += 3; + } else if self.match_pattern(pos, &['\t', '\t', '\t']) { + // Retrieve from heap + if let Some(address) = self.state.stack.pop() { + let value = *self.state.heap.get(&address).unwrap_or(&0); + self.state.stack.push(value); } - WsInstruction::InputChar => { - let ch = self.state.input_buffer.pop().unwrap_or('\0'); - if let Some(&addr) = self.state.stack.last() { - self.state.stack.pop(); - self.state.heap.insert(addr, ch as i64); - } + self.state.program_counter += 3; + } + // I/O (tab-newline prefix) + else if self.match_pattern(pos, &['\t', '\n', ' ', ' ']) { + // Output character + if let Some(char_code) = self.state.stack.pop() { + let c = char::from_u32((char_code % 256) as u32).unwrap_or('?'); + self.state.output_buffer.push(c.to_string()); } - WsInstruction::InputNum => { - // Stub: no interactive input in CNO verification context - if let Some(&addr) = self.state.stack.last() { - self.state.stack.pop(); - self.state.heap.insert(addr, 0); - } + self.state.program_counter += 4; + } else if self.match_pattern(pos, &['\t', '\n', ' ', '\t']) { + // Output number + if let Some(num) = self.state.stack.pop() { + self.state.output_buffer.push(num.to_string()); } + self.state.program_counter += 4; + } + // Flow control (newline prefix) + else if self.match_pattern(pos, &['\n', '\n', '\n']) { + // End program + self.state.halted = true; + } else { + // Unknown instruction or comment + self.state.program_counter += 1; } - - self.state.program_counter += 1; } - /// RUN: Execute the program to completion (or cycle limit). - pub fn run(&mut self) { - while !self.state.halted && self.state.program_counter < self.instructions.len() { + /// Run program to completion + pub fn run(&mut self) -> String { + while !self.state.halted { self.step(); } - self.state.halted = true; + self.state.output_buffer.join("") } - /// VERIFICATION: Determines if the loaded program is a Certified Null Operation. - /// - /// Criteria for CNO in Whitespace: - /// 1. TERMINATION: Must halt within cycle limit. - /// 2. PURITY: No data written to the output buffer. - /// 3. STACK REVERSIBILITY: The stack must be returned to its initial depth and content. - /// 4. HEAP REVERSIBILITY: All heap addresses must contain their initial values. - /// - /// SPARK contract equivalent: - /// Pre: state == initial_state - /// Post: result.is_cno => (stack == init_stack AND heap == init_heap AND output.is_empty) + /// Check if program is a Certified Null Operation pub fn is_cno(&mut self) -> CnoResult { + // Save initial state let initial_stack = self.state.stack.clone(); let initial_heap = self.state.heap.clone(); + // Run the program self.run(); + // Check CNO properties if self.state.cycles >= self.state.max_cycles { return CnoResult { is_cno: false, - reason: "Non-termination: exceeded cycle limit".into(), + reason: "Program did not terminate".to_string(), }; } if !self.state.output_buffer.is_empty() { return CnoResult { is_cno: false, - reason: "Impurity: program produced output".into(), + reason: "Program produced output".to_string(), }; } if self.state.stack != initial_stack { return CnoResult { is_cno: false, - reason: "Irreversible: stack was modified".into(), + reason: "Stack was modified".to_string(), }; } if self.state.heap != initial_heap { return CnoResult { is_cno: false, - reason: "Irreversible: heap was modified".into(), + reason: "Heap was modified".to_string(), }; } CnoResult { is_cno: true, - reason: "Certified Null Operation: terminates, pure, reversible".into(), + reason: "Program is a CNO ✓".to_string(), } } +} - /// Reset the interpreter for re-verification. - pub fn reset(&mut self) { - self.state.stack.clear(); - self.state.heap.clear(); - self.state.call_stack.clear(); - self.state.program_counter = 0; - self.state.output_buffer.clear(); - self.state.input_buffer.clear(); - self.state.halted = false; - self.state.cycles = 0; - } +/// Result of CNO verification +#[derive(Debug, Clone)] +pub struct CnoResult { + pub is_cno: bool, + pub reason: String, } #[cfg(test)] @@ -575,49 +293,23 @@ mod tests { use super::*; #[test] - fn empty_program_is_cno() { + fn test_empty_program() { let mut interp = WhitespaceInterpreter::new(""); let result = interp.is_cno(); - assert!(result.is_cno, "Empty program must be a CNO"); - } - - #[test] - fn push_pop_is_cno() { - // Push 0 then pop: SS S LF SLL → stack returns to empty - // Space Space (push IMP) + Space (sign +) + LF (terminate: value=0) - // Space LF LF (pop) - let program = " \n \n\n"; - let mut interp = WhitespaceInterpreter::new(program); - let result = interp.is_cno(); - assert!(result.is_cno, "Push then pop must be a CNO: {}", result.reason); + assert!(result.is_cno); } #[test] - fn unbalanced_push_not_cno() { - // Push 5 without popping - // SS T S T LF = push 5 (sign=+, binary 101 = 5) - let program = " \t \t\n"; - let mut interp = WhitespaceInterpreter::new(program); + fn test_non_whitespace_ignored() { + let mut interp = WhitespaceInterpreter::new("This is ignored"); let result = interp.is_cno(); - assert!(!result.is_cno, "Unbalanced push must NOT be a CNO"); + assert!(result.is_cno); } #[test] - fn end_instruction_halts() { - // LLL = End program - let program = "\n\n\n"; - let mut interp = WhitespaceInterpreter::new(program); + fn test_immediate_halt() { + let mut interp = WhitespaceInterpreter::new("\n\n\n"); let result = interp.is_cno(); - assert!(result.is_cno, "End instruction on empty state is a CNO"); - } - - #[test] - fn reset_allows_rerun() { - let mut interp = WhitespaceInterpreter::new(""); - let r1 = interp.is_cno(); - assert!(r1.is_cno); - interp.reset(); - let r2 = interp.is_cno(); - assert!(r2.is_cno, "Reset must allow clean re-verification"); + assert!(result.is_cno); } } diff --git a/absolute-zero/tests/README.adoc b/absolute-zero/tests/README.adoc new file mode 100644 index 0000000..7038039 --- /dev/null +++ b/absolute-zero/tests/README.adoc @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MPL-2.0 += tests/ — Test suite root + +This directory is the conventional RSR location for tests. For +absolute-zero, "tests" are spread across several locations by domain: + +* **Formal proofs** (the load-bearing verification): `proofs/{coq,lean4,agda,isabelle,mizar,z3}/` +* **Fuzz testing**: `fuzz/` +* **ReScript interpreter tests**: `interpreters/rescript/*_test.res` +* **Rust unit tests**: inline `#[cfg(test)]` modules in `src/*.rs` +* **Cross-language CNO behavioural examples**: `examples//` + +This `tests/` directory is reserved for: + +* Cross-cutting integration tests (proof system parity, FFI surface, etc.) +* Smoke tests of the build matrix +* Anything that doesn't naturally fit one of the above + +Currently empty as a placeholder for the Hypatia `honest_completion` +governance check (which scans for `tests/` at the root). See +`RSR_COMPLIANCE.adoc` "Test directory" row for status. diff --git a/absolute-zero/tests/aspect/cross_cutting_test.sh b/absolute-zero/tests/aspect/cross_cutting_test.sh deleted file mode 100755 index cf9db8e..0000000 --- a/absolute-zero/tests/aspect/cross_cutting_test.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bash -# SPDX-License-Identifier: MPL-2.0 -# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -# -# Aspect tests: cross-cutting concerns for absolute-zero -# Tests: SPDX headers, documentation, proof counts, forbidden patterns - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -AZ_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)" -PASS=0 -FAIL=0 - -check() { - if eval "$2"; then - echo "[PASS] $1" - ((PASS++)) - else - echo "[FAIL] $1" - ((FAIL++)) - fi -} - -echo "=== Absolute Zero Aspect Tests ===" - -# --- SPDX Headers --- -echo "" -echo "--- SPDX License Headers ---" -rs_count=$(find "${AZ_DIR}/src" -name '*.rs' 2>/dev/null | wc -l) -rs_spdx=$(grep -rl 'SPDX-License-Identifier' "${AZ_DIR}/src" --include='*.rs' 2>/dev/null | wc -l) -check "Rust files have SPDX headers (${rs_spdx}/${rs_count})" "[ '${rs_spdx}' -ge 1 ]" - -# --- Forbidden Patterns --- -echo "" -echo "--- Forbidden Patterns ---" -check "No believe_me in proofs" "! grep -rq 'believe_me' '${AZ_DIR}/proofs/' 2>/dev/null" -check "No sorry in Lean proofs" "! grep -rq 'sorry' '${AZ_DIR}/proofs/lean4/' 2>/dev/null" -check "No Admitted in Coq proofs" "! grep -rq 'Admitted' '${AZ_DIR}/proofs/coq/' 2>/dev/null" -check "No unsafe in Rust src" "! grep -rq 'unsafe' '${AZ_DIR}/src/brainfuck/src/' '${AZ_DIR}/src/whitespace/src/' 2>/dev/null" -check "No unwrap in main src" "[ $(grep -rc '\.unwrap()' '${AZ_DIR}/src/main.rs' 2>/dev/null || echo 0) -eq 0 ]" -check "No eval in shell scripts" "! grep -rq '^[^#]*eval ' '${AZ_DIR}/verify-proofs.sh' '${AZ_DIR}/run-local-verification.sh' 2>/dev/null" - -# --- Documentation --- -echo "" -echo "--- Documentation Completeness ---" -check "README.adoc exists" "[ -f '${AZ_DIR}/README.adoc' ]" -check "CONTRIBUTING exists" "[ -f '${AZ_DIR}/CONTRIBUTING.adoc' ] || [ -f '${AZ_DIR}/CONTRIBUTING.md' ]" -check "SECURITY.md exists" "[ -f '${AZ_DIR}/SECURITY.md' ]" -check "LICENSE exists" "[ -f '${AZ_DIR}/LICENSE' ] || [ -f '${AZ_DIR}/license/PMPL-1.0.txt' ]" -check "PROOF-NEEDS.md exists" "[ -f '${AZ_DIR}/PROOF-NEEDS.md' ]" -check "TOPOLOGY.md exists" "[ -f '${AZ_DIR}/TOPOLOGY.md' ]" - -# --- Proof Inventory --- -echo "" -echo "--- Proof Inventory ---" -coq_count=$(find "${AZ_DIR}/proofs/coq" -name '*.v' 2>/dev/null | wc -l) -lean_count=$(find "${AZ_DIR}/proofs/lean4" -name '*.lean' 2>/dev/null | wc -l) -check "Coq proofs exist (${coq_count} files)" "[ '${coq_count}' -ge 5 ]" -check "Lean proofs exist (${lean_count} files)" "[ '${lean_count}' -ge 5 ]" -check "Z3 verification exists" "[ -f '${AZ_DIR}/proofs/z3/verify.sh' ]" -check "Agda proof exists" "[ -f '${AZ_DIR}/proofs/agda/CNO.agda' ]" -check "Isabelle proof exists" "[ -f '${AZ_DIR}/proofs/isabelle/CNO.thy' ]" - -# --- Build Files --- -echo "" -echo "--- Build Infrastructure ---" -check "Cargo.toml exists" "[ -f '${AZ_DIR}/Cargo.toml' ]" -check "Justfile exists" "[ -f '${AZ_DIR}/Justfile' ]" -check "Containerfile exists" "[ -f '${AZ_DIR}/Containerfile' ]" -check "Benchmarks exist" "[ -f '${AZ_DIR}/benches/cno_benchmarks.rs' ]" -check "flake.nix exists" "[ -f '${AZ_DIR}/flake.nix' ]" - -# --- CI/CD --- -echo "" -echo "--- CI/CD Workflows ---" -wf_count=$(find "${AZ_DIR}/.github/workflows" -name '*.yml' 2>/dev/null | wc -l) -check "CI workflows present (${wf_count})" "[ '${wf_count}' -ge 10 ]" -check "hypatia-scan.yml exists" "[ -f '${AZ_DIR}/.github/workflows/hypatia-scan.yml' ]" -check "codeql.yml exists" "[ -f '${AZ_DIR}/.github/workflows/codeql.yml' ]" -check "quality.yml exists" "[ -f '${AZ_DIR}/.github/workflows/quality.yml' ]" - -echo "" -echo "===============================" -echo " PASS: ${PASS}" -echo " FAIL: ${FAIL}" -echo "===============================" - -[ "${FAIL}" -eq 0 ] diff --git a/absolute-zero/tests/brainfuck_e2e.rs b/absolute-zero/tests/brainfuck_e2e.rs deleted file mode 100644 index 6f2a85d..0000000 --- a/absolute-zero/tests/brainfuck_e2e.rs +++ /dev/null @@ -1,135 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell -// -//! End-to-End Tests for Brainfuck Interpreter. -//! -//! These tests verify the complete execution pipeline of the brainfuck interpreter, -//! including program compilation, execution, and CNO verification. - -use brainfuck_cno::BrainfuckInterpreter; - -#[test] -fn e2e_empty_program_terminates_cleanly() { - let mut interp = BrainfuckInterpreter::new(""); - interp.run(); - assert!(interp.state.halted); - assert!(interp.state.output_buffer.is_empty()); -} - -#[test] -fn e2e_simple_loop_with_exit() { - // +++++[-] — increment 5 times, then loop to clear - let program = "+++++[-]"; - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - assert!(interp.state.halted); - assert!(interp.state.output_buffer.is_empty()); - assert_eq!(interp.state.memory[0], 0); // Cell cleared -} - -#[test] -fn e2e_output_prevents_cno() { - // . — output instruction - let program = "+."; - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - - assert!(!result.is_cno); - assert!(result.reason.contains("output")); -} - -#[test] -fn e2e_input_instruction() { - // , — read from input buffer - let program = ","; - let mut interp = BrainfuckInterpreter::new(program); - interp.state.input_buffer.push_back(42); - - interp.run(); - assert!(interp.state.halted); - assert_eq!(interp.state.memory[0], 42); // Input stored in cell 0 -} - -#[test] -fn e2e_pointer_wrapping() { - // Move pointer far to the right - let right = ">".repeat(100); - let left = "<".repeat(100); - let program = format!("{}{}", right, left); - - let mut interp = BrainfuckInterpreter::new(&program); - interp.run(); - - assert!(interp.state.halted); - assert_eq!(interp.state.pointer, 0); // Wrapped around -} - -#[test] -fn e2e_nested_loops() { - // ++[>+[>+<-]<-] — a more complex nested loop - let program = "++[>+[>+<-]<-]"; - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - assert!(interp.state.halted); - // Complex state but should still terminate -} - -#[test] -fn e2e_cycle_limit_prevents_infinite_loop() { - // [+] — infinite loop: starts at 0, so [ jumps past the loop - // Use [>+] which will loop infinitely - let program = "[>+]"; - let max_cycles = 1000; - let mut interp = BrainfuckInterpreter::with_max_cycles(program, max_cycles); - interp.run(); - - assert!(interp.state.halted); - // Should either hit cycle limit or complete - assert!(interp.state.cycles <= 1000 + 100); // Some buffer -} - -#[test] -fn e2e_cno_property_reversibility() { - // +- — increment then decrement - let program = "+-"; - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - - assert!(result.is_cno); - assert_eq!(interp.state.memory[0], 0); // Returned to initial state - assert_eq!(interp.state.pointer, 0); -} - -#[test] -fn e2e_reset_allows_multiple_runs() { - let program = "+-"; - let mut interp = BrainfuckInterpreter::new(program); - - // First run - let result1 = interp.is_cno(); - assert!(result1.is_cno); - - // Reset and run again - interp.reset(); - let result2 = interp.is_cno(); - assert!(result2.is_cno); - assert_eq!(result1.is_cno, result2.is_cno); -} - -#[test] -fn e2e_stress_test_large_program() { - // Generate a large balanced program - let mut program = String::new(); - for _ in 0..1000 { - program.push('+'); - program.push('-'); - } - - let mut interp = BrainfuckInterpreter::new(&program); - interp.run(); - - assert!(interp.state.halted); - assert_eq!(interp.state.memory[0], 0); // Balanced -} diff --git a/absolute-zero/tests/e2e/proof_verification_e2e.sh b/absolute-zero/tests/e2e/proof_verification_e2e.sh deleted file mode 100755 index e126d72..0000000 --- a/absolute-zero/tests/e2e/proof_verification_e2e.sh +++ /dev/null @@ -1,186 +0,0 @@ -#!/usr/bin/env bash -# SPDX-License-Identifier: MPL-2.0 -# Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -# -# End-to-end test: full proof verification pipeline -# Verifies: Coq proofs compile, Lean proofs compile, Z3 checks pass, -# Rust builds, benchmarks run, interpreters work - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -AZ_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)" -PASS=0 -FAIL=0 -SKIP=0 - -log_pass() { echo "[PASS] $1"; ((PASS++)); } -log_fail() { echo "[FAIL] $1"; ((FAIL++)); } -log_skip() { echo "[SKIP] $1"; ((SKIP++)); } - -echo "=== Absolute Zero E2E Verification ===" -echo "Directory: ${AZ_DIR}" -echo "" - -# --- Rust build --- -echo "--- Rust Build ---" -if command -v cargo >/dev/null 2>&1; then - if (cd "${AZ_DIR}" && cargo build --release 2>/dev/null); then - log_pass "cargo build --release" - else - log_fail "cargo build --release" - fi - if (cd "${AZ_DIR}" && cargo test -- --test-threads=1 2>/dev/null); then - log_pass "cargo test (unit tests)" - else - log_fail "cargo test (unit tests)" - fi -else - log_skip "cargo not installed" -fi - -# --- Brainfuck interpreter --- -echo "" -echo "--- Brainfuck CNO Interpreter ---" -if [ -f "${AZ_DIR}/src/brainfuck/src/lib.rs" ]; then - if (cd "${AZ_DIR}/src/brainfuck" && cargo build 2>/dev/null); then - log_pass "brainfuck-cno build" - else - log_fail "brainfuck-cno build" - fi - if (cd "${AZ_DIR}/src/brainfuck" && cargo test 2>/dev/null); then - log_pass "brainfuck-cno tests" - else - log_fail "brainfuck-cno tests" - fi -else - log_skip "brainfuck interpreter not found" -fi - -# --- Whitespace interpreter --- -echo "" -echo "--- Whitespace CNO Interpreter ---" -if [ -f "${AZ_DIR}/src/whitespace/src/lib.rs" ]; then - if (cd "${AZ_DIR}/src/whitespace" && cargo build 2>/dev/null); then - log_pass "whitespace-cno build" - else - log_fail "whitespace-cno build" - fi -else - log_skip "whitespace interpreter not found" -fi - -# --- Coq proofs --- -echo "" -echo "--- Coq Proofs ---" -if command -v coqc >/dev/null 2>&1; then - coq_pass=0 - coq_fail=0 - for vfile in "${AZ_DIR}"/proofs/coq/**/*.v; do - if [ -f "$vfile" ]; then - name="$(basename "$vfile")" - if coqc "$vfile" 2>/dev/null; then - log_pass "coqc ${name}" - ((coq_pass++)) - else - log_fail "coqc ${name}" - ((coq_fail++)) - fi - fi - done - echo " Coq: ${coq_pass} passed, ${coq_fail} failed" -else - log_skip "coqc not installed" -fi - -# --- Lean 4 proofs --- -echo "" -echo "--- Lean 4 Proofs ---" -if command -v lake >/dev/null 2>&1; then - if (cd "${AZ_DIR}/proofs/lean4" && lake build 2>/dev/null); then - log_pass "lake build (Lean 4)" - else - log_fail "lake build (Lean 4)" - fi -else - log_skip "lake (Lean 4) not installed" -fi - -# --- Z3 SMT --- -echo "" -echo "--- Z3 SMT Verification ---" -if command -v z3 >/dev/null 2>&1; then - if [ -f "${AZ_DIR}/proofs/z3/verify.sh" ]; then - if (cd "${AZ_DIR}/proofs/z3" && bash verify.sh 2>/dev/null); then - log_pass "Z3 verification" - else - log_fail "Z3 verification" - fi - else - log_skip "Z3 verify.sh not found" - fi -else - log_skip "z3 not installed" -fi - -# --- Agda proofs --- -echo "" -echo "--- Agda Proofs ---" -if command -v agda >/dev/null 2>&1; then - if [ -f "${AZ_DIR}/proofs/agda/CNO.agda" ]; then - if agda --safe "${AZ_DIR}/proofs/agda/CNO.agda" 2>/dev/null; then - log_pass "agda --safe CNO.agda" - else - log_fail "agda --safe CNO.agda" - fi - else - log_skip "CNO.agda not found" - fi -else - log_skip "agda not installed" -fi - -# --- Zig FFI --- -echo "" -echo "--- Zig FFI ---" -if command -v zig >/dev/null 2>&1; then - if [ -f "${AZ_DIR}/ffi/zig/build.zig" ]; then - if (cd "${AZ_DIR}/ffi/zig" && zig build test 2>/dev/null); then - log_pass "zig build test (FFI)" - else - log_fail "zig build test (FFI)" - fi - else - log_skip "Zig FFI not found" - fi -else - log_skip "zig not installed" -fi - -# --- Panic Attack --- -echo "" -echo "--- Panic Attack Assail ---" -if command -v panic-attack >/dev/null 2>&1; then - report_file="$(mktemp)" - if panic-attack assail "${AZ_DIR}" --output-format json --output "${report_file}" --quiet 2>/dev/null; then - wp_count=$(python3 -c "import json; d=json.load(open('${report_file}')); print(len(d.get('weak_points',[])))" 2>/dev/null || echo "?") - log_pass "panic-attack assail (${wp_count} weak points)" - else - log_fail "panic-attack assail" - fi - rm -f "${report_file}" -else - log_skip "panic-attack not installed" -fi - -# --- Summary --- -echo "" -echo "===============================" -echo " PASS: ${PASS}" -echo " FAIL: ${FAIL}" -echo " SKIP: ${SKIP}" -echo "===============================" - -if [ "${FAIL}" -gt 0 ]; then - exit 1 -fi diff --git a/absolute-zero/tests/property_based.rs b/absolute-zero/tests/property_based.rs deleted file mode 100644 index ccc9db6..0000000 --- a/absolute-zero/tests/property_based.rs +++ /dev/null @@ -1,203 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell -// -//! Property-Based Tests for absolute-zero. -//! -//! These tests verify properties that must hold across all inputs: -//! - Determinism: same input always produces same output -//! - Idempotence: repeated operations are consistent -//! - Equivalence: different representations of the same operation yield the same result - -use brainfuck_cno::BrainfuckInterpreter; - -#[test] -fn property_brainfuck_deterministic() { - // For a given program, repeated runs should produce identical state - let program = "+++++[-]"; - - for _ in 0..10 { - let mut interp = BrainfuckInterpreter::new(program); - let result1 = interp.is_cno(); - - interp.reset(); - let result2 = interp.is_cno(); - - assert_eq!(result1.is_cno, result2.is_cno); - } -} - -#[test] -fn property_balanced_operations_are_cno() { - // Any balanced sequence of +/- or >/< is a CNO - // Note: "++>--<" modifies cell 0 before moving, so final state may differ - let test_cases = vec![ - "+-", - "+-+-+-", - "++++----", - "<>", - "<><>", - "<<<>>>", - ]; - - for program in test_cases { - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - assert!( - result.is_cno, - "Balanced program '{}' must be CNO, but got: {}", - program, - result.reason - ); - } -} - -#[test] -fn property_output_always_breaks_cno() { - // Any program with . (output) is not a CNO - let test_cases = vec!["+.", ".", "-.", "+-+."]; - - for program in test_cases { - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - assert!( - !result.is_cno, - "Program with output '{}' must NOT be CNO, but got: {}", - program, - result.reason - ); - } -} - -#[test] -fn property_unbalanced_increment_breaks_cno() { - // Any program with net +/- not returning to zero is not CNO - let test_cases = vec!["+", "++", "---", "++-"]; - - for program in test_cases { - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - assert!( - !result.is_cno, - "Unbalanced program '{}' must NOT be CNO", - program - ); - } -} - -#[test] -fn property_unbalanced_pointer_breaks_cno() { - // Any program with net >/< not returning to cell 0 is not CNO - let test_cases = vec![">>", ">>><<>>", ">>>"]; - - for program in test_cases { - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - assert!( - !result.is_cno, - "Pointer displacement '{}' must NOT be CNO", - program - ); - } -} - -#[test] -fn property_comments_are_ignored() { - // Non-command characters should be ignored - let program_with_comments = "+-comments+-more"; - let program_clean = "+-+-"; - - let mut interp1 = BrainfuckInterpreter::new(program_with_comments); - let result1 = interp1.is_cno(); - - let mut interp2 = BrainfuckInterpreter::new(program_clean); - let result2 = interp2.is_cno(); - - // Both should produce the same result (both CNO) - assert_eq!(result1.is_cno, result2.is_cno); -} - -#[test] -fn property_empty_loops_are_cno() { - // [] with zero cell is skipped (CNO) - let program = "[]"; - let mut interp = BrainfuckInterpreter::new(program); - let result = interp.is_cno(); - - assert!(result.is_cno, "Empty loop must be CNO"); -} - -#[test] -fn property_reset_restores_initial_state() { - // After reset(), running again should produce same result - let program = "+-+-"; - let mut interp = BrainfuckInterpreter::new(program); - - let initial_cycles = interp.state.cycles; - interp.run(); - let cycles_after_first = interp.state.cycles; - - interp.reset(); - let cycles_after_reset = interp.state.cycles; - - assert_eq!(cycles_after_reset, initial_cycles); - assert_ne!(cycles_after_reset, cycles_after_first); // Should have reset - - interp.run(); - assert_eq!(interp.state.cycles, cycles_after_first); // Same cycle count -} - -#[test] -fn property_step_by_step_same_as_run() { - // Stepping through a program one instruction at a time - // should yield the same result as running all at once - let program = "+++-"; - - let mut interp1 = BrainfuckInterpreter::new(program); - interp1.run(); - let state1 = interp1.state.clone(); - - let mut interp2 = BrainfuckInterpreter::new(program); - while !interp2.state.halted { - interp2.step(); - } - let state2 = interp2.state.clone(); - - assert_eq!(state1.memory, state2.memory); - assert_eq!(state1.pointer, state2.pointer); - assert_eq!(state1.output_buffer, state2.output_buffer); -} - -#[test] -fn property_cycle_limit_enforces_termination() { - // Programs with potential infinite loops should terminate - let program = "[+]"; - let mut interp = BrainfuckInterpreter::with_max_cycles(program, 100); - - interp.run(); - assert!(interp.state.halted); - assert!(interp.state.cycles <= 100 + 10); // Small buffer for boundary -} - -#[test] -fn property_idempotent_operations() { - // Test that equivalent programs have the same CNO property - let test_pairs = vec![ - ("+-", "+-"), // Same program, definitely equivalent - (">< test", "<>"), // Comments ignored, both balanced - ("+-+-", "+-+-"), // Same program repeated - ]; - - for (prog1, prog2) in test_pairs { - let mut interp1 = BrainfuckInterpreter::new(prog1); - let result1 = interp1.is_cno(); - - let mut interp2 = BrainfuckInterpreter::new(prog2); - let result2 = interp2.is_cno(); - - assert_eq!( - result1.is_cno, result2.is_cno, - "Equivalent programs should have same CNO property: '{}' vs '{}'", - prog1, prog2 - ); - } -} diff --git a/absolute-zero/tests/security_aspects.rs b/absolute-zero/tests/security_aspects.rs deleted file mode 100644 index 68dae86..0000000 --- a/absolute-zero/tests/security_aspects.rs +++ /dev/null @@ -1,163 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell -// -//! Security Aspect Tests for absolute-zero. -//! -//! These tests verify security-critical properties: -//! - No infinite loops without bounds -//! - Pointer stays within memory bounds -//! - Malicious inputs are handled safely - -use brainfuck_cno::BrainfuckInterpreter; - -#[test] -fn security_infinite_loop_bounded() { - // [+] is an infinite loop without max_cycles - let program = "[+]"; - let max_cycles = 10000; - - let mut interp = BrainfuckInterpreter::with_max_cycles(program, max_cycles); - interp.run(); - - // Must halt within the cycle limit - assert!(interp.state.halted); - assert!(interp.state.cycles <= max_cycles); -} - -#[test] -fn security_pointer_never_overflows() { - // Move pointer far to the right - let program = &">".repeat(100_000); - - let mut interp = BrainfuckInterpreter::with_max_cycles(program, 1_000_000); - interp.run(); - - // Pointer should wrap around within memory bounds - assert!(interp.state.pointer < interp.state.memory.len()); -} - -#[test] -fn security_pointer_never_underflows() { - // Try to move pointer below zero - let program = "<"; - - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - // Pointer should wrap around (wrapping semantics) - assert!(interp.state.pointer < interp.state.memory.len()); -} - -#[test] -fn security_memory_never_exceeds_limit() { - // Increment a cell many times - let program = &"+".repeat(1000); - - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - // Memory should not be resized - assert_eq!(interp.state.memory.len(), 30000); // Default size -} - -#[test] -fn security_byte_wrapping_is_safe() { - // Increment beyond u8::MAX - let program = &"+".repeat(300); - - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - // Should wrap around safely (u8 is always < 256 so this always passes) - let _value = interp.state.memory[0]; - assert!(true); // Wrapping is guaranteed by u8 type -} - -#[test] -fn security_unmatched_bracket_halts() { - // Closing bracket with no matching opening - let program = "]]]"; - - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - // Should halt safely - assert!(interp.state.halted); -} - -#[test] -fn security_deeply_nested_loops_bounded() { - // [[[[[[]]]]]] — deeply nested loops - let program = "[[[[[[]]]]]]"; - - let mut interp = BrainfuckInterpreter::with_max_cycles(program, 100_000); - interp.run(); - - // Should handle nested brackets without stack overflow - assert!(interp.state.halted); -} - -#[test] -fn security_large_program_no_dos() { - // Generate a very large program - let mut program = String::new(); - for _ in 0..10000 { - program.push_str("+-"); - } - - let mut interp = BrainfuckInterpreter::with_max_cycles(&program, 100_000); - interp.run(); - - // Should complete in reasonable time/cycles - assert!(interp.state.halted); - assert!(interp.state.cycles < 100_000); -} - -#[test] -fn security_state_isolation_per_instance() { - // Two interpreters should not interfere - let program = "+++"; - - let mut interp1 = BrainfuckInterpreter::new(program); - interp1.run(); - - let mut interp2 = BrainfuckInterpreter::new(program); - interp2.run(); - - // Both should have independent state - assert_eq!(interp1.state.memory[0], 3); - assert_eq!(interp2.state.memory[0], 3); - assert_eq!(interp1.state.cycles, interp2.state.cycles); -} - -#[test] -fn security_reset_clears_sensitive_state() { - // Ensure reset truly clears all state - let program = "+++."; - - let mut interp = BrainfuckInterpreter::new(program); - interp.run(); - - let output_before = interp.state.output_buffer.clone(); - assert!(!output_before.is_empty()); // Had output - - interp.reset(); - - assert!(interp.state.output_buffer.is_empty()); // Output cleared - assert_eq!(interp.state.memory[0], 0); // Memory cleared - assert_eq!(interp.state.pointer, 0); // Pointer reset -} - -#[test] -fn security_input_buffer_exhaustion() { - // Try to read more input than available - let program = ","; - - let mut interp = BrainfuckInterpreter::new(program); - interp.state.input_buffer.push_back(42); // One byte - - interp.run(); - - // Should have read the input - assert_eq!(interp.state.memory[0], 42); -} diff --git a/absolute-zero/tests/unit/cno_properties_test.rs b/absolute-zero/tests/unit/cno_properties_test.rs deleted file mode 100644 index db9c3fc..0000000 --- a/absolute-zero/tests/unit/cno_properties_test.rs +++ /dev/null @@ -1,149 +0,0 @@ -// SPDX-License-Identifier: MPL-2.0 -// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) -// -// Unit tests for CNO (Certified Null Operation) properties -// Tests the core invariants that absolute-zero guarantees - -#[cfg(test)] -mod cno_tests { - /// CNO Property 1: An empty program is always a CNO - #[test] - fn empty_program_is_cno() { - let tape = vec![0u8; 30_000]; - let initial = tape.clone(); - // Empty program: no instructions executed - assert_eq!(tape, initial, "Empty program must not modify state"); - } - - /// CNO Property 2: Balanced increment/decrement is a CNO - #[test] - fn balanced_inc_dec_is_cno() { - let mut tape = vec![0u8; 30_000]; - let initial = tape.clone(); - - // +- cancels out - tape[0] = tape[0].wrapping_add(1); - tape[0] = tape[0].wrapping_sub(1); - - assert_eq!(tape, initial, "+- must cancel to identity"); - } - - /// CNO Property 3: Balanced pointer movement is a CNO - #[test] - fn balanced_pointer_movement_is_cno() { - let mut ptr: usize = 0; - let tape_len = 30_000; - - // >< cancels out - ptr = (ptr + 1) % tape_len; - ptr = ptr.checked_sub(1).unwrap_or(tape_len - 1); - - assert_eq!(ptr, 0, ">< must return pointer to origin"); - } - - /// CNO Property 4: N increments followed by N decrements is a CNO - #[test] - fn n_inc_n_dec_is_cno() { - let mut val: u8 = 0; - let n = 42; - - for _ in 0..n { - val = val.wrapping_add(1); - } - for _ in 0..n { - val = val.wrapping_sub(1); - } - - assert_eq!(val, 0, "N increments + N decrements must equal identity"); - } - - /// CNO Property 5: Wrapping arithmetic preserves CNO (256 increments = identity) - #[test] - fn wrapping_256_is_cno() { - let mut val: u8 = 0; - for _ in 0..256 { - val = val.wrapping_add(1); - } - assert_eq!(val, 0, "256 wrapping increments must overflow back to 0"); - } - - /// Non-CNO: A program that produces output is NOT a CNO - #[test] - fn output_program_is_not_cno() { - let mut output: Vec = Vec::new(); - // '.' instruction writes to output - output.push(65); // ASCII 'A' - assert!(!output.is_empty(), "Program with output is not a CNO"); - } - - /// Non-CNO: Unbalanced operations modify state - #[test] - fn unbalanced_is_not_cno() { - let mut val: u8 = 0; - val = val.wrapping_add(1); - // No decrement — state is modified - assert_ne!(val, 0, "Unbalanced increment is not a CNO"); - } - - /// CNO composition: if A is CNO and B is CNO, then A;B is CNO - #[test] - fn cno_composition() { - let mut tape = vec![0u8; 100]; - let initial = tape.clone(); - - // CNO A: +- on cell 0 - tape[0] = tape[0].wrapping_add(1); - tape[0] = tape[0].wrapping_sub(1); - - // CNO B: ><>< on pointer (no tape mutation) - let mut ptr = 0usize; - ptr = (ptr + 1) % tape.len(); - ptr = ptr.checked_sub(1).unwrap_or(tape.len() - 1); - - assert_eq!(tape, initial, "Composition of CNOs must be a CNO"); - assert_eq!(ptr, 0, "Pointer must return to origin"); - } - - /// CNO parallel: two independent CNOs on disjoint regions compose - #[test] - fn cno_parallel_disjoint() { - let mut tape = vec![0u8; 100]; - let initial = tape.clone(); - - // CNO on cell 0 - tape[0] = tape[0].wrapping_add(5); - tape[0] = tape[0].wrapping_sub(5); - - // CNO on cell 50 (disjoint) - tape[50] = tape[50].wrapping_add(10); - tape[50] = tape[50].wrapping_sub(10); - - assert_eq!(tape, initial, "Parallel CNOs on disjoint regions compose"); - } - - /// Whitespace stack: push then pop is a CNO - #[test] - fn ws_push_pop_is_cno() { - let mut stack: Vec = Vec::new(); - let initial = stack.clone(); - - stack.push(42); - stack.pop(); - - assert_eq!(stack, initial, "Push then pop must be a CNO on the stack"); - } - - /// Whitespace heap: store then restore is a CNO - #[test] - fn ws_heap_store_restore_is_cno() { - use std::collections::HashMap; - let mut heap: HashMap = HashMap::new(); - - // Store value at address 0 - heap.insert(0, 42); - // Restore by removing - heap.remove(&0); - - assert!(heap.is_empty(), "Store then remove must be a CNO on the heap"); - } -} diff --git a/absolute-zero/tools/README.adoc b/absolute-zero/tools/README.adoc new file mode 100644 index 0000000..6bce419 --- /dev/null +++ b/absolute-zero/tools/README.adoc @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: MPL-2.0 += tools/ — Developer tools + +RSR-conventional location for developer utilities (scripts that build, +verify, or inspect the project but are not part of the published +artefact). + +For per-language build entry points, see `Justfile` recipes. +For verification scripts that act as test runners, see `verification/`. diff --git a/absolute-zero/verification/README.adoc b/absolute-zero/verification/README.adoc new file mode 100644 index 0000000..ba5d043 --- /dev/null +++ b/absolute-zero/verification/README.adoc @@ -0,0 +1,15 @@ +// SPDX-License-Identifier: MPL-2.0 += verification/ — Formal verification entry points + +RSR-conventional location for verification scripts. These wrap the +per-prover proof building (Coq, Lean 4, Z3, Agda, Isabelle, Mizar) and +the Idris2 ABI checks. + +== Scripts + +* `setup-and-verify.sh` — bootstrap dependencies + run full verification +* `run-local-verification.sh` — fast local verify (assumes deps already installed) +* `verify-proofs.sh` — proof-suite-only verifier + +For the proof sources themselves, see `proofs/`. +For the Idris2 ABI surface, see `src/abi/` + `absolute-zero-abi.ipkg`. diff --git a/absolute-zero/run-local-verification.sh b/absolute-zero/verification/run-local-verification.sh similarity index 65% rename from absolute-zero/run-local-verification.sh rename to absolute-zero/verification/run-local-verification.sh index d57ca2c..205b774 100755 --- a/absolute-zero/run-local-verification.sh +++ b/absolute-zero/verification/run-local-verification.sh @@ -26,10 +26,6 @@ PASSED_CHECKS=0 FAILED_CHECKS=0 SKIPPED_CHECKS=0 -# Create a secure temporary directory for check logs -TMPDIR_CHECKS="$(mktemp -d)" -trap 'rm -rf "${TMPDIR_CHECKS}"' EXIT - # Function to check if command exists command_exists() { command -v "$1" >/dev/null 2>&1 @@ -38,21 +34,18 @@ command_exists() { # Function to run a check run_check() { local name="$1" - shift - local check_cmd=("$@") + local command="$2" TOTAL_CHECKS=$((TOTAL_CHECKS + 1)) - local log_file="${TMPDIR_CHECKS}/check-${TOTAL_CHECKS}.log" - - echo -n "[${TOTAL_CHECKS}] ${name}... " - if "${check_cmd[@]}" > "${log_file}" 2>&1; then + echo -n "[$TOTAL_CHECKS] $name... " + if eval "$command" > /tmp/absolute-zero-check-$TOTAL_CHECKS.log 2>&1; then echo -e "${GREEN}PASS${NC}" PASSED_CHECKS=$((PASSED_CHECKS + 1)) return 0 else echo -e "${RED}FAIL${NC}" FAILED_CHECKS=$((FAILED_CHECKS + 1)) - echo " Error log: ${log_file}" + echo " Error log: /tmp/absolute-zero-check-$TOTAL_CHECKS.log" return 1 fi } @@ -63,7 +56,7 @@ skip_check() { local reason="$2" TOTAL_CHECKS=$((TOTAL_CHECKS + 1)) SKIPPED_CHECKS=$((SKIPPED_CHECKS + 1)) - echo -e "[${TOTAL_CHECKS}] ${name}... ${YELLOW}SKIP${NC} (${reason})" + echo -e "[$TOTAL_CHECKS] $name... ${YELLOW}SKIP${NC} ($reason)" } echo "==== Tool Availability Check ====" @@ -119,9 +112,9 @@ echo "==== Running Verification ====" echo "" # Z3 SMT Verification -if [ "${Z3_AVAILABLE}" -eq 1 ]; then +if [ $Z3_AVAILABLE -eq 1 ]; then echo "---- Z3 SMT Solver ----" - run_check "Z3: CNO Properties" z3 proofs/z3/cno_properties.smt2 + run_check "Z3: CNO Properties" "z3 proofs/z3/cno_properties.smt2" echo "" else skip_check "Z3: CNO Properties" "z3 not installed" @@ -129,14 +122,14 @@ else fi # Coq Verification -if [ "${COQ_AVAILABLE}" -eq 1 ]; then +if [ $COQ_AVAILABLE -eq 1 ]; then echo "---- Coq Proof Assistant ----" - run_check "Coq: Phase 1 Core (CNO.v)" coqc -Q proofs/coq/common CNO proofs/coq/common/CNO.v - run_check "Coq: Statistical Mechanics" coqc -Q proofs/coq/common CNO -Q proofs/coq/physics Physics proofs/coq/physics/StatMech.v - run_check "Coq: Category Theory" coqc -Q proofs/coq/common CNO -Q proofs/coq/category Category proofs/coq/category/CNOCategory.v - run_check "Coq: Lambda Calculus" coqc -Q proofs/coq/common CNO -Q proofs/coq/lambda Lambda proofs/coq/lambda/LambdaCNO.v - run_check "Coq: Quantum CNO" coqc -Q proofs/coq/common CNO -Q proofs/coq/quantum Quantum proofs/coq/quantum/QuantumCNO.v - run_check "Coq: Filesystem CNO" coqc -Q proofs/coq/common CNO -Q proofs/coq/filesystem Filesystem proofs/coq/filesystem/FilesystemCNO.v + run_check "Coq: Phase 1 Core (CNO.v)" "coqc -Q proofs/coq/common CNO proofs/coq/common/CNO.v" + run_check "Coq: Statistical Mechanics" "coqc -Q proofs/coq/common CNO -Q proofs/coq/physics Physics proofs/coq/physics/StatMech.v" + run_check "Coq: Category Theory" "coqc -Q proofs/coq/common CNO -Q proofs/coq/category Category proofs/coq/category/CNOCategory.v" + run_check "Coq: Lambda Calculus" "coqc -Q proofs/coq/common CNO -Q proofs/coq/lambda Lambda proofs/coq/lambda/LambdaCNO.v" + run_check "Coq: Quantum CNO" "coqc -Q proofs/coq/common CNO -Q proofs/coq/quantum Quantum proofs/coq/quantum/QuantumCNO.v" + run_check "Coq: Filesystem CNO" "coqc -Q proofs/coq/common CNO -Q proofs/coq/filesystem Filesystem proofs/coq/filesystem/FilesystemCNO.v" echo "" else skip_check "Coq: All proofs" "coqc not installed" @@ -144,10 +137,10 @@ else fi # Lean 4 Verification -if [ "${LEAN_AVAILABLE}" -eq 1 ]; then +if [ $LEAN_AVAILABLE -eq 1 ]; then echo "---- Lean 4 Proof Assistant ----" if [ -f "proofs/lean4/lakefile.lean" ]; then - run_check "Lean 4: Build all proofs" bash -c "cd proofs/lean4 && lake build" + run_check "Lean 4: Build all proofs" "cd proofs/lean4 && lake build" else skip_check "Lean 4: Build all proofs" "lakefile.lean not found" fi @@ -158,9 +151,9 @@ else fi # Agda Verification -if [ "${AGDA_AVAILABLE}" -eq 1 ]; then +if [ $AGDA_AVAILABLE -eq 1 ]; then echo "---- Agda Proof Assistant ----" - run_check "Agda: CNO Core" agda proofs/agda/CNO.agda + run_check "Agda: CNO Core" "agda proofs/agda/CNO.agda" echo "" else skip_check "Agda: CNO Core" "agda not installed" @@ -168,9 +161,9 @@ else fi # Isabelle Verification -if [ "${ISABELLE_AVAILABLE}" -eq 1 ]; then +if [ $ISABELLE_AVAILABLE -eq 1 ]; then echo "---- Isabelle/HOL ----" - run_check "Isabelle: CNO Theory" isabelle build -d proofs/isabelle -b CNO + run_check "Isabelle: CNO Theory" "isabelle build -d proofs/isabelle -b CNO" echo "" else skip_check "Isabelle: CNO Theory" "isabelle not installed" @@ -182,22 +175,22 @@ echo "========================================" echo "Verification Summary" echo "========================================" echo "" -echo "Total checks: ${TOTAL_CHECKS}" -echo -e "${GREEN}Passed: ${PASSED_CHECKS}${NC}" -echo -e "${RED}Failed: ${FAILED_CHECKS}${NC}" -echo -e "${YELLOW}Skipped: ${SKIPPED_CHECKS}${NC}" +echo "Total checks: $TOTAL_CHECKS" +echo -e "${GREEN}Passed: $PASSED_CHECKS${NC}" +echo -e "${RED}Failed: $FAILED_CHECKS${NC}" +echo -e "${YELLOW}Skipped: $SKIPPED_CHECKS${NC}" echo "" -if [ "${FAILED_CHECKS}" -eq 0 ] && [ "${PASSED_CHECKS}" -gt 0 ]; then +if [ $FAILED_CHECKS -eq 0 ] && [ $PASSED_CHECKS -gt 0 ]; then echo -e "${GREEN}✓ All available verifications passed!${NC}" exit 0 -elif [ "${PASSED_CHECKS}" -eq 0 ]; then +elif [ $PASSED_CHECKS -eq 0 ]; then echo -e "${YELLOW}⚠ No verification tools available locally${NC}" echo "Consider installing: coqc, z3, lean, agda, isabelle" echo "Or run: podman build -t absolute-zero . && podman run --rm absolute-zero ./verify-proofs.sh" exit 2 else echo -e "${RED}✗ Some verifications failed${NC}" - echo "Check error logs in ${TMPDIR_CHECKS}/" + echo "Check error logs in /tmp/absolute-zero-check-*.log" exit 1 fi diff --git a/absolute-zero/setup-and-verify.sh b/absolute-zero/verification/setup-and-verify.sh similarity index 87% rename from absolute-zero/setup-and-verify.sh rename to absolute-zero/verification/setup-and-verify.sh index 5d5d26b..fe88f0e 100755 --- a/absolute-zero/setup-and-verify.sh +++ b/absolute-zero/verification/setup-and-verify.sh @@ -14,7 +14,7 @@ export GIT_DISCOVERY_ACROSS_FILESYSTEM=1 cd "$(dirname "$0")" REPO_ROOT=$(pwd) -echo "Repository root: ${REPO_ROOT}" +echo "Repository root: $REPO_ROOT" echo "" # ============================================================================ @@ -75,11 +75,11 @@ echo "=== Step 3: Tool Availability ===" echo "" check_tool() { - if command -v "$1" &> /dev/null; then - echo "✓ $1: $(command -v "$1")" + if command -v $1 &> /dev/null; then + echo "✓ $1: $(command -v $1)" return 0 else - echo "✗ ${1}: NOT FOUND" + echo "✗ $1: NOT FOUND" return 1 fi } @@ -117,7 +117,7 @@ fi echo "" -if [ "${#MISSING_TOOLS[@]}" -gt 0 ]; then +if [ ${#MISSING_TOOLS[@]} -gt 0 ]; then echo "❌ Missing REQUIRED tools: ${MISSING_TOOLS[*]}" echo "" echo "Install with:" @@ -132,7 +132,7 @@ if [ "${#MISSING_TOOLS[@]}" -gt 0 ]; then echo "" fi -if [ "${#OPTIONAL_TOOLS[@]}" -gt 0 ]; then +if [ ${#OPTIONAL_TOOLS[@]} -gt 0 ]; then echo "ℹ️ Missing OPTIONAL tools: ${OPTIONAL_TOOLS[*]}" echo "" echo "Install with:" @@ -159,16 +159,16 @@ echo "Coq proofs:" COQC_TOTAL=$(find proofs/coq -name "*.v" -exec grep -h "^Theorem\|^Lemma\|^Corollary" {} \; 2>/dev/null | wc -l) COQC_ADMITTED=$(grep -r "Admitted\." proofs/coq/ 2>/dev/null | wc -l) COQC_PROVEN=$((COQC_TOTAL - COQC_ADMITTED)) -if [ "${COQC_TOTAL}" -gt 0 ]; then +if [ $COQC_TOTAL -gt 0 ]; then COQC_PERCENT=$((COQC_PROVEN * 100 / COQC_TOTAL)) else COQC_PERCENT=0 fi -echo " Total theorems: ${COQC_TOTAL}" -echo " Proven: ${COQC_PROVEN}" -echo " Admitted: ${COQC_ADMITTED}" -echo " Completion: ${COQC_PERCENT}%" +echo " Total theorems: $COQC_TOTAL" +echo " Proven: $COQC_PROVEN" +echo " Admitted: $COQC_ADMITTED" +echo " Completion: $COQC_PERCENT%" echo "" # Count Lean theorems and sorry @@ -176,26 +176,26 @@ echo "Lean 4 proofs:" LEAN_TOTAL=$(find proofs/lean4 -name "*.lean" -exec grep -h "^theorem\|^lemma" {} \; 2>/dev/null | wc -l) LEAN_SORRY=$(grep -r "sorry" proofs/lean4/ 2>/dev/null | wc -l) LEAN_PROVEN=$((LEAN_TOTAL - LEAN_SORRY)) -if [ "${LEAN_TOTAL}" -gt 0 ]; then +if [ $LEAN_TOTAL -gt 0 ]; then LEAN_PERCENT=$((LEAN_PROVEN * 100 / LEAN_TOTAL)) else LEAN_PERCENT=0 fi -echo " Total theorems: ${LEAN_TOTAL}" -echo " Proven: ${LEAN_PROVEN}" -echo " Sorry: ${LEAN_SORRY}" -echo " Completion: ${LEAN_PERCENT}%" +echo " Total theorems: $LEAN_TOTAL" +echo " Proven: $LEAN_PROVEN" +echo " Sorry: $LEAN_SORRY" +echo " Completion: $LEAN_PERCENT%" echo "" # List files with Admitted/sorry -if [ "${COQC_ADMITTED}" -gt 0 ]; then +if [ $COQC_ADMITTED -gt 0 ]; then echo "Files with Admitted:" grep -r "Admitted\." proofs/coq/ 2>/dev/null | cut -d: -f1 | sort -u | sed 's/^/ - /' echo "" fi -if [ "${LEAN_SORRY}" -gt 0 ]; then +if [ $LEAN_SORRY -gt 0 ]; then echo "Files with sorry:" grep -r "sorry" proofs/lean4/ 2>/dev/null | cut -d: -f1 | sort -u | sed 's/^/ - /' echo "" @@ -210,7 +210,7 @@ echo "" read -p "Run verification now? (y/n) " -n 1 -r echo "" -if [[ "${REPLY}" =~ ^[Yy]$ ]]; then +if [[ $REPLY =~ ^[Yy]$ ]]; then if command -v just &> /dev/null; then echo "Using Justfile..." just verify-all @@ -250,8 +250,8 @@ echo "" echo "Choose what you want to do:" echo "" echo "1. FIX ADMITTED PROOFS:" -echo " - ${COQC_ADMITTED} Coq proofs need completion" -echo " - ${LEAN_SORRY} Lean proofs need completion" +echo " - $COQC_ADMITTED Coq proofs need completion" +echo " - $LEAN_SORRY Lean proofs need completion" echo " See files listed above" echo "" echo "2. VERIFY EXISTING PROOFS:" @@ -305,13 +305,13 @@ Next Priority: EOF # Substitute actual values -sed -i "s/{COQC_PROVEN}/${COQC_PROVEN}/g" QUICKSTART.txt -sed -i "s/{COQC_TOTAL}/${COQC_TOTAL}/g" QUICKSTART.txt -sed -i "s/{COQC_PERCENT}/${COQC_PERCENT}/g" QUICKSTART.txt -sed -i "s/{LEAN_PROVEN}/${LEAN_PROVEN}/g" QUICKSTART.txt -sed -i "s/{LEAN_TOTAL}/${LEAN_TOTAL}/g" QUICKSTART.txt -sed -i "s/{LEAN_PERCENT}/${LEAN_PERCENT}/g" QUICKSTART.txt -sed -i "s/{COQC_ADMITTED}/${COQC_ADMITTED}/g" QUICKSTART.txt +sed -i "s/{COQC_PROVEN}/$COQC_PROVEN/g" QUICKSTART.txt +sed -i "s/{COQC_TOTAL}/$COQC_TOTAL/g" QUICKSTART.txt +sed -i "s/{COQC_PERCENT}/$COQC_PERCENT/g" QUICKSTART.txt +sed -i "s/{LEAN_PROVEN}/$LEAN_PROVEN/g" QUICKSTART.txt +sed -i "s/{LEAN_TOTAL}/$LEAN_TOTAL/g" QUICKSTART.txt +sed -i "s/{LEAN_PERCENT}/$LEAN_PERCENT/g" QUICKSTART.txt +sed -i "s/{COQC_ADMITTED}/$COQC_ADMITTED/g" QUICKSTART.txt echo "✓ Created QUICKSTART.txt with current status" echo "" diff --git a/absolute-zero/verify-proofs.sh b/absolute-zero/verification/verify-proofs.sh similarity index 78% rename from absolute-zero/verify-proofs.sh rename to absolute-zero/verification/verify-proofs.sh index 5d45b82..98d4fe9 100755 --- a/absolute-zero/verify-proofs.sh +++ b/absolute-zero/verification/verify-proofs.sh @@ -31,21 +31,21 @@ SKIPPED_TESTS=0 # Helper functions log_info() { - echo -e "${BLUE}[INFO]${NC} ${1}" + echo -e "${BLUE}[INFO]${NC} $1" } log_success() { - echo -e "${GREEN}[✓]${NC} ${1}" + echo -e "${GREEN}[✓]${NC} $1" ((PASSED_TESTS++)) } log_failure() { - echo -e "${RED}[✗]${NC} ${1}" + echo -e "${RED}[✗]${NC} $1" ((FAILED_TESTS++)) } log_skip() { - echo -e "${YELLOW}[SKIP]${NC} ${1}" + echo -e "${YELLOW}[SKIP]${NC} $1" ((SKIPPED_TESTS++)) } @@ -57,34 +57,29 @@ check_command() { fi } -# Create a secure temporary directory for test output -TMPDIR_VERIFY="$(mktemp -d)" -trap 'rm -rf "${TMPDIR_VERIFY}"' EXIT - run_test() { local test_name="$1" - shift - local test_cmd=("$@") + local test_command="$2" ((TOTAL_TESTS++)) - local log_file="${TMPDIR_VERIFY}/test_output_${TOTAL_TESTS}.log" - if $VERBOSE; then echo "" - log_info "Running: ${test_name}" - log_info "Command: ${test_cmd[*]}" + log_info "Running: $test_name" + log_info "Command: $test_command" fi - if "${test_cmd[@]}" &> "${log_file}"; then - log_success "${test_name}" + if eval "$test_command" &> /tmp/test_output_$$.log; then + log_success "$test_name" if $VERBOSE; then - cat "${log_file}" + cat /tmp/test_output_$$.log fi + rm -f /tmp/test_output_$$.log return 0 else - log_failure "${test_name}" + log_failure "$test_name" echo " Error output:" - sed 's/^/ /' "${log_file}" | head -20 + sed 's/^/ /' /tmp/test_output_$$.log | head -20 + rm -f /tmp/test_output_$$.log return 1 fi } @@ -112,10 +107,10 @@ if check_command coqc; then log_info "Coq found: $(coqc --version | head -1)" run_test "Coq: CNO.v (common)" \ - bash -c "cd proofs/coq/common && coqc CNO.v" + "cd proofs/coq/common && coqc CNO.v" run_test "Coq: MalbolgeCore.v" \ - bash -c "cd proofs/coq/malbolge && coqc -R ../common CNO MalbolgeCore.v" + "cd proofs/coq/malbolge && coqc -R ../common CNO MalbolgeCore.v" else log_skip "Coq not installed (coqc not found)" ((TOTAL_TESTS+=2)) @@ -134,11 +129,11 @@ if check_command z3; then # Check if verify.sh exists and is executable if [[ -x "proofs/z3/verify.sh" ]]; then run_test "Z3: CNO properties" \ - bash -c "cd proofs/z3 && ./verify.sh" + "cd proofs/z3 && ./verify.sh" else # Run z3 directly run_test "Z3: CNO properties" \ - bash -c "cd proofs/z3 && z3 cno_properties.smt2 | grep -q 'sat'" + "cd proofs/z3 && z3 cno_properties.smt2 | grep -q 'sat'" fi else log_skip "Z3 not installed (z3 not found)" @@ -156,7 +151,7 @@ if check_command lean; then log_info "Lean found: $(lean --version | head -1)" run_test "Lean 4: CNO.lean" \ - bash -c "cd proofs/lean4 && lake build" + "cd proofs/lean4 && lake build" else log_skip "Lean 4 not installed (lean not found)" ((TOTAL_TESTS+=1)) @@ -173,7 +168,7 @@ if check_command agda; then log_info "Agda found: $(agda --version | head -1)" run_test "Agda: CNO.agda" \ - bash -c "cd proofs/agda && agda CNO.agda" + "cd proofs/agda && agda CNO.agda" else log_skip "Agda not installed (agda not found)" ((TOTAL_TESTS+=1)) @@ -190,7 +185,7 @@ if check_command isabelle; then log_info "Isabelle found: $(isabelle version)" run_test "Isabelle/HOL: CNO.thy" \ - isabelle build -D proofs/isabelle + "isabelle build -D proofs/isabelle" else log_skip "Isabelle/HOL not installed (isabelle not found)" ((TOTAL_TESTS+=1)) @@ -206,14 +201,14 @@ echo "========================================" echo " Verification Summary" echo "========================================" echo "" -echo "Total tests: ${TOTAL_TESTS}" -echo -e "Passed: ${GREEN}${PASSED_TESTS}${NC}" -echo -e "Failed: ${RED}${FAILED_TESTS}${NC}" -echo -e "Skipped: ${YELLOW}${SKIPPED_TESTS}${NC}" +echo "Total tests: $TOTAL_TESTS" +echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}" +echo -e "Failed: ${RED}$FAILED_TESTS${NC}" +echo -e "Skipped: ${YELLOW}$SKIPPED_TESTS${NC}" echo "" -if [[ "${FAILED_TESTS}" -eq 0 ]]; then - if [[ "${SKIPPED_TESTS}" -eq 0 ]]; then +if [[ $FAILED_TESTS -eq 0 ]]; then + if [[ $SKIPPED_TESTS -eq 0 ]]; then echo -e "${GREEN}✓ All proofs verified successfully!${NC}" exit 0 else