diff --git a/.github/workflows/c293-morse-finite.yml b/.github/workflows/c293-morse-finite.yml new file mode 100644 index 000000000..bfd6fa7b0 --- /dev/null +++ b/.github/workflows/c293-morse-finite.yml @@ -0,0 +1,71 @@ +name: C293 Morse finite critical (hosted Lean, no scientific promotion) +'on': + pull_request: + paths: + - 'frontiers/morse_finite_critical_20261018/**' + - 'tools/c293_hosted_verify.py' + - 'tests/test_c293_hosted_verify.py' + - '.github/workflows/c293-morse-finite.yml' + - 'formal/lean-toolchain' + - 'formal/lakefile.toml' + - 'formal/lake-manifest.json' + - 'specifications/lean_statements_20261010/Specifications/Lifetime.lean' + - 'companions/torus_filtration_20261011/TorusTopology.lean' + push: + branches: [main] + paths: + - 'frontiers/morse_finite_critical_20261018/**' + - 'tools/c293_hosted_verify.py' + - 'tests/test_c293_hosted_verify.py' + - '.github/workflows/c293-morse-finite.yml' + - 'formal/lean-toolchain' + - 'formal/lakefile.toml' + - 'formal/lake-manifest.json' + - 'specifications/lean_statements_20261010/Specifications/Lifetime.lean' + - 'companions/torus_filtration_20261011/TorusTopology.lean' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: c293-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} +jobs: + c293-hosted-formal: + name: c293-hosted-formal + runs-on: ubuntu-24.04 + timeout-minutes: 55 + env: + LEAN_NUM_THREADS: '2' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + fetch-depth: 1 + - name: Verify source identities and eight registration engineering tests + run: | + python3 -B -S tools/c293_hosted_verify.py source + python3 -B -S -m unittest discover -s tests -p test_c293_hosted_verify.py -v + python3 -B -O -S -m unittest discover -s tests -p test_c293_hosted_verify.py -v + - 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: Build five C293 objects, kernel replay, audit and missing-premise rejection + run: | + cd formal + lake env python3 -B -S ../tools/c293_hosted_verify.py execute + - name: Retain exact tested-run C293 outputs including failures + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: c293-hosted-${{ github.run_id }}-${{ github.run_attempt }} + path: .lake/c293-hosted-evidence/ + include-hidden-files: true + if-no-files-found: warn + retention-days: 90 diff --git a/docs/c293-hosted-formal-verification.md b/docs/c293-hosted-formal-verification.md new file mode 100644 index 000000000..8ed887774 --- /dev/null +++ b/docs/c293-hosted-formal-verification.md @@ -0,0 +1,37 @@ +# C293 hosted formal replay — engineering-only registration + +**Scientific effect: NONE.** This is source-bound, hosted Lean verification of C293's conditional finite-critical-class declaration; it is not acceptance of C292, elder pairing, or the persistence-lifetime law. + +## Ownership, source and current gates + +Source PR: https://github.com/d6g8k5htny-coder/Math-/pull/482 at exact head 0ea97aff489f9420632b4cee81ad82dbec5fe88e. The stacked CI branch is based on that head; it does not change source modules, source reviews, historical receipts, negative controls, or original evidence. + +The existing required math-downstream-gates invokes the original formal-lean.yml, which builds the independent formal/ target. Neither that required job nor the existing torus-filtration.yml companion executes this new C293 declaration. The latter's Claude companion ownership and the separate Sol/elder-registration work remain undisturbed. + +The addition is a dedicated C293 workflow named c293-morse-finite.yml. Its c293-hosted-formal job is **not a branch-protection-required context** and is not inserted into formal/gate.py or the required aggregate. Enforcing it as required should follow separately with current gate owners after hosted execution, capacity evidence, source review and readback. + +## Hosted invocation and pins + +The job uses Lean 4.34.1 and exactly the existing formal Lake project and its nine package pins, including Mathlib d13f23b723b8a846827a245b89c10fc7d3f11612. Python source checks compare all five C293 Lean modules to their published byte counts/SHA-256 values and require exact identity with the canonical Lifetime and TorusTopology upstream files. A mutated control, pin, source or upstream copy fails closed; normal and optimized test modes exercise the guard. + +To repeat after installing the formal Lake dependencies, execute from the repository root: + + python3 -B -S tools/c293_hosted_verify.py source + python3 -B -S -m unittest discover -s tests -p test_c293_hosted_verify.py -v + python3 -B -O -S -m unittest discover -s tests -p test_c293_hosted_verify.py -v + cd formal + lake env python3 -B -S ../tools/c293_hosted_verify.py execute + +The runner verifies tested GitHub commit, repository, run ID and attempt; Lean version; exact installed revisions and clean source; then compiles from new isolated outputs in the order Lifetime, TorusTopology, MorseFiniteCritical, MorseFiniteControls, MorseFiniteAxiomAudit. The three new modules use warnings-as-errors; all builds and the negative control use -j2 -M14000. + +**Memory deviation:** The original author receipts use -M4096. Anthropic/Claude's provider-distinct Linux replay, recorded in https://github.com/d6g8k5htny-coder/Math-/pull/482#issuecomment-6246988654 , needed -M14000 for six build/negative invocations. This workflow records the new limit without altering the original receipts. + +All five new .olean files must match the published object SHA-256 values. Three named-module leanchecker -v passes, the full 169-declaration (103/38/20/8) standard-only transitive axiom audit, and the exact intended missing-IsMorseDistinct rejection are mandatory. A nonzero result for an unrelated reason is not a pass. + +The 90-day workflow artifact contains phase stdout/stderr, digests and exact-run RESULT.json. Hosted standard named-module replay is **not** a hosted leanchecker --fresh of the entire import closure. External --fresh is a separate evidence record; neither implies institutional mathematical acceptance. + +## Source review and protected integration + +This change should receive review of its *CI verifier*, not substitute for the source author's C293 mathematical review. Inspect the new hosted c293-hosted-formal job and its real logs on the exact tested PR merge; do not reclassify old green checks. Keep this implementation stacked until C293 source PR #482 receives its own legitimate integration disposition. Do not automatically merge into the source author's draft branch, alter rulesets, waive reviewer independence or set a scientific status. Before any later merge, re-check ownership, base/head, source hashes, reviews, gates and the protected merge process. + +C293 does not close critical-level local path connectivity or path attainment, the full C292 adapter, almost-sure Morse, elder pairing, exhaustive once-counting, all-small-bars converse, regional collisions or stochastic lifetime transfer. diff --git a/tests/test_c293_hosted_verify.py b/tests/test_c293_hosted_verify.py new file mode 100644 index 000000000..8d0e822d9 --- /dev/null +++ b/tests/test_c293_hosted_verify.py @@ -0,0 +1,239 @@ +"""Fail-closed C293 hosted-registration tests; no Lean execution or theorem acceptance.""" +import importlib.util +from pathlib import Path +import shutil +import tempfile +import unittest + +REPO = Path(__file__).resolve().parents[1] +MODULE_PATH = REPO / "tools/c293_hosted_verify.py" +spec = importlib.util.spec_from_file_location("c293_hosted_verify", MODULE_PATH) +c293 = importlib.util.module_from_spec(spec) +spec.loader.exec_module(c293) + + +class C293HostedRegistrationTests(unittest.TestCase): + def test_actual_published_source_and_pin_crosswalk(self): + result = c293.verify_sources() + self.assertEqual(result["source_commit"], c293.SOURCE_COMMIT) + self.assertEqual(len(result["module_sha256"]), 5) + self.assertEqual(result["dependency_pins"]["mathlib"], c293.MATHLIB_PIN) + + def make_source_fixture(self): + temp = tempfile.TemporaryDirectory() + root = Path(temp.name) + src = Path("frontiers/morse_finite_critical_20261018") + for name in c293.SOURCES: + p = src / "final-project" / f"{name}.lean" + (root / p).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(REPO / p, root / p) + for p in [src / "negative-project/WithoutMorse.lean", + Path("formal/lakefile.toml"), Path("formal/lean-toolchain"), + Path("formal/lake-manifest.json")]: + (root / p).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(REPO / p, root / p) + for p in c293.UPSTREAM.values(): + (root / p).parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(REPO / p, root / p) + return temp, root + + def test_modified_theorem_source_rejected(self): + temp, root = self.make_source_fixture() + with temp: + p = root / "frontiers/morse_finite_critical_20261018/final-project/MorseFiniteCritical.lean" + p.write_bytes(p.read_bytes() + b"\n-- mutation\n") + with self.assertRaisesRegex(RuntimeError, "source identity mismatch"): + c293.verify_sources(root) + + def test_modified_upstream_copy_rejected(self): + temp, root = self.make_source_fixture() + with temp: + p = root / c293.UPSTREAM["TorusTopology"] + p.write_bytes(p.read_bytes() + b"\n-- changed upstream\n") + with self.assertRaisesRegex(RuntimeError, "upstream C293 input differs"): + c293.verify_sources(root) + + def test_missing_premise_control_mutation_rejected(self): + temp, root = self.make_source_fixture() + with temp: + p = root / "frontiers/morse_finite_critical_20261018/negative-project/WithoutMorse.lean" + p.write_bytes(p.read_bytes() + b"\n-- mutation\n") + with self.assertRaisesRegex(RuntimeError, "control modified"): + c293.verify_sources(root) + + def test_changed_dependency_pin_rejected(self): + temp, root = self.make_source_fixture() + with temp: + p = root / "formal/lean-toolchain" + p.write_text("leanprover/lean4:v4.35.0\n") + with self.assertRaisesRegex(RuntimeError, "toolchain pin changed"): + c293.verify_sources(root) + + def test_audit_requires_169_exact_reports(self): + preamble = "\n".join( + f"MORSE_AUDIT_MODULE {module} COUNT {count}" + for module, count in c293.MODULE_COUNTS.items() + ) + preamble += ("\nMORSE_AUDIT_STANDARD_ONLY_PASS COUNT 169\n" + "'TorusMorseFinite.quotientCriticalSet_finite' depends on axioms:" + " [propext, Classical.choice, Quot.sound]\n") + good = preamble + "MORSE_AUDIT_DECL name AXIOMS []\n" * 169 + c293.validate_audit(good) + with self.assertRaisesRegex(RuntimeError, "169 declaration reports"): + c293.validate_audit(preamble + "MORSE_AUDIT_DECL name AXIOMS []\n" * 168) + with self.assertRaisesRegex(RuntimeError, "standard-only"): + c293.validate_audit(good.replace("MORSE_AUDIT_STANDARD_ONLY_PASS", "INCOMPLETE")) + + def test_negative_requires_intended_failure_not_just_nonzero(self): + diagnostic = ("file:10:2: error: Type mismatch\n" + "quotientCriticalSet_finite d L hL g hs hp\n" + "has type IsMorseDistinct d L g → ...\n" + "but is expected to have type ...") + c293.validate_negative(1, diagnostic) + for code, output in ((0, diagnostic), (2, diagnostic), + (1, "error: unknown module MorseFiniteCritical"), + (1, diagnostic + "\nerror: unrelated")): + with self.subTest(code=code, output=output[:30]): + with self.assertRaises(RuntimeError): + c293.validate_negative(code, output) + + def test_symlink_source_rejected(self): + temp, root = self.make_source_fixture() + with temp: + p = root / "frontiers/morse_finite_critical_20261018/final-project/Lifetime.lean" + elsewhere = root / "lifetime-copy" + shutil.copyfile(p, elsewhere) + p.unlink() + p.symlink_to(elsewhere) + with self.assertRaisesRegex(RuntimeError, "symlink"): + c293.verify_sources(root) + + def test_same_size_source_mutation_rejected(self): + temp, root = self.make_source_fixture() + with temp: + p = root / "frontiers/morse_finite_critical_20261018/final-project/MorseFiniteControls.lean" + data = bytearray(p.read_bytes()) + data[-2] ^= 0x01 + p.write_bytes(bytes(data)) + with self.assertRaisesRegex(RuntimeError, "source identity mismatch"): + c293.verify_sources(root) + + def test_changed_lakefile_or_lock_pin_rejected(self): + for rel, old, new, message in ( + ("formal/lakefile.toml", c293.MATHLIB_PIN, "0" * 40, "Lake mathlib pin changed"), + ("formal/lake-manifest.json", c293.PACKAGE_PINS["batteries"], "0" * 40, + "dependency pins differ")): + temp, root = self.make_source_fixture() + with temp, self.subTest(path=rel): + p = root / rel + self.assertIn(old, p.read_text()) + p.write_text(p.read_text().replace(old, new)) + with self.assertRaisesRegex(RuntimeError, message): + c293.verify_sources(root) + + def test_out_of_tree_source_rejected(self): + temp, root = self.make_source_fixture() + with temp, tempfile.TemporaryDirectory() as other: + outside = Path(other) / "Lifetime.lean" + outside.write_text("-- outside\n") + with self.assertRaisesRegex(RuntimeError, "outside repository"): + c293.safe_source(outside, root) + + def audit_text(self, decls=169, counts=None, main=True): + counts = counts or c293.MODULE_COUNTS + text = "\n".join(f"MORSE_AUDIT_MODULE {m} COUNT {n}" for m, n in counts.items()) + text += "\nMORSE_AUDIT_STANDARD_ONLY_PASS COUNT 169\n" + if main: + text += ("'TorusMorseFinite.quotientCriticalSet_finite' depends on axioms:" + " [propext, Classical.choice, Quot.sound]\n") + return text + "MORSE_AUDIT_DECL name AXIOMS []\n" * decls + + def test_audit_rejects_wrong_census_extra_reports_and_missing_main_report(self): + c293.validate_audit(self.audit_text()) + wrong = dict(c293.MODULE_COUNTS, Lifetime=102) + for text, message in ((self.audit_text(counts=wrong), "audit missing Lifetime census"), + (self.audit_text(decls=170), "169 declaration reports"), + (self.audit_text(main=False), "main theorem axiom report absent")): + with self.subTest(message=message): + with self.assertRaisesRegex(RuntimeError, message): + c293.validate_audit(text) + + def test_negative_rejects_wrong_mismatch_and_unrelated_failure(self): + diagnostic = ("file:10:2: error: Type mismatch\n" + "quotientCriticalSet_finite d L hL g hs hp\n" + "has type IsMorseDistinct d L g → ...\n" + "but is expected to have type ...") + for output in ("file:10:2: error: Type mismatch\nsomething else entirely\n", + diagnostic + "\nINTERNAL PANIC: lean::memory_exception"): + with self.subTest(output=output[-40:]): + with self.assertRaisesRegex(RuntimeError, "negative control"): + c293.validate_negative(1, output) + + def test_hosted_context_requires_actual_run_identity(self): + names = ("GITHUB_SHA", "GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT", "GITHUB_REPOSITORY") + saved = {k: c293.os.environ.get(k) for k in names} + try: + try: + head = c293.git("rev-parse", "HEAD") + except (OSError, c293.subprocess.CalledProcessError): + self.skipTest("not a git checkout") + good = {"GITHUB_SHA": head, "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1", + "GITHUB_REPOSITORY": "d6g8k5htny-coder/Math-"} + c293.os.environ.update(good) + self.assertEqual(c293.verify_context()["github_sha"], head) + for key, value, message in (("GITHUB_REPOSITORY", "someone/Math-", "wrong execution repository"), + ("GITHUB_SHA", "0" * 40, "tested checkout mismatch"), + ("GITHUB_RUN_ID", "", "actual GitHub run identity")): + with self.subTest(key=key): + c293.os.environ.update(good) + c293.os.environ[key] = value + with self.assertRaisesRegex(RuntimeError, message): + c293.verify_context() + finally: + for k, v in saved.items(): + if v is None: + c293.os.environ.pop(k, None) + else: + c293.os.environ[k] = v + + def test_unexpected_success_of_negative_phase_rejected(self): + saved = c293.EVIDENCE + with tempfile.TemporaryDirectory() as t: + c293.EVIDENCE = Path(t) + try: + with self.assertRaisesRegex(RuntimeError, "unexpected exit: 0"): + c293.run_phase("negative-probe", [c293.sys.executable, "-c", "pass"], t, + dict(c293.os.environ), expected_success=False) + finally: + c293.EVIDENCE = saved + + def test_installed_dependency_commit_and_cleanliness_checked(self): + saved = (c293.FORMAL, c293.PACKAGE_PINS) + with tempfile.TemporaryDirectory() as t: + pkg = Path(t) / ".lake/packages/demo" + pkg.mkdir(parents=True) + run = lambda *a: c293.subprocess.run(["git", "-C", str(pkg), *a], check=True, + capture_output=True, text=True) + run("init", "-q") + (pkg / "f.txt").write_text("1\n") + run("add", "f.txt") + run("-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false", + "commit", "-q", "-m", "x") + head = c293.git("-C", str(pkg), "rev-parse", "HEAD") + c293.FORMAL = Path(t) + try: + c293.PACKAGE_PINS = {"demo": head} + self.assertEqual(c293.verify_packages(), {"demo": head}) + c293.PACKAGE_PINS = {"demo": "0" * 40} + with self.assertRaisesRegex(RuntimeError, "wrong installed dependency commit"): + c293.verify_packages() + c293.PACKAGE_PINS = {"demo": head} + (pkg / "f.txt").write_text("2\n") + with self.assertRaisesRegex(RuntimeError, "dirty installed dependency checkout"): + c293.verify_packages() + finally: + c293.FORMAL, c293.PACKAGE_PINS = saved + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/c293_hosted_verify.py b/tools/c293_hosted_verify.py new file mode 100644 index 000000000..42baa8bca --- /dev/null +++ b/tools/c293_hosted_verify.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""C293-only hosted Lean replay. Engineering evidence, not scientific acceptance. + +The source and historical execution receipts in PR #482 are immutable inputs. +Run in the pinned formal/ Lake environment (see the dedicated Actions workflow). +""" +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +PACKAGE = ROOT / "frontiers/morse_finite_critical_20261018" +FINAL = PACKAGE / "final-project" +NEGATIVE = PACKAGE / "negative-project/WithoutMorse.lean" +FORMAL = ROOT / "formal" +EVIDENCE = ROOT / ".lake/c293-hosted-evidence" +BUILD = ROOT / ".lake/c293-hosted-build" + +SOURCE_COMMIT = "0ea97aff489f9420632b4cee81ad82dbec5fe88e" +MATHLIB_PIN = "d13f23b723b8a846827a245b89c10fc7d3f11612" +LEAN_VERSION = "4.34.1" +# These are SHA-256 hashes of the *published UTF-8 file bytes*, not Git blob IDs. +SOURCES = { + "Lifetime": ("90f4892608e953ecc696bb32ea159d1c178ceb8a1c6edfd11acfceb14af462c6", 51383), + "TorusTopology": ("ddb145b3f791c181d4f2a51e54e711937297bd6476ba55bcd5252b7ddb57cfe1", 12257), + "MorseFiniteCritical": ("95a660134eda49eecfe6181884bd23b4e4ca210e228d2463de29e5f821df047b", 9445), + "MorseFiniteControls": ("e6171c949ec60a3aea21a8cc028180e16c82e4946a232107d9e82bf8018cdac1", 2843), + "MorseFiniteAxiomAudit": ("326a1cab271bf46a1c7db750ee1565e08dc4856c62e0abce3f5c9f90d923ce9d", 3025), +} +NEGATIVE_SHA = "4c9726b692dbb83237b82344e7b5aab621749da6da699c0187cf9893dca8d80f" +UPSTREAM = { + "Lifetime": "specifications/lean_statements_20261010/Specifications/Lifetime.lean", + "TorusTopology": "companions/torus_filtration_20261011/TorusTopology.lean", +} +# Published C293 objects, independently reproduced on a separate Linux machine. +OBJECTS = { + "Lifetime": "b3e14c2951b452222ca0c7b1448458cf785225971da704e4e3e6f0cc93107da4", + "TorusTopology": "ccb13e9469d55da8b5202706a1f013fa7a2755b2184542b8a0534f722d993125", + "MorseFiniteCritical": "34ff2a9ed529609dd48a22204b8eacc66eeb943805e2d6e8dee4481cde8ef4e2", + "MorseFiniteControls": "5eebfbb98a8cb05ac420d260dd08461ac037b2e086620fe79ee330defd345efa", + "MorseFiniteAxiomAudit": "3c3f30110ec4a3c0a0c1ba6f1769634d0c04bfc4e444ab1bcfd46c5dffa4ff4b", +} +PACKAGE_PINS = { + "plausible": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "LeanSearchClient": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "importGraph": "e928b72544873815af278d38681b31c0293588e3", + "proofwidgets": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "aesop": "355695d523e41d0554926416cba2a2b3544fbbc9", + "Qq": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "batteries": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "Cli": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "mathlib": MATHLIB_PIN, +} +MODULE_COUNTS = {"Lifetime": 103, "TorusTopology": 38, + "MorseFiniteCritical": 20, "MorseFiniteControls": 8} + + +def sha256(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def safe_source(path, root=ROOT): + """Require a regular, in-tree file without symlinked ancestors.""" + path = Path(path) + root = Path(root) + if not path.is_relative_to(root): + raise RuntimeError(f"source outside repository: {path}") + parts = path.relative_to(root).parts + for i in range(1, len(parts) + 1): + if (root.joinpath(*parts[:i])).is_symlink(): + raise RuntimeError(f"symlink in source: {path}") + if not path.is_file(): + raise RuntimeError(f"source missing or not regular: {path}") + + +def verify_sources(root=ROOT): + """Check C293 source identities AND the actual upstream source crosswalk.""" + root = Path(root) + prefix = root / "frontiers/morse_finite_critical_20261018" + for module, (digest, size) in SOURCES.items(): + path = prefix / "final-project" / f"{module}.lean" + safe_source(path, root) + if path.stat().st_size != size or sha256(path) != digest: + raise RuntimeError(f"C293 source identity mismatch: {module}") + if module in UPSTREAM: + other = root / UPSTREAM[module] + safe_source(other, root) + if other.read_bytes() != path.read_bytes(): + raise RuntimeError(f"upstream C293 input differs: {module}") + neg = prefix / "negative-project/WithoutMorse.lean" + safe_source(neg, root) + if sha256(neg) != NEGATIVE_SHA: + raise RuntimeError("C293 missing-premise control modified") + toolchain = root / "formal/lean-toolchain" + lakefile = root / "formal/lakefile.toml" + manifest_file = root / "formal/lake-manifest.json" + for path in (toolchain, lakefile, manifest_file): + safe_source(path, root) + if toolchain.read_text().strip() != "leanprover/lean4:v" + LEAN_VERSION: + raise RuntimeError("Lean toolchain pin changed") + if f'rev = "{MATHLIB_PIN}"' not in lakefile.read_text(): + raise RuntimeError("Lake mathlib pin changed") + lock = json.loads(manifest_file.read_text()) + actual = {p["name"]: p["rev"] for p in lock["packages"]} + if actual != PACKAGE_PINS: + raise RuntimeError("C293 dependency pins differ from registered formal Lake lock") + return {"source_commit": SOURCE_COMMIT, "module_sha256": + {name: digest for name, (digest, _) in SOURCES.items()}, + "negative_sha256": NEGATIVE_SHA, "dependency_pins": actual} + + +def validate_audit(output): + for module, count in MODULE_COUNTS.items(): + if f"MORSE_AUDIT_MODULE {module} COUNT {count}" not in output: + raise RuntimeError(f"C293 audit missing {module} census") + if "MORSE_AUDIT_STANDARD_ONLY_PASS COUNT 169" not in output: + raise RuntimeError("C293 complete standard-only audit did not finish") + declarations = re.findall(r"(?m)^MORSE_AUDIT_DECL ", output) + if len(declarations) != 169: + raise RuntimeError(f"C293 expected 169 declaration reports, got {len(declarations)}") + if "quotientCriticalSet_finite' depends on axioms:" not in output: + raise RuntimeError("C293 main theorem axiom report absent") + + +def validate_negative(returncode, output): + """Reject a fake pass, import failure or unrelated syntax/error diagnostic.""" + required = ("error: Type mismatch", "quotientCriticalSet_finite d L hL g hs hp", + "IsMorseDistinct d L g", "but is expected to have type") + if returncode != 1 or output.count("error:") != 1 or not all(x in output for x in required): + raise RuntimeError("C293 negative control did not reject the missing Morse premise") + if any(s in output for s in ("unknown identifier", "unknown module", + "file not found", "lean::memory_exception", + "out of memory", "unexpected token")): + raise RuntimeError("C293 negative control failed for an unrelated reason") + + +def git(*args, cwd=ROOT): + return subprocess.check_output(["git", *args], cwd=cwd, text=True).strip() + + +def verify_packages(): + packages = FORMAL / ".lake/packages" + out = {} + for name, commit in PACKAGE_PINS.items(): + path = packages / name + if not path.is_dir(): + raise RuntimeError(f"missing pinned dependency checkout: {name}") + actual = git("-C", str(path), "rev-parse", "HEAD") + if actual != commit: + raise RuntimeError(f"wrong installed dependency commit: {name} {actual}") + if git("-C", str(path), "status", "--porcelain", "--untracked-files=no"): + raise RuntimeError(f"dirty installed dependency checkout: {name}") + out[name] = actual + return out + + +def verify_context(): + required = ("GITHUB_SHA", "GITHUB_RUN_ID", "GITHUB_RUN_ATTEMPT", "GITHUB_REPOSITORY") + if any(not os.environ.get(x) for x in required): + raise RuntimeError("hosted execution needs actual GitHub run identity") + if os.environ["GITHUB_REPOSITORY"] != "d6g8k5htny-coder/Math-": + raise RuntimeError("wrong execution repository") + head = git("rev-parse", "HEAD") + if head != os.environ["GITHUB_SHA"]: + raise RuntimeError(f"tested checkout mismatch {head} != GITHUB_SHA") + return {k.lower(): os.environ[k] for k in required} + + +def run_phase(name, args, cwd, env, expected_success=True, timeout=900): + started = time.monotonic() + try: + result = subprocess.run(args, cwd=cwd, env=env, text=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=timeout, check=False) + code, stdout, stderr = result.returncode, result.stdout, result.stderr + except subprocess.TimeoutExpired as exc: + code = "TIMEOUT" + stdout = (exc.stdout or b"").decode("utf8", "replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") + stderr = (exc.stderr or b"").decode("utf8", "replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "") + (EVIDENCE / f"{name}.stdout").write_text(stdout) + (EVIDENCE / f"{name}.stderr").write_text(stderr) + record = {"name": name, "command": args, "exit_code": code, + "duration_seconds": round(time.monotonic() - started, 2), + "stdout_sha256": sha256(EVIDENCE / f"{name}.stdout"), + "stderr_sha256": sha256(EVIDENCE / f"{name}.stderr")} + print(f"C293 {name}: exit={code} seconds={record['duration_seconds']}", flush=True) + if (expected_success and code != 0) or (not expected_success and code == 0) or code == "TIMEOUT": + print((stdout + stderr)[-4000:], flush=True) + raise RuntimeError(f"C293 {name} unexpected exit: {code}") + return record, stdout + stderr, code + + +def execute(): + context = verify_context() + identity = verify_sources() + EVIDENCE.mkdir(parents=True, exist_ok=False) + BUILD.mkdir(parents=True, exist_ok=False) + report = {"status": "HOLD_NOT_COMPLETED", "scientific_effect": "NONE", + "scope": "C293 finite critical classes only", "context": context, + "source_identity": identity, "memory_limit": "-M14000", + "memory_limit_reason": "Six commands required -M14000 on provider-distinct Linux replay; original -M4096 receipts preserved.", + "phase_results": []} + def save(): + (EVIDENCE / "RESULT.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + save() + try: + packages_before = verify_packages() + version = subprocess.check_output(["lean", "--version"], cwd=FORMAL, text=True).strip() + (EVIDENCE / "toolchain.txt").write_text(version + "\n") + if "version " + LEAN_VERSION not in version: + raise RuntimeError(f"wrong Lean runtime: {version}") + report["packages_before"] = packages_before + env = dict(os.environ) + env["LEAN_PATH"] = str(BUILD) + os.pathsep + env.get("LEAN_PATH", "") + env["LEAN_NUM_THREADS"] = "2" + for name in SOURCES: + args = ["lean", "-j2", "-M14000"] + if name.startswith("Morse"): + args.append("-DwarningAsError=true") + args += ["-o", str(BUILD / f"{name}.olean"), str(FINAL / f"{name}.lean")] + rec, stdout, _ = run_phase("build-" + name, args, FINAL, env) + report["phase_results"].append(rec) + if name == "MorseFiniteAxiomAudit": + validate_audit(stdout) + digest = sha256(BUILD / f"{name}.olean") + if digest != OBJECTS[name]: + raise RuntimeError(f"C293 object digest mismatch: {name}: {digest}") + rec["object_sha256"] = digest + verify_sources() + save() + for name in ("MorseFiniteCritical", "MorseFiniteControls", "MorseFiniteAxiomAudit"): + args = ["leanchecker", "-v", name] + rec, _, _ = run_phase("kernel-" + name, args, FINAL, env) + report["phase_results"].append(rec) + save() + args = ["lean", "-j2", "-M14000", str(NEGATIVE)] + rec, stdout, code = run_phase("negative-WithoutMorse", args, NEGATIVE.parent, env, expected_success=False) + validate_negative(code, stdout) + report["phase_results"].append(rec) + report["packages_after"] = verify_packages() + report["source_identity_after"] = verify_sources() + report["status"] = "PASS_HOSTED_C293_EXACT_TARGETS" + save() + print("C293_HOSTED_FORMAL_PASS: five exact objects, 169 audited declarations, " + "three kernel replays and expected missing-premise rejection. " + "No C292 or elder-rule scientific promotion.", flush=True) + finally: + save() + + +if __name__ == "__main__": + if sys.argv[1:] == ["source"]: + print(json.dumps(verify_sources(), sort_keys=True)) + elif sys.argv[1:] == ["execute"]: + execute() + else: + raise SystemExit("usage: c293_hosted_verify.py source|execute")