diff --git a/.github/workflows/d2-moment-bridge.yml b/.github/workflows/d2-moment-bridge.yml new file mode 100644 index 000000000..6bcf23d82 --- /dev/null +++ b/.github/workflows/d2-moment-bridge.yml @@ -0,0 +1,48 @@ +name: D2 actual-law moment bridge (isolated Lean companion) +'on': + pull_request: + paths: + - 'companions/d2_moment_bridge_20261006/**' + - '.github/workflows/d2-moment-bridge.yml' + push: + branches: [main] + paths: + - 'companions/d2_moment_bridge_20261006/**' + - '.github/workflows/d2-moment-bridge.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + d2-moment-bridge: + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + LEAN_NUM_THREADS: 2 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - name: Install pinned Lean and retrieve dependency cache + uses: leanprover/lean-action@f061402b660e0c34644504b324e830f2991d4865 + with: + lake-package-directory: formal + auto-config: 'false' + build: 'false' + test: 'false' + lint: 'false' + use-mathlib-cache: 'true' + use-github-cache: 'false' + - name: Replay core and actual-law companion with exact negative controls + shell: bash + run: bash companions/d2_moment_bridge_20261006/replay.sh + - name: Preserve original execution evidence on success or failure + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a + with: + name: d2-moment-${{ github.run_id }}-${{ github.run_attempt }} + path: | + .lake/d2-moment-evidence/ + formal/.lake/formal-evidence/ + include-hidden-files: true + if-no-files-found: error + retention-days: 30 diff --git a/companions/d2_moment_bridge_20261006/D2MomentBridge.lean b/companions/d2_moment_bridge_20261006/D2MomentBridge.lean new file mode 100644 index 000000000..b3184107e --- /dev/null +++ b/companions/d2_moment_bridge_20261006/D2MomentBridge.lean @@ -0,0 +1,238 @@ +import ResearchFormalCoreR1.D2Schur +import Mathlib.MeasureTheory.Integral.Bochner.Basic +import Mathlib.Tactic + +/-! +# Actual-law d2 moment bridge + +Dylan Roy — delegated AI work. Author: OpenAI / GPT-6 Astra Pro. +This companion uses actual integrals, not assigned scalar moments. It does not +construct a periodic spectral law, a Gaussian field, or a Palm conditioning. +Second/fourth/sixth integrability and positive atom masses remain explicit. +-/ + +noncomputable section +namespace D2MomentBridge + +open MeasureTheory ResearchFormalCoreR1 +set_option autoImplicit false + +variable {Ω : Type*} [MeasurableSpace Ω] + +def moment (μ : Measure Ω) (X : Ω → ℝ) (n : ℕ) : ℝ := ∫ w, X w ^ n ∂μ + +def cubicResidual (c x : ℝ) : ℝ := x ^ 3 - c * x + +theorem residual_sq_expand (c x : ℝ) : + cubicResidual c x ^ 2 = x ^ 6 - (2 * c) * x ^ 4 + c ^ 2 * x ^ 2 := by + unfold cubicResidual + ring + +theorem residual_sq_integrable (μ : Measure Ω) (X : Ω → ℝ) (c : ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) : + Integrable (fun w => cubicResidual c (X w) ^ 2) μ := by + simp_rw [residual_sq_expand] + exact (h6.sub (h4.const_mul (2 * c))).add (h2.const_mul (c ^ 2)) + +/-- The exact residual identity; integrability prevents Bochner totalization. -/ +theorem residual_integral_eq_delta (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (hm2 : moment μ X 2 ≠ 0) : + (∫ w, cubicResidual (moment μ X 4 / moment μ X 2) (X w) ^ 2 ∂μ) = + d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) := by + simp_rw [residual_sq_expand] + have hs : Integrable + (fun w => X w ^ 6 - (2 * (moment μ X 4 / moment μ X 2)) * X w ^ 4) μ := + h6.sub (h4.const_mul (2 * (moment μ X 4 / moment μ X 2))) + have hl : Integrable + (fun w => (moment μ X 4 / moment μ X 2) ^ 2 * X w ^ 2) μ := + h2.const_mul ((moment μ X 4 / moment μ X 2) ^ 2) + rw [integral_add hs hl, + integral_sub h6 (h4.const_mul (2 * (moment μ X 4 / moment μ X 2))), + integral_const_mul, integral_const_mul] + change moment μ X 6 - (2 * (moment μ X 4 / moment μ X 2)) * moment μ X 4 + + (moment μ X 4 / moment μ X 2) ^ 2 * moment μ X 2 = + d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) + unfold d2Delta + field_simp [hm2] + ring + +theorem delta_nonneg (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (hm2 : moment μ X 2 ≠ 0) : + 0 ≤ d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) := by + rw [← residual_integral_eq_delta μ X h2 h4 h6 hm2] + exact integral_nonneg (fun w => sq_nonneg _) + +theorem delta_eq_zero_iff_residual (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (hm2 : moment μ X 2 ≠ 0) : + d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) = 0 ↔ + ∀ᵐ w ∂μ, cubicResidual (moment μ X 4 / moment μ X 2) (X w) = 0 := by + rw [← residual_integral_eq_delta μ X h2 h4 h6 hm2] + have hz := integral_eq_zero_iff_of_nonneg_ae + (Filter.Eventually.of_forall (fun w => sq_nonneg + (cubicResidual (moment μ X 4 / moment μ X 2) (X w)))) + (residual_sq_integrable μ X _ h2 h4 h6) + constructor + · intro h + filter_upwards [hz.mp h] with w hw + exact sq_eq_zero_iff.mp hw + · intro h + apply hz.mpr + filter_upwards [h] with w hw + change cubicResidual (moment μ X 4 / moment μ X 2) (X w) ^ 2 = 0 + exact sq_eq_zero_iff.mpr hw + +theorem cubicResidual_eq_zero_iff (c x : ℝ) : + cubicResidual c x = 0 ↔ x = 0 ∨ x ^ 2 = c := by + have h : cubicResidual c x = x * (x ^ 2 - c) := by + unfold cubicResidual + ring + rw [h, mul_eq_zero, sub_eq_zero] + +/-- Zero may carry positive mass: the nonzero support, not all |X|, has one radius. -/ +theorem delta_eq_zero_iff_support (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (hm2 : moment μ X 2 ≠ 0) : + d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) = 0 ↔ + ∀ᵐ w ∂μ, X w = 0 ∨ X w ^ 2 = moment μ X 4 / moment μ X 2 := by + rw [delta_eq_zero_iff_residual μ X h2 h4 h6 hm2] + simp_rw [cubicResidual_eq_zero_iff] + +theorem delta_pos_iff_not_support (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (hm2 : moment μ X 2 ≠ 0) : + 0 < d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) ↔ + ¬ (∀ᵐ w ∂μ, X w = 0 ∨ X w ^ 2 = moment μ X 4 / moment μ X 2) := by + have hn := delta_nonneg μ X h2 h4 h6 hm2 + have he := delta_eq_zero_iff_support μ X h2 h4 h6 hm2 + constructor + · intro hp hs + exact (ne_of_gt hp) (he.mpr hs) + · intro hs + by_contra hp + exact hs (he.mp (le_antisymm (le_of_not_gt hp) hn)) + +/-- Positive mass turns an a.e. value property into a property of that atom. -/ +theorem property_of_ae_of_atom (μ : Measure Ω) (X : Ω → ℝ) (p : ℝ → Prop) + (h : ∀ᵐ w ∂μ, p (X w)) (a : ℝ) (ha : μ {w | X w = a} ≠ 0) : p a := by + by_contra hp + apply ha + have hz : μ {w | ¬ p (X w)} = 0 := ae_iff.mp h + refine measure_mono_null ?_ hz + intro w hw + change X w = a at hw + change ¬ p (X w) + simpa only [hw] using hp + +theorem moment_two_pos_of_atom (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (a : ℝ) (ha0 : a ≠ 0) (ha : μ {w | X w = a} ≠ 0) : 0 < moment μ X 2 := by + have hn : 0 ≤ moment μ X 2 := integral_nonneg (fun w => sq_nonneg _) + by_contra hp + have he : moment μ X 2 = 0 := le_antisymm (le_of_not_gt hp) hn + have hz := (integral_eq_zero_iff_of_nonneg_ae + (Filter.Eventually.of_forall (fun w => sq_nonneg (X w))) h2).mp he + have hz' : ∀ᵐ w ∂μ, X w ^ 2 = 0 := hz + have ha2 := property_of_ae_of_atom μ X (fun x => x ^ 2 = 0) hz' a ha + exact ha0 (sq_eq_zero_iff.mp ha2) + +theorem delta_pos_of_two_atoms (μ : Measure Ω) (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (a b : ℝ) (ha0 : a ≠ 0) (hb0 : b ≠ 0) (hab : a ^ 2 ≠ b ^ 2) + (ha : μ {w | X w = a} ≠ 0) (hb : μ {w | X w = b} ≠ 0) : + 0 < d2Delta (moment μ X 2) (moment μ X 4) (moment μ X 6) := by + have hm2 := moment_two_pos_of_atom μ X h2 a ha0 ha + apply (delta_pos_iff_not_support μ X h2 h4 h6 (ne_of_gt hm2)).mpr + intro hs + have hsa := property_of_ae_of_atom μ X + (fun x => x = 0 ∨ x ^ 2 = moment μ X 4 / moment μ X 2) hs a ha + have hsb := property_of_ae_of_atom μ X + (fun x => x = 0 ∨ x ^ 2 = moment μ X 4 / moment μ X 2) hs b hb + exact hab ((hsa.resolve_left ha0).trans (hsb.resolve_left hb0).symm) + +theorem square_gap_integrable (μ : Measure Ω) [IsProbabilityMeasure μ] (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) : + Integrable (fun w => (X w ^ 2 - moment μ X 2) ^ 2) μ := by + have hf : (fun w => (X w ^ 2 - moment μ X 2) ^ 2) = + (fun w => X w ^ 4 - (2 * moment μ X 2) * X w ^ 2 + (moment μ X 2) ^ 2) := by + funext w + ring + rw [hf] + exact (h4.sub (h2.const_mul _)).add (integrable_const _) + +/-- Probability normalization is essential for the unscaled m4-m2^2 gap. -/ +theorem square_gap_integral (μ : Measure Ω) [IsProbabilityMeasure μ] (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) : + (∫ w, (X w ^ 2 - moment μ X 2) ^ 2 ∂μ) = moment μ X 4 - (moment μ X 2) ^ 2 := by + have hf : (fun w => (X w ^ 2 - moment μ X 2) ^ 2) = + (fun w => X w ^ 4 - (2 * moment μ X 2) * X w ^ 2 + (moment μ X 2) ^ 2) := by + funext w + ring + have hs : Integrable + (fun w => X w ^ 4 - (2 * moment μ X 2) * X w ^ 2) μ := + h4.sub (h2.const_mul (2 * moment μ X 2)) + have hc : Integrable (fun _ : Ω => (moment μ X 2) ^ 2) μ := integrable_const _ + rw [hf, integral_add hs hc, + integral_sub h4 (h2.const_mul (2 * moment μ X 2)), integral_const_mul] + simp only [integral_const, probReal_univ, one_smul] + change moment μ X 4 - (2 * moment μ X 2) * moment μ X 2 + (moment μ X 2) ^ 2 = _ + ring + +theorem fourth_gt_second_sq_of_two_atoms (μ : Measure Ω) [IsProbabilityMeasure μ] + (X : Ω → ℝ) (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (a b : ℝ) (hab : a ^ 2 ≠ b ^ 2) + (ha : μ {w | X w = a} ≠ 0) (hb : μ {w | X w = b} ≠ 0) : + (moment μ X 2) ^ 2 < moment μ X 4 := by + have hn : 0 ≤ moment μ X 4 - (moment μ X 2) ^ 2 := by + rw [← square_gap_integral μ X h2 h4] + exact integral_nonneg (fun w => sq_nonneg _) + by_contra hp + have he : moment μ X 4 - (moment μ X 2) ^ 2 = 0 := by linarith + rw [← square_gap_integral μ X h2 h4] at he + have hz := (integral_eq_zero_iff_of_nonneg_ae + (Filter.Eventually.of_forall (fun w => sq_nonneg (X w ^ 2 - moment μ X 2))) + (square_gap_integrable μ X h2 h4)).mp he + have hs : ∀ᵐ w ∂μ, X w ^ 2 = moment μ X 2 := by + filter_upwards [hz] with w hw + exact sub_eq_zero.mp (sq_eq_zero_iff.mp hw) + exact hab ((property_of_ae_of_atom μ X (fun x => x ^ 2 = moment μ X 2) hs a ha).trans + (property_of_ae_of_atom μ X (fun x => x ^ 2 = moment μ X 2) hs b hb).symm) + +/-- The actual-law sufficient assumptions now supply all strict moment premises. -/ +theorem tau_pos_of_two_atoms (μ : Measure Ω) [IsProbabilityMeasure μ] (X : Ω → ℝ) + (h2 : Integrable (fun w => X w ^ 2) μ) + (h4 : Integrable (fun w => X w ^ 4) μ) + (h6 : Integrable (fun w => X w ^ 6) μ) + (a b q : ℝ) (ha0 : a ≠ 0) (hb0 : b ≠ 0) (hab : a ^ 2 ≠ b ^ 2) + (ha : μ {w | X w = a} ≠ 0) (hb : μ {w | X w = b} ≠ 0) + (hq0 : 0 ≤ q) (hq1 : q ≤ 1 / 4) : + 0 < d2Tau (moment μ X 2) (moment μ X 4) (moment μ X 6) q := + d2_tau_pos _ _ _ q (moment_two_pos_of_atom μ X h2 a ha0 ha) + (fourth_gt_second_sq_of_two_atoms μ X h2 h4 a b hab ha hb) + (delta_pos_of_two_atoms μ X h2 h4 h6 a b ha0 hb0 hab ha hb) hq0 hq1 + +/-- Moments of the zero/+-1 countermodel; the actual finite law is tested separately. -/ +theorem zero_atom_counterexample : + (1 / 2 : ℝ) - (1 / 2) ^ 2 = 1 / 4 ∧ d2Delta (1 / 2) (1 / 2) (1 / 2) = 0 := by + norm_num [d2Delta] + +end D2MomentBridge diff --git a/companions/d2_moment_bridge_20261006/README.md b/companions/d2_moment_bridge_20261006/README.md new file mode 100644 index 000000000..63b6282a5 --- /dev/null +++ b/companions/d2_moment_bridge_20261006/README.md @@ -0,0 +1,127 @@ +# D2 actual-law moment bridge + +Author: OpenAI / GPT-6 Astra Pro, `d2-moment-law-bridge-20261006`. +Dylan Roy — delegated AI work. Scientific effect **NONE**; organizational +independence credit **0**. This is an author-side candidate until actual execution +and review records establish their distinct scopes. No author self-merge. + +## Bound sources and purpose + +Base: `2f8b6f372be383d752e9dd30d38234faa977243c`, the actual #309 landing. +The complete unchanged primary `formal/` tree is +`d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14`; primary manifest SHA256 +`5d7ccdb0885af7bf4a2aa6ec4dce5f5c41435bb10a0a7a426a8af286d4f035e4`. +`ResearchFormalCoreR1.D2Schur` is the consumed scalar companion, blob +`b95460c0d263a32ea274b347079cca6aaab3d2e9`. +The source note is #302 `reviews/side24_d2_certified_small_L_claude_20261005/NOTE.md`, +blob `852f7403a8a06a1ef061e363df9502ae16f7a341`. Its section4 and C7 record +certified positive minima and the existing Gram floors at the listed periods. +This packet neither replaces those results nor supplies another numerical bound. + +Motivation: review correction AUD-309-REVIEW-STRICTNESS-01 (#309/6006934456; +reviewer correction in6006807347). Strict Jensen for X^2 does not imply strict +Cauchy--Schwarz for X and X^3: P(0)=1/2, P(+-1)=1/4 has m4-m2^2=1/4 but Delta=0. +The old Lean statement already assumes Delta>0 separately and remains unchanged. + +## What the new actual-law statements say + +`moment mu X n` is the **actual Bochner integral** of X^n, not an arbitrary +real named a moment. `cubicResidual c x = x^3-c*x`. Integrability of X^2,X^4,X^6 +is explicit where used. No independence, symmetry or Gaussian assumption is +required. No measurability assumption is silently substituted for integrability. + +For any measure, with these three integrability premises and m2!=0: + + integral (X^3-(m4/m2)X)^2 = Delta = m6-m4^2/m2 >= 0. + Delta=0 iff almost everywhere [X=0 or X^2=m4/m2]. + +The zero atom is deliberately permitted. This is an a.e. value-set description, +not a statement about topological support or a necessary two-atom condition. +Any positive-mass atom inherits an a.e. value property. Hence two positive-mass +nonzero atoms a,b with a^2!=b^2 suffice for m2>0 and Delta>0. The distinction is +**squared radii**, not just a!=b; a and -a do not suffice. + +For a **probability** measure, the actual square-gap identity additionally gives +m4-m2^2 = integral (X^2-m2)^2. Two positive-mass atoms of different squared radii +make this gap strict. The final theorem supplies all three strict moment premises +to the unchanged `d2_tau_pos` on the closed q interval [0,1/4]. Probability mass +one is essential for this unscaled gap identity; it is not needed for the cubic +residual identity or its equality classification. + +## Declaration map: 16 theorems, 2 definitions + +| Theorem | Explicit scope | +|---|---| +| residual_sq_expand | Polynomial identity for arbitrary real c,x. | +| residual_sq_integrable | Powers2/4/6 integrable imply residual square integrable. | +| residual_integral_eq_delta | Actual integral identity, m2!=0. | +| delta_nonneg | Nonnegative actual residual variance, same hypotheses. | +| delta_eq_zero_iff_residual | Exact a.e. residual-zero characterization. | +| cubicResidual_eq_zero_iff | Pointwise zero or squared-radius factorization. | +| delta_eq_zero_iff_support | Exact a.e. zero-plus-one-radius characterization. | +| delta_pos_iff_not_support | Strictness iff that a.e. condition fails. | +| property_of_ae_of_atom | Atom mass nonzero transfers any a.e. value property. | +| moment_two_pos_of_atom | Integrable second power and a nonzero positive-mass atom. | +| delta_pos_of_two_atoms | Three integrabilities; two nonzero, distinct squared radii. | +| square_gap_integrable | Probability normalization; powers2/4 integrable. | +| square_gap_integral | Exact unscaled fourth-minus-second-square identity. | +| fourth_gt_second_sq_of_two_atoms | Probability law, two distinct squared radii. | +| tau_pos_of_two_atoms | Actual moment premises feed the existing scalar theorem. | +| zero_atom_counterexample | Exact scalar moments of the tested three-point law. | + +The last theorem is a scalar control, not a Lean construction of that finite +measure. The Python tests instantiate the finite law separately. There are 18 +explicit axiom/type targets, not18 new theorems and not a new combined primary +manifest. No existing theorem or gate is edited. + +## Execution and review contract + +Run from a complete checkout with the pinned primary toolchain installed: + + bash companions/d2_moment_bridge_20261006/replay.sh + +The new read-only workflow uses the existing Lean/action pins. It executes both +Python test modes, the unchanged63-target primary gate, fresh compilation of this +module with warnings-as-errors, positive examples, all18 transitive axiom reports, +all18 elaborated types, a fresh leanchecker call, and two intended False-goal +negative controls. `check.py` imports the **hash-authenticated existing** primary +axiom parser; it does not replace RF-GATE-01/PR312 work. Exact names and bytes of +this small companion must still receive a real source review. A target inventory +or lexical test is not a general Lean parser or a proof of semantic equivalence. + +The source check binds the whole primary tree and every companion/workflow byte +to actual Git HEAD, including its own manifest. Before/after records must agree. +A changed primary tree is a new integration/review scope, not automatically +accepted because the same theorem names remain. Original run/attempt, output, +exit codes, source identities and primary receipt are retained. Two negative +controls must fail specifically with an unsolved False goal at their expected +source file and exit1; crashes, extra errors and exit2 do not qualify. Normal +replay failures remain failures. The evidence directory must be new. + +The local test suite checks finite exact laws, omitted-hypothesis countermodels, +source inventory and diagnostic handling. Local Python is not a Lean run. Hosted +build/axiom/recheck evidence, nonauthor mathematical review, full independent +alignment and scientific acceptance are separate predicates. No uniform spectral +floor, concrete periodic probability law, moment summability for that law, +trigonometric q map, Gaussian/Palm identification, interval quadrature, numerical +coefficient or persistence/cap theorem is proved by this packet. + +## Initial failure and author repair + +The original dedicated run37399665489 failed in the new Lean module at two +integral-linearity rewrites: implicit scalar metavariables were not inferred +through the pointwise function operations. Its unchanged63-target core replay +passed. The successor names the two exact integrable summands and explicit +scalar multipliers; no theorem statement, hypothesis or warning policy changes. +Separately, a new real-shell regression exposed that piping the final receipt +producer through tee into its own hashed directory would record a still-changing +output. The successor removes that tee. The failing original artifact and +separate red/green shell test are retained; the hosted failure did not reach the +final receipt step. Ten local test methods now cover this additional regression. +A successor kernel pass is not claimed by this historical explanation. + +The next hosted run37400492648 reached one remaining probability-normalization +lemma-name error. The pinned mathlib Probability.lean exposes `probReal_univ`; +that name replaces the unavailable shorthand without changing the proof target. +The correction reference above points to the actual updated review6006807347; +the initial auxiliary acknowledgment identifier was not retrievable. diff --git a/companions/d2_moment_bridge_20261006/SOURCE_FILES.json b/companions/d2_moment_bridge_20261006/SOURCE_FILES.json new file mode 100644 index 000000000..01f86fc86 --- /dev/null +++ b/companions/d2_moment_bridge_20261006/SOURCE_FILES.json @@ -0,0 +1,60 @@ +{ + "core_tree": "d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14", + "definitions": [ + "moment", + "cubicResidual" + ], + "files": { + ".github/workflows/d2-moment-bridge.yml": { + "bytes": 1625, + "git_blob": "6bcf23d82faebcd47c2ac85289c9929e3cc3eb63", + "sha256": "9edb37a63294bc442d6575aa5fc7f35f6ec391224d78f3a55fadd852743916e2" + }, + "companions/d2_moment_bridge_20261006/D2MomentBridge.lean": { + "bytes": 10696, + "git_blob": "b3184107e290189b91e3e18fd2aa1cb631bb9bde", + "sha256": "cde3bbd96eb29eb9ab7ff1448ffab1f794fb2b80355ac618800155eea6ccc42f" + }, + "companions/d2_moment_bridge_20261006/README.md": { + "bytes": 7648, + "git_blob": "63b6282a520fc5271dabf146713ec0e07c7c4e07", + "sha256": "3414d6745702501b8dc34ac3b4f9c55d282341775000ac553bca03c137901531" + }, + "companions/d2_moment_bridge_20261006/check.py": { + "bytes": 8037, + "git_blob": "812d02625a6829652d2482832ee03c20e36dcca4", + "sha256": "57de5071189ae73cfb1099898fbab22ef5b1a80e8cf41c760a666760817db1f1" + }, + "companions/d2_moment_bridge_20261006/replay.sh": { + "bytes": 2195, + "git_blob": "85c0de87f883386a8a36f5db79c51391313f09c9", + "sha256": "9df04dab884e78d8404334724dc62bf4f3e4c44248cbd5968225885af388f303" + }, + "companions/d2_moment_bridge_20261006/test_bridge.py": { + "bytes": 7607, + "git_blob": "d9cdef8effe3de4748611f46d358d6d64fd8deff", + "sha256": "260aef9a9fd0ae4351d60fe19e5b29dae808fa394a78a3385fb5b7e1f3a46653" + } + }, + "schema": 1, + "scientific_effect": "NONE", + "source_commit": "2f8b6f372be383d752e9dd30d38234faa977243c", + "theorems": [ + "residual_sq_expand", + "residual_sq_integrable", + "residual_integral_eq_delta", + "delta_nonneg", + "delta_eq_zero_iff_residual", + "cubicResidual_eq_zero_iff", + "delta_eq_zero_iff_support", + "delta_pos_iff_not_support", + "property_of_ae_of_atom", + "moment_two_pos_of_atom", + "delta_pos_of_two_atoms", + "square_gap_integrable", + "square_gap_integral", + "fourth_gt_second_sq_of_two_atoms", + "tau_pos_of_two_atoms", + "zero_atom_counterexample" + ] +} diff --git a/companions/d2_moment_bridge_20261006/check.py b/companions/d2_moment_bridge_20261006/check.py new file mode 100644 index 000000000..812d02625 --- /dev/null +++ b/companions/d2_moment_bridge_20261006/check.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 +"""Source-bound companion evidence, not an acceptance engine or a general Lean parser.""" +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import subprocess + +SIDE=Path(__file__).resolve().parent +ROOT=SIDE.parents[1] +PACKAGE='companions/d2_moment_bridge_20261006' +WORKFLOW='.github/workflows/d2-moment-bridge.yml' +CORE_TREE='d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14' +CORE_MANIFEST='5d7ccdb0885af7bf4a2aa6ec4dce5f5c41435bb10a0a7a426a8af286d4f035e4' +CORE_GATE='958b149ea3a4ce735644a2079f817b5deddf5dc0d5ca347904ad09db6ad47d68' +REPO='d6g8k5htny-coder/Math-' +CONTROLS=('RejectZeroAtom','RejectSameRadius') + + +def require(condition,message): + if not condition:raise ValueError(message) + + +def sha(raw):return hashlib.sha256(raw).hexdigest() + +def blob(raw):return hashlib.sha1(b'blob %d\0'%len(raw)+raw).hexdigest() + +def strict(raw): + def pairs(items): + result={} + for k,v in items: + require(k not in result,'duplicate JSON key') + result[k]=v + return result + def nonfinite(_):raise ValueError('nonfinite JSON') + return json.loads(raw,object_pairs_hook=pairs,parse_constant=nonfinite) + + +def git(*args): + return subprocess.run(['git',*args],cwd=ROOT,check=True,capture_output=True,text=True).stdout.strip() + + +def metadata():return strict((SIDE/'SOURCE_FILES.json').read_bytes()) + +def names(meta): + result=['D2MomentBridge.'+n for n in meta['definitions']+meta['theorems']] + require(result and len(result)==len(set(result)),'duplicate/empty declaration list') + require(all(re.fullmatch(r'D2MomentBridge\.[A-Za-z][A-Za-z0-9_]*',n) for n in result),'invalid declaration') + return result + + +def source(): + meta=metadata();head=git('rev-parse','HEAD') + require(re.fullmatch(r'[0-9a-f]{40}',head),'invalid HEAD') + require(meta['core_tree']==CORE_TREE and meta['scientific_effect']=='NONE','source scope') + require(git('rev-parse',head+':formal')==CORE_TREE,'core tree changed; new source review required') + require(sha((ROOT/'formal/manifest.json').read_bytes())==CORE_MANIFEST,'core manifest changed') + require(sha((ROOT/'formal/gate.py').read_bytes())==CORE_GATE,'core verifier changed') + if os.environ.get('GITHUB_ACTIONS')=='true': + require(os.environ.get('GITHUB_SHA')==head and os.environ.get('GITHUB_REPOSITORY')==REPO,'host/source mismatch') + require(os.environ.get('GITHUB_RUN_ID') and os.environ.get('GITHUB_RUN_ATTEMPT'),'run identity absent') + expected=set(meta['files'])|{PACKAGE+'/SOURCE_FILES.json'} + actual=set(git('ls-tree','-r','--name-only',head,'--',PACKAGE).splitlines())|{WORKFLOW} + require(actual==expected,'tracked companion membership') + ids={} + for path in sorted(expected): + require(path.startswith(PACKAGE+'/') or path==WORKFLOW,'unexpected source path') + p=ROOT/path + require(not any((ROOT.joinpath(*Path(path).parts[:i])).is_symlink() for i in range(1,len(Path(path).parts)+1)),'symlink source') + raw=p.read_bytes();bid=blob(raw) + require(git('rev-parse',head+':'+path)==bid,'dirty execution/source bytes: '+path) + if path in meta['files']: + require(meta['files'][path]=={'bytes':len(raw),'sha256':sha(raw),'git_blob':bid},'manifest source mismatch: '+path) + ids[path]={'sha256':sha(raw),'git_blob':bid,'bytes':len(raw)} + git('diff','--exit-code','HEAD','--','formal',PACKAGE,WORKFLOW) + return {'checked_commit':head,'repository':REPO,'run_id':os.environ.get('GITHUB_RUN_ID','local'), + 'run_attempt':os.environ.get('GITHUB_RUN_ATTEMPT','local'),'core_tree':CORE_TREE, + 'sources':ids,'declarations':names(meta),'scientific_effect':'NONE'} + + +def core_gate(): + path=ROOT/'formal/gate.py' + require(sha(path.read_bytes())==CORE_GATE,'core verifier changed') + spec=importlib.util.spec_from_file_location('bound_core_gate',path) + module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + return module + + +def types(text,targets): + require('error:' not in text and 'warning:' not in text,'type diagnostic') + matches=list(re.finditer(r'^D2MomentBridge\.[A-Za-z][A-Za-z0-9_]*',text,re.M)) + actual=[m.group() for m in matches] + require(actual==targets and len(set(actual))==len(actual),'type inventory mismatch') + require(not text[:matches[0].start()].strip(),'unrecognized type preamble') + return actual + + +def negative(text,control,status): + require(control in CONTROLS,'unknown negative control') + require(type(status) is int and status==1,'negative exit must be exactly one') + pattern=r'(?:[^\r\n]*[/\\])?'+control+r'\.lean:[0-9]+:[0-9]+: error: unsolved goals\s*\n⊢ False\s*' + require(re.fullmatch(pattern,text) is not None,'not the intended False-goal diagnostic') + return control + + +def emit(out): + target=names(metadata()) + (out/'Audit.lean').write_text('import D2MomentBridge\n'+'\n'.join('#print axioms '+n for n in target)+'\n') + (out/'Types.lean').write_text('import D2MomentBridge\nset_option pp.explicit true\n'+'\n'.join('#check '+n for n in target)+'\n') + (out/'Positive.lean').write_text('''import D2MomentBridge +open D2MomentBridge ResearchFormalCoreR1 +example (c x : ℝ) : cubicResidual c x = 0 ↔ x = 0 ∨ x ^ 2 = c := + cubicResidual_eq_zero_iff c x +example : cubicResidual 1 (0 : ℝ) = 0 := by norm_num [cubicResidual] +example : cubicResidual 1 (2 : ℝ) ≠ 0 := by norm_num [cubicResidual] +example : d2Delta (1 / 2) (1 / 2) (1 / 2) = 0 := zero_atom_counterexample.2 +''') + for name,statement in [ + ('RejectZeroAtom','(1 / 2 : ℝ) ^ 2 < 1 / 2 → 0 < d2Delta (1 / 2) (1 / 2) (1 / 2)'), + ('RejectSameRadius','0 < d2Delta (1 : ℝ) 1 1')]: + (out/(name+'.lean')).write_text('import D2MomentBridge\nopen ResearchFormalCoreR1\nexample : '+statement+' := by\n norm_num [d2Delta]\n') + + +def finish(out): + initial=strict((out/'source.json').read_bytes());current=source() + require(initial==current,'source changed across execution') + target=names(metadata()) + ax=core_gate().audit_axioms((out/'axioms.log').read_text(),target) + types((out/'types.log').read_text(),target) + for control in CONTROLS: + status=int((out/(control+'.status')).read_text()) + negative((out/(control+'.log')).read_text(),control,status) + for label in ('build','positive','axioms','types','leanchecker'): + require((out/(label+'.status')).read_text()=='0\n','missing successful process: '+label) + core=ROOT/'formal/.lake/formal-evidence/receipt.json' + raw=core.read_bytes();receipt=strict(raw) + require(receipt['checked_commit']==current['checked_commit'],'core executed different source') + require(receipt['manifest_sha256']==CORE_MANIFEST,'core receipt manifest') + require(receipt['formalization_status']=='kernel-checked','no core kernel receipt') + result={**current,'axioms':ax,'theorem_count':len(metadata()['theorems']), + 'definition_count':len(metadata()['definitions']),'core_receipt_sha256':sha(raw), + 'formalization_status':'kernel-checked','alignment_status':'PENDING_INDEPENDENT_REVIEW', + 'scientific_acceptance':False,'log_sha256':{p.name:sha(p.read_bytes()) for p in sorted(out.iterdir()) if p.is_file()}} + (out/'receipt.json').write_text(json.dumps(result,indent=2,sort_keys=True)+'\n') + return result + + +def main(): + ap=argparse.ArgumentParser(description=__doc__) + ap.add_argument('command',choices=('source','emit','finish','negative')) + ap.add_argument('path',type=Path,nargs='?') + ap.add_argument('--control',choices=CONTROLS) + ap.add_argument('--status',type=int) + args=ap.parse_args() + if args.command=='source':result=source() + elif args.command=='emit':emit(args.path);result={'emitted':True} + elif args.command=='finish':result=finish(args.path) + else:result={'negative':negative(args.path.read_text(),args.control,args.status)} + print(json.dumps(result,sort_keys=True,indent=2)) + + +if __name__=='__main__':main() diff --git a/companions/d2_moment_bridge_20261006/replay.sh b/companions/d2_moment_bridge_20261006/replay.sh new file mode 100644 index 000000000..85c0de87f --- /dev/null +++ b/companions/d2_moment_bridge_20261006/replay.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +SIDE="$ROOT/companions/d2_moment_bridge_20261006" +OUT="$ROOT/.lake/d2-moment-evidence" +cd "$ROOT" +test ! -e "$OUT" +mkdir -p "$OUT" +python3 -B -S "$SIDE/check.py" source | tee "$OUT/source.json" +python3 -B -S "$SIDE/test_bridge.py" 2>&1 | tee "$OUT/tests.log" +python3 -B -O -S "$SIDE/test_bridge.py" 2>&1 | tee "$OUT/tests-optimized.log" +python3 -B -S -m unittest discover -s formal/tests -v 2>&1 | tee "$OUT/core-tests.log" +python3 -B -O -S -m unittest discover -s formal/tests -v 2>&1 | tee "$OUT/core-tests-optimized.log" +python3 -B -S formal/gate.py --execute 2>&1 | tee "$OUT/core-execute.log" +python3 -B -S "$SIDE/check.py" emit "$OUT" +export MOMENT_SIDE="$SIDE" MOMENT_OUT="$OUT" +cd "$ROOT/formal" +lake env bash <<'INNER' +set -euo pipefail +export LEAN_PATH="$MOMENT_SIDE:${LEAN_PATH:-}" +export LEAN_SRC_PATH="$MOMENT_SIDE:${LEAN_SRC_PATH:-}" +lean --version | tee "$MOMENT_OUT/toolchain.log" +run_lean() { + local label="$1"; shift + local code=0 + "$@" >"$MOMENT_OUT/$label.log" 2>&1 || code=$? + printf '%s\n' "$code" >"$MOMENT_OUT/$label.status" + cat "$MOMENT_OUT/$label.log" + test "$code" -eq 0 +} +run_lean build lean -DwarningAsError=true --root="$MOMENT_SIDE" -o "$MOMENT_SIDE/D2MomentBridge.olean" "$MOMENT_SIDE/D2MomentBridge.lean" +run_lean positive lean -DwarningAsError=true --root="$MOMENT_OUT" "$MOMENT_OUT/Positive.lean" +run_lean axioms lean -DwarningAsError=true --root="$MOMENT_OUT" "$MOMENT_OUT/Audit.lean" +run_lean types lean -DwarningAsError=true --root="$MOMENT_OUT" "$MOMENT_OUT/Types.lean" +run_lean leanchecker leanchecker --fresh D2MomentBridge +for control in RejectZeroAtom RejectSameRadius; do + code=0 + lean -DwarningAsError=true --root="$MOMENT_OUT" "$MOMENT_OUT/$control.lean" >"$MOMENT_OUT/$control.log" 2>&1 || code=$? + printf '%s\n' "$code" >"$MOMENT_OUT/$control.status" + python3 -B -S "$MOMENT_SIDE/check.py" negative "$MOMENT_OUT/$control.log" --control "$control" --status "$code" +done +INNER +cd "$ROOT" +python3 -B -S "$SIDE/check.py" finish "$OUT" +echo 'PASS: actual-law D2 companion; concrete periodic law and scientific acceptance remain unproved here.' diff --git a/companions/d2_moment_bridge_20261006/test_bridge.py b/companions/d2_moment_bridge_20261006/test_bridge.py new file mode 100644 index 000000000..d9cdef8ef --- /dev/null +++ b/companions/d2_moment_bridge_20261006/test_bridge.py @@ -0,0 +1,151 @@ +"""Exact finite-law and protocol controls, not substitutes for arbitrary-law Lean proofs.""" +from fractions import Fraction as F +import importlib.util +import itertools +import json +from pathlib import Path +import re +import unittest +import subprocess +import tempfile +import hashlib +import os + +SIDE = Path(__file__).resolve().parent +THEOREMS = '''residual_sq_expand residual_sq_integrable residual_integral_eq_delta delta_nonneg delta_eq_zero_iff_residual cubicResidual_eq_zero_iff delta_eq_zero_iff_support delta_pos_iff_not_support property_of_ae_of_atom moment_two_pos_of_atom delta_pos_of_two_atoms square_gap_integrable square_gap_integral fourth_gt_second_sq_of_two_atoms tau_pos_of_two_atoms zero_atom_counterexample'''.split() +DEFINITIONS = ['moment', 'cubicResidual'] + + +def moments(law): + return [sum(p*x**k for x,p in law) for k in (2,4,6)] + + +def laws(): + # Zero plus two possible radii, including absent and equal-radius atoms. + for a,b,z,u,v in itertools.product((F(1,2),F(1),F(2)),(F(1),F(2),F(3)),range(3),range(3),range(3)): + if u+v == 0: + continue + total=z+u+v + yield [(F(0),F(z,total)),(a,F(u,2*total)),(-a,F(u,2*total)), + (b,F(v,2*total)),(-b,F(v,2*total))] + + +class BridgeTests(unittest.TestCase): + def test_source_exists_and_no_admission(self): + self.assertTrue((SIDE/'D2MomentBridge.lean').is_file(), 'new Lean module missing') + text=(SIDE/'D2MomentBridge.lean').read_text() + code=re.sub(r'/\-.*?\-/', '', text, flags=re.S) + for token in ('sorry','admit','axiom','unsafe','native_decide'): + self.assertIsNone(re.search(r'\b'+token+r'\b',code), token) + self.assertIn('import ResearchFormalCoreR1.D2Schur', text) + self.assertIn('Integrable (fun w => X w ^ 6) μ', text) + + def test_exact_declared_inventory(self): + self.assertTrue((SIDE/'SOURCE_FILES.json').is_file(), 'new inventory missing') + meta=json.loads((SIDE/'SOURCE_FILES.json').read_text()) + text=(SIDE/'D2MomentBridge.lean').read_text() + self.assertEqual(re.findall(r'^theorem (\w+)',text,re.M),THEOREMS) + self.assertEqual(re.findall(r'^(?:noncomputable )?def (\w+)',text,re.M),DEFINITIONS) + self.assertEqual(meta['theorems'],THEOREMS) + self.assertEqual(meta['definitions'],DEFINITIONS) + self.assertEqual(meta['scientific_effect'],'NONE') + self.assertEqual(meta['core_tree'],'d7422c6b1acbf3e20c75a1ed7fc13fc30125ec14') + + def test_residual_identity_and_exact_equality_class(self): + count=0 + for law in laws(): + m2,m4,m6=moments(law); c=m4/m2; delta=m6-m4*m4/m2 + residual=sum(p*(x**3-c*x)**2 for x,p in law) + self.assertEqual(delta,residual) + self.assertGreaterEqual(delta,0) + one_nonzero_radius=all(x==0 or x*x==c for x,p in law if p>0) + self.assertEqual(delta==0,one_nonzero_radius) + count+=1 + self.assertEqual(count,216) + + def test_two_nonzero_distinct_squared_atoms(self): + strict=0 + for law in laws(): + xs=[x for x,p in law if p>0 and x!=0] + if any(a*a!=b*b for a,b in itertools.combinations(xs,2)): + m2,m4,m6=moments(law) + self.assertGreater(m2,0) + self.assertGreater(m4,m2*m2) + self.assertGreater(m6-m4*m4/m2,0) + for q in (F(0),F(1,16),F(1,8),F(1,4)): + delta=m6-m4*m4/m2 + tau=(1-4*q)*delta+q*(delta+9*m2*(m4-m2*m2)) + self.assertGreater(tau,0) + strict+=1 + self.assertGreater(strict,0) + + def test_zero_atom_and_same_radius_countermodels(self): + law=[(F(0),F(1,2)),(F(1),F(1,4)),(F(-1),F(1,4))] + m2,m4,m6=moments(law) + self.assertGreater(m4,m2*m2) + self.assertEqual(m6-m4*m4/m2,0) + a,b=F(1),F(-1) + self.assertNotEqual(a,b) + self.assertEqual(a*a,b*b) + self.assertEqual(moments([(a,F(1,2)),(b,F(1,2))]),[1,1,1]) + + def test_fourth_gap_needs_probability_normalization(self): + # Mass2 is NOT probability: raw fourth gap can be negative. + m2,m4,_=moments([(F(1),F(2))]) + self.assertLess(m4-m2*m2,0) + for law in laws(): + m2,m4,_=moments(law) + self.assertEqual(sum(p*(x*x-m2)**2 for x,p in law),m4-m2*m2) + + def test_residual_factorization(self): + for x,c in itertools.product([F(i,3) for i in range(-9,10)], [F(i,4) for i in range(-8,9)]): + self.assertEqual((x**3-c*x)**2,x**6-2*c*x**4+c*c*x*x) + self.assertEqual(x**3-c*x==0,x==0 or x*x==c) + + def checker(self): + self.assertTrue((SIDE/'check.py').is_file(),'evidence checker missing') + spec=importlib.util.spec_from_file_location('moment_checker',SIDE/'check.py') + m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) + return m + + def test_negative_control_accepts_only_intended_false(self): + m=self.checker() + text='/tmp/evidence/RejectZeroAtom.lean:4:2: error: unsolved goals\n⊢ False\n' + self.assertEqual(m.negative(text,'RejectZeroAtom',1),'RejectZeroAtom') + for bad,status in [(text,0),(text,2),(text.replace('False','True'),1), + (text.replace('RejectZeroAtom','Other'),1), + (text+'error: unknown identifier\n',1), + ('Traceback: bad runtime\n',1),('error: unsolved goals\n',1)]: + with self.subTest(bad=bad,status=status), self.assertRaises(ValueError): + m.negative(bad,'RejectZeroAtom',status) + with self.assertRaises(ValueError):m.negative(text,'Unknown',1) + + def test_final_command_does_not_hash_a_live_tee_output(self): + # Execute the actual final shell invocation against a synthetic snapshot writer. + # A live tee destination must not change after the receipt hashes that directory. + command=next(line for line in (SIDE/'replay.sh').read_text().splitlines() + if 'check.py" finish' in line) + with tempfile.TemporaryDirectory() as tmp: + root=Path(tmp); out=root/'evidence'; out.mkdir() + (root/'check.py').write_text("import pathlib,json,hashlib,time,sys\n" + "out=pathlib.Path(sys.argv[-1]);time.sleep(0.05)\n" + "r={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in out.iterdir()}\n" + "(out/'receipt.json').write_text(json.dumps(r))\nprint('completed synthetic fixture')\n") + run=subprocess.run(['bash','-c','set -euo pipefail\n'+command], + capture_output=True,env={**os.environ,'SIDE':str(root),'OUT':str(out)}) + self.assertEqual(run.returncode,0,run.stderr) + recorded=json.loads((out/'receipt.json').read_text()) + for name,digest in recorded.items(): + self.assertEqual(hashlib.sha256((out/name).read_bytes()).hexdigest(),digest, + 'receipt hashed an output that was still being written') + + def test_type_inventory_missing_duplicate_unrecognized(self): + m=self.checker(); names=['D2MomentBridge.a','D2MomentBridge.b'] + self.assertEqual(m.types('D2MomentBridge.a : True\nD2MomentBridge.b : False\n',names),names) + for bad in ('D2MomentBridge.a : True\n','D2MomentBridge.a : True\nD2MomentBridge.a : True\n', + 'error: crash\nD2MomentBridge.a : True\nD2MomentBridge.b : False\n'): + with self.assertRaises(ValueError):m.types(bad,names) + + +if __name__=='__main__': + unittest.main(verbosity=2)