diff --git a/.github/workflows/formal-gate.yml b/.github/workflows/formal-gate.yml new file mode 100644 index 000000000..bdf07fa41 --- /dev/null +++ b/.github/workflows/formal-gate.yml @@ -0,0 +1,85 @@ +name: Layer 1 formal gate (Lean kernel replay) +'on': + pull_request: + paths: ['formal/**', '.github/workflows/formal-gate.yml'] + push: + branches: [main] + paths: ['formal/**', '.github/workflows/formal-gate.yml'] + workflow_dispatch: +permissions: + contents: read +jobs: + gate-controls: + name: gate tests, mutants, pins (no Lean) + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.11' + - name: Pins, tests in both modes, gate replay + env: + PYTHONDONTWRITEBYTECODE: '1' + run: | + set -euo pipefail + python -B -S formal/pin_sources.py --check + python -B -S formal/run_validation.py --output "$RUNNER_TEMP/formal-gate-run" + python -B -S - <<'PY' + import json, os, pathlib + report = json.loads((pathlib.Path(os.environ['RUNNER_TEMP']) / 'formal-gate-run' / 'REPORT.json').read_text()) + if not report['passed'] or report['distinct_tests'] != 27 or report['distinct_semantic_mutants'] != 33: + raise SystemExit('unexpected gate-control scope') + if report['mathematical_acceptance'] is not False or report['lemma_closed'] is not False or report['scientific_effect'] != 'NONE': + raise SystemExit('forbidden scientific promotion') + print('FORMAL_GATE_CONTROLS_PASSED') + PY + - name: Preserve evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: formal-gate-controls-${{ github.run_id }} + path: ${{ runner.temp }}/formal-gate-run + if-no-files-found: error + retention-days: 30 + + lean-kernel: + name: lake build + #print axioms evidence replay + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: '3.11' + - name: Build the pinned Lean project (Mathlib cache) + uses: leanprover/lean-action@50fcf42d2e460296f1a34b402e990d1b24f8b596 + with: + lake-package-directory: formal/lean + use-mathlib-cache: true + build: true + test: false + lint: false + auto-config: false + - name: Regenerate kernel evidence and compare with committed bytes + env: + PYTHONDONTWRITEBYTECODE: '1' + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/formal-kernel" + python -B -S formal/lean_build_evidence.py --check | tee "$RUNNER_TEMP/formal-kernel/evidence_check.log" + python -B -S formal/formal_gate.py --json | tee "$RUNNER_TEMP/formal-kernel/gate_report.txt" + python -B -S formal/blueprint_check.py | tee "$RUNNER_TEMP/formal-kernel/blueprint_check.txt" + git diff --exit-code + - name: Preserve evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: formal-kernel-${{ github.run_id }} + path: ${{ runner.temp }}/formal-kernel + if-no-files-found: error + retention-days: 30 diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..7a60b85e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +__pycache__/ +*.pyc diff --git a/AGENTS.md b/AGENTS.md index 6a9c83c0c..65ee38fa2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,8 +14,21 @@ Private exploratory workspace. Eng-only pointers; **no** research-status flips. - Treat a green local probe as theorem discharge or claim closure. - Ask Dylan for re-approval of work already covered by owner autonomy. +## Layer 1 — formal verification (Lean 4 + Mathlib) + +Owner instruction 2026-09-27 (pre-approved, no re-approval): extend the verification stack +with a formal lane. It lives in [`formal/`](formal/README.md) until ported to Math- +([`handoff/`](handoff/README.md) has per-repository patches and the hard-gate extension spec). + +- Ladders: `formalization_status ∈ none < specified < proved < kernel-checked`, + `formalization_review ∈ none | author-side | nonauthor-aligned`. Declared ≤ verifiable, enforced by `formal_gate.py`. +- Every formal token is **non-discharge** except `KERNEL_CHECKED_NONAUTHOR_ALIGNED`, which satisfies the formal lane only. +- Any `.lean` edit regenerates `SOURCE_FILES.json` + `BUILD_EVIDENCE.json` and updates `lean_statement`/blueprint/glossary in the same commit. No `sorry`; parents parametrized or registered `axiom`s with scope notes. +- Kernel acceptance ≠ statement alignment ≠ analytic acceptance. `lemma_closed` stays false. + ## Start here 1. This [README](README.md) 2. [`governance-` working contract](https://github.com/d6g8k5htny-coder/governance-) 3. [`trial` multi-agent access](https://github.com/d6g8k5htny-coder/trial/blob/main/docs/MULTI_AGENT_ACCESS.md) — add **sandbox** to every App install; Cloud Agent env deps / `repositoryDependencies` are declared on trial only +4. [`formal/README.md`](formal/README.md) then [`handoff/README.md`](handoff/README.md) — the formal lane and what each repository does next diff --git a/README.md b/README.md index 4e8251f9b..3de8aaec8 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,18 @@ scientific-status register. | `governance-` | Cross-repository working contract | | `sandbox` | experiments only — automatic public export | -copy sandbox files, outputs, paths, or hashes into public catalogs, -public workflow artifacts, or Drive replicas. +Do not copy sandbox files, outputs, paths, or hashes into public catalogs, +public workflow artifacts, or Drive replicas. + +## Layer 1 — formal verification (Lean 4 + Mathlib) + +[`formal/`](formal/README.md) holds the formal-verification lane: a Lean 4 + Mathlib +project kernel-checking components of the Math- SIDE24 coefficient note, a fail-closed +`formalization_status` gate (`none < specified < proved < kernel-checked`), byte-bound +kernel evidence, a Lean Blueprint, a terminology glossary and an alignment-review lane. +[`handoff/`](handoff/README.md) carries the per-repository patches and the Math- hard-gate +extension spec so every agent on `main`, `Math-`, `trial` and `governance-` can take it up. +Kernel acceptance is not statement alignment and not analytic acceptance. Scientific effect from this README: **NONE**. Never flip `lemma_closed`, prizes, or premises. Agent entry: [AGENTS.md](AGENTS.md). diff --git a/formal/BUILD_EVIDENCE.json b/formal/BUILD_EVIDENCE.json new file mode 100644 index 000000000..a65bb23bf --- /dev/null +++ b/formal/BUILD_EVIDENCE.json @@ -0,0 +1,199 @@ +{ + "build": { + "command": "lake build", + "exit_code": 0 + }, + "declarations": { + "Side24.D2_algebra": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.D2_bounds": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.D2_lt_untruncated": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.cone_integral_identity": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.covariance_relative_lt_eps": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.density_comparison_lt_reported": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.enclosure_of_reference": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.enclosure_statement": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.exp_neg_288_lt": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.exp_partial_sum_gt_ten": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.exponent_budget_d2": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.exponent_budget_d3": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.gaussian_exp_moment": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.gaussian_fourth_moment": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.geometric_ratio_lt_half": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.image_constant_eq": { + "axioms": [ + "propext" + ] + }, + "Side24.periodization_statement": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.perturbed_bounds": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.ratio_bound_statement": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.referenceCoefficient": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.reference_enclosure_statement": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + }, + "Side24.ten_lt_exp_288_div_125": { + "axioms": [ + "Classical.choice", + "Quot.sound", + "propext" + ] + } + }, + "lean_version": "Lean (version 4.34.1, x86_64-unknown-linux-gnu, commit 5045d0056413266e57c625dcd7c365b10e377c52, Release)", + "lemma_closed": false, + "mathlib_rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "meaning": "kernel acceptance of the encoded statements at these exact bytes; not translation fidelity, not theorem acceptance", + "object": "FORMAL-LAYER-BUILD-EVIDENCE-v1", + "schema_version": 1, + "scientific_effect": "NONE", + "sorry_free": true, + "sources": { + "Side24Formal.lean": { + "bytes": 88, + "sha256": "75307dcf6471d6201557fd610013e2a5ef5a47b27b2011f88fa3eb34ee7d06d5" + }, + "Side24Formal/ConeMoment.lean": { + "bytes": 8182, + "sha256": "b34affce872a8ffdbd9e738e8e8c3ad6b02f89422f12b9bf65c45b6c6b9288c5" + }, + "Side24Formal/Ledger.lean": { + "bytes": 4189, + "sha256": "d3be23f13130614b3858f9a1262c4141c87a1a1d8dbcb77879ffd6a62b85716b" + }, + "Side24Formal/Reference.lean": { + "bytes": 6206, + "sha256": "0281d652a01997964ec72facda9ea76bcb660f332dbacfd8bf45ee59b8782cec" + }, + "lake-manifest.json": { + "bytes": 3146, + "sha256": "b6bf071a38d455614c7628855312ec82d1045afaf0a561e4124c173de203fa40" + }, + "lakefile.toml": { + "bytes": 169, + "sha256": "a7dd307f3c5dbbfb0ed6b7e43f2149332a1770834de69214c9c02504a1eb3dac" + }, + "lean-toolchain": { + "bytes": 25, + "sha256": "d5edba4e4b8faad9c1baeadb265716d20d03be4d1a2647dc5e35b0c0325bea7b" + } + }, + "toolchain": "leanprover/lean4:v4.34.1" +} diff --git a/formal/FORMALIZATION_REVIEW_LANE.md b/formal/FORMALIZATION_REVIEW_LANE.md new file mode 100644 index 000000000..37fe54b42 --- /dev/null +++ b/formal/FORMALIZATION_REVIEW_LANE.md @@ -0,0 +1,94 @@ +# Formalization review lane (statement alignment) + +**Object:** FORMAL-REVIEW-LANE-20260927-v1. **Scientific effect: NONE.** + +The Lean kernel already re-checks every proof. What it cannot check is whether the +Lean *statement* says what the informal theorem says. That is the only job of this +lane. The reviewer does **not** re-prove anything. + +This lane sits beside — and does not replace — the existing review topology +([`governance-/REVIEW_TOPOLOGY.md`](https://github.com/d6g8k5htny-coder/governance-/blob/main/REVIEW_TOPOLOGY.md)): +author derivation, same-author replay, nonauthor analytic review and formal +verification stay distinct. An `ALIGNED` verdict here is *evidence consumed by* the +Math- hard gate; it never assigns scientific status by itself. + +## Ladder + +| `formalization_review` | Meaning | Who may set it | +|---|---|---| +| `none` | component has no Lean artifact | — | +| `author-side` | the formal author wrote both the Lean text and the `lean_statement` binding; unreviewed | the formal author (default) | +| `nonauthor-aligned` | a distinct reviewer attested statement alignment; record bound to the module sha256 | only by adding a review record that `formal_gate.py` accepts | + +`formal_gate.py` refuses `nonauthor-aligned` unless the record exists, has verdict +`ALIGNED`, binds the *current* module bytes and the *current* `lean_statement`, and +declares `authored_formalization: false`. Any edit to the Lean module stales the +review (hash mismatch → gate FAIL) — carrying approval across heads silently is +impossible by construction. + +## Reviewer checklist + +For each component under review (one record per component): + +1. **Read the informal statement** at the exact pinned source + (`objects[].informal_source`: repository / path / commit / sha256). Read the + `informal_ref` pointer (section, equation). +2. **Read the Lean declaration** named `lean_decl` in `lean_module` at the pinned + sha256 (`SOURCE_FILES.json`). Confirm `lean_statement` is the declaration you read. +3. **Check hypotheses = scope.** Every hypothesis of the Lean theorem must be either + in the informal statement or explicitly listed in `does_not_claim` / the docstring. + Anything the Lean statement assumes that the prose does not, or vice versa, is a + finding. +4. **Check quantifiers, domains, normalisations.** Real vs rational literals, strict vs + non-strict inequalities, `ℕ` subtraction, `d ∈ {2,3}` vs all `d`, measure + normalisation (`gaussianReal 0 v` takes the *variance* `v`), interval endpoints. +5. **Check the glossary.** Every project term in the informal statement must have a + `MAPPED` row in `GLOSSARY.md` whose standard object is what the Lean text encodes. +6. **Check `does_not_claim`.** It must be accurate and not understate what the Lean + statement leaves open. +7. **Check `conditional_on`.** If the gate report lists assumed axioms, confirm each + has a scope note in the `assumed_axioms` registry and that the informal source + treats the same dependency as open. +8. Record **one** of: `ALIGNED`, `AMEND_REQUIRED` (with the exact mismatch), or + `BLOCKED` (cannot read the pinned source). `AMEND_REQUIRED`/`BLOCKED` are recorded + findings, never acceptance. + +## Record format (`formal/reviews/..json`) + +```json +{ + "review_id": "FREV-20260927-side24.ledger.image-constant-openai", + "component_id": "side24.ledger.image-constant", + "verdict": "ALIGNED", + "reviewed_module": "Side24Formal/Ledger.lean", + "reviewed_module_sha256": "", + "reviewed_lean_statement": "", + "informal_source": {"repository": "d6g8k5htny-coder/Math-", "path": "coefficients/side24_v1/PROOF.md", "commit": "760340e921ac4ceda296b8118da936f1133e956e", "sha256": "c06daccc4ba4b9168522b9888b76a7d599934fc3b91bd753ee5d492262917769"}, + "findings": [], + "reviewer_provenance": { + "provider": "OpenAI", + "model_family": "GPT", + "session": "UNKNOWN", + "authored_formalization": false, + "source_exposure": "read pinned PROOF.md and Ledger.lean only" + }, + "timestamp": "2026-09-27T00:00:00Z", + "scientific_effect": "NONE" +} +``` + +Provenance rules follow REVIEW_TOPOLOGY v1.1: unknown values stay `UNKNOWN`; a +same-provider or unknown-provider review earns **no** organizational-independence +credit (the gate reports `organizational_independence: false` in that case, and +`ATTESTED_NOT_VALIDATED` otherwise — never `true`, because no validator exists). +The reviewer who edits the Lean file becomes a co-author of the successor and cannot +supply its nonauthor key. + +## What the lane is not + +* Not a proof check — the kernel does that (`BUILD_EVIDENCE.json`). +* Not an analytic review of the informal theorem — that stays on main issues (#63, #65). +* Not organizational-independence validation — attested only. +* Not promotion — even `KERNEL_CHECKED_NONAUTHOR_ALIGNED` on every component only + satisfies the *formal lane* of the Math- hard gate; the analytic lanes and the #90 + rules still apply, and `lemma_closed` stays `false`. diff --git a/formal/FORMALIZATION_STATUS.json b/formal/FORMALIZATION_STATUS.json new file mode 100644 index 000000000..799197b78 --- /dev/null +++ b/formal/FORMALIZATION_STATUS.json @@ -0,0 +1,314 @@ +{ + "schema_version": 1, + "object": "FORMAL-LAYER-STATUS-20260927-v1", + "layer": "L1-formal (Lean 4 + Mathlib); Layer 0 = provenance/scope/hard gate in Math-", + "repository": "d6g8k5htny-coder/sandbox", + "scientific_effect": "NONE", + "lemma_closed": false, + "mathematical_acceptance": false, + "status_ladder": [ + "none", + "specified", + "proved", + "kernel-checked" + ], + "review_ladder": [ + "none", + "author-side", + "nonauthor-aligned" + ], + "standard_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "assumed_axioms": [], + "assumed_axioms_meaning": "registry of every `axiom` written in the Lean project (parent theorems assumed, not verified); each needs a scope note; a kernel-checked theorem depending on one is CONDITIONAL and never satisfies the formal lane", + "lean": { + "project_root": "formal/lean", + "toolchain": "leanprover/lean4:v4.34.1", + "mathlib": { + "scope": "leanprover-community", + "rev": "v4.34.1" + }, + "build_evidence": "formal/BUILD_EVIDENCE.json" + }, + "ladder_meaning": { + "none": "no Lean artifact", + "specified": "the statement (or object) is a Lean definition that compiles; nothing is proved", + "proved": "a sorry-free Lean theorem exists in the pinned module (author-side text-level check only)", + "kernel-checked": "BUILD_EVIDENCE.json records `lake build` success and `#print axioms` ⊆ standard ∪ declared assumed axioms for exactly these source bytes", + "author-side": "formalization written by the formal author; statement alignment unreviewed", + "nonauthor-aligned": "a distinct reviewer attested that the Lean statement matches the informal statement, bound to the module sha256 (FORMALIZATION_REVIEW_LANE.md)" + }, + "objects": [ + { + "object_id": "SIDE24-COEFFICIENT-D23-20260924-v1", + "hard_gate_node": "math.side24-coefficient", + "informal_source": { + "repository": "d6g8k5htny-coder/Math-", + "path": "coefficients/side24_v1/PROOF.md", + "commit": "760340e921ac4ceda296b8118da936f1133e956e", + "blob": "44b66f04f89fcd87383b3603fa69f1feb64cdddd", + "sha256": "c06daccc4ba4b9168522b9888b76a7d599934fc3b91bd753ee5d492262917769" + }, + "informal_disposition": "AUTHOR_SIDE_CANDIDATE in Math- GRAPH.json; HOLD_WITH_DOMAIN in LANDING_CLAIMS.json; parent main #63 unreviewed", + "authorship": { + "informal_provider": "OpenAI / ChatGPT", + "formal_provider": "Anthropic / Claude (Cursor cloud agent)", + "formal_note": "AI-generated Lean; author-side until a distinct reviewer aligns statements" + }, + "parent_dependencies": [ + { + "id": "main#63:eq15.2-parent", + "formalization_status": "none", + "handling": "not introduced as a Lean axiom; every statement about c_d,24 is parametrized by an arbitrary c : ℕ → ℝ, so the hypotheses of enclosure_of_reference are the scope" + } + ], + "components": [ + { + "component_id": "side24.ledger.image-constant", + "informal_ref": "PROOF.md §2 eq.(2): E = 1458·(76·24^6+15)·10^(-125) = 21175738586478·10^(-125)", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.image_constant_eq", + "lean_statement": "theorem image_constant_eq : (1458 : ℕ) * (76 * 24 ^ 6 + 15) = 21175738586478", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the derivative bound (2) itself: only the integer product is checked" + }, + { + "component_id": "side24.ledger.exp-partial-sum", + "informal_ref": "PROOF.md §2: \"The code proves e^(288/125)>10 using the positive rational Taylor sum through 20\" — the rational partial sum", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.exp_partial_sum_gt_ten", + "lean_statement": "theorem exp_partial_sum_gt_ten : (10 : ℝ) < ∑ i ∈ range 21, ((288 : ℝ) / 125) ^ i / (Nat.factorial i : ℝ)", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "that the partial sum bounds exp (that is the next component)" + }, + { + "component_id": "side24.ledger.exp-lower", + "informal_ref": "PROOF.md §2: e^(288/125) > 10", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.ten_lt_exp_288_div_125", + "lean_statement": "theorem ten_lt_exp_288_div_125 : (10 : ℝ) < Real.exp (288 / 125)", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "anything about the periodic covariance" + }, + { + "component_id": "side24.ledger.exp-neg-288", + "informal_ref": "PROOF.md §2: \"hence e^(-288)<10^(-125)\"", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.exp_neg_288_lt", + "lean_statement": "theorem exp_neg_288_lt : Real.exp (-288) < 1 / (10 : ℝ) ^ 125", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the image-sum inequality that uses it" + }, + { + "component_id": "side24.ledger.geometric-ratio", + "informal_ref": "PROOF.md §2: \"successive terms have ratio at most 512e^(-864)<1/2\"", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.geometric_ratio_lt_half", + "lean_statement": "theorem geometric_ratio_lt_half : (512 : ℝ) * Real.exp (-864) < 1 / 2", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "that the displayed ratio is the correct term ratio of the image series (informal step)" + }, + { + "component_id": "side24.ledger.covariance-relative", + "informal_ref": "PROOF.md eq.(3): 60E < ε = 10^(-108)", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.covariance_relative_lt_eps", + "lean_statement": "theorem covariance_relative_lt_eps : (60 : ℚ) * (21175738586478 / 10 ^ 125) < 1 / 10 ^ 108", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the spectral-norm and Schur-complement comparison (3) itself" + }, + { + "component_id": "side24.ledger.density-comparison", + "informal_ref": "PROOF.md §4: \"safely between 1-32ε and 1+32ε\", hence (4) with 32ε < 10^(-106)", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.density_comparison_lt_reported", + "lean_statement": "theorem density_comparison_lt_reported : (32 : ℚ) / 10 ^ 108 < 1 / 10 ^ 106", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the ratio bound 1±32ε (specified separately)" + }, + { + "component_id": "side24.ledger.exponent-budget-d2", + "informal_ref": "PROOF.md §4: a=m+2/3+n/2, b=d+n/2; for d=2, a+2b<14 and 2a+b<13", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.exponent_budget_d2", + "lean_statement": "theorem exponent_budget_d2 : a 2 + 2 * b 2 < 14 ∧ 2 * a 2 + b 2 < 13", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the Gaussian density comparison that motivates a and b" + }, + { + "component_id": "side24.ledger.exponent-budget-d3", + "informal_ref": "PROOF.md §4: for d=3, a+2b<14 and 2a+b<13", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.exponent_budget_d3", + "lean_statement": "theorem exponent_budget_d3 : a 3 + 2 * b 3 < 14 ∧ 2 * a 3 + b 3 < 13", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the Gaussian density comparison that motivates a and b" + }, + { + "component_id": "side24.ledger.ratio-bound", + "informal_ref": "PROOF.md §4: \"elementary bounds on log(1+ε), -log(1-ε) and exp give ratio ... safely between 1-32ε and 1+32ε\"", + "lean_module": "Side24Formal/Ledger.lean", + "lean_decl": "Side24.ratio_bound_statement", + "lean_statement": "def ratio_bound_statement : Prop := ∀ d ∈ ({2, 3} : Finset ℕ), ∀ ε : ℝ, 0 < ε → ε < 1 / 28 → (1 + ε) ^ (a d : ℝ) / (1 - ε) ^ (b d : ℝ) < 1 + 32 * ε ∧ 1 - 32 * ε < (1 - ε) ^ (a d : ℝ) / (1 + ε) ^ (b d : ℝ)", + "formalization_status": "specified", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "truth of the statement; it is a Prop definition without proof" + }, + { + "component_id": "side24.cone.integral-identity", + "informal_ref": "PROOF.md §1: ∫_0^a (a-z)^2 e^(-z/2) dz/2 = a^2-4a+8-8e^(-a/2) (informal: a ≥ 0; formal: every real a)", + "lean_module": "Side24Formal/ConeMoment.lean", + "lean_decl": "Side24.cone_integral_identity", + "lean_statement": "theorem cone_integral_identity (a : ℝ) : ∫ z in (0 : ℝ)..a, (a - z) ^ 2 * Real.exp (-z / 2) / 2 = a ^ 2 - 4 * a + 8 - 8 * Real.exp (-a / 2)", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "that this integral is the conditional cone moment (Gaussian step is specified separately)" + }, + { + "component_id": "side24.cone.d2-algebra", + "informal_ref": "PROOF.md §1: D_2 = (1/2)[25/3-20/3+8-8sqrt(3/8)] = 29/6-sqrt(6)", + "lean_module": "Side24Formal/ConeMoment.lean", + "lean_decl": "Side24.D2_algebra", + "lean_statement": "theorem D2_algebra : (1 / 2 : ℝ) * (25 / 3 - 20 / 3 + 8 - 8 * Real.sqrt (3 / 8)) = D2", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the Gaussian moment values 25/3, 5/3, sqrt(3/8) (specified separately)" + }, + { + "component_id": "side24.cone.d2-bounds", + "informal_ref": "ENCLOSURE.json cone_moments[\"3\"] = \"29/6-sqrt(6)\"; outward decimal enclosure of that constant", + "lean_module": "Side24Formal/ConeMoment.lean", + "lean_decl": "Side24.D2_bounds", + "lean_statement": "theorem D2_bounds : (2.38384359054 : ℝ) < D2 ∧ D2 < 2.38384359056", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "that 29/6-sqrt(6) is the true cone moment of the periodic law" + }, + { + "component_id": "side24.cone.truncation-essential", + "informal_ref": "PROOF.md §1: \"half the UNTRUNCATED determinant-squared moment would instead give 29/6, an incorrect value\"", + "lean_module": "Side24Formal/ConeMoment.lean", + "lean_decl": "Side24.D2_lt_untruncated", + "lean_statement": "theorem D2_lt_untruncated : D2 < 29 / 6", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "which of the two values is the cone moment; only that they differ (D_2 < 29/6)" + }, + { + "component_id": "side24.cone.gaussian-fourth-moment", + "informal_ref": "PROOF.md §1: \"E s^2=5/3, E s^4=25/3\" for the shared shift s ~ N(0,5/3)", + "lean_module": "Side24Formal/ConeMoment.lean", + "lean_decl": "Side24.gaussian_fourth_moment", + "lean_statement": "theorem gaussian_fourth_moment : (∫ s, s ^ 4 ∂(gaussianReal 0 (5 / 3 : NNReal))) = 25 / 3", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "that s (the trace-direction shift of the conditional Hessian) has law N(0,5/3); only the moment of that law (gaussianReal takes the variance as second argument)" + }, + { + "component_id": "side24.cone.gaussian-exp-moment", + "informal_ref": "PROOF.md §1: \"E exp(-s^2/2)=sqrt(3/8)\" for s ~ N(0,5/3)", + "lean_module": "Side24Formal/ConeMoment.lean", + "lean_decl": "Side24.gaussian_exp_moment", + "lean_statement": "theorem gaussian_exp_moment : (∫ s, Real.exp (-s ^ 2 / 2) ∂(gaussianReal 0 (5 / 3 : NNReal))) = Real.sqrt (3 / 8)", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "the law of s; only the integral of exp(-s^2/2) against N(0,5/3)" + }, + { + "component_id": "side24.reference.definition", + "informal_ref": "PROOF.md eq.(1): c_d,ref = Γ(7/6)(3/2)^(1/3) D_(d-1) / [2√3 π^(d-1) √π]", + "lean_module": "Side24Formal/Reference.lean", + "lean_decl": "Side24.referenceCoefficient", + "lean_statement": "noncomputable def referenceCoefficient (d : ℕ) : ℝ := Real.Gamma (7 / 6) * (3 / 2 : ℝ) ^ ((1 : ℝ) / 3) * coneMoment (d - 1) / (2 * Real.sqrt 3 * Real.pi ^ (d - 1) * Real.sqrt Real.pi)", + "formalization_status": "specified", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "that c_d,ref equals the parent coefficient; it is the nonperiodic reference expression only" + }, + { + "component_id": "side24.reference.enclosure-statement", + "informal_ref": "coefficient.py reference_coefficient(d): 80-digit outward rational enclosure of c_d,ref (author rational-interval arithmetic)", + "lean_module": "Side24Formal/Reference.lean", + "lean_decl": "Side24.reference_enclosure_statement", + "lean_statement": "def reference_enclosure_statement : Prop := (ref2Lo : ℝ) < referenceCoefficient 2 ∧ referenceCoefficient 2 < ref2Hi ∧ (ref3Lo : ℝ) < referenceCoefficient 3 ∧ referenceCoefficient 3 < ref3Hi", + "formalization_status": "specified", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "kernel verification of Γ(7/6), π and root enclosures; informal evidence is the Python interval code" + }, + { + "component_id": "side24.reference.periodization", + "informal_ref": "PROOF.md eq.(4): |c_d,24/c_d,ref - 1| < 10^(-106), d=2,3", + "lean_module": "Side24Formal/Reference.lean", + "lean_decl": "Side24.periodization_statement", + "lean_statement": "def periodization_statement (c : ℕ → ℝ) : Prop := ∀ d ∈ ({2, 3} : Finset ℕ), |c d / referenceCoefficient d - 1| < (periodizationBound : ℝ)", + "formalization_status": "specified", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "truth of (4); depends on the unformalized parent (main #63) and §3–§4 analysis" + }, + { + "component_id": "side24.reference.perturbed-bounds", + "informal_ref": "PROOF.md §5: relative perturbation applied to exact rational endpoints", + "lean_module": "Side24Formal/Reference.lean", + "lean_decl": "Side24.perturbed_bounds", + "lean_statement": "theorem perturbed_bounds {c r lo hi δ : ℝ} (hlo : 0 < lo) (h₁ : lo < r) (h₂ : r < hi) (hδ : 0 < δ) (hδ1 : δ < 1) (h : |c / r - 1| < δ) : (1 - δ) * lo < c ∧ c < (1 + δ) * hi", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "any numerical value; pure real-inequality lemma" + }, + { + "component_id": "side24.reference.enclosure-of-reference", + "informal_ref": "PROOF.md §5: \"The periodization allowance in (4) is applied to exact rational endpoints BEFORE the final outward rounding\" — the implication (reference enclosure ∧ (4)) → displayed bounds", + "lean_module": "Side24Formal/Reference.lean", + "lean_decl": "Side24.enclosure_of_reference", + "lean_statement": "theorem enclosure_of_reference (c : ℕ → ℝ) (href : reference_enclosure_statement) (hper : periodization_statement c) : enclosure_statement c", + "formalization_status": "kernel-checked", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "either hypothesis; the theorem is conditional on two specified Props" + }, + { + "component_id": "side24.theorem.enclosure", + "informal_ref": "PROOF.md displayed theorem: 0.07340691930603427103 < c_2,24 < 0.07340691930603427104 and 0.04177593184059834334 < c_3,24 < 0.04177593184059834335", + "lean_module": "Side24Formal/Reference.lean", + "lean_decl": "Side24.enclosure_statement", + "lean_statement": "def enclosure_statement (c : ℕ → ℝ) : Prop := (0.07340691930603427103 : ℝ) < c 2 ∧ c 2 < 0.07340691930603427104 ∧ (0.04177593184059834334 : ℝ) < c 3 ∧ c 3 < 0.04177593184059834335", + "formalization_status": "specified", + "formalization_review": "author-side", + "review_record": null, + "does_not_claim": "truth for the parent-defined c_d,24; the periodic coefficient is not defined in Lean (parent main #63 unformalized)" + } + ] + } + ] +} diff --git a/formal/GLOSSARY.md b/formal/GLOSSARY.md new file mode 100644 index 000000000..04c7953eb --- /dev/null +++ b/formal/GLOSSARY.md @@ -0,0 +1,55 @@ +# Formal glossary — project terms → standard mathematics → Lean + +**Object:** FORMAL-GLOSSARY-20260927-v1. **Scientific effect: NONE.** This table +changes no claim status. It exists so that every non-standard term used in the +research repositories has a standard mathematical meaning *before* it is formalized, +and so that external readers (journals, Lean community, AI provers) can read the work +without project vocabulary. + +Rules (from the Layer 1 roadmap): + +1. A term that cannot be mapped to a standard object is either **ill-defined** or + **novel**. Both are recorded as `UNMAPPED`; novelty must be justified against the + literature before the term is used in a Lean statement. +2. A Lean name in the last column means the standard object is *defined* in + `formal/lean`. It does not mean anything about it is proved; see + `FORMALIZATION_STATUS.json` for the status of each statement. +3. Extend this table in the same change that introduces a new term to a Lean file. + +| Project term | Where it is used | Standard mathematical object | Lean (`Side24` namespace) | Mapping status | +|---|---|---|---|---| +| Universal Law mathematics | repo names (`query-`, ULW) | Umbrella label for the programme: **Gaussian random fields** and **persistent homology of excursion/level sets** (H₀ bars of a smooth Gaussian field on a torus). Not a mathematical object. | — | PROJECT-LABEL | +| SIDE24 / `K_24` | Math- `coefficients/side24_v1` | Stationary centred Gaussian field on the flat torus `(ℝ/24ℤ)^d`, `d ∈ {2,3}`, with covariance the **periodisation** of the Gaussian kernel `exp(-|z|²/2)`, normalised to variance one | not yet (covariance not formalised) | MAPPED (definition only in prose) | +| image sum / omitted periodic images | PROOF.md §2 | The lattice sum `Σ_{n≠0} φ(z+24n)` and its derivatives; the **Poisson-periodisation remainder** | arithmetic inputs only: `image_constant_eq`, `exp_neg_288_lt`, `geometric_ratio_lt_half` | MAPPED | +| contact covariance / reference law | PROOF.md §1 | Joint Gaussian law of `(∇f, ∇²f, ∂₁³f)` at a point for the non-periodic kernel `exp(-|z|²/2)`; conditional covariance via **Schur complement** | — | MAPPED (not formalised) | +| shared scalar shift `Z I_m` / `s` | PROOF.md §1 | Trace-direction component of the conditional Hessian; a centred Gaussian scalar with variance `5/3` for `m=2` | `gaussian_fourth_moment`, `gaussian_exp_moment` | MAPPED | +| cone moment `D_m` | PROOF.md §1, ENCLOSURE.json | `E[det(A)² · 1{A ≺ 0}]` for the conditional Gaussian symmetric `m×m` matrix `A`; the **negative-definite cone** is `{A ≺ 0}` | `D2`, `coneMoment`, `cone_integral_identity`, `D2_algebra` | MAPPED | +| untruncated half moment | PROOF.md §1 | `½·E[det(A)²]` without the indicator; the incorrect value `29/6` | `D2_lt_untruncated` | MAPPED | +| lifetime coefficient `c_{d,24}` | PROOF.md, main #63 eq. 15.2 | Leading coefficient in the **Kac–Rice** expression for the density of H₀ bar lifetimes (birth–death gaps) of the field; defined by the parent source | *parametrised* as an arbitrary `c : ℕ → ℝ` in `enclosure_statement`, `periodization_statement` | MAPPED-BY-REFERENCE (parent unformalised) | +| reference coefficient `c_{d,ref}` | PROOF.md eq. (1) | `Γ(7/6)·(3/2)^{1/3}·D_{d-1} / (2√3·π^{d-1}·√π)` | `referenceCoefficient` | MAPPED | +| lifetime density / per-unit-volume lifetime density | Math- `LIFETIME_REMAINDER.md`, LANDING_CLAIMS | Intensity measure (w.r.t. `dℓ`) of the point process of finite H₀ bar lengths of a Gaussian field on a torus, normalised by volume | — | MAPPED (not formalised) | +| elder rule / elder selection | main #63, `LIFETIME_REMAINDER.md` | Standard **elder rule** of persistent homology: when two components merge at a saddle, the younger (higher-birth) component dies | — | MAPPED (standard term) | +| elder density | main #63 | Conditional density of critical points (saddle/maximum pairs) given the elder-rule pairing event — i.e. a conditional Kac–Rice density | — | MAPPED (prose only) | +| candidate density | project reviews | Density of a *specified* Gaussian field model proposed as a candidate; the word "candidate" is a review status, not mathematics | — | PROJECT-LABEL | +| pin / pin Jacobian / height-gradient pin | PROOF.md, RN packages | Conditioning on `∇f = 0` (and a height value) in Kac–Rice; the Jacobian factor `|det ∇²f|` | — | MAPPED | +| RN / 24-jet / JETMOD | GRAPH.json, governance | Project labels for a family of remainder/jet-modulus obligations on the D3–D5 layers; each must be mapped individually when formalised | — | UNMAPPED (label family; map per object) | +| P15 | Math- `frontiers/*price*` | A **combinatorial optimisation** family (price budgets, palettes, demands) unrelated to Gaussian fields; own glossary needed | — | OUT-OF-SCOPE for this glossary | +| outward rational arithmetic | coefficient.py | **Interval arithmetic** over ℚ with outward rounding to a fixed grid `10^{-80}` | rational endpoints `ref2Lo`, …; transfer lemma `perturbed_bounds` | MAPPED | +| periodization allowance | PROOF.md §5 | Relative error bound `|c/c_ref − 1| < 10^{-106}` applied multiplicatively to the reference enclosure | `periodizationBound`, `enclosure_of_reference` | MAPPED | +| hard gate | Math- `frontiers/downstream_gate_20260925` | Engineering: fail-closed promotion control over a dependency graph. Not mathematics. | — | ENGINEERING | +| verification museum | main `docs/site` | Engineering: public display of pinned source bytes and review status. Not mathematics. | — | ENGINEERING | +| kernel-checked | this layer | A Lean 4 declaration accepted by the Lean kernel with `#print axioms ⊆ {propext, Classical.choice, Quot.sound}` at pinned source bytes | `BUILD_EVIDENCE.json` | ENGINEERING (defined in `FORMALIZATION_STATUS.json`) | + +## Standard references used for the mappings + +* Kac–Rice formula and Gaussian critical points: Adler & Taylor, *Random Fields and Geometry* (2007), Ch. 11–12. +* Elder rule / persistence barcodes: Edelsbrunner & Harer, *Computational Topology* (2010), Ch. VII. +* Gaussian conditioning / Schur complement: any multivariate-normal reference (e.g. Anderson, *Introduction to Multivariate Statistical Analysis*, §2.5). +* Gamma function remainder (Stirling): NIST DLMF §5.11 (cited in PROOF.md). + +## Unmapped terms — action + +`RN`, `24-jet`, `JETMOD` are label families. Before any Lean statement mentions them, +the responsible author adds a row per concrete object (statement, domain, normalisation) +to this table. Until then they stay `UNMAPPED` and cannot appear in +`FORMALIZATION_STATUS.json`. diff --git a/formal/README.md b/formal/README.md new file mode 100644 index 000000000..1c34f4046 --- /dev/null +++ b/formal/README.md @@ -0,0 +1,139 @@ +# Layer 1 — formal verification (Lean 4 + Mathlib) + +**Object:** FORMAL-LAYER-20260927-v1. **Engineering author:** Cursor cloud agent +(Anthropic / Claude), author-side. **Scientific effect: NONE.** `lemma_closed` stays +`false`; nothing here promotes, closes or discharges a claim. + +## What this is + +The research stack already has **Layer 0**: provenance (SHA-256, commits, blobs), +explicit scope and "does not claim" statements, review-status tracking, the fail-closed +Math- hard gate and the public verification museum. Layer 0 verifies *identity* and +*process*. It cannot verify *logic*. + +Layer 1 adds machine-checked logic without replacing anything: + +| Layer | Verifies | Where | +|---|---|---| +| 0 provenance / scope / hard gate | these bytes are the reviewed bytes; scope is explicit; promotion is fail-closed | Math- `frontiers/downstream_gate_20260925`, `claims/LANDING_CLAIMS.json`, main museum | +| **1 formal (this directory)** | the encoded statement is a theorem of Lean 4 + Mathlib (kernel-checked); the statement text is byte-bound to the informal object | `formal/lean`, `FORMALIZATION_STATUS.json`, `BUILD_EVIDENCE.json` | +| 1r alignment review | the Lean statement means what the prose means | `FORMALIZATION_REVIEW_LANE.md`, `formal/reviews/` | +| 2 analytic nonauthor review, peer review | significance and correctness of the informal mathematics | main issues (#63, #65 …), journals | + +The hard gate is meant to enforce that no lane is skipped. Layer 1 emits tokens for it +(below); it never decides promotion. + +## Status ladder (`formalization_status`) and review ladder + +``` +none < specified < proved < kernel-checked formalization_review: none | author-side | nonauthor-aligned +``` + +* `specified` — the statement (or object) is a Lean definition that compiles. Nothing proved. +* `proved` — a sorry-free Lean theorem exists in the pinned module (text-level, author-side). +* `kernel-checked` — `BUILD_EVIDENCE.json` records `lake build` success and + `#print axioms ⊆ {propext, Classical.choice, Quot.sound} ∪ registered assumed axioms`, + bound to exactly the pinned source bytes. + +`formal_gate.py` recomputes the *verifiable* level for every component and fails if the +*declared* level is higher. Declared ≤ verifiable is the only direction allowed. + +Tokens handed to the Math- hard gate (see `handoff/MATH_HARD_GATE_EXTENSION.md`): + +| Token | When | Discharge? | +|---|---|---| +| `FORMAL_SPECIFIED` | statement exists | non-discharge | +| `FORMAL_PROVED_AUTHOR_SIDE` | sorry-free theorem, no kernel evidence | non-discharge | +| `KERNEL_CHECKED_AUTHOR_SIDE` | kernel evidence, alignment unreviewed | non-discharge | +| `KERNEL_CHECKED_CONDITIONAL` | kernel evidence but depends on a registered assumed axiom (e.g. an unformalized parent theorem) | non-discharge | +| `KERNEL_CHECKED_NONAUTHOR_ALIGNED` | kernel evidence **and** a distinct reviewer's alignment record bound to these bytes, no assumed axioms | satisfies the *formal lane only*; analytic lanes and #90 rules still apply | + +## Pilot: SIDE24 coefficient (Math- `coefficients/side24_v1/PROOF.md`) + +Bound to commit `760340e921ac4ceda296b8118da936f1133e956e`, sha256 +`c06daccc…7769` (the same identity the museum and `GRAPH.json` pin). 22 components: + +* **kernel-checked (16):** the §2–§4 arithmetic ledger (image constant, `e^{288/125} > 10` + via Mathlib's exponential partial sums, `e^{-288} < 10^{-125}`, `512e^{-864} < 1/2`, + `60E < ε`, `32ε < 10^{-106}`, exponent budgets for `d = 2, 3`); the §1 cone integral + `∫₀ᵃ (a−z)²e^{−z/2}dz/2 = a²−4a+8−8e^{−a/2}`; the §1 Gaussian inputs `E s⁴ = 25/3` (via + the MGF `mgf_id_gaussianReal`) and `E e^{−s²/2} = √(3/8)` (via `integral_gaussian`) for + `s ~ N(0, 5/3)`; the algebra `D₂ = 29/6 − √6`, its outward enclosure and `D₂ < 29/6` + (truncation essential); the §5 transfer lemma and the implication + *(reference enclosure ∧ eq. (4)) ⇒ displayed 20-digit bounds*. +* **specified (6):** the §4 ratio bound `1 ± 32ε`; the reference coefficient eq. (1) as a + definition; the author's 80-digit reference enclosure; eq. (4); and the displayed + theorem itself. + +The periodic coefficient `c_{d,24}` is **not** defined in Lean because its definition is +the unformalized parent (main #63, eq. 15.2). Every statement about it is parametrized by +an arbitrary `c : ℕ → ℝ`, so the hypotheses of `Side24.enclosure_of_reference` *are* the +scope. No parent theorem is introduced as an axiom; the `assumed_axioms` registry is +empty. The headline theorem therefore stays `specified`, honestly. + +The private sandbox Monte Carlo (`experiments/cone_v1`) samples `D₂` — it is now a +sanity check against a kernel-checked constant, and still not evidence of anything. + +## Run + +```sh +python -B -S formal/pin_sources.py --check # Lean bytes match SOURCE_FILES.json +python -B -S formal/formal_gate.py # status ≤ evidence, alignment bytes, axioms +python -B -S formal/blueprint_check.py # blueprint ↔ status +python -B -S -m unittest discover -s formal -p 'test_*.py' -v +python -B -O -S -m unittest discover -s formal -p 'test_*.py' -v +python -B -S formal/run_validation.py --output /tmp/formal-gate-new-run +``` + +27 distinct tests and 33 assertion-detected semantic mutants are required in both Python +modes. With a Lean toolchain (`elan`, toolchain in `formal/lean/lean-toolchain`): + +```sh +cd formal/lean && lake exe cache get && lake build && cd ../.. +python -B -S formal/lean_build_evidence.py --check # regenerate evidence, cmp with committed +``` + +CI (`.github/workflows/formal-gate.yml`) runs both: the Python controls, and a Lean job +that rebuilds with the Mathlib cache, regenerates `BUILD_EVIDENCE.json` and refuses any +byte difference. + +## Changing anything + +* Edit a `.lean` file → regenerate `SOURCE_FILES.json` (`pin_sources.py`) and + `BUILD_EVIDENCE.json` (`lean_build_evidence.py`) in the same commit, and update the + `lean_statement` of any component whose header changed. Any `nonauthor-aligned` review + of that module is now stale (hash mismatch) and must be redone — by design. +* Add a theorem → add a component (`informal_ref`, `lean_statement`, `does_not_claim`), + a blueprint environment, and a glossary row for any new project term. +* Need a parent theorem you cannot prove → do **not** add `sorry`. Either parametrize + (preferred, as here) or add a Lean `axiom` *and* a registry entry with a scope note; the + dependent theorems become `KERNEL_CHECKED_CONDITIONAL`. +* Never widen `standard_axioms`, never set `lemma_closed`/`mathematical_acceptance`, never + extend the ladders. Each of these is a refused mutant. + +## Files + +| File | Role | +|---|---| +| `lean/` | Lake project (`Side24Formal`), toolchain `leanprover/lean4:v4.34.1`, Mathlib `v4.34.1` | +| `FORMALIZATION_STATUS.json` | per-component declared status, verbatim statements, informal source binding | +| `SOURCE_FILES.json` | byte/sha256 pins of the Lean project | +| `BUILD_EVIDENCE.json` | deterministic `lake build` + `#print axioms` record (no timestamps) | +| `formal_gate.py`, `test_formal_gate.py` | the gate and its mutants | +| `blueprint/`, `blueprint_check.py` | Lean Blueprint document and alignment check | +| `GLOSSARY.md` | project terms → standard mathematics → Lean names | +| `FORMALIZATION_REVIEW_LANE.md` | alignment reviewer protocol and record format | +| `run_validation.py` | both-mode replay with `REPORT.json` | + +## Roadmap (from the Layer 1 plan) + +1. ✔ Pilot on SIDE24 (this directory). 2. ✔ Glossary. 3. ✔ Review lane defined (no +review yet — every component is `author-side`). 4. ✔ CI `lake build` + evidence replay +here; **Math- hard gate extension pending** (see `handoff/`). 5. Expand: prove the +remaining `specified` Props (the `1 ± 32ε` ratio bound; `Γ(7/6)`/`π` enclosures — the +Gaussian moments were `specified` in the first revision and are now kernel-checked, which is +the intended ladder progression), then the next Math- object (BF six-pin certificates are exact +finite arithmetic — good candidates). 6. External validation once a nonauthor alignment +review exists. 7. AI-prover cross-check lane: run an independent Lean prover on the +`specified` Props; any kernel-accepted proof is recorded as evidence with its own +provenance, still author-side until aligned. diff --git a/formal/SOURCE_FILES.json b/formal/SOURCE_FILES.json new file mode 100644 index 000000000..80f210ce7 --- /dev/null +++ b/formal/SOURCE_FILES.json @@ -0,0 +1,37 @@ +{ + "files": { + "Side24Formal.lean": { + "bytes": 88, + "sha256": "75307dcf6471d6201557fd610013e2a5ef5a47b27b2011f88fa3eb34ee7d06d5" + }, + "Side24Formal/ConeMoment.lean": { + "bytes": 8182, + "sha256": "b34affce872a8ffdbd9e738e8e8c3ad6b02f89422f12b9bf65c45b6c6b9288c5" + }, + "Side24Formal/Ledger.lean": { + "bytes": 4189, + "sha256": "d3be23f13130614b3858f9a1262c4141c87a1a1d8dbcb77879ffd6a62b85716b" + }, + "Side24Formal/Reference.lean": { + "bytes": 6206, + "sha256": "0281d652a01997964ec72facda9ea76bcb660f332dbacfd8bf45ee59b8782cec" + }, + "lake-manifest.json": { + "bytes": 3146, + "sha256": "b6bf071a38d455614c7628855312ec82d1045afaf0a561e4124c173de203fa40" + }, + "lakefile.toml": { + "bytes": 169, + "sha256": "a7dd307f3c5dbbfb0ed6b7e43f2149332a1770834de69214c9c02504a1eb3dac" + }, + "lean-toolchain": { + "bytes": 25, + "sha256": "d5edba4e4b8faad9c1baeadb265716d20d03be4d1a2647dc5e35b0c0325bea7b" + } + }, + "meaning": "byte identities of the Lean project; a match proves identity, not correctness or acceptance", + "object": "FORMAL-LAYER-SOURCE-FILES-v1", + "project_root": "formal/lean", + "schema_version": 1, + "scientific_effect": "NONE" +} diff --git a/formal/blueprint/README.md b/formal/blueprint/README.md new file mode 100644 index 000000000..19966059a --- /dev/null +++ b/formal/blueprint/README.md @@ -0,0 +1,26 @@ +# Lean Blueprint — SIDE24 pilot + +`src/content.tex` is a [leanblueprint](https://github.com/PatrickMassot/leanblueprint) +document: informal statements with `\lean{}` bindings to declarations in +`formal/lean`, `\leanok` where the proof is kernel-checked, and `\uses{}` for the +dependency graph. + +Two checks keep it honest: + +* `python -B -S formal/blueprint_check.py` — every `\lean{}` name must be a component + in `FORMALIZATION_STATUS.json`; `\leanok` is allowed only on `kernel-checked` + components; every formalized component must appear. Run in CI. +* `formal_gate.py` binds each component's `lean_statement` verbatim to the module + bytes, so the Lean statement cannot drift from what the blueprint aligned. + +To render (optional, not required by CI): + +```sh +pip install leanblueprint # needs a TeX distribution + plasTeX +cd formal/blueprint && leanblueprint pdf && leanblueprint web +``` + +`lean_decls` lists the bound declarations for `lake exe checkdecls` if a future +change adds the `checkdecls` dependency to `lakefile.toml`. + +Scientific effect: NONE. diff --git a/formal/blueprint/lean_decls b/formal/blueprint/lean_decls new file mode 100644 index 000000000..f0aca3e2e --- /dev/null +++ b/formal/blueprint/lean_decls @@ -0,0 +1,22 @@ +Side24.image_constant_eq +Side24.exp_partial_sum_gt_ten +Side24.ten_lt_exp_288_div_125 +Side24.exp_neg_288_lt +Side24.geometric_ratio_lt_half +Side24.covariance_relative_lt_eps +Side24.density_comparison_lt_reported +Side24.exponent_budget_d2 +Side24.exponent_budget_d3 +Side24.ratio_bound_statement +Side24.cone_integral_identity +Side24.gaussian_fourth_moment +Side24.gaussian_exp_moment +Side24.D2_algebra +Side24.D2_bounds +Side24.D2_lt_untruncated +Side24.referenceCoefficient +Side24.reference_enclosure_statement +Side24.periodization_statement +Side24.perturbed_bounds +Side24.enclosure_statement +Side24.enclosure_of_reference diff --git a/formal/blueprint/src/content.tex b/formal/blueprint/src/content.tex new file mode 100644 index 000000000..4be8e11cb --- /dev/null +++ b/formal/blueprint/src/content.tex @@ -0,0 +1,116 @@ +% Lean Blueprint for the SIDE24 pilot (Layer 1). +% Each environment is bound to a Lean declaration with \lean{}; \leanok marks a +% kernel-checked proof (status kernel-checked in FORMALIZATION_STATUS.json). +% Environments without \leanok are *specified*: the Lean statement exists, no proof. +% Scientific effect: NONE. + +\chapter{Scope} + +This blueprint aligns the informal note +\href{https://github.com/d6g8k5htny-coder/Math-/blob/760340e921ac4ceda296b8118da936f1133e956e/coefficients/side24_v1/PROOF.md}{\texttt{coefficients/side24\_v1/PROOF.md}} +(object \texttt{SIDE24-COEFFICIENT-D23-20260924-v1}, author OpenAI/ChatGPT) with the Lean +project \texttt{formal/lean}. The periodic coefficient $c_{d,24}$ is defined by the parent +source (main~\#63, eq.~15.2), which is not formalised; every statement about it is +parametrised by an arbitrary $c:\mathbb N\to\mathbb R$. + +\chapter{Image ledger (PROOF.md \S2--\S4)} + +\begin{lemma}\label{lem:image-constant}\lean{Side24.image_constant_eq}\leanok +$1458\cdot(76\cdot 24^6+15)=21175738586478$. +\end{lemma} + +\begin{lemma}\label{lem:exp-partial-sum}\lean{Side24.exp_partial_sum_gt_ten}\leanok +$\sum_{i=0}^{20} (288/125)^i/i! > 10$. +\end{lemma} + +\begin{lemma}\label{lem:exp-lower}\lean{Side24.ten_lt_exp_288_div_125}\leanok\uses{lem:exp-partial-sum} +$e^{288/125}>10$. +\end{lemma} + +\begin{lemma}\label{lem:exp-neg}\lean{Side24.exp_neg_288_lt}\leanok\uses{lem:exp-lower} +$e^{-288}<10^{-125}$. +\end{lemma} + +\begin{lemma}\label{lem:ratio}\lean{Side24.geometric_ratio_lt_half}\leanok\uses{lem:exp-lower} +$512\,e^{-864}<1/2$. +\end{lemma} + +\begin{lemma}\label{lem:cov}\lean{Side24.covariance_relative_lt_eps}\leanok +$60\cdot 21175738586478\cdot 10^{-125} < 10^{-108}$. +\end{lemma} + +\begin{lemma}\label{lem:density}\lean{Side24.density_comparison_lt_reported}\leanok +$32\cdot 10^{-108}<10^{-106}$. +\end{lemma} + +\begin{lemma}\label{lem:budget2}\lean{Side24.exponent_budget_d2}\leanok +For $d=2$: with $m=d-1$, $n=m(m+1)/2$, $a=m+2/3+n/2$, $b=d+n/2$, one has $a+2b<14$ and $2a+b<13$. +\end{lemma} + +\begin{lemma}\label{lem:budget3}\lean{Side24.exponent_budget_d3}\leanok +The same for $d=3$. +\end{lemma} + +\begin{proposition}\label{prop:ratio-bound}\lean{Side24.ratio_bound_statement} +For $d\in\{2,3\}$ and $0<\varepsilon<1/28$, +$(1+\varepsilon)^a/(1-\varepsilon)^b<1+32\varepsilon$ and $1-32\varepsilon<(1-\varepsilon)^a/(1+\varepsilon)^b$. +\emph{Specified only; not proved.} +\end{proposition} + +\chapter{Cone moment (PROOF.md \S1)} + +\begin{lemma}\label{lem:cone-integral}\lean{Side24.cone_integral_identity}\leanok +For every real $a$, $\int_0^a (a-z)^2 e^{-z/2}\,dz/2 = a^2-4a+8-8e^{-a/2}$. +(The prose states $a\ge 0$; the identity holds for all $a$.) +\end{lemma} + +\begin{lemma}\label{lem:gaussian-fourth}\lean{Side24.gaussian_fourth_moment}\leanok +For $s\sim N(0,5/3)$: $\mathbb E s^4=25/3$ (via the moment-generating function). +\end{lemma} + +\begin{lemma}\label{lem:gaussian-exp}\lean{Side24.gaussian_exp_moment}\leanok +For $s\sim N(0,5/3)$: $\mathbb E e^{-s^2/2}=\sqrt{3/8}$ (via $\int e^{-bx^2}=\sqrt{\pi/b}$). +\end{lemma} + +\begin{lemma}\label{lem:d2-algebra}\lean{Side24.D2_algebra}\leanok\uses{lem:cone-integral,lem:gaussian-fourth,lem:gaussian-exp} +$\tfrac12\bigl[25/3-20/3+8-8\sqrt{3/8}\bigr]=29/6-\sqrt6 =: D_2$. +\end{lemma} + +\begin{lemma}\label{lem:d2-bounds}\lean{Side24.D2_bounds}\leanok +$2.38384359054 dict: + formal = root / 'formal' + status = fg.load_json_strict((formal / 'FORMALIZATION_STATUS.json').read_text(encoding='utf-8')) + content = content if content is not None else (formal / 'blueprint' / 'src' / 'content.tex').read_text(encoding='utf-8') + decls_text = decls_text if decls_text is not None else (formal / 'blueprint' / 'lean_decls').read_text(encoding='utf-8') + by_decl = {c['lean_decl']: c for o in status['objects'] for c in o['components'] if c['formalization_status'] != 'none'} + + problems: list[str] = [] + seen: dict[str, bool] = {} + for kind, body in _ENV.findall(content): + names = _LEAN.findall(body) + if len(names) != 1: + problems.append('%s environment must bind exactly one \\lean{} name' % kind) + continue + name = names[0].strip() + leanok = '\\leanok' in body + comp = by_decl.get(name) + if comp is None: + problems.append('\\lean{%s} is not a formalized component' % name) + continue + if leanok and comp['formalization_status'] != 'kernel-checked': + problems.append('\\leanok on %s but status is %s' % (name, comp['formalization_status'])) + if not leanok and comp['formalization_status'] == 'kernel-checked': + problems.append('kernel-checked %s lacks \\leanok' % name) + if kind != 'definition' and comp['formalization_status'] != 'kernel-checked' and 'specified' not in body.lower(): + problems.append('%s is not kernel-checked; the blueprint text must say so' % name) + seen[name] = seen.get(name, False) or leanok + for name in by_decl: + if name not in seen: + problems.append('component %s missing from blueprint' % name) + listed = [line.strip() for line in decls_text.splitlines() if line.strip()] + if sorted(listed) != sorted(seen): + problems.append('blueprint/lean_decls differs from bound \\lean{} names') + return {'passed': not problems, 'problems': problems, 'bound': sorted(seen), 'scientific_effect': 'NONE'} + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--root', type=Path, default=ROOT.parent) + args = parser.parse_args(argv) + result = check(args.root.resolve()) + for problem in result['problems']: + print('FAIL ' + problem) + print('BLUEPRINT_CHECK %s (%d bound declarations; scientific effect NONE)' % ( + 'PASSED' if result['passed'] else 'FAILED', len(result['bound']))) + return 0 if result['passed'] else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/formal/formal_gate.py b/formal/formal_gate.py new file mode 100644 index 000000000..5219c1457 --- /dev/null +++ b/formal/formal_gate.py @@ -0,0 +1,428 @@ +"""Layer 1 formal-verification gate (fail-closed; scientific effect NONE). + +Reads FORMALIZATION_STATUS.json, the pinned Lean sources, BUILD_EVIDENCE.json +and optional alignment-review records, and checks that every *declared* +formalization status is backed by evidence of at least that level: + + none < specified < proved < kernel-checked + +A declared level above the verifiable level fails closed. The gate never +grants nonauthor review, never edits status files, and never touches +``lemma_closed``. A green run means: the encoded Lean statements are what the +status file says they are, and the recorded kernel evidence is bound to exactly +these bytes. It does not mean the informal theorem is accepted; translation +fidelity is a separate review lane (``FORMALIZATION_REVIEW_LANE.md``). + +Standard library only. Run from anywhere: + + python -B -S formal/formal_gate.py [--root REPO_ROOT] [--json] +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import sys +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parent +STATUS_PATH = ROOT / 'FORMALIZATION_STATUS.json' +SOURCE_FILES_PATH = ROOT / 'SOURCE_FILES.json' +EVIDENCE_PATH = ROOT / 'BUILD_EVIDENCE.json' + +STATUS_LADDER = ('none', 'specified', 'proved', 'kernel-checked') +REVIEW_LADDER = ('none', 'author-side', 'nonauthor-aligned') +STANDARD_AXIOMS = frozenset({'propext', 'Classical.choice', 'Quot.sound'}) + +# Tokens handed to the downstream (Math-) hard gate. Every token except the +# last is NON-DISCHARGE: it can never by itself justify promotion. +TOKEN_SPECIFIED = 'FORMAL_SPECIFIED' +TOKEN_PROVED_AUTHOR = 'FORMAL_PROVED_AUTHOR_SIDE' +TOKEN_KERNEL_AUTHOR = 'KERNEL_CHECKED_AUTHOR_SIDE' +TOKEN_KERNEL_CONDITIONAL = 'KERNEL_CHECKED_CONDITIONAL' +TOKEN_KERNEL_ALIGNED = 'KERNEL_CHECKED_NONAUTHOR_ALIGNED' +FORMAL_NON_DISCHARGE = (TOKEN_SPECIFIED, TOKEN_PROVED_AUTHOR, + TOKEN_KERNEL_AUTHOR, TOKEN_KERNEL_CONDITIONAL) + +_DECL_KINDS = ('theorem', 'lemma', 'def', 'abbrev', 'noncomputable def') +_SORRY_RE = re.compile(r'(? Any: + def pairs(items): + out = {} + for key, value in items: + if key in out: + raise GateError('duplicate JSON key: ' + key) + out[key] = value + return out + + def constant(value): + raise GateError('non-finite JSON constant: ' + value) + + try: + return json.loads(text, object_pairs_hook=pairs, parse_constant=constant) + except json.JSONDecodeError as exc: + raise GateError('malformed JSON: ' + str(exc)) from exc + + +def sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _norm_ws(text: str) -> str: + return ' '.join(text.split()) + + +def _require(cond: bool, message: str) -> None: + if not cond: + raise GateError(message) + + +def _exact_bool(value: Any) -> bool: + return type(value) is bool + + +def _level(status: str) -> int: + _require(status in STATUS_LADDER, 'unknown formalization_status: ' + repr(status)) + return STATUS_LADDER.index(status) + + +# ------------------------------------------------------------- Lean sources + +def scan_lean_module(text: str) -> dict[str, Any]: + """Text-level facts about one Lean module. Not a parser; fail-closed hints.""" + stripped = _strip_comments(text) + decls: dict[str, dict[str, Any]] = {} + namespace = _NAMESPACE_RE.findall(stripped) + prefix = (namespace[0] + '.') if namespace else '' + if len(set(namespace)) > 1: + raise GateError('gate supports a single namespace per module') + decl_re = re.compile( + r'^\s*(?:@\[[^\]]*\]\s*)?(?:private\s+|protected\s+)?' + r'(noncomputable\s+def|theorem|lemma|def|abbrev)\s+([A-Za-z_][\w\']*)', + re.MULTILINE) + for kind, name in decl_re.findall(stripped): + full = prefix + name + if full in decls: + raise GateError('duplicate declaration in module: ' + full) + decls[full] = {'kind': kind, 'short': name} + return { + 'declarations': decls, + 'sorry': bool(_SORRY_RE.search(stripped)), + 'axioms': [prefix + a if '.' not in a else a for a in _AXIOM_RE.findall(stripped)], + 'namespace': namespace[0] if namespace else '', + } + + +def _strip_comments(text: str) -> str: + text = re.sub(r'/-.*?-/', ' ', text, flags=re.DOTALL) + return re.sub(r'--[^\n]*', ' ', text) + + +def statement_present(module_text: str, statement: str) -> bool: + """Blueprint-lite alignment: the reviewed statement bytes must appear verbatim + (modulo whitespace runs) in the module. Any drift stales the review.""" + _require(isinstance(statement, str) and statement.strip(), 'empty lean_statement') + return _norm_ws(statement) in _norm_ws(_strip_comments(module_text)) + + +# ---------------------------------------------------------------- pin checks + +def verify_source_pins(root: Path, pins: dict[str, Any]) -> dict[str, dict[str, Any]]: + _require(isinstance(pins, dict) and pins.get('schema_version') == 1, 'unsupported SOURCE_FILES schema') + files = pins.get('files') + _require(isinstance(files, dict) and files, 'SOURCE_FILES.files must be a nonempty object') + project = root / pins['project_root'] + out = {} + for rel, identity in files.items(): + path = project / rel + _require(not path.is_symlink() and path.is_file(), 'pinned source missing or not regular: ' + rel) + _require('..' not in Path(rel).parts, 'pinned source escapes project root: ' + rel) + data = path.read_bytes() + _require(type(identity.get('bytes')) is int and identity['bytes'] == len(data), + 'source byte-length mismatch: ' + rel) + _require(identity.get('sha256') == sha256_bytes(data), 'source sha256 mismatch: ' + rel) + out[rel] = {'bytes': len(data), 'sha256': identity['sha256'], 'text': data.decode('utf-8')} + return out + + +def verify_build_evidence(evidence: Any, sources: dict[str, dict[str, Any]], lean_cfg: dict[str, Any]) -> dict[str, Any]: + """Evidence is only usable when bound to exactly the pinned bytes.""" + _require(isinstance(evidence, dict) and evidence.get('schema_version') == 1, 'unsupported BUILD_EVIDENCE schema') + _require(evidence.get('scientific_effect') == 'NONE', 'build evidence must declare scientific_effect NONE') + build = evidence.get('build') + _require(isinstance(build, dict) and build.get('exit_code') == 0 and build.get('command') == 'lake build', + 'build evidence does not record a successful `lake build`') + _require(evidence.get('toolchain') == lean_cfg['toolchain'], 'build evidence toolchain differs from status file') + ev_sources = evidence.get('sources') + _require(isinstance(ev_sources, dict), 'build evidence lacks sources') + for rel, identity in sources.items(): + _require(rel in ev_sources, 'build evidence does not cover pinned source: ' + rel) + _require(ev_sources[rel].get('sha256') == identity['sha256'] and ev_sources[rel].get('bytes') == identity['bytes'], + 'build evidence is stale for source: ' + rel) + for rel in ev_sources: + _require(rel in sources, 'build evidence covers an unpinned source: ' + rel) + decls = evidence.get('declarations') + _require(isinstance(decls, dict), 'build evidence lacks declarations') + for name, record in decls.items(): + _require(isinstance(record, dict) and isinstance(record.get('axioms'), list) + and all(isinstance(a, str) for a in record['axioms']), + 'malformed axiom record for ' + name) + _require(_exact_bool(evidence.get('sorry_free')) and evidence['sorry_free'] is True, + 'build evidence must record sorry_free == true') + return decls + + +# ------------------------------------------------------------ review records + +def verify_review_record(root: Path, component: dict[str, Any], module_identity: dict[str, Any], + formal_author_provider: str) -> dict[str, Any]: + record_ref = component.get('review_record') + _require(isinstance(record_ref, dict) and isinstance(record_ref.get('path'), str), + 'nonauthor-aligned requires a review_record.path') + path = root / record_ref['path'] + _require(path.is_file(), 'review record missing: ' + record_ref['path']) + record = load_json_strict(path.read_text(encoding='utf-8')) + _require(record.get('verdict') == 'ALIGNED', 'review record verdict is not ALIGNED') + _require(record.get('component_id') == component['component_id'], 'review record binds a different component') + _require(record.get('reviewed_module_sha256') == module_identity['sha256'], + 'review record is bound to different module bytes (stale review)') + _require(_norm_ws(record.get('reviewed_lean_statement', '')) == _norm_ws(component['lean_statement']), + 'review record statement differs from current lean_statement') + prov = record.get('reviewer_provenance') + _require(isinstance(prov, dict) and isinstance(prov.get('provider'), str) and prov['provider'].strip(), + 'review record lacks reviewer provenance') + _require(prov.get('authored_formalization') is False, 'reviewer participated in authorship; not a nonauthor key') + same_provider = prov['provider'].strip().lower() == formal_author_provider.strip().lower() + return { + 'path': record_ref['path'], + 'reviewer_provider': prov['provider'], + # Same-provider review earns no organizational-independence credit + # (governance REVIEW_TOPOLOGY v1.1). Reported, never inferred as true. + 'organizational_independence': False if same_provider or prov.get('provider', '').upper() == 'UNKNOWN' else 'ATTESTED_NOT_VALIDATED', + } + + +# ------------------------------------------------------------------- gate + +def evaluate_component(root: Path, component: dict[str, Any], sources: dict[str, dict[str, Any]], + evidence_decls: dict[str, Any] | None, standard_axioms: frozenset[str], + assumed_registry: dict[str, dict[str, Any]], formal_author_provider: str) -> dict[str, Any]: + cid = component.get('component_id') + _require(isinstance(cid, str) and cid.strip(), 'component without component_id') + declared = component.get('formalization_status') + declared_level = _level(declared) + review = component.get('formalization_review') + _require(review in REVIEW_LADDER, 'unknown formalization_review: ' + repr(review)) + _require(isinstance(component.get('does_not_claim'), str) and component['does_not_claim'].strip(), + 'component must state what it does not claim: ' + cid) + + result: dict[str, Any] = { + 'component_id': cid, + 'declared_status': declared, + 'declared_review': review, + 'verified_status': 'none', + 'verified_review': 'none', + 'conditional_on': [], + 'reasons': [], + } + if declared == 'none': + _require(review == 'none', 'unformalized component cannot carry a review level') + result['promotion_token'] = None + result['non_discharge'] = True + result['ok'] = True + return result + + module_rel = component.get('lean_module') + _require(module_rel in sources, 'lean_module is not a pinned source: ' + repr(module_rel)) + module = sources[module_rel] + scan = scan_lean_module(module['text']) + decl = component.get('lean_decl') + _require(isinstance(decl, str) and decl in scan['declarations'], + 'lean_decl not found in module: ' + repr(decl)) + _require(statement_present(module['text'], component.get('lean_statement', '')), + 'lean_statement text is not present verbatim in module (alignment drift): ' + cid) + kind = scan['declarations'][decl]['kind'] + verified = 1 # specified + + # Every axiom written in the module must be registered with a scope note. + unregistered = [a for a in scan['axioms'] if a not in assumed_registry] + _require(not unregistered, 'module declares axioms not in assumed_axioms registry: ' + ','.join(unregistered)) + conditional: set[str] = set() + + if kind in ('theorem', 'lemma') and not scan['sorry']: + verified = 2 # proved (author-side text level); conservatively conditional on all module axioms + conditional = set(scan['axioms']) + if evidence_decls is not None and decl in evidence_decls: + axioms = set(evidence_decls[decl]['axioms']) + _require('sorryAx' not in axioms, 'kernel evidence shows sorryAx for ' + decl) + foreign = sorted(axioms - standard_axioms - set(assumed_registry)) + _require(not foreign, 'kernel evidence shows unregistered axioms for %s: %s' % (decl, ','.join(foreign))) + conditional = axioms - standard_axioms + verified = 3 # kernel-checked + result['kernel_axioms'] = sorted(axioms) + elif kind in ('theorem', 'lemma') and scan['sorry']: + result['reasons'].append('module contains sorry; theorem cannot exceed specified') + else: + _require(declared_level <= 1, 'a def/abbrev cannot be declared proved or kernel-checked: ' + decl) + + result['conditional_on'] = sorted(conditional) + result['verified_status'] = STATUS_LADDER[verified] + if declared_level > verified: + result['reasons'].append('declared %s exceeds verifiable %s' % (declared, STATUS_LADDER[verified])) + + # Review lane. The gate can confirm a nonauthor record is bound to these + # bytes; it cannot manufacture organizational independence. + result['verified_review'] = 'author-side' + if review == 'nonauthor-aligned': + result['review'] = verify_review_record(root, component, module, formal_author_provider) + result['verified_review'] = 'nonauthor-aligned' + elif review == 'none': + result['reasons'].append('formalized component must at least be author-side') + + effective = STATUS_LADDER[min(declared_level, verified)] + if effective == 'specified': + token = TOKEN_SPECIFIED + elif effective == 'proved': + token = TOKEN_PROVED_AUTHOR + elif conditional: + token = TOKEN_KERNEL_CONDITIONAL + elif result['verified_review'] == 'nonauthor-aligned': + token = TOKEN_KERNEL_ALIGNED + else: + token = TOKEN_KERNEL_AUTHOR + result['promotion_token'] = token + result['non_discharge'] = token in FORMAL_NON_DISCHARGE + result['ok'] = not result['reasons'] + return result + + +def run_gate(root: Path | None = None, *, status: dict[str, Any] | None = None, + pins: dict[str, Any] | None = None, evidence: dict[str, Any] | None = None, + require_evidence: bool = True) -> dict[str, Any]: + root = (root or ROOT.parent).resolve() + formal_dir = root / 'formal' + status = status if status is not None else load_json_strict((formal_dir / 'FORMALIZATION_STATUS.json').read_text(encoding='utf-8')) + pins = pins if pins is not None else load_json_strict((formal_dir / 'SOURCE_FILES.json').read_text(encoding='utf-8')) + + _require(isinstance(status, dict) and status.get('schema_version') == 1, 'unsupported FORMALIZATION_STATUS schema') + _require(status.get('scientific_effect') == 'NONE', 'status file must declare scientific_effect NONE') + _require(_exact_bool(status.get('lemma_closed')) and status['lemma_closed'] is False, 'lemma_closed must be exact false') + _require(_exact_bool(status.get('mathematical_acceptance')) and status['mathematical_acceptance'] is False, + 'mathematical_acceptance must be exact false') + _require(tuple(status.get('status_ladder', ())) == STATUS_LADDER, 'status_ladder differs from gate ladder') + _require(tuple(status.get('review_ladder', ())) == REVIEW_LADDER, 'review_ladder differs from gate ladder') + standard = frozenset(status.get('standard_axioms', ())) + _require(standard == STANDARD_AXIOMS, 'standard_axioms differ from the Lean kernel standard set') + lean_cfg = status.get('lean') + _require(isinstance(lean_cfg, dict) and isinstance(lean_cfg.get('toolchain'), str) + and lean_cfg.get('project_root') == pins.get('project_root'), + 'lean project configuration missing or inconsistent with SOURCE_FILES') + toolchain_file = root / lean_cfg['project_root'] / 'lean-toolchain' + _require(toolchain_file.is_file() and toolchain_file.read_text().strip() == lean_cfg['toolchain'], + 'lean-toolchain file differs from declared toolchain') + + sources = verify_source_pins(root, pins) + + registry_raw = status.get('assumed_axioms') + _require(isinstance(registry_raw, list), 'assumed_axioms registry must be a list (possibly empty)') + assumed_registry: dict[str, dict[str, Any]] = {} + for entry in registry_raw: + _require(isinstance(entry, dict) and isinstance(entry.get('name'), str) and entry['name'].strip() + and isinstance(entry.get('scope_note'), str) and entry['scope_note'].strip(), + 'each assumed axiom needs a name and a nonempty scope_note') + _require(entry['name'] not in standard, 'standard axioms are not assumed axioms: ' + entry['name']) + _require(entry['name'] not in assumed_registry, 'duplicate assumed axiom: ' + entry['name']) + assumed_registry[entry['name']] = entry + + evidence_decls: dict[str, Any] | None = None + evidence_path = formal_dir / 'BUILD_EVIDENCE.json' + if evidence is None and evidence_path.is_file(): + evidence = load_json_strict(evidence_path.read_text(encoding='utf-8')) + if evidence is not None: + evidence_decls = verify_build_evidence(evidence, sources, lean_cfg) + elif require_evidence: + raise GateError('BUILD_EVIDENCE.json is required (run lean_build_evidence.py)') + + objects = status.get('objects') + _require(isinstance(objects, list) and objects, 'status file has no objects') + seen_components: set[str] = set() + report_objects = [] + for obj in objects: + _require(isinstance(obj, dict) and isinstance(obj.get('object_id'), str), 'malformed object record') + src = obj.get('informal_source') + _require(isinstance(src, dict) and all(isinstance(src.get(k), str) and src[k] for k in ('repository', 'path', 'commit', 'sha256')), + 'object must bind an informal source by repository/path/commit/sha256: ' + obj['object_id']) + _require(re.fullmatch(r'[0-9a-f]{40}', src['commit']) is not None, 'informal_source.commit must be a full OID') + author = obj.get('authorship') + _require(isinstance(author, dict) and isinstance(author.get('formal_provider'), str), 'object lacks authorship.formal_provider') + comps = obj.get('components') + _require(isinstance(comps, list) and comps, 'object has no components: ' + obj['object_id']) + results = [] + for comp in comps: + res = evaluate_component(root, comp, sources, evidence_decls, standard, assumed_registry, author['formal_provider']) + _require(res['component_id'] not in seen_components, 'duplicate component_id: ' + res['component_id']) + seen_components.add(res['component_id']) + results.append(res) + report_objects.append({ + 'object_id': obj['object_id'], + 'hard_gate_node': obj.get('hard_gate_node'), + 'informal_source': src, + 'components': results, + 'formal_lane_satisfied': all(r.get('promotion_token') == TOKEN_KERNEL_ALIGNED for r in results if r['declared_status'] != 'none') and any(r['declared_status'] != 'none' for r in results), + }) + + failures = [r['component_id'] + ': ' + '; '.join(r['reasons']) + for o in report_objects for r in o['components'] if not r['ok']] + return { + 'object': status.get('object'), + 'passed': not failures, + 'failures': failures, + 'evidence_present': evidence is not None, + 'objects': report_objects, + 'lemma_closed': False, + 'mathematical_acceptance': False, + 'scientific_effect': 'NONE', + 'meaning': 'formalization-status integrity only; kernel evidence verifies encoded statements, not translation fidelity or theorem acceptance', + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--root', type=Path, default=ROOT.parent) + parser.add_argument('--json', action='store_true', help='print the full report') + parser.add_argument('--allow-missing-evidence', action='store_true', + help='text-level checks only; kernel-checked declarations will fail') + args = parser.parse_args(argv) + try: + report = run_gate(args.root, require_evidence=not args.allow_missing_evidence) + except GateError as exc: + print('FORMAL_GATE REFUSED: ' + str(exc)) + return 2 + if args.json: + print(json.dumps(report, indent=2, sort_keys=True)) + else: + for obj in report['objects']: + for comp in obj['components']: + print('%-40s declared=%-14s verified=%-14s review=%-18s token=%s' % ( + comp['component_id'], comp['declared_status'], comp['verified_status'], + comp['verified_review'], comp.get('promotion_token'))) + for failure in report['failures']: + print('FAIL ' + failure) + print('FORMAL_GATE ' + ('PASSED' if report['passed'] else 'FAILED') + ' (scientific effect NONE; lemma_closed false)') + return 0 if report['passed'] else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/formal/lean/.gitignore b/formal/lean/.gitignore new file mode 100644 index 000000000..4080d07df --- /dev/null +++ b/formal/lean/.gitignore @@ -0,0 +1 @@ +/.lake/ diff --git a/formal/lean/Side24Formal.lean b/formal/lean/Side24Formal.lean new file mode 100644 index 000000000..e9affc416 --- /dev/null +++ b/formal/lean/Side24Formal.lean @@ -0,0 +1,3 @@ +import Side24Formal.Ledger +import Side24Formal.ConeMoment +import Side24Formal.Reference diff --git a/formal/lean/Side24Formal/ConeMoment.lean b/formal/lean/Side24Formal/ConeMoment.lean new file mode 100644 index 000000000..f2a22acc3 --- /dev/null +++ b/formal/lean/Side24Formal/ConeMoment.lean @@ -0,0 +1,177 @@ +import Mathlib.Analysis.SpecialFunctions.Integrals.Basic +import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus +import Mathlib.Analysis.Real.Sqrt +import Mathlib.Probability.Distributions.Gaussian.Real +import Mathlib.Probability.Moments.MGFAnalytic +import Mathlib.Analysis.SpecialFunctions.Gaussian.GaussianIntegral +import Mathlib.Tactic + +/-! +# SIDE24 cone moment `D₂ = 29/6 − √6` (Math- `coefficients/side24_v1/PROOF.md`, §1) + +Formal object: `SIDE24-COEFFICIENT-D23-20260924-v1`, components `side24.cone.*`. + +The informal §1 computes the transverse cone moment `D₂ = E[det(A)² 1{A<0}]` for the +`m = 2` reference law through (i) an elementary integral, (ii) two Gaussian moments +of the shared shift `s ~ N(0, 5/3)`, and (iii) algebra. All three are kernel-checked +here; (ii) is stated against Mathlib's `ProbabilityTheory.gaussianReal` (whose second +argument is the *variance*). What is **not** formalised is the probabilistic reduction +from the conditional Hessian law to these scalar integrals (PROOF.md §1 prose). + +The private sandbox experiment `experiments/cone_v1/cone_probe.py` samples the same +quantity; that Monte Carlo output is a sanity check, never evidence. Scientific effect: NONE. +-/ + +namespace Side24 + +open MeasureTheory ProbabilityTheory + +/-- Antiderivative of `z ↦ (a − z)² e^(−z/2) / 2`. -/ +noncomputable def coneAntiderivative (a z : ℝ) : ℝ := + -Real.exp (-z / 2) * ((a - z) ^ 2 - 4 * (a - z) + 8) + +theorem hasDerivAt_coneAntiderivative (a z : ℝ) : + HasDerivAt (coneAntiderivative a) ((a - z) ^ 2 * Real.exp (-z / 2) / 2) z := by + have hlin : HasDerivAt (fun z : ℝ => -z / 2) (-1 / 2) z := by + simpa using ((hasDerivAt_id z).neg).div_const 2 + have hexp : HasDerivAt (fun z : ℝ => Real.exp (-z / 2)) (Real.exp (-z / 2) * (-1 / 2)) z := + hlin.exp + have hs : HasDerivAt (fun z : ℝ => a - z) (-1) z := by + simpa using (hasDerivAt_id z).const_sub a + have hpoly : HasDerivAt (fun z : ℝ => (a - z) ^ 2 - 4 * (a - z) + 8) + (((2 : ℕ) : ℝ) * (a - z) ^ (2 - 1) * (-1) - 4 * (-1)) z := + ((hs.pow 2).sub (hs.const_mul 4)).add_const 8 + have := hexp.neg.mul hpoly + unfold coneAntiderivative + convert this using 1 + simp only [Pi.neg_apply] + push_cast + ring + +/-- PROOF.md §1: `∫₀ᵃ (a − z)² e^(−z/2) dz / 2 = a² − 4a + 8 − 8e^(−a/2)`. +The informal text states this for `a ≥ 0`; the identity holds for every real `a`. -/ +theorem cone_integral_identity (a : ℝ) : + ∫ z in (0 : ℝ)..a, (a - z) ^ 2 * Real.exp (-z / 2) / 2 + = a ^ 2 - 4 * a + 8 - 8 * Real.exp (-a / 2) := by + rw [intervalIntegral.integral_eq_sub_of_hasDerivAt + (fun z _ => hasDerivAt_coneAntiderivative a z)] + · unfold coneAntiderivative + simp + ring + · exact (by fun_prop : Continuous fun z : ℝ => (a - z) ^ 2 * Real.exp (-z / 2) / 2).intervalIntegrable _ _ + +/-- The `m = 2` cone moment as stated in PROOF.md §1. -/ +noncomputable def D2 : ℝ := 29 / 6 - Real.sqrt 6 + +/-- PROOF.md §1 algebra: `(1/2)[25/3 − 20/3 + 8 − 8√(3/8)] = 29/6 − √6`. -/ +theorem D2_algebra : + (1 / 2 : ℝ) * (25 / 3 - 20 / 3 + 8 - 8 * Real.sqrt (3 / 8)) = D2 := by + have h : Real.sqrt (3 / 8) = Real.sqrt 6 / 4 := by + rw [show (3 / 8 : ℝ) = 6 / 4 ^ 2 by norm_num, Real.sqrt_div' _ (by norm_num), + Real.sqrt_sq (by norm_num)] + unfold D2 + rw [h] + ring + +/-- Outward rational enclosure of `D₂`. -/ +theorem D2_bounds : (2.38384359054 : ℝ) < D2 ∧ D2 < 2.38384359056 := by + have h1 : Real.sqrt 6 < 2.449489742784 := by + rw [Real.sqrt_lt' (by norm_num)]; norm_num + have h2 : (2.449489742783 : ℝ) < Real.sqrt 6 := by + rw [Real.lt_sqrt (by norm_num)]; norm_num + unfold D2 + constructor <;> linarith + +/-- PROOF.md §1: the truncation `R < |s|` is essential — the untruncated half moment +`29/6` is strictly larger than `D₂`. -/ +theorem D2_lt_untruncated : D2 < 29 / 6 := by + unfold D2 + have : 0 < Real.sqrt 6 := Real.sqrt_pos.mpr (by norm_num) + linarith + +/-- Derivative of `p(t)·exp(v t²/2)` for a differentiable `p` (MGF bookkeeping). -/ +theorem hasDerivAt_poly_mul_gauss {v : ℝ} {p : ℝ → ℝ} {p' t : ℝ} (hp : HasDerivAt p p' t) : + HasDerivAt (fun t => p t * Real.exp (v * t ^ 2 / 2)) + ((p' + p t * (v * t)) * Real.exp (v * t ^ 2 / 2)) t := by + have hq : HasDerivAt (fun t : ℝ => v * t ^ 2 / 2) (v * t) t := by + have := (((hasDerivAt_id' t).pow 2).const_mul v).div_const 2 + convert this using 1 + simp; ring + have := hp.mul hq.exp + convert this using 1 + ring + +/-- Fourth derivative at `0` of the centred Gaussian MGF `t ↦ exp(v t²/2)` is `3v²`. -/ +theorem iteratedDeriv_gauss_four (v : ℝ) : + iteratedDeriv 4 (fun t : ℝ => Real.exp (v * t ^ 2 / 2)) 0 = 3 * v ^ 2 := by + have d1 : deriv (fun t : ℝ => Real.exp (v * t ^ 2 / 2)) + = fun t => (v * t) * Real.exp (v * t ^ 2 / 2) := by + funext t + have := hasDerivAt_poly_mul_gauss (v := v) (hasDerivAt_const t (1 : ℝ)) + simpa using this.deriv + have d2 : deriv (fun t : ℝ => (v * t) * Real.exp (v * t ^ 2 / 2)) + = fun t => (v + v ^ 2 * t ^ 2) * Real.exp (v * t ^ 2 / 2) := by + funext t + have hp : HasDerivAt (fun t : ℝ => v * t) v t := by simpa using (hasDerivAt_id' t).const_mul v + have := (hasDerivAt_poly_mul_gauss (v := v) hp).deriv + rw [this]; ring + have d3 : deriv (fun t : ℝ => (v + v ^ 2 * t ^ 2) * Real.exp (v * t ^ 2 / 2)) + = fun t => (3 * v ^ 2 * t + v ^ 3 * t ^ 3) * Real.exp (v * t ^ 2 / 2) := by + funext t + have hp : HasDerivAt (fun t : ℝ => v + v ^ 2 * t ^ 2) (v ^ 2 * (2 * t)) t := by + have := (((hasDerivAt_id' t).pow 2).const_mul (v ^ 2)).const_add v + convert this using 1; simp + have := (hasDerivAt_poly_mul_gauss (v := v) hp).deriv + rw [this]; ring + have d4 : deriv (fun t : ℝ => (3 * v ^ 2 * t + v ^ 3 * t ^ 3) * Real.exp (v * t ^ 2 / 2)) + = fun t => (3 * v ^ 2 + 6 * v ^ 3 * t ^ 2 + v ^ 4 * t ^ 4) * Real.exp (v * t ^ 2 / 2) := by + funext t + have hp : HasDerivAt (fun t : ℝ => 3 * v ^ 2 * t + v ^ 3 * t ^ 3) + (3 * v ^ 2 + v ^ 3 * (3 * t ^ 2)) t := by + have h1 : HasDerivAt (fun t : ℝ => 3 * v ^ 2 * t) (3 * v ^ 2) t := by + simpa using (hasDerivAt_id' t).const_mul (3 * v ^ 2) + have h2 : HasDerivAt (fun t : ℝ => v ^ 3 * t ^ 3) (v ^ 3 * (3 * t ^ 2)) t := by + have := ((hasDerivAt_id' t).pow 3).const_mul (v ^ 3) + convert this using 1; simp + exact h1.add h2 + have := (hasDerivAt_poly_mul_gauss (v := v) hp).deriv + rw [this]; ring + rw [show (4 : ℕ) = 0 + 1 + 1 + 1 + 1 from rfl, iteratedDeriv_succ, iteratedDeriv_succ, + iteratedDeriv_succ, iteratedDeriv_succ, iteratedDeriv_zero, d1, d2, d3, d4] + simp + +/-- PROOF.md §1: `E s⁴ = 25/3` for `s ~ N(0, 5/3)` (fourth moment `3·Var(s)²`), +via the moment-generating function `mgf_id_gaussianReal`. -/ +theorem gaussian_fourth_moment : + (∫ s, s ^ 4 ∂(gaussianReal 0 (5 / 3 : NNReal))) = 25 / 3 := by + have h := iteratedDeriv_mgf_zero (X := id) (μ := gaussianReal 0 (5 / 3 : NNReal)) (by simp) 4 + rw [mgf_id_gaussianReal] at h + simp only [zero_mul, zero_add] at h + rw [iteratedDeriv_gauss_four ((5 / 3 : NNReal) : ℝ)] at h + have : (∫ s, s ^ 4 ∂(gaussianReal 0 (5 / 3 : NNReal))) = (gaussianReal 0 (5 / 3 : NNReal))[id ^ 4] := by + congr 1 + rw [this, ← h] + norm_num + +/-- PROOF.md §1: `E exp(−s²/2) = √(3/8)` for `s ~ N(0, 5/3)`, via the Gaussian integral +`∫ exp(−b x²) = √(π/b)`. -/ +theorem gaussian_exp_moment : + (∫ s, Real.exp (-s ^ 2 / 2) ∂(gaussianReal 0 (5 / 3 : NNReal))) = Real.sqrt (3 / 8) := by + rw [integral_gaussianReal_eq_integral_smul (by norm_num)] + simp only [gaussianPDFReal, smul_eq_mul, sub_zero] + have hcoe : ((5 / 3 : NNReal) : ℝ) = 5 / 3 := by norm_num + rw [hcoe] + have hpt : ∀ x : ℝ, (√(2 * Real.pi * (5 / 3)))⁻¹ * Real.exp (-x ^ 2 / (2 * (5 / 3))) + * Real.exp (-x ^ 2 / 2) = (√(2 * Real.pi * (5 / 3)))⁻¹ * Real.exp (-(4 / 5) * x ^ 2) := by + intro x + rw [mul_assoc, ← Real.exp_add] + congr 2 + ring + simp_rw [hpt] + rw [integral_const_mul, integral_gaussian] + rw [← Real.sqrt_inv, ← Real.sqrt_mul (by positivity)] + congr 1 + field_simp + ring + +end Side24 diff --git a/formal/lean/Side24Formal/Ledger.lean b/formal/lean/Side24Formal/Ledger.lean new file mode 100644 index 000000000..beb7bf5f0 --- /dev/null +++ b/formal/lean/Side24Formal/Ledger.lean @@ -0,0 +1,96 @@ +import Mathlib.Analysis.Complex.Exponential +import Mathlib.Tactic + +/-! +# SIDE24 image ledger — exact arithmetic (Math- `coefficients/side24_v1/PROOF.md`, §2–§4) + +Formal object: `SIDE24-COEFFICIENT-D23-20260924-v1`, components `side24.ledger.*`. + +Every statement in this file is a closed arithmetic fact that the informal proof +uses as an input. They mirror `image_ledger()` in `coefficient.py`, which checks the +same facts with Python `Fraction` arithmetic. Here the Lean kernel checks them. + +Scientific effect: NONE. Nothing here evaluates the parent coefficient or accepts +the parent theorem (main #63); the file proves only the finite arithmetic it states. +-/ + +namespace Side24 + +open Finset + +/-- PROOF.md eq. (2): the image constant `1458·(76·24⁶ + 15)`. -/ +theorem image_constant_eq : (1458 : ℕ) * (76 * 24 ^ 6 + 15) = 21175738586478 := by + norm_num + +/-- PROOF.md §2: the positive Taylor partial sum of `exp` through degree 20 at +`288/125` exceeds `10`. Rational arithmetic only. -/ +theorem exp_partial_sum_gt_ten : + (10 : ℝ) < ∑ i ∈ range 21, ((288 : ℝ) / 125) ^ i / (Nat.factorial i : ℝ) := by + simp only [sum_range_succ, sum_range_zero] + norm_num [Nat.factorial] + +/-- PROOF.md §2: `e^(288/125) > 10`. Uses Mathlib's `Real.sum_le_exp_of_nonneg` +(the partial sums of the exponential series are lower bounds for `exp` at `x ≥ 0`). -/ +theorem ten_lt_exp_288_div_125 : (10 : ℝ) < Real.exp (288 / 125) := + lt_of_lt_of_le exp_partial_sum_gt_ten (Real.sum_le_exp_of_nonneg (by norm_num) 21) + +/-- PROOF.md §2: `e^288 > 10^125`. -/ +theorem ten_pow_125_lt_exp_288 : (10 : ℝ) ^ 125 < Real.exp 288 := by + have h : Real.exp 288 = Real.exp (288 / 125) ^ 125 := by + rw [← Real.exp_nat_mul]; norm_num + rw [h] + exact pow_lt_pow_left₀ ten_lt_exp_288_div_125 (by norm_num) (by norm_num) + +/-- PROOF.md §2: `e^(-288) < 10^(-125)`, written with a positive reciprocal. -/ +theorem exp_neg_288_lt : Real.exp (-288) < 1 / (10 : ℝ) ^ 125 := by + rw [Real.exp_neg, one_div] + exact inv_strictAnti₀ (by positivity) ten_pow_125_lt_exp_288 + +/-- PROOF.md §2: successive image terms have ratio at most `512·e^(-864) < 1/2`. -/ +theorem geometric_ratio_lt_half : (512 : ℝ) * Real.exp (-864) < 1 / 2 := by + have h3 : Real.exp 864 = Real.exp 288 ^ 3 := by + rw [← Real.exp_nat_mul]; norm_num + have hgt : ((10 : ℝ) ^ 125) ^ 3 < Real.exp 864 := by + rw [h3] + exact pow_lt_pow_left₀ ten_pow_125_lt_exp_288 (by positivity) (by norm_num) + rw [Real.exp_neg, mul_inv_lt_iff₀ (Real.exp_pos 864)] + calc (512 : ℝ) < 1 / 2 * ((10 : ℝ) ^ 125) ^ 3 := by norm_num + _ < 1 / 2 * Real.exp 864 := by gcongr + +/-- PROOF.md eq. (2)→(3): `60·E < ε` with `E = 21175738586478·10^(-125)` and `ε = 10^(-108)`. -/ +theorem covariance_relative_lt_eps : + (60 : ℚ) * (21175738586478 / 10 ^ 125) < 1 / 10 ^ 108 := by + norm_num + +/-- PROOF.md eq. (4): `32·ε < 10^(-106)`, the reported relative periodization bound. -/ +theorem density_comparison_lt_reported : (32 : ℚ) / 10 ^ 108 < 1 / 10 ^ 106 := by + norm_num + +/-- Transverse dimension `m = d − 1`. -/ +def m (d : ℕ) : ℕ := d - 1 + +/-- Number of independent symmetric-matrix coordinates `n = m(m+1)/2`. -/ +def n (d : ℕ) : ℕ := m d * (m d + 1) / 2 + +/-- PROOF.md §4 exponent `a = m + 2/3 + n/2`. -/ +def a (d : ℕ) : ℚ := m d + 2 / 3 + n d / 2 + +/-- PROOF.md §4 exponent `b = d + n/2`. -/ +def b (d : ℕ) : ℚ := d + n d / 2 + +/-- PROOF.md §4: for `d = 2`, `a + 2b < 14` and `2a + b < 13`. -/ +theorem exponent_budget_d2 : a 2 + 2 * b 2 < 14 ∧ 2 * a 2 + b 2 < 13 := by + norm_num [a, b, m, n] + +/-- PROOF.md §4: for `d = 3`, `a + 2b < 14` and `2a + b < 13`. -/ +theorem exponent_budget_d3 : a 3 + 2 * b 3 < 14 ∧ 2 * a 3 + b 3 < 13 := by + norm_num [a, b, m, n] + +/-- PROOF.md §4, statement only (status `specified`): for `0 < ε < 1/28` the density +ratio lies between `1 − 32ε` and `1 + 32ε`. Not proved in this pilot. -/ +def ratio_bound_statement : Prop := + ∀ d ∈ ({2, 3} : Finset ℕ), ∀ ε : ℝ, 0 < ε → ε < 1 / 28 → + (1 + ε) ^ (a d : ℝ) / (1 - ε) ^ (b d : ℝ) < 1 + 32 * ε ∧ + 1 - 32 * ε < (1 - ε) ^ (a d : ℝ) / (1 + ε) ^ (b d : ℝ) + +end Side24 diff --git a/formal/lean/Side24Formal/Reference.lean b/formal/lean/Side24Formal/Reference.lean new file mode 100644 index 000000000..2af3fcec0 --- /dev/null +++ b/formal/lean/Side24Formal/Reference.lean @@ -0,0 +1,122 @@ +import Mathlib.Analysis.SpecialFunctions.Gamma.Basic +import Mathlib.Analysis.SpecialFunctions.Pow.Real +import Mathlib.Tactic +import Side24Formal.ConeMoment + +/-! +# SIDE24 reference coefficient and the enclosure statement +(Math- `coefficients/side24_v1/PROOF.md`, eq. (1), (4) and the displayed theorem) + +Formal object: `SIDE24-COEFFICIENT-D23-20260924-v1`, components `side24.reference.*`. + +## What is and is not defined here + +* `referenceCoefficient d` is eq. (1) in standard objects (`Real.Gamma`, `Real.pi`, + `Real.sqrt`, real powers). It is the *nonperiodic reference* expression. +* The periodic coefficient `c_{d,24}` is **not** defined: it is fixed by the parent + source (main #63, eq. 15.2), which is not formalized. Every statement about it is + therefore parametrized by an arbitrary `c : ℕ → ℝ`. The hypotheses of + `enclosure_of_reference` are exactly the scope of what is proved. +* `reference_enclosure_statement` records the author's 80-digit outward rational + enclosure of `referenceCoefficient` (from `coefficient.py`). It is *specified*, not + proved: bounding `Γ(7/6)`, `π` and the roots in Lean is future work. +* `periodization_statement c` is eq. (4). It depends on the parent analysis and is + *specified*, not proved. + +`enclosure_of_reference` is the kernel-checked logical step of PROOF.md §5: +"the periodization allowance in (4) is applied to exact rational endpoints BEFORE the +final outward rounding". Scientific effect: NONE. +-/ + +namespace Side24 + +/-- Cone moments `D_m` for `m = d − 1 ∈ {1, 2}` (PROOF.md §1); `0` outside that range. -/ +noncomputable def coneMoment : ℕ → ℝ + | 1 => 4 / 3 + | 2 => D2 + | _ => 0 + +/-- PROOF.md eq. (1): `c_{d,ref} = Γ(7/6)·(3/2)^(1/3)·D_{d−1} / (2√3·π^(d−1)·√π)`. -/ +noncomputable def referenceCoefficient (d : ℕ) : ℝ := + Real.Gamma (7 / 6) * (3 / 2 : ℝ) ^ ((1 : ℝ) / 3) * coneMoment (d - 1) + / (2 * Real.sqrt 3 * Real.pi ^ (d - 1) * Real.sqrt Real.pi) + +/-- Author-side 80-digit outward lower endpoint for `referenceCoefficient 2`. -/ +def ref2Lo : ℚ := + 7340691930603427103013596295776273618445946768885664197004403216711382893223557 / 10 ^ 80 + +/-- Author-side 80-digit outward upper endpoint for `referenceCoefficient 2`. -/ +def ref2Hi : ℚ := + 7340691930603427103013596295777417013380655703769646772200313740800240533333043 / 10 ^ 80 + +/-- Author-side 80-digit outward lower endpoint for `referenceCoefficient 3`. -/ +def ref3Lo : ℚ := + 4177593184059834334293666542856911775587214492195145252592066752648167407187767 / 10 ^ 80 + +/-- Author-side 80-digit outward upper endpoint for `referenceCoefficient 3`. -/ +def ref3Hi : ℚ := + 4177593184059834334293666542857562482486657407720240268849039889886922519700256 / 10 ^ 80 + +/-- The relative periodization allowance of PROOF.md eq. (4). -/ +def periodizationBound : ℚ := 1 / 10 ^ 106 + +/-- Statement only (status `specified`): the reference coefficient lies in the author's +rational enclosure. Its informal evidence is `coefficient.py`; not kernel-checked. -/ +def reference_enclosure_statement : Prop := + (ref2Lo : ℝ) < referenceCoefficient 2 ∧ referenceCoefficient 2 < ref2Hi ∧ + (ref3Lo : ℝ) < referenceCoefficient 3 ∧ referenceCoefficient 3 < ref3Hi + +/-- Statement only (status `specified`): PROOF.md eq. (4), `|c_{d,24}/c_{d,ref} − 1| < 10^(−106)` +for `d ∈ {2, 3}`, for the periodic coefficient `c` fixed by the (unformalized) parent. -/ +def periodization_statement (c : ℕ → ℝ) : Prop := + ∀ d ∈ ({2, 3} : Finset ℕ), |c d / referenceCoefficient d - 1| < (periodizationBound : ℝ) + +/-- The displayed theorem of PROOF.md as a statement about an arbitrary `c : ℕ → ℝ`. -/ +def enclosure_statement (c : ℕ → ℝ) : Prop := + (0.07340691930603427103 : ℝ) < c 2 ∧ c 2 < 0.07340691930603427104 ∧ + (0.04177593184059834334 : ℝ) < c 3 ∧ c 3 < 0.04177593184059834335 + +/-- Relative-perturbation transfer: if `r ∈ (lo, hi)` with `lo > 0` and `|c/r − 1| < δ`, +then `(1 − δ)·lo < c < (1 + δ)·hi`. -/ +theorem perturbed_bounds {c r lo hi δ : ℝ} (hlo : 0 < lo) (h₁ : lo < r) (h₂ : r < hi) + (hδ : 0 < δ) (hδ1 : δ < 1) (h : |c / r - 1| < δ) : + (1 - δ) * lo < c ∧ c < (1 + δ) * hi := by + have hr : 0 < r := hlo.trans h₁ + rw [abs_sub_lt_iff] at h + obtain ⟨hA, hB⟩ := h + have hu : c < (1 + δ) * r := by + have := (div_lt_iff₀ hr).mp (show c / r < 1 + δ by linarith) + linarith + have hl : (1 - δ) * r < c := by + have := (lt_div_iff₀ hr).mp (show 1 - δ < c / r by linarith) + linarith + constructor + · calc (1 - δ) * lo < (1 - δ) * r := by gcongr + _ < c := hl + · calc c < (1 + δ) * r := hu + _ < (1 + δ) * hi := by gcongr + +/-- PROOF.md §5, kernel-checked: the author's rational reference enclosure together with +the relative periodization bound (4) implies the displayed 20-digit enclosure. +Both hypotheses are `specified` Props; this theorem discharges neither. -/ +theorem enclosure_of_reference (c : ℕ → ℝ) + (href : reference_enclosure_statement) (hper : periodization_statement c) : + enclosure_statement c := by + obtain ⟨lo2, hi2, lo3, hi3⟩ := href + have h2 := hper 2 (by simp) + have h3 := hper 3 (by simp) + have hδ : (0 : ℝ) < (periodizationBound : ℝ) := by norm_num [periodizationBound] + have hδ1 : (periodizationBound : ℝ) < 1 := by norm_num [periodizationBound] + obtain ⟨l2, u2⟩ := perturbed_bounds (by norm_num [ref2Lo]) lo2 hi2 hδ hδ1 h2 + obtain ⟨l3, u3⟩ := perturbed_bounds (by norm_num [ref3Lo]) lo3 hi3 hδ hδ1 h3 + have e2l : (0.07340691930603427103 : ℝ) ≤ (1 - (periodizationBound : ℝ)) * (ref2Lo : ℝ) := by + norm_num [periodizationBound, ref2Lo] + have e2u : (1 + (periodizationBound : ℝ)) * (ref2Hi : ℝ) ≤ 0.07340691930603427104 := by + norm_num [periodizationBound, ref2Hi] + have e3l : (0.04177593184059834334 : ℝ) ≤ (1 - (periodizationBound : ℝ)) * (ref3Lo : ℝ) := by + norm_num [periodizationBound, ref3Lo] + have e3u : (1 + (periodizationBound : ℝ)) * (ref3Hi : ℝ) ≤ 0.04177593184059834335 := by + norm_num [periodizationBound, ref3Hi] + exact ⟨e2l.trans_lt l2, u2.trans_le e2u, e3l.trans_lt l3, u3.trans_le e3u⟩ + +end Side24 diff --git a/formal/lean/lake-manifest.json b/formal/lean/lake-manifest.json new file mode 100644 index 000000000..336c7d65c --- /dev/null +++ b/formal/lean/lake-manifest.json @@ -0,0 +1,96 @@ +{"version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": + [{"url": "https://github.com/leanprover-community/mathlib4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.1", + "inherited": false, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "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": "e928b72544873815af278d38681b31c0293588e3", + "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": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean"}, + {"url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "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": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml"}], + "name": "side24formal", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/formal/lean/lakefile.toml b/formal/lean/lakefile.toml new file mode 100644 index 000000000..4e1b774ce --- /dev/null +++ b/formal/lean/lakefile.toml @@ -0,0 +1,10 @@ +name = "side24formal" +defaultTargets = ["Side24Formal"] + +[[require]] +name = "mathlib" +scope = "leanprover-community" +rev = "v4.34.1" + +[[lean_lib]] +name = "Side24Formal" diff --git a/formal/lean/lean-toolchain b/formal/lean/lean-toolchain new file mode 100644 index 000000000..ba8ebf2db --- /dev/null +++ b/formal/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.34.1 diff --git a/formal/lean_build_evidence.py b/formal/lean_build_evidence.py new file mode 100644 index 000000000..3ab7d89e6 --- /dev/null +++ b/formal/lean_build_evidence.py @@ -0,0 +1,158 @@ +"""Produce (or check) BUILD_EVIDENCE.json for the Layer 1 Lean project. + +Runs ``lake build`` in the pinned project, then asks Lean for ``#print axioms`` of +every declaration listed in FORMALIZATION_STATUS.json, and records the result +together with the byte identities of the pinned sources. The record is +deterministic (no timestamps) so CI can regenerate it and ``cmp`` against the +committed copy. + +The output is evidence about *these bytes* only. formal_gate.py refuses to use it +when any pinned source has changed since the build. Standard library only. + + python -B -S formal/lean_build_evidence.py # build + write + python -B -S formal/lean_build_evidence.py --check # build + compare with committed +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +_AXIOM_LINE = re.compile(r"^'([^']+)' depends on axioms: \[([^\]]*)\]\s*$") +_NO_AXIOM_LINE = re.compile(r"^'([^']+)' does not depend on any axioms\s*$") + + +def _strict(path: Path): + def pairs(items): + out = {} + for k, v in items: + if k in out: + raise ValueError('duplicate JSON key: ' + k) + out[k] = v + return out + return json.loads(path.read_text(encoding='utf-8'), object_pairs_hook=pairs) + + +def _module_name(rel: str) -> str | None: + if not rel.endswith('.lean'): + return None + return rel[:-5].replace('/', '.') + + +def _run(cmd: list[str], cwd: Path, timeout: int) -> subprocess.CompletedProcess: + env = dict(os.environ) + elan_bin = Path.home() / '.elan' / 'bin' + if elan_bin.is_dir(): + env['PATH'] = str(elan_bin) + os.pathsep + env.get('PATH', '') + return subprocess.run(cmd, cwd=str(cwd), env=env, capture_output=True, text=True, timeout=timeout) + + +def collect(root: Path, *, skip_build: bool = False, build_timeout: int = 3600) -> dict: + formal = root / 'formal' + status = _strict(formal / 'FORMALIZATION_STATUS.json') + pins = _strict(formal / 'SOURCE_FILES.json') + project = root / pins['project_root'] + toolchain = (project / 'lean-toolchain').read_text().strip() + if toolchain != status['lean']['toolchain']: + raise ValueError('lean-toolchain differs from FORMALIZATION_STATUS.lean.toolchain') + + sources = {} + for rel in pins['files']: + data = (project / rel).read_bytes() + sources[rel] = {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()} + + decls = sorted({c['lean_decl'] for o in status['objects'] for c in o['components'] + if c['formalization_status'] != 'none'}) + modules = sorted({m for m in (_module_name(r) for r in pins['files']) if m}) + + if skip_build: + build = {'command': 'lake build', 'exit_code': 0, 'note': 'reused existing build artifacts'} + build_stdout = '' + else: + proc = _run(['lake', 'build'], project, build_timeout) + build = {'command': 'lake build', 'exit_code': proc.returncode} + build_stdout = proc.stdout + proc.stderr + if proc.returncode != 0: + build['tail'] = build_stdout[-4000:] + sorry_warning = 'declaration uses \'sorry\'' in build_stdout + + declarations: dict[str, dict] = {} + if build['exit_code'] == 0: + with tempfile.NamedTemporaryFile('w', suffix='.lean', dir=str(project), delete=False, encoding='utf-8') as handle: + for module in modules: + handle.write('import %s\n' % module) + for decl in decls: + handle.write('#print axioms %s\n' % decl) + probe = Path(handle.name) + try: + proc = _run(['lake', 'env', 'lean', probe.name], project, 600) + finally: + probe.unlink(missing_ok=True) + if proc.returncode != 0: + raise RuntimeError('axiom probe failed:\n' + proc.stdout + proc.stderr) + for line in proc.stdout.splitlines(): + match = _AXIOM_LINE.match(line.strip()) + if match: + axioms = [a.strip() for a in match.group(2).split(',') if a.strip()] + declarations[match.group(1)] = {'axioms': sorted(axioms)} + continue + match = _NO_AXIOM_LINE.match(line.strip()) + if match: + declarations[match.group(1)] = {'axioms': []} + missing = [d for d in decls if d not in declarations] + if missing: + raise RuntimeError('no axiom report for: ' + ', '.join(missing)) + + version = _run(['lean', '--version'], project, 60).stdout.strip() + manifest = _strict(project / 'lake-manifest.json') + mathlib = next((p for p in manifest['packages'] if p['name'] == 'mathlib'), None) + sorry_free = (not sorry_warning) and all('sorryAx' not in d['axioms'] for d in declarations.values()) + return { + 'schema_version': 1, + 'object': 'FORMAL-LAYER-BUILD-EVIDENCE-v1', + 'toolchain': toolchain, + 'lean_version': version, + 'mathlib_rev': mathlib['rev'] if mathlib else None, + 'build': build, + 'sources': sources, + 'declarations': declarations, + 'sorry_free': sorry_free, + 'meaning': 'kernel acceptance of the encoded statements at these exact bytes; not translation fidelity, not theorem acceptance', + 'scientific_effect': 'NONE', + 'lemma_closed': False, + } + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--root', type=Path, default=ROOT.parent) + parser.add_argument('--output', type=Path, default=None) + parser.add_argument('--check', action='store_true', help='compare with the committed evidence instead of writing') + parser.add_argument('--skip-build', action='store_true') + args = parser.parse_args(argv) + root = args.root.resolve() + evidence = collect(root, skip_build=args.skip_build) + text = json.dumps(evidence, indent=2, sort_keys=True) + '\n' + target = args.output or (root / 'formal' / 'BUILD_EVIDENCE.json') + if args.check: + committed = target.read_text(encoding='utf-8') + if committed != text: + sys.stdout.write(text) + print('BUILD_EVIDENCE differs from committed record', file=sys.stderr) + return 1 + print('BUILD_EVIDENCE matches committed record (scientific effect NONE)') + return 0 + target.write_text(text, encoding='utf-8') + print('wrote ' + str(target)) + return 0 if evidence['build']['exit_code'] == 0 else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/formal/pin_sources.py b/formal/pin_sources.py new file mode 100644 index 000000000..5f6eb706f --- /dev/null +++ b/formal/pin_sources.py @@ -0,0 +1,64 @@ +"""Regenerate SOURCE_FILES.json: byte/sha256 pins for the Layer 1 Lean project. + +Deliberate regeneration only. A pin mismatch in formal_gate.py means the Lean +sources changed without this file being refreshed; refreshing a pin does not move +any formalization status and never touches lemma_closed. Standard library only. + + python -B -S formal/pin_sources.py # rewrite formal/SOURCE_FILES.json + python -B -S formal/pin_sources.py --check # exit 1 if pins are stale +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +PROJECT_ROOT = 'formal/lean' +PINNED_TOP_LEVEL = ('lean-toolchain', 'lakefile.toml', 'lake-manifest.json', 'Side24Formal.lean') +MODULE_DIR = 'Side24Formal' + + +def build_pins(repo_root: Path) -> dict: + project = repo_root / PROJECT_ROOT + files = {} + names = list(PINNED_TOP_LEVEL) + sorted( + str(p.relative_to(project)) for p in (project / MODULE_DIR).glob('*.lean')) + for rel in names: + path = project / rel + if path.is_symlink() or not path.is_file(): + raise ValueError('pinned source must be a regular file: ' + rel) + data = path.read_bytes() + files[rel] = {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()} + return { + 'schema_version': 1, + 'object': 'FORMAL-LAYER-SOURCE-FILES-v1', + 'project_root': PROJECT_ROOT, + 'files': files, + 'meaning': 'byte identities of the Lean project; a match proves identity, not correctness or acceptance', + 'scientific_effect': 'NONE', + } + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--root', type=Path, default=ROOT.parent) + parser.add_argument('--check', action='store_true') + args = parser.parse_args(argv) + text = json.dumps(build_pins(args.root.resolve()), indent=2, sort_keys=True) + '\n' + target = args.root.resolve() / 'formal' / 'SOURCE_FILES.json' + if args.check: + if not target.is_file() or target.read_text(encoding='utf-8') != text: + print('SOURCE_FILES.json is stale; regenerate deliberately', file=sys.stderr) + return 1 + print('SOURCE_FILES.json matches the Lean sources') + return 0 + target.write_text(text, encoding='utf-8') + print('wrote ' + str(target)) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/formal/run_validation.py b/formal/run_validation.py new file mode 100644 index 000000000..888c335d1 --- /dev/null +++ b/formal/run_validation.py @@ -0,0 +1,100 @@ +"""Replay the Layer 1 gate controls in both Python modes and write REPORT.json. + +Mirrors the Math- package convention (normal + optimized unittest runs, distinct +test and semantic-mutant counts, explicit non-acceptance flags). Optionally +regenerates and compares BUILD_EVIDENCE.json when a Lean toolchain is present. + + python -B -S formal/run_validation.py --output /tmp/formal-gate-run [--with-lean] +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +EXPECTED_TESTS = 27 +EXPECTED_MUTANTS = 33 + + +def _count_mutants() -> int: + text = (ROOT / 'test_formal_gate.py').read_text(encoding='utf-8') + block = text[text.index('MUTANTS = ['):text.index(']', text.index('MUTANTS = ['))] + return len(re.findall(r'_m_\w+', block)) + + +def _run_tests(flags: list[str], log: Path) -> int: + proc = subprocess.run([sys.executable, *flags, '-B', '-S', '-m', 'unittest', 'discover', + '-s', str(ROOT), '-p', 'test_*.py', '-v'], + capture_output=True, text=True, timeout=900) + log.write_text(proc.stdout + proc.stderr, encoding='utf-8') + match = re.search(r'^Ran (\d+) tests', proc.stderr, re.MULTILINE) + if proc.returncode != 0 or not match: + raise RuntimeError('unittest failed in mode ' + ' '.join(flags or ['normal'])) + return int(match.group(1)) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--with-lean', action='store_true', help='also rebuild and compare BUILD_EVIDENCE.json') + args = parser.parse_args(argv) + out = args.output.resolve() + if out.exists() and any(out.iterdir()): + raise SystemExit('choose a new, empty output directory outside the source tree') + if ROOT in out.parents or out == ROOT: + raise SystemExit('output directory must be outside formal/') + out.mkdir(parents=True, exist_ok=True) + + counts = {'normal': _run_tests([], out / 'unittest_normal.log'), + 'optimized': _run_tests(['-O'], out / 'unittest_optimized.log')} + mutants = _count_mutants() + + gate = subprocess.run([sys.executable, '-B', '-S', str(ROOT / 'formal_gate.py'), '--json'], + capture_output=True, text=True, timeout=300) + (out / 'gate_stdout.txt').write_text(gate.stdout + gate.stderr, encoding='utf-8') + gate_report = json.loads(gate.stdout[:gate.stdout.rindex('}') + 1]) if gate.returncode == 0 else None + blueprint = subprocess.run([sys.executable, '-B', '-S', str(ROOT / 'blueprint_check.py')], + capture_output=True, text=True, timeout=300) + (out / 'blueprint_stdout.txt').write_text(blueprint.stdout + blueprint.stderr, encoding='utf-8') + + lean = None + if args.with_lean: + proc = subprocess.run([sys.executable, '-B', '-S', str(ROOT / 'lean_build_evidence.py'), '--check'], + capture_output=True, text=True, timeout=7200) + (out / 'lean_evidence_check.log').write_text(proc.stdout + proc.stderr, encoding='utf-8') + lean = {'evidence_matches_committed': proc.returncode == 0} + + files = {p.name: {'bytes': p.stat().st_size, 'sha256': hashlib.sha256(p.read_bytes()).hexdigest()} + for p in sorted(ROOT.iterdir()) if p.is_file()} + passed = (counts['normal'] == counts['optimized'] == EXPECTED_TESTS and mutants == EXPECTED_MUTANTS + and gate.returncode == 0 and gate_report is not None and gate_report['passed'] + and blueprint.returncode == 0 + and (lean is None or lean['evidence_matches_committed'])) + report = { + 'object': 'FORMAL-LAYER-VALIDATION-v1', + 'passed': passed, + 'distinct_tests': counts['normal'], + 'distinct_semantic_mutants': mutants, + 'modes': ['normal', 'optimized'], + 'gate_exit_code': gate.returncode, + 'blueprint_exit_code': blueprint.returncode, + 'lean': lean, + 'python': sys.version, + 'files': files, + 'mathematical_acceptance': False, + 'lemma_closed': False, + 'scientific_effect': 'NONE', + 'meaning': 'software-behavior replay of the formalization gate; not theorem acceptance or nonauthor review', + } + (out / 'REPORT.json').write_text(json.dumps(report, indent=2, sort_keys=True) + '\n', encoding='utf-8') + print(json.dumps({k: report[k] for k in ('passed', 'distinct_tests', 'distinct_semantic_mutants', 'scientific_effect')})) + return 0 if passed else 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/formal/test_blueprint_check.py b/formal/test_blueprint_check.py new file mode 100644 index 000000000..774879eb7 --- /dev/null +++ b/formal/test_blueprint_check.py @@ -0,0 +1,45 @@ +"""Tests for blueprint_check.py (software behavior only; scientific effect NONE).""" +from __future__ import annotations + +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import blueprint_check as bc # noqa: E402 + +REPO = Path(__file__).resolve().parents[1] +CONTENT = (REPO / 'formal' / 'blueprint' / 'src' / 'content.tex').read_text(encoding='utf-8') +DECLS = (REPO / 'formal' / 'blueprint' / 'lean_decls').read_text(encoding='utf-8') + + +class BlueprintTests(unittest.TestCase): + def test_committed_blueprint_aligns(self): + result = bc.check(REPO) + self.assertTrue(result['passed'], result['problems']) + self.assertEqual(len(result['bound']), 22) + + def test_leanok_on_specified_component_is_refused(self): + mutated = CONTENT.replace('\\lean{Side24.ratio_bound_statement}', '\\lean{Side24.ratio_bound_statement}\\leanok') + self.assertFalse(bc.check(REPO, content=mutated, decls_text=DECLS)['passed']) + + def test_missing_leanok_on_kernel_checked_is_refused(self): + mutated = CONTENT.replace('\\lean{Side24.image_constant_eq}\\leanok', '\\lean{Side24.image_constant_eq}') + self.assertFalse(bc.check(REPO, content=mutated, decls_text=DECLS)['passed']) + + def test_unknown_declaration_is_refused(self): + mutated = CONTENT.replace('\\lean{Side24.image_constant_eq}', '\\lean{Side24.parent_theorem}') + self.assertFalse(bc.check(REPO, content=mutated, decls_text=DECLS)['passed']) + + def test_dropped_component_is_refused(self): + start = CONTENT.index('\\begin{lemma}\\label{lem:truncation}') + end = CONTENT.index('\\end{lemma}', start) + len('\\end{lemma}') + mutated = CONTENT[:start] + CONTENT[end:] + self.assertFalse(bc.check(REPO, content=mutated, decls_text=DECLS)['passed']) + + def test_stale_decl_list_is_refused(self): + self.assertFalse(bc.check(REPO, content=CONTENT, decls_text=DECLS + 'Side24.extra\n')['passed']) + + +if __name__ == '__main__': + unittest.main() diff --git a/formal/test_formal_gate.py b/formal/test_formal_gate.py new file mode 100644 index 000000000..be56ad666 --- /dev/null +++ b/formal/test_formal_gate.py @@ -0,0 +1,479 @@ +"""Tests and assertion-detected semantic mutants for formal_gate.py. + +Every mutant is an in-memory edit of the real status/pins/evidence trees that a +careless or adversarial author could make; each must be refused. Passing tests +prove software behavior only (scientific effect NONE). + + python -B -S -m unittest discover -s formal -p 'test_*.py' -v + python -B -O -S -m unittest discover -s formal -p 'test_*.py' -v +""" +from __future__ import annotations + +import contextlib +import copy +import io +import json +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import formal_gate as fg # noqa: E402 + +REPO = Path(__file__).resolve().parents[1] +FORMAL = REPO / 'formal' + + +def _load(name: str): + return fg.load_json_strict((FORMAL / name).read_text(encoding='utf-8')) + + +def _component(status, cid): + for obj in status['objects']: + for comp in obj['components']: + if comp['component_id'] == cid: + return comp + raise KeyError(cid) + + +class _Tree: + """Copy of the formal tree in a temp dir so mutants can rewrite Lean bytes.""" + + def __init__(self): + self.dir = Path(tempfile.mkdtemp(prefix='formal-gate-')) + shutil.copytree(FORMAL, self.dir / 'formal', ignore=shutil.ignore_patterns('.lake', '__pycache__')) + self.status = _load('FORMALIZATION_STATUS.json') + self.pins = _load('SOURCE_FILES.json') + self.evidence = _load('BUILD_EVIDENCE.json') + + def module(self, rel: str) -> Path: + return self.dir / self.pins['project_root'] / rel + + def rewrite_module(self, rel: str, text: str, *, repin: bool = True, re_evidence: bool = True): + path = self.module(rel) + path.write_text(text, encoding='utf-8') + data = path.read_bytes() + identity = {'bytes': len(data), 'sha256': fg.sha256_bytes(data)} + if repin: + self.pins['files'][rel] = dict(identity) + if re_evidence: + self.evidence['sources'][rel] = dict(identity) + + def run(self, **kw): + return fg.run_gate(self.dir, status=self.status, pins=self.pins, evidence=self.evidence, **kw) + + def cleanup(self): + shutil.rmtree(self.dir, ignore_errors=True) + + +KERNEL = 'side24.ledger.image-constant' +SPECIFIED = 'side24.theorem.enclosure' +THEOREM_MODULE = 'Side24Formal/Ledger.lean' + + +class RealTreeTests(unittest.TestCase): + def test_committed_tree_passes(self): + report = fg.run_gate(REPO) + self.assertTrue(report['passed'], report['failures']) + self.assertEqual(report['scientific_effect'], 'NONE') + self.assertIs(report['lemma_closed'], False) + self.assertIs(report['mathematical_acceptance'], False) + + def test_no_component_reaches_nonauthor_lane_by_default(self): + report = fg.run_gate(REPO) + tokens = {c['promotion_token'] for o in report['objects'] for c in o['components']} + self.assertNotIn(fg.TOKEN_KERNEL_ALIGNED, tokens) + self.assertFalse(any(o['formal_lane_satisfied'] for o in report['objects'])) + + def test_every_formal_token_except_aligned_is_non_discharge(self): + report = fg.run_gate(REPO) + for obj in report['objects']: + for comp in obj['components']: + self.assertTrue(comp['non_discharge'], comp['component_id']) + self.assertIn(comp['promotion_token'], fg.FORMAL_NON_DISCHARGE) + + def test_kernel_checked_components_use_standard_axioms_only(self): + report = fg.run_gate(REPO) + for obj in report['objects']: + for comp in obj['components']: + if comp['verified_status'] == 'kernel-checked': + self.assertTrue(set(comp['kernel_axioms']) <= fg.STANDARD_AXIOMS) + self.assertEqual(comp['conditional_on'], []) + + def test_declared_status_never_exceeds_verified(self): + report = fg.run_gate(REPO) + for obj in report['objects']: + for comp in obj['components']: + self.assertLessEqual(fg.STATUS_LADDER.index(comp['declared_status']), + fg.STATUS_LADDER.index(comp['verified_status'])) + + def test_headline_theorem_is_only_specified(self): + report = fg.run_gate(REPO) + comp = next(c for o in report['objects'] for c in o['components'] if c['component_id'] == SPECIFIED) + self.assertEqual(comp['verified_status'], 'specified') + self.assertEqual(comp['promotion_token'], fg.TOKEN_SPECIFIED) + + def test_pins_match_lean_sources(self): + pins = _load('SOURCE_FILES.json') + for rel, identity in pins['files'].items(): + data = (REPO / pins['project_root'] / rel).read_bytes() + self.assertEqual(identity['sha256'], fg.sha256_bytes(data), rel) + self.assertEqual(identity['bytes'], len(data), rel) + + def test_evidence_sorry_free_and_successful_build(self): + evidence = _load('BUILD_EVIDENCE.json') + self.assertIs(evidence['sorry_free'], True) + self.assertEqual(evidence['build']['exit_code'], 0) + self.assertEqual(evidence['scientific_effect'], 'NONE') + + def test_cli_passes_and_prints_scientific_effect(self): + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + code = fg.main(['--root', str(REPO)]) + self.assertEqual(code, 0) + self.assertIn('FORMAL_GATE PASSED (scientific effect NONE; lemma_closed false)', buffer.getvalue()) + + def test_missing_evidence_is_refused_unless_allowed(self): + tree = _Tree() + try: + (tree.dir / 'formal' / 'BUILD_EVIDENCE.json').unlink() + with self.assertRaises(fg.GateError): + fg.run_gate(tree.dir, status=tree.status, pins=tree.pins, evidence=None) + # allow-missing: kernel-checked declarations now exceed verifiable 'proved' + report = fg.run_gate(tree.dir, status=tree.status, pins=tree.pins, evidence=None, require_evidence=False) + self.assertFalse(report['passed']) + self.assertFalse(report['evidence_present']) + kernel = next(c for o in report['objects'] for c in o['components'] if c['component_id'] == KERNEL) + self.assertEqual(kernel['verified_status'], 'proved') + finally: + tree.cleanup() + + +class ScanTests(unittest.TestCase): + def test_scan_finds_declarations_with_namespace(self): + scan = fg.scan_lean_module('namespace X\ntheorem foo : True := trivial\nnoncomputable def bar : Nat := 0\nend X\n') + self.assertEqual(scan['declarations']['X.foo']['kind'], 'theorem') + self.assertEqual(scan['declarations']['X.bar']['kind'], 'noncomputable def') + self.assertFalse(scan['sorry']) + self.assertEqual(scan['axioms'], []) + + def test_scan_detects_sorry_and_axiom_but_not_in_comments(self): + scan = fg.scan_lean_module('namespace X\n-- sorry here is a comment\n/- axiom nope -/\naxiom hidden : False\ntheorem foo : True := by sorry\nend X\n') + self.assertTrue(scan['sorry']) + self.assertEqual(scan['axioms'], ['X.hidden']) + + def test_scan_ignores_identifiers_containing_sorry(self): + scan = fg.scan_lean_module('theorem notsorry_lemma : True := trivial\n') + self.assertFalse(scan['sorry']) + + def test_statement_presence_is_whitespace_insensitive_only(self): + text = 'theorem foo :\n 1 + 1 = 2 := by norm_num\n' + self.assertTrue(fg.statement_present(text, 'theorem foo : 1 + 1 = 2')) + self.assertFalse(fg.statement_present(text, 'theorem foo : 1 + 1 = 3')) + + def test_strict_json_rejects_duplicates_and_nan(self): + with self.assertRaises(fg.GateError): + fg.load_json_strict('{"a": 1, "a": 2}') + with self.assertRaises(fg.GateError): + fg.load_json_strict('{"a": NaN}') + + +# ------------------------------------------------------------------ mutants + +def _m_declare_specified_as_kernel(t: _Tree): + _component(t.status, SPECIFIED)['formalization_status'] = 'kernel-checked' + + +def _m_declare_specified_as_proved(t: _Tree): + _component(t.status, SPECIFIED)['formalization_status'] = 'proved' + + +def _m_insert_sorry(t: _Tree): + text = t.module(THEOREM_MODULE).read_text(encoding='utf-8') + text = text.replace('theorem image_constant_eq : (1458 : ℕ) * (76 * 24 ^ 6 + 15) = 21175738586478 := by\n norm_num', + 'theorem image_constant_eq : (1458 : ℕ) * (76 * 24 ^ 6 + 15) = 21175738586478 := by\n sorry') + assert 'sorry' in text + t.rewrite_module(THEOREM_MODULE, text) + + +def _m_undeclared_axiom(t: _Tree): + text = t.module(THEOREM_MODULE).read_text(encoding='utf-8') + t.rewrite_module(THEOREM_MODULE, text.replace('namespace Side24\n', 'namespace Side24\naxiom parent_theorem : False\n', 1)) + + +def _m_source_edit_without_repin(t: _Tree): + text = t.module(THEOREM_MODULE).read_text(encoding='utf-8') + t.rewrite_module(THEOREM_MODULE, text + '\n', repin=False, re_evidence=True) + + +def _m_source_edit_with_stale_evidence(t: _Tree): + text = t.module(THEOREM_MODULE).read_text(encoding='utf-8') + t.rewrite_module(THEOREM_MODULE, text + '\n', repin=True, re_evidence=False) + + +def _m_statement_drift(t: _Tree): + _component(t.status, KERNEL)['lean_statement'] = 'theorem image_constant_eq : (1458 : ℕ) * (76 * 24 ^ 6 + 15) = 21175738586479' + + +def _m_decl_missing(t: _Tree): + _component(t.status, KERNEL)['lean_decl'] = 'Side24.not_a_declaration' + + +def _m_evidence_sorry_axiom(t: _Tree): + t.evidence['declarations']['Side24.image_constant_eq']['axioms'].append('sorryAx') + + +def _m_evidence_foreign_axiom(t: _Tree): + t.evidence['declarations']['Side24.image_constant_eq']['axioms'].append('Side24.parent_theorem') + + +def _m_evidence_failed_build(t: _Tree): + t.evidence['build']['exit_code'] = 1 + + +def _m_evidence_not_sorry_free(t: _Tree): + t.evidence['sorry_free'] = False + + +def _m_evidence_sorry_free_string(t: _Tree): + t.evidence['sorry_free'] = 'true' + + +def _m_evidence_wrong_toolchain(t: _Tree): + t.evidence['toolchain'] = 'leanprover/lean4:v4.0.0' + + +def _m_lemma_closed_true(t: _Tree): + t.status['lemma_closed'] = True + + +def _m_lemma_closed_string_false(t: _Tree): + t.status['lemma_closed'] = 'false' + + +def _m_mathematical_acceptance_true(t: _Tree): + t.status['mathematical_acceptance'] = True + + +def _m_scientific_effect(t: _Tree): + t.status['scientific_effect'] = 'PROMOTION' + + +def _m_ladder_extended(t: _Tree): + t.status['status_ladder'] = list(t.status['status_ladder']) + ['accepted'] + + +def _m_standard_axioms_widened(t: _Tree): + t.status['standard_axioms'] = list(t.status['standard_axioms']) + ['Side24.parent_theorem'] + + +def _m_nonauthor_without_record(t: _Tree): + _component(t.status, KERNEL)['formalization_review'] = 'nonauthor-aligned' + + +def _m_nonauthor_stale_record(t: _Tree): + comp = _component(t.status, KERNEL) + comp['formalization_review'] = 'nonauthor-aligned' + comp['review_record'] = {'path': 'formal/reviews/stale.json'} + (t.dir / 'formal' / 'reviews').mkdir(exist_ok=True) + (t.dir / 'formal' / 'reviews' / 'stale.json').write_text(json.dumps({ + 'verdict': 'ALIGNED', 'component_id': KERNEL, + 'reviewed_module_sha256': '0' * 64, + 'reviewed_lean_statement': comp['lean_statement'], + 'reviewer_provenance': {'provider': 'OpenAI', 'authored_formalization': False}, + }), encoding='utf-8') + + +def _m_nonauthor_record_by_author(t: _Tree): + comp = _component(t.status, KERNEL) + comp['formalization_review'] = 'nonauthor-aligned' + comp['review_record'] = {'path': 'formal/reviews/self.json'} + (t.dir / 'formal' / 'reviews').mkdir(exist_ok=True) + (t.dir / 'formal' / 'reviews' / 'self.json').write_text(json.dumps({ + 'verdict': 'ALIGNED', 'component_id': KERNEL, + 'reviewed_module_sha256': t.pins['files'][THEOREM_MODULE]['sha256'], + 'reviewed_lean_statement': comp['lean_statement'], + 'reviewer_provenance': {'provider': 'Anthropic / Claude', 'authored_formalization': True}, + }), encoding='utf-8') + + +def _m_nonauthor_record_amend_required(t: _Tree): + comp = _component(t.status, KERNEL) + comp['formalization_review'] = 'nonauthor-aligned' + comp['review_record'] = {'path': 'formal/reviews/amend.json'} + (t.dir / 'formal' / 'reviews').mkdir(exist_ok=True) + (t.dir / 'formal' / 'reviews' / 'amend.json').write_text(json.dumps({ + 'verdict': 'AMEND_REQUIRED', 'component_id': KERNEL, + 'reviewed_module_sha256': t.pins['files'][THEOREM_MODULE]['sha256'], + 'reviewed_lean_statement': comp['lean_statement'], + 'reviewer_provenance': {'provider': 'OpenAI', 'authored_formalization': False}, + }), encoding='utf-8') + + +def _m_assumed_axiom_without_scope_note(t: _Tree): + t.status['assumed_axioms'] = [{'name': 'Side24.parent_theorem', 'scope_note': ''}] + + +def _m_registry_lists_standard_axiom(t: _Tree): + t.status['assumed_axioms'] = [{'name': 'propext', 'scope_note': 'smuggle'}] + + +def _m_registered_axiom_still_blocks_aligned_lane(t: _Tree): + """A registered parent axiom used by a nonauthor-aligned theorem must stay CONDITIONAL.""" + text = t.module(THEOREM_MODULE).read_text(encoding='utf-8') + t.rewrite_module(THEOREM_MODULE, text.replace('namespace Side24\n', 'namespace Side24\naxiom parent_theorem : True\n', 1)) + t.status['assumed_axioms'] = [{'name': 'Side24.parent_theorem', 'scope_note': 'assumed parent'}] + t.evidence['declarations']['Side24.image_constant_eq']['axioms'].append('Side24.parent_theorem') + comp = _component(t.status, KERNEL) + comp['formalization_review'] = 'nonauthor-aligned' + comp['review_record'] = {'path': 'formal/reviews/ok.json'} + (t.dir / 'formal' / 'reviews').mkdir(exist_ok=True) + (t.dir / 'formal' / 'reviews' / 'ok.json').write_text(json.dumps({ + 'verdict': 'ALIGNED', 'component_id': KERNEL, + 'reviewed_module_sha256': t.pins['files'][THEOREM_MODULE]['sha256'], + 'reviewed_lean_statement': comp['lean_statement'], + 'reviewer_provenance': {'provider': 'OpenAI', 'authored_formalization': False}, + }), encoding='utf-8') + t.expect_token = fg.TOKEN_KERNEL_CONDITIONAL + + +def _m_missing_does_not_claim(t: _Tree): + _component(t.status, KERNEL)['does_not_claim'] = '' + + +def _m_informal_source_short_commit(t: _Tree): + t.status['objects'][0]['informal_source']['commit'] = '760340e' + + +def _m_duplicate_component(t: _Tree): + comps = t.status['objects'][0]['components'] + comps.append(copy.deepcopy(comps[0])) + + +def _m_toolchain_file_drift(t: _Tree): + (t.dir / t.pins['project_root'] / 'lean-toolchain').write_text('leanprover/lean4:v4.0.0\n') + + +def _m_unpinned_module_referenced(t: _Tree): + del t.pins['files'][THEOREM_MODULE] + del t.evidence['sources'][THEOREM_MODULE] + + +def _m_evidence_missing_module(t: _Tree): + del t.evidence['sources'][THEOREM_MODULE] + + +MUTANTS = [ + _m_declare_specified_as_kernel, _m_declare_specified_as_proved, _m_insert_sorry, + _m_undeclared_axiom, _m_source_edit_without_repin, _m_source_edit_with_stale_evidence, + _m_statement_drift, _m_decl_missing, _m_evidence_sorry_axiom, _m_evidence_foreign_axiom, + _m_evidence_failed_build, _m_evidence_not_sorry_free, _m_evidence_sorry_free_string, + _m_evidence_wrong_toolchain, _m_lemma_closed_true, _m_lemma_closed_string_false, + _m_mathematical_acceptance_true, _m_scientific_effect, _m_ladder_extended, + _m_standard_axioms_widened, _m_nonauthor_without_record, _m_nonauthor_stale_record, + _m_nonauthor_record_by_author, _m_nonauthor_record_amend_required, + _m_assumed_axiom_without_scope_note, _m_registry_lists_standard_axiom, _m_missing_does_not_claim, + _m_informal_source_short_commit, _m_duplicate_component, _m_toolchain_file_drift, + _m_unpinned_module_referenced, _m_evidence_missing_module, _m_registered_axiom_still_blocks_aligned_lane, +] + + +class MutantTests(unittest.TestCase): + def _refused(self, mutant): + """True when the mutant is refused, or (for token mutants) demoted to the expected token.""" + tree = _Tree() + try: + mutant(tree) + try: + report = tree.run() + except fg.GateError: + return True + expected = getattr(tree, 'expect_token', None) + if expected is not None: + res = next(c for o in report['objects'] for c in o['components'] if c['component_id'] == KERNEL) + return res['promotion_token'] == expected and res['non_discharge'] and not report['objects'][0]['formal_lane_satisfied'] + return not report['passed'] + finally: + tree.cleanup() + + def test_unmutated_copy_passes(self): + tree = _Tree() + try: + self.assertTrue(tree.run()['passed']) + finally: + tree.cleanup() + + def test_every_semantic_mutant_is_refused(self): + survivors = [m.__name__ for m in MUTANTS if not self._refused(m)] + self.assertEqual(survivors, [], 'mutants survived: ' + ','.join(survivors)) + + def test_mutant_count_is_the_documented_scope(self): + self.assertEqual(len(MUTANTS), 33) + + +class HonestReviewRecordTests(unittest.TestCase): + def test_valid_nonauthor_record_reaches_aligned_lane_without_promotion(self): + tree = _Tree() + try: + comp = _component(tree.status, KERNEL) + comp['formalization_review'] = 'nonauthor-aligned' + comp['review_record'] = {'path': 'formal/reviews/ok.json'} + (tree.dir / 'formal' / 'reviews').mkdir(exist_ok=True) + (tree.dir / 'formal' / 'reviews' / 'ok.json').write_text(json.dumps({ + 'verdict': 'ALIGNED', 'component_id': KERNEL, + 'reviewed_module_sha256': tree.pins['files'][THEOREM_MODULE]['sha256'], + 'reviewed_lean_statement': comp['lean_statement'], + 'reviewer_provenance': {'provider': 'OpenAI', 'authored_formalization': False}, + }), encoding='utf-8') + report = tree.run() + self.assertTrue(report['passed'], report['failures']) + res = next(c for o in report['objects'] for c in o['components'] if c['component_id'] == KERNEL) + self.assertEqual(res['promotion_token'], fg.TOKEN_KERNEL_ALIGNED) + self.assertFalse(res['non_discharge']) + self.assertEqual(res['review']['organizational_independence'], 'ATTESTED_NOT_VALIDATED') + # one aligned component does not satisfy the object lane + self.assertFalse(report['objects'][0]['formal_lane_satisfied']) + self.assertIs(report['lemma_closed'], False) + finally: + tree.cleanup() + + def test_same_provider_review_gets_no_independence_credit(self): + tree = _Tree() + try: + comp = _component(tree.status, KERNEL) + comp['formalization_review'] = 'nonauthor-aligned' + comp['review_record'] = {'path': 'formal/reviews/same.json'} + (tree.dir / 'formal' / 'reviews').mkdir(exist_ok=True) + (tree.dir / 'formal' / 'reviews' / 'same.json').write_text(json.dumps({ + 'verdict': 'ALIGNED', 'component_id': KERNEL, + 'reviewed_module_sha256': tree.pins['files'][THEOREM_MODULE]['sha256'], + 'reviewed_lean_statement': comp['lean_statement'], + 'reviewer_provenance': {'provider': 'Anthropic / Claude (Cursor cloud agent)', 'authored_formalization': False}, + }), encoding='utf-8') + report = tree.run() + res = next(c for o in report['objects'] for c in o['components'] if c['component_id'] == KERNEL) + self.assertIs(res['review']['organizational_independence'], False) + finally: + tree.cleanup() + + def test_assumed_axiom_with_scope_note_yields_conditional_token(self): + tree = _Tree() + try: + text = tree.module(THEOREM_MODULE).read_text(encoding='utf-8') + tree.rewrite_module(THEOREM_MODULE, text.replace('namespace Side24\n', 'namespace Side24\naxiom parent_theorem : True\n', 1)) + tree.status['assumed_axioms'] = [{'name': 'Side24.parent_theorem', 'scope_note': 'parent main #63 assumed; not independently verified'}] + tree.evidence['declarations']['Side24.image_constant_eq']['axioms'].append('Side24.parent_theorem') + report = tree.run() + self.assertTrue(report['passed'], report['failures']) + res = next(c for o in report['objects'] for c in o['components'] if c['component_id'] == KERNEL) + self.assertEqual(res['promotion_token'], fg.TOKEN_KERNEL_CONDITIONAL) + self.assertEqual(res['conditional_on'], ['Side24.parent_theorem']) + self.assertTrue(res['non_discharge']) + finally: + tree.cleanup() + + +if __name__ == '__main__': + unittest.main() diff --git a/handoff/MATH_HARD_GATE_EXTENSION.md b/handoff/MATH_HARD_GATE_EXTENSION.md new file mode 100644 index 000000000..ef8f0fc91 --- /dev/null +++ b/handoff/MATH_HARD_GATE_EXTENSION.md @@ -0,0 +1,104 @@ +# Extending the Math- hard gate with the formal lane + +**Target:** Math- `frontiers/downstream_gate_20260925/hard_gate.py` (+ `GRAPH.json`, +`test_hard_gate.py`, `SOURCE_FILES.json`, `RESULTS.json`, `run_validation.py`). +**Scientific effect: NONE.** This adds a stricter *necessary* criterion; it removes no +existing rule and promotes nothing. + +The hard gate today decides `promotion_allowed(graph, node)` from classifications +(`PROVED_REVIEWED` etc.) and refuses promotion justified only by non-discharge tokens +(`GREEN_CI`, `HASH_MATCH`, …). The extension makes the gate aware of Layer 1 without +letting Layer 1 decide anything on its own. + +## 1. Node field + +```json +"math.side24-coefficient": { + "...": "...", + "formalization": { + "status": "specified", // none | specified | proved | kernel-checked (object-level = min over required components) + "review": "author-side", // none | author-side | nonauthor-aligned + "required": false, // when true, CONTROLLING needs the formal lane satisfied + "evidence": { + "repository": "d6g8k5htny-coder/Math-", // where formal/ lives after the port + "status_file": "formal/FORMALIZATION_STATUS.json", + "commit": "", + "sha256": "" + } + } +} +``` + +Missing `formalization` ⇒ treated as `{"status": "none", "review": "none", "required": false}`. +`formalization.required` defaults to `false` so that existing nodes behave exactly as +today; turning it on for a node is an explicit, reviewable graph edit. + +**Validation (fail-closed, in `_validate_graph_shape`):** status/review must be exact +strings from the ladders; `required` must be an exact boolean; `evidence.commit` a full +40-hex OID when status ≠ `none`; `review ≠ none` requires `status ≠ none`. + +## 2. Tokens + +Extend `NON_DISCHARGE_DEFAULT` (and `GRAPH.json.non_discharge_tokens`) with + +``` +FORMAL_SPECIFIED, FORMAL_PROVED_AUTHOR_SIDE, KERNEL_CHECKED_AUTHOR_SIDE, KERNEL_CHECKED_CONDITIONAL +``` + +and add `KERNEL_CHECKED_NONAUTHOR_ALIGNED` to the *known* (not non-discharge) list in +`refuse_non_discharge_promotion`. A promotion justified **only** by +`KERNEL_CHECKED_NONAUTHOR_ALIGNED` must still be refused: it satisfies one lane, and the +analytic lanes (`LINE_BY_LINE_ANALYTIC_REVIEW`, `PROVED_REVIEWED`) are still required. +Implement as: `only_non_discharge or tokens == {KERNEL_CHECKED_NONAUTHOR_ALIGNED}` ⇒ refused +with reason `formal lane alone is not theorem acceptance`. + +## 3. Rule in `promotion_allowed` + +```python +formal = node.get('formalization', {'status': 'none', 'review': 'none', 'required': False}) +if formal.get('required'): + if formal['status'] != 'kernel-checked' or formal['review'] != 'nonauthor-aligned': + reasons.append('formal lane required: needs kernel-checked + nonauthor-aligned') +``` + +Return the formal record in the decision (`'formalization': formal`) so the museum can +display it. Nothing else in the decision changes. + +## 4. Reverse impact + +A change of `formalization.evidence.sha256` or of `status`/`review` on a node is a node +record change; `reverse_impact_between` already marks dependents `REVALIDATION_REQUIRED` +because it compares complete canonical node records. No new code; add a test asserting it. + +## 5. Sync from Layer 1 (no manual editing of the field) + +Add `tools/sync_formalization.py` (stdlib): reads `formal/FORMALIZATION_STATUS.json`, runs +`formal_gate.run_gate()`, and for each `objects[].hard_gate_node` writes +`status = min(verified_status over components)`, `review = min(verified_review …)`, +`evidence.sha256 = sha256(status file)`, `evidence.commit = HEAD`. Refuse (exit 2) if the +gate did not pass. Run it in the same commit as any Lean change; CI runs it with `--check` +and `git diff --exit-code`. The gate output is the only writer of `formalization`. + +## 6. Tests and mutants to add (`test_hard_gate.py`) + +1. `formalization.required=true` + status `specified` ⇒ not allowed, reason present. +2. `required=true` + `kernel-checked` + `author-side` ⇒ not allowed. +3. `required=true` + `kernel-checked` + `nonauthor-aligned` + node `PROVED_REVIEWED` + deps satisfied ⇒ allowed (and identical to today's outcome when `required=false`). +4. Tokens `['KERNEL_CHECKED_AUTHOR_SIDE']` ⇒ refused as non-discharge. +5. Tokens `['KERNEL_CHECKED_NONAUTHOR_ALIGNED']` alone ⇒ refused (`formal lane alone`). +6. `formalization.status = 'accepted'` ⇒ `ValueError('unknown formalization status')`. +7. `required = 'true'` (string) ⇒ `ValueError`. +8. `review = 'nonauthor-aligned'` with `status = 'none'` ⇒ `ValueError`. +9. Evidence sha256 change on a node ⇒ dependents `REVALIDATION_REQUIRED`. +10. `hist.lemma_closed` with a formalization record ⇒ still `FALSE`, never promoted. + +Update the documented counts (`67 distinct tests / 24 mutants` → new numbers) in +`README.md`, `run_validation.py` and the workflow assertion together, and regenerate +`SOURCE_FILES.json` / `RESULTS.json` on the final tree (measured amendment: pins fail +first otherwise). + +## 7. Museum (main) + +`tools/museum_data.py` gains a `formalization` field per displayed source, read from the +Math- `GRAPH.json` node at the pinned Math commit. Display the ladder value and the +token name verbatim; never render `kernel-checked` as "verified". diff --git a/handoff/PORT.md b/handoff/PORT.md new file mode 100644 index 000000000..576587631 --- /dev/null +++ b/handoff/PORT.md @@ -0,0 +1,52 @@ +# Porting `formal/` from sandbox to Math- (and what goes where) + +**Scientific effect: NONE.** Moving files moves no status. + +## Why port + +The sandbox-launched Cloud Agent that built Layer 1 measured `403 Permission denied to +cursor[bot]` on push to `trial`, `main`, `Math-` and `governance-` (2026-09-27; matches +the governance write-scope amendment). Layer 1 therefore landed here. Its intended home +is Math-, next to the informal objects it binds and the hard gate it feeds. + +## Destination map + +| Content | Destination | Reason | +|---|---|---| +| `formal/lean/**`, `FORMALIZATION_STATUS.json`, `SOURCE_FILES.json`, `BUILD_EVIDENCE.json`, `formal_gate.py`, `test_formal_gate.py`, `run_validation.py`, `pin_sources.py`, `lean_build_evidence.py`, `blueprint/**`, `blueprint_check.py`, `test_blueprint_check.py`, `GLOSSARY.md`, `FORMALIZATION_REVIEW_LANE.md`, `README.md` | Math- `formal/` (same relative layout) | proofs live with their informal sources; hard gate consumes the status file | +| `.github/workflows/formal-gate.yml` | Math- `.github/workflows/formal-gate.yml` | Math- already runs per-package exact-replay workflows | +| `handoff/MATH_HARD_GATE_EXTENSION.md` | implement in Math- `frontiers/downstream_gate_20260925/` | see that file | +| cross-repo pin test (status `informal_source` ↔ live Math- bytes) | trial `federation/` | trial owns cross-repo eng tests | +| museum `formalization` column, per-object alignment-review issues | main | main owns display and review discussion | +| process amendment (ladders, tokens, non-discharge rule) | governance- README "Process amendments" + `AGENTS.md` | working contract | + +## Steps (any agent with Math- write; owner autonomy already granted) + +```sh +# 1. Take the exact bytes from the sandbox tip you are porting. +git -C sandbox rev-parse HEAD # record this OID in the PR body +git -C sandbox archive --format=tar HEAD formal .github/workflows/formal-gate.yml | tar -x -C Math- + +# 2. Nothing in formal/ hard-codes 'sandbox' paths; the informal_source already points at Math-. +# Update FORMALIZATION_STATUS.json "repository" to "d6g8k5htny-coder/Math-". + +# 3. Replay everything on the final tree. +python -B -S formal/pin_sources.py --check +python -B -S formal/run_validation.py --output /tmp/formal-port-run +cd formal/lean && lake exe cache get && lake build && cd ../.. +python -B -S formal/lean_build_evidence.py --check + +# 4. Open a DRAFT PR; keep it draft until the Lean CI job is green; scientific Booleans stay false. +``` + +Then apply `handoff/agents/Math-.AGENTS.md.patch` (`git apply`), and follow +`MATH_HARD_GATE_EXTENSION.md` in a **separate** PR (it touches byte-pinned gate sources). + +## Do not + +* Do not copy `experiments/` or anything outside `formal/` + the workflow — sandbox stays + private per the contract; the formal layer references only public Math- identities. +* Do not "fix" a `specified` component by adding `sorry`. It fails the gate and the kernel + records `sorryAx`. +* Do not mark any `formalization_review` as `nonauthor-aligned` while porting. Porting is + not review. diff --git a/handoff/README.md b/handoff/README.md new file mode 100644 index 000000000..9d2511fe3 --- /dev/null +++ b/handoff/README.md @@ -0,0 +1,68 @@ +# Handoff — Layer 1 formal verification, for every agent on every repository + +**Object:** FORMAL-LAYER-HANDOFF-20260927-v1. **Scientific effect: NONE.** + +## Owner instruction (verbatim intent) + +Dylan Roy, 2026-09-27: incorporate a formal verification layer (Lean 4 + Mathlib) on top +of the existing provenance / scope / hard-gate / museum system, so that +"provenance-bound natural-language proofs" become "provenance-bound formal proofs" that +are also machine-checked; coordinate with all current and future agents on all +repositories. **"I, Dylan Roy, pre-approve any decision, request, or action needed to +achieve this goal."** No agent needs to ask for re-approval of work inside this scope. + +## What was built (in `sandbox`, this repository) + +[`formal/`](../formal/README.md) — Lean 4 project, status ladder, fail-closed gate, +kernel evidence, blueprint, glossary, alignment-review lane, CI. Pilot object: the SIDE24 +coefficient note from Math- (16 kernel-checked components, 6 specified, 0 axioms, 0 sorry). + +## Why here and not in Math- + +Measured 2026-09-27 from this sandbox-launched Cloud Agent: `git push` to `trial`, +`main`, `Math-` and `governance-` returns `403 Permission denied to cursor[bot]`. This is +the known write-scope behaviour recorded in the governance contract ("Cloud Agent write +scope follows the launch environment"). The work therefore landed where it could and +ships with ready-to-apply artifacts for the other repositories. + +## What each repository does next (OFFERED — not activity until an agent claims it) + +| Repo | Task | Artifact here | +|---|---|---| +| **Math-** | Port `formal/` + workflow; then extend `hard_gate.py` with the `formalization` node field, the four non-discharge formal tokens and the `required` rule | [`PORT.md`](PORT.md), [`MATH_HARD_GATE_EXTENSION.md`](MATH_HARD_GATE_EXTENSION.md), [`agents/Math-.AGENTS.md.patch`](agents/Math-.AGENTS.md.patch) | +| **main** | Add `formalization` lane to museum/STATUS; open one alignment-review issue per formal object (pilot: SIDE24, linking #63/#65); adopt glossary terminology in new prose | [`agents/main.AGENTS.md.patch`](agents/main.AGENTS.md.patch), `formal/GLOSSARY.md`, `formal/FORMALIZATION_REVIEW_LANE.md` | +| **trial** | Cross-repo eng test: Math- `formal/FORMALIZATION_STATUS.json` `informal_source` pins match live Math- bytes; `BUILD_EVIDENCE.sources == SOURCE_FILES.files` | [`agents/trial.AGENTS.md.patch`](agents/trial.AGENTS.md.patch) | +| **governance-** | Record the process amendment (ladders, tokens, non-discharge rule, same-provider no-credit, measured 403) | [`agents/governance-.AGENTS.md.patch`](agents/governance-.AGENTS.md.patch) | +| **any nonauthor agent (OpenAI, Grok, …)** | First alignment review of the pilot: follow the checklist, write `formal/reviews/..json` per component, set `formalization_review` accordingly — in Math- after the port, or as a PR here before it | `formal/FORMALIZATION_REVIEW_LANE.md` | +| **AI-prover cross-check lane** | Attempt the `specified` Props (`ratio_bound_statement`, `reference_enclosure_statement`, `periodization_statement`) with an independent Lean prover; any kernel-accepted proof is recorded with its own provenance and stays author-side until aligned | `formal/lean/Side24Formal/*.lean` | + +Patches were generated against these sibling tips and apply with `git apply`: +trial `abae0b4f931e988f582d629f932bb35623dc3af9`, main `f8591b0e1101d97753677044f04e9d87f2fc719a`, +Math- `3b2ac59f8f02b9573d01087aefff85bbc279a55a`, governance- `ae1b92ef1bb794050e584bec1c6f58f9495a018e`. +If a tip moved, re-append the section by hand — it is self-contained. + +## Rules that every agent inherits from this layer + +1. **Declared ≤ verifiable.** `formalization_status` may never exceed what + `formal_gate.py` can verify from pinned bytes and kernel evidence. +2. **Kernel ≠ meaning.** `kernel-checked` says the encoded statement is a theorem. Whether + the encoding matches the prose is the alignment lane; whether the prose is + mathematically accepted is the analytic lane. Three lanes, none skippable. +3. **Non-discharge by default.** Every formal token is non-discharge except + `KERNEL_CHECKED_NONAUTHOR_ALIGNED`, which satisfies the formal lane only. +4. **No hidden assumptions.** Parents are parametrized or registered as `axiom` with a + scope note; `sorry` is refused; conditional theorems carry `KERNEL_CHECKED_CONDITIONAL`. +5. **Same commit.** Lean edit ⇒ pins + evidence + `lean_statement` + blueprint + glossary + in the same commit. A stale alignment review fails by hash, never by memory. +6. **Standard terminology.** Map every project term in `formal/GLOSSARY.md` before it + appears in Lean. `UNMAPPED` terms cannot enter `FORMALIZATION_STATUS.json`. +7. **Same-provider review earns no independence credit** (REVIEW_TOPOLOGY v1.1). The gate + reports `organizational_independence` as `false` or `ATTESTED_NOT_VALIDATED`, never `true`. +8. **Unchanged:** `lemma_closed=false`, prizes, premises, the #90 rules, sandbox privacy. + +## For future agents reading this cold + +Start with [`formal/README.md`](../formal/README.md), run the six commands under "Run", +read the pilot's `FORMALIZATION_STATUS.json` to see how a component is declared, then pick +the row above for your repository. Coordination is through existing PRs and the +governance work-lease ledger; this file offers tasks, it does not assign or claim them. diff --git a/handoff/agents/Math-.AGENTS.md.patch b/handoff/agents/Math-.AGENTS.md.patch new file mode 100644 index 000000000..6397a5f6e --- /dev/null +++ b/handoff/agents/Math-.AGENTS.md.patch @@ -0,0 +1,26 @@ +diff --git a/AGENTS.md b/AGENTS.md +index 3b92fbc..c6c963e 100644 +--- a/AGENTS.md ++++ b/AGENTS.md +@@ -21,3 +21,21 @@ Mathematical candidates, proofs, programs, and reproducible calculations. Not a + 1. This repository’s [README](README.md) + 2. [`governance-` working contract](https://github.com/d6g8k5htny-coder/governance-) + 3. [`trial` multi-agent access](https://github.com/d6g8k5htny-coder/trial/blob/main/docs/MULTI_AGENT_ACCESS.md) (Cloud Agent env deps live on trial `.cursor/environment.json`) ++ ++## Layer 1 — formal verification (Lean 4 + Mathlib) ++ ++Math- is the intended home of the Lean project and the extended hard gate. The pilot ++(SIDE24 ledger/cone/§5 implication, 16 kernel-checked + 6 specified components) and the ++fail-closed `formal_gate.py` are in [`sandbox/formal`](https://github.com/d6g8k5htny-coder/sandbox/tree/main/formal); port per [handoff](https://github.com/d6g8k5htny-coder/sandbox/tree/main/handoff) ++(`PORT.md`, `MATH_HARD_GATE_EXTENSION.md`). ++ ++- Add `formalization` to `GRAPH.json` nodes only through `formal_gate.py` output; declared ++ status may never exceed verifiable status. ++- New non-discharge tokens: `FORMAL_SPECIFIED`, `FORMAL_PROVED_AUTHOR_SIDE`, ++ `KERNEL_CHECKED_AUTHOR_SIDE`, `KERNEL_CHECKED_CONDITIONAL`. Only ++ `KERNEL_CHECKED_NONAUTHOR_ALIGNED` satisfies the formal lane; it is necessary, not sufficient. ++- Lean edits regenerate `SOURCE_FILES.json` + `BUILD_EVIDENCE.json` in the same commit ++ (same rule as the exact-replay source identities). No `sorry`; parents are parametrized ++ or registered `axiom`s with scope notes, never silent. ++- Decimal bounds go in as exact rationals (`norm_num`); numerical experiments stay ++ `NUMERICAL_EXPERIMENT` (non-discharge). diff --git a/handoff/agents/governance-.AGENTS.md.patch b/handoff/agents/governance-.AGENTS.md.patch new file mode 100644 index 000000000..2cb45a9c2 --- /dev/null +++ b/handoff/agents/governance-.AGENTS.md.patch @@ -0,0 +1,26 @@ +diff --git a/AGENTS.md b/AGENTS.md +index e341268..f751f4c 100644 +--- a/AGENTS.md ++++ b/AGENTS.md +@@ -22,3 +22,21 @@ Cross-repository working contract and useful process amendments only. + 3. [`trial` multi-agent access](https://github.com/d6g8k5htny-coder/trial/blob/main/docs/MULTI_AGENT_ACCESS.md) (Cloud Agent env deps / `repositoryDependencies` live on trial only) + 4. Recent measured conflicts: [`amendments/20260925-measured-conflicts.md`](amendments/20260925-measured-conflicts.md) + 5. Mesoscopic d=2 chart handoff (for Math- #7 authors; not a Math- publication): [`amendments/20260925-mesoscopic-d2-chart-handoff.md`](amendments/20260925-mesoscopic-d2-chart-handoff.md) ++ ++## Layer 1 — formal verification lane (process amendment, 2026-09-27) ++ ++Owner instruction (Dylan Roy, pre-approved, no re-approval needed): extend the ++verification stack with a Lean 4 + Mathlib formal lane. Definitions, gate and pilot: ++[`sandbox/formal`](https://github.com/d6g8k5htny-coder/sandbox/tree/main/formal); cross-repo coordination: [handoff](https://github.com/d6g8k5htny-coder/sandbox/tree/main/handoff). ++ ++- Ladders: `formalization_status ∈ none < specified < proved < kernel-checked`; ++ `formalization_review ∈ none | author-side | nonauthor-aligned`. ++- Kernel acceptance verifies the *encoded* statement at its trust boundary (REVIEW_TOPOLOGY ++ v1.1); translation fidelity is the separate alignment lane; analytic review is unchanged. ++- Tokens: all `FORMAL_*`/`KERNEL_CHECKED_*` are non-discharge except ++ `KERNEL_CHECKED_NONAUTHOR_ALIGNED`, which satisfies the formal lane only. ++- Same-provider alignment review earns no organizational-independence credit; the gate ++ reports it, never infers it. ++- Measured 2026-09-27: a sandbox-launched Cloud Agent App token gets 403 on trial/main/Math-/governance- ++ (consistent with the write-scope amendment above); Layer 1 was therefore landed in sandbox ++ with per-repo patches under `handoff/agents/`. diff --git a/handoff/agents/main.AGENTS.md.patch b/handoff/agents/main.AGENTS.md.patch new file mode 100644 index 000000000..04d298af9 --- /dev/null +++ b/handoff/agents/main.AGENTS.md.patch @@ -0,0 +1,24 @@ +diff --git a/AGENTS.md b/AGENTS.md +index d6eaef1..ae29b23 100644 +--- a/AGENTS.md ++++ b/AGENTS.md +@@ -30,3 +30,19 @@ not a reason to ask for permission already granted. + Drive record, and collaboration surfaces. This `main` initially contains the renewed + landing, not the complete research stack. Bring improvements into it coherently; + there is no permanent landing-only restriction. ++ ++## Layer 1 — formal verification (Lean 4 + Mathlib) ++ ++The provenance/scope/hard-gate stack is **Layer 0**. [`sandbox/formal`](https://github.com/d6g8k5htny-coder/sandbox/tree/main/formal) adds ++**Layer 1**: kernel-checked Lean statements byte-bound to the informal object, a ++`formalization_status` ladder (`none < specified < proved < kernel-checked`) and an ++alignment review lane (`author-side | nonauthor-aligned`). Read [handoff](https://github.com/d6g8k5htny-coder/sandbox/tree/main/handoff) first. ++ ++- main's job: display the formal lane in the museum/STATUS (a `formalization` column ++ sourced from Math- `formal/FORMALIZATION_STATUS.json` at a pinned commit), host the ++ alignment-review discussion for each object (like #63/#65 do for analytic review), and ++ keep the lanes distinct: kernel evidence ≠ translation fidelity ≠ analytic acceptance. ++- `KERNEL_CHECKED_*` tokens are non-discharge except `KERNEL_CHECKED_NONAUTHOR_ALIGNED`, ++ which satisfies the formal lane **only**. #90 rules and `lemma_closed=false` unchanged. ++- Use standard terminology from `formal/GLOSSARY.md` in new prose; map any new project ++ term there before it appears in a Lean statement. diff --git a/handoff/agents/trial.AGENTS.md.patch b/handoff/agents/trial.AGENTS.md.patch new file mode 100644 index 000000000..1f3c81b1c --- /dev/null +++ b/handoff/agents/trial.AGENTS.md.patch @@ -0,0 +1,19 @@ +diff --git a/AGENTS.md b/AGENTS.md +index 126d0ba..00dd156 100644 +--- a/AGENTS.md ++++ b/AGENTS.md +@@ -28,3 +28,14 @@ Do not wait for permissions/approvals. Path A or Path B OK for ALIGNED restore + 3. `docs/OWNER_ACTIONS_MAIN.md` + 4. `docs/MULTI_AGENT_ACCESS.md` — grant Cursor + ChatGPT/Codex + Claude + Grok (PAT) Read/write on all **8** owner repos including **sandbox** (`./scripts/owner_grant_ai_agent_access.sh`; App UI: select ALL repositories including sandbox) + 5. `docs/AUTONOMOUS_48H_LOG.md` (if an autonomous window is active) ++ ++## Layer 1 — formal verification (Lean 4 + Mathlib) ++ ++Pilot and gate live in [`sandbox/formal`](https://github.com/d6g8k5htny-coder/sandbox/tree/main/formal) (see [handoff](https://github.com/d6g8k5htny-coder/sandbox/tree/main/handoff)). Status ladder ++`none < specified < proved < kernel-checked`; review ladder `author-side | nonauthor-aligned`. ++Every formal token except `KERNEL_CHECKED_NONAUTHOR_ALIGNED` is **non-discharge**. ++ ++- trial's job: cross-repo eng checks only — `federation/` test that Math- `formal/FORMALIZATION_STATUS.json` ++ `informal_source` pins still match live Math- bytes, and that `BUILD_EVIDENCE.json` sources equal `SOURCE_FILES.json`. ++- Do not host the Lean project here; port `formal/` to Math- (`handoff/PORT.md`). Portable copies under `portable/` are fallback only. ++- A green `lake build` is kernel acceptance of the *encoded* statement — never theorem acceptance, never `lemma_closed`.