From 1f1e1e5cc0d6751960569049cb7c804431c9d66c Mon Sep 17 00:00:00 2001 From: Dylan Roy <249851642+d6g8k5htny-coder@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:41:46 -0500 Subject: [PATCH 1/2] Add current-source native kernel gate and isolate cusp numeric certification Introduce an all-native eight-project kernel/axiom lane that inventories every source module, builds freshly, replays each module with leanchecker, compares two compiled censuses and audits transitive axioms. Bound source/dependency/tool identities to the tested commit; preserve prior complete/incomplete execution evidence and refuse unqualified module-system sidecars. Auditor self-verification:44 kernel controls plus13 mutation-harness controls in normal/optimized Python;8/8 declared Python guard mutants killed in both modes. Actual pinned Lean core preflight builds/rechecks valid and empty modules, rejects unused axiom/sorry/native cases, and detects one real generated-auditor theorem-value-traversal mutation. This qualifies controls only: all-eight/Mathlib execution is NOT_EVALUATED until its actual hosted run. Quarantine the binary64 cusp numerical endpoints and named inherited numerical consumers under A3. Preserve all16 packet files and original replay/mutant commands.18 quarantine and8 original protocol tests pass per mode;6 narrow validator mutants rejected. No analytic theorem is refuted or promoted; no global A3 certificate is claimed. Preserve concurrent determinant admission repair/quarantine. Register tools, exact commands, limits and decisions. Actual author: OpenAI Codex under the owner Crystalline Baseline Protocol. --- .github/workflows/cbz-kernel.yml | 91 ++ .../workflows/cusp-coefficient-certified.yml | 20 +- DECISIONS.md | 26 + GOVERNANCE.md | 20 + PROOF_INDEX.md | 8 + STATUS.md | 22 + TOOLING.md | 44 + quarantine/Q-CUSP-BINARY64-20261029.json | 292 ++++++ tests/test_cbz_kernel_gate.py | 333 +++++++ tests/test_cbz_kernel_mutations.py | 136 +++ tests/test_cusp_quarantine.py | 183 ++++ tools/cbz_kernel_gate.py | 829 ++++++++++++++++++ tools/cbz_kernel_mutations.py | 212 +++++ tools/cbz_kernel_registry.json | 65 ++ tools/check_cusp_quarantine.py | 172 ++++ 15 files changed, 2450 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/cbz-kernel.yml create mode 100644 DECISIONS.md create mode 100644 GOVERNANCE.md create mode 100644 STATUS.md create mode 100644 TOOLING.md create mode 100644 quarantine/Q-CUSP-BINARY64-20261029.json create mode 100644 tests/test_cbz_kernel_gate.py create mode 100644 tests/test_cbz_kernel_mutations.py create mode 100644 tests/test_cusp_quarantine.py create mode 100644 tools/cbz_kernel_gate.py create mode 100644 tools/cbz_kernel_mutations.py create mode 100644 tools/cbz_kernel_registry.json create mode 100644 tools/check_cusp_quarantine.py diff --git a/.github/workflows/cbz-kernel.yml b/.github/workflows/cbz-kernel.yml new file mode 100644 index 000000000..642662d3b --- /dev/null +++ b/.github/workflows/cbz-kernel.yml @@ -0,0 +1,91 @@ +name: CBZ native Lean kernel and axiom audit + +'on': + workflow_dispatch: + workflow_call: + pull_request: + paths: + - 'formal/**' + - 'specifications/lean_statements_20261010/**' + - 'specifications/lean_statement_proofs_20261011/**' + - 'frontiers/cap_first_exit_lean_20261002/**' + - 'frontiers/determinant_moment_20261025/**' + - 'frontiers/source_smooth_realization_20261011/**' + - 'frontiers/source_lifetime_realization_20261017/**' + - 'frontiers/source_derivative_gaussian_20261025/**' + - 'tools/cbz_kernel_gate.py' + - 'tools/cbz_kernel_registry.json' + - 'tools/cbz_kernel_mutations.py' + - 'tests/test_cbz_kernel_gate.py' + - 'tests/test_cbz_kernel_mutations.py' + - '.github/workflows/cbz-kernel.yml' + push: + branches: [main] + paths: + - 'formal/**' + - 'specifications/lean_statements_20261010/**' + - 'specifications/lean_statement_proofs_20261011/**' + - 'frontiers/cap_first_exit_lean_20261002/**' + - 'frontiers/determinant_moment_20261025/**' + - 'frontiers/source_smooth_realization_20261011/**' + - 'frontiers/source_lifetime_realization_20261017/**' + - 'frontiers/source_derivative_gaussian_20261025/**' + - 'tools/cbz_kernel_gate.py' + - 'tools/cbz_kernel_registry.json' + - 'tools/cbz_kernel_mutations.py' + - 'tests/test_cbz_kernel_gate.py' + - 'tests/test_cbz_kernel_mutations.py' + - '.github/workflows/cbz-kernel.yml' + +permissions: + contents: read + +concurrency: + group: cbz-kernel-${{ github.ref }} + cancel-in-progress: false + +jobs: + native-kernel-audit: + runs-on: ubuntu-24.04 + timeout-minutes: 330 + env: + LEAN_NUM_THREADS: '2' + PYTHONDONTWRITEBYTECODE: '1' + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 + with: + python-version: '3.11.16' + - name: Refusal tests and exact native source inventory + run: | + python3 -B -S -m unittest discover -s tests -p test_cbz_kernel_mutations.py -v + python3 -B -O -S -m unittest discover -s tests -p test_cbz_kernel_mutations.py -v + python3 -B -S tools/cbz_kernel_mutations.py --output .lake/cbz-kernel/mutations + python3 -B -S tools/cbz_kernel_gate.py --inventory + - name: Install exact Lean once and retrieve shared pinned Mathlib dependencies + uses: leanprover/lean-action@24581d74d674803a25a81b10b059c5c0cdd344c6 + with: + lake-package-directory: formal + auto-config: 'false' + build: 'false' + test: 'false' + lint: 'false' + use-mathlib-cache: 'true' + use-github-cache: 'false' + - name: Fresh native builds, every-module kernel replay, complete dual census and refusal controls + run: >- + python3 -B -S tools/cbz_kernel_gate.py --execute + --expected-commit "${{ github.sha }}" + --timeout 1800 + - name: Retain exact commands, current sources, object hashes and actual terminal outcomes + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: cbz-native-kernel-${{ github.run_id }}-${{ github.run_attempt }} + path: .lake/cbz-kernel/ + include-hidden-files: true + if-no-files-found: error + retention-days: 90 + diff --git a/.github/workflows/cusp-coefficient-certified.yml b/.github/workflows/cusp-coefficient-certified.yml index 9a356a331..2d024599f 100644 --- a/.github/workflows/cusp-coefficient-certified.yml +++ b/.github/workflows/cusp-coefficient-certified.yml @@ -1,10 +1,14 @@ -name: Cusp coefficient c1 (certified replay) +name: Cusp coefficient c1 (diagnostic replay; A3 quarantined) 'on': pull_request: paths: - 'frontiers/cusp_coefficient_certified_20261001/**' - '.github/workflows/cusp-coefficient-certified.yml' + - 'quarantine/Q-CUSP-BINARY64-20261029.json' + - 'tools/check_cusp_quarantine.py' + - 'tests/test_cusp_quarantine.py' + - 'PROOF_INDEX.md' - 'coefficients/side24_v1/PROOF.md' - 'coefficients/side24_v1/ENCLOSURE.json' - 'imports/lifetime_parent_20260925/UNIFORM_MATRIX_CAP_AND_LIFETIME.md' @@ -16,6 +20,7 @@ permissions: jobs: certified-replay: + name: Diagnostic replay (${{ matrix.flags }}); A3 quarantined runs-on: ubuntu-latest timeout-minutes: 90 strategy: @@ -29,7 +34,16 @@ jobs: - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 with: python-version: '3.11.16' - - name: Verify manifest and main-resident pins + - name: Quarantine integrity and nonconsumption controls + run: | + set -euo pipefail + python -B -S -m unittest discover -s tests -p 'test_cusp_quarantine.py' -v + python -B -O -S -m unittest discover -s tests -p 'test_cusp_quarantine.py' -v + python -B -S tools/check_cusp_quarantine.py + rc=0 + python -B -S tools/check_cusp_quarantine.py --consume frontiers/cusp_coefficient_certified_20261001/certificate.py || rc=$? + test "$rc" -eq 1 + - name: Verify preserved diagnostic manifest and main-resident pins env: PYTHONDONTWRITEBYTECODE: '1' run: | @@ -59,7 +73,7 @@ jobs: raise ValueError('consumed source identity mismatch on this tree: ' + entry['path']) print('manifest and pins verified') PY - - name: Self-test, full replay against RESULTS.json, mutants + - name: Diagnostic self-test, full replay against RESULTS.json, mutants env: PYTHONDONTWRITEBYTECODE: '1' FLAGS: ${{ matrix.flags }} diff --git a/DECISIONS.md b/DECISIONS.md new file mode 100644 index 000000000..6aa01fb75 --- /dev/null +++ b/DECISIONS.md @@ -0,0 +1,26 @@ +# Math CBZ engineering decisions + +## 2026-10-29: preserve the concurrent native base + +Compose on 74565f013575b7b05ecfc4034cd5d638ee355353 (tree 19b3e91bad1a4d7f5a21b1ea5e273fd300acb6f4), after reading all 12 changed engineering files from Math-#528. Preserve those component files and their quarantine. Earlier 8151 discovery and contributor source cuts are historical pins, not a substitute for the integration base. + +## 2026-10-29: add current-source native execution + +Register tools/cbz_kernel_gate.py and .github/workflows/cbz-kernel.yml. Keep each native package layout, install the pinned toolchain once and share only the exact pinned dependency checkouts/cache. Require commit-blob source attestation, complete no-follow physical/Git source coverage, fresh native objects, standalone kernel replay, lossless paired declaration censuses, exact standard axiom closure and compiled controls. Refuse native module-system headers until sidecar qualification. Python tests and historical logs cannot award runtime status. + +## 2026-10-29: isolate binary64 certification + +Adopt the narrow Q-CUSP-BINARY64-20261029 record and validator without changing any of the 16 packet files, proof statements, intervals or existing diagnostic mutants. Keep owner unassigned and maintenance zero in that record. Integrity success denies certificate admission; unrelated sources stay NOT_COVERED. The policy distinction requires exact rational/verified-real CBZ certification and does not assert the older outward intervals are false. + +## 2026-10-29: keep execution and mathematical scope separate + +Record all-native runtime as NOT_EVALUATED until actual execution qualifies the tested source and scope. A future generic native receipt does not itself bind the determinant component's null compiled_inventory, discharge semantic alignment/non-vacuity, clear quarantine or close a parent research theorem. Root owns publication and current remote-head reconciliation. + + +## 2026-10-29: exercise the auditor itself + +Require eight declared source-guard mutations against the unchanged 44-test baseline in both Python modes, and one actual generated Lean theorem-value traversal mutation exposed by the compiled sorry control. Keep all receipts and failures; errors, skips, startup failures or stale anchors never count as kills. This bounded tool evidence does not discharge untested generated-code behavior or all-native package execution. + +## 2026-10-29: preserve sequential rerun custody + +Use a fresh native execution directory per call and retain old attempts plus top-level reference history. Keep G0 mutation results separate; archive their old output on rerun and publish REFUSED even for early input/precondition failures. Current success must never be inferred from a previous attempt. diff --git a/GOVERNANCE.md b/GOVERNANCE.md new file mode 100644 index 000000000..912a6b72f --- /dev/null +++ b/GOVERNANCE.md @@ -0,0 +1,20 @@ +# Math crystalline baseline governance + +This file governs the bounded CBZ engineering tools registered in TOOLING.md. It does not replace the source statements, historical scientific register or component quarantine records. + +The owner directive authorizes autonomous implementation and automated verification. Layer A remains immutable: preserve proof statements and quantitative bounds; admit no sorry/admit placeholders, undeclared axioms, vacuous closure claims or finite-precision arithmetic as exact-bound certification; keep failed and missing evidence explicit. Standard transitive axioms permitted by the native kernel gate are exactly propext, Classical.choice and Quot.sound. + +The native gate builds the eight named packages in their native layouts, replays every module with leanchecker, compares independent compiled declaration censuses and audits all-declaration transitive closure. Source/configuration/gate bytes are bound to the tested commit blobs, independently of Git index/status hints. Dependency source commits are attested separately; dependency cache objects are not claimed freshly rebuilt. Native module-system sources and isModule headers are refused until their sidecar objects are qualified. An all-native receipt establishes its stated execution scope only. + +The cusp validator is a one-packet quarantine and nonconsumption boundary. A successful integrity result admits no arithmetic certificate. Its record preserves all 16 packet files and denies the named numerical sources and byte-identical aliases; unrelated sources return NOT_COVERED. Exact rational or verified-real evidence is required to resume CBZ bound certification. + +That checker is opt-in. Other downstream workflows do not automatically enforce this quarantine, and its descriptive consumer/reference hashes are not all authenticated by this validator. Neither default integrity success nor this integration establishes global isolation or A3 closure. + +Integration source base: 74565f013575b7b05ecfc4034cd5d638ee355353, tree 19b3e91bad1a4d7f5a21b1ea5e273fd300acb6f4. The determinant engineering changes from Math-#528 and their component GOVERNANCE.md, TOOLING.md, STATUS.md and QUARANTINE.json are preserved. The generic native gate does not invent the determinant component's missing compiled_inventory binding or clear its quarantine. + +Current native execution status is NOT_EVALUATED. Test counts, old receipts, source scans and workflow success outside the exact audited source/scope do not supply missing kernel evidence. Scientific effect: NONE. + + +Auditor self-testing is bounded and fail-closed: the declared Python guard mutants require intended assertion kills with healthy positive baselines and no errors/skips; the generated theorem-value collector mutation requires actual Lean execution and detection by the compiled sorry fixture. Missing, stale or unexecuted mutation evidence cannot qualify the auditor. + +Execution custody is append-only by attempt: fresh execution subdirectories preserve previous complete and incomplete logs/receipts, while a separate current reference states the new outcome. G0 mutation evidence stays separate. An early failure invalidates current success without destroying historical evidence. diff --git a/PROOF_INDEX.md b/PROOF_INDEX.md index 6b406a44a..f833162e8 100644 --- a/PROOF_INDEX.md +++ b/PROOF_INDEX.md @@ -2,6 +2,14 @@ This file links full proof text, exact reviews, and explicitly incomplete proof obligations. Local links open the retained files in this public repository; immutable external links identify sources still on other public branches. Scientific status is unchanged by this index. Review descriptions below report the linked records, checked on 2026-09-26; packets integrated 27–29 September 2026 are listed by availability in the navigation-refresh section near the end of this file, with their review records in [docs/integration/2026-09-29-navigation-refresh.md](docs/integration/2026-09-29-navigation-refresh.md). That section was rebased onto `main` `6f74f7a` on 2026-10-02 (merges only) without changing its 26–29 September cut: packets that landed later are not listed there, and a separately scoped continuation will index them. None of this replaces the claim manifest or the source statements. +## Crystalline baseline quarantine — 2026-10-29 + +**[Q-CUSP-BINARY64-20261029](quarantine/Q-CUSP-BINARY64-20261029.json): QUARANTINED, A3_NOT_PROVEN.** The retained [cusp coefficient packet](frontiers/cusp_coefficient_certified_20261001/README.md) computes outward-rounded binary64 enclosures. Its Gaussian `c1` intervals, derived `I_cand`/ratios and inherited absolute torus intervals are not admitted as CBZ numerical certificates. The record binds all 16 unchanged source files at `8151f592918a845bf19eb8eafaf8444540a32734`, names the dependent numerical displays and conditional outputs, and states the exact unproved arithmetic boundary. No interval is declared false; the analytic reductions and conditional transfer inequalities are not reclassified here. + +Original packet wording and the historical availability inventory remain verbatim. The existing replay and mutants remain available as diagnostics; a green replay does not discharge A3. Owner: unassigned. Maintenance: zero. Resumption requires exact-rational or verified-real bounds and source-bound reconciliation of inherited numerical consumers; see the quarantine record. + + + ## Current-reading guidance — 2026-10-07 For the C7 total rejected-density proof listed as #150 in the dated inventory below, use the [packet README](frontiers/c7_total_bounded_20260929/README.md). Read Section 3's normalized-form remark with the [normalized-form scope erratum](frontiers/c7_total_bounded_20260929/ERRATUM_NORMALIZED_FORM.md), and Section 4's final rate comparison with the [gap-cutoff rate clarification](frontiers/c7_total_bounded_20260929/RATE_READING.md). This dated guidance leaves the inventory's 26–29 September 2026 cut and its original proof/status labels unchanged. diff --git a/STATUS.md b/STATUS.md new file mode 100644 index 000000000..7802739d8 --- /dev/null +++ b/STATUS.md @@ -0,0 +1,22 @@ +# Math CBZ evidence boundaries + +This is a technical execution/quarantine ledger for the registered tools. It grants no mathematical acceptance or parent theorem closure. + +| Item | Current status | Missing evidence or boundary | +|---|---|---| +| Eight native packages / 119 source modules | NOT_EVALUATED under the new gate | Actual source-pinned fresh native builds, every-module kernel replay, full independent compiled censuses, transitive axiom closure and compiled controls | +| Cusp binary64 coefficient packet | QUARANTINED; A3_NOT_PROVEN | Exact rational/verified-real bound certification and source-bound reconciliation of the denied numerical consumers | +| Determinant component gate from Math-#528 | QUARANTINED | Existing compiled_inventory is null; package-specific bound census and repaired-gate execution remain unestablished | +| Native module-system sidecars | NOT_QUALIFIED | New module sources and compiled isModule headers are refused by this gate | +| Semantic alignment, non-vacuity and parent research joins | NOT_EVALUATED by this engineering change | Actual mathematical evidence at the original statements and scopes | + +Use the exact commands in TOOLING.md. Successful Python checks verify their stated engineering behavior; they do not establish Lean execution. A missing compiler, failed phase, omitted native source or mismatched commit/object must not be reported as clean. + +## Historical scoped evidence + +The predecessor formal/ job in run 40726237480 at 8151f592918a845bf19eb8eafaf8444540a32734 printed a 63-user-theorem / 116-compiled-declaration standard-axiom receipt. It covers formal/ at that source, not all native packages or this integration. Its original logs and receipts remain historical scoped evidence. + +The determinant component's earlier receipts, proved metadata and source-only/unit records retain their original scope. Its current component-level status and explanation remain in frontiers/determinant_moment_20261025/STATUS.md and QUARANTINE.json. The 16 cusp packet files and historical numerical intervals remain unchanged; quarantine does not declare the older enclosures false. + +Integration base read and source-verified: 74565f013575b7b05ecfc4034cd5d638ee355353, tree 19b3e91bad1a4d7f5a21b1ea5e273fd300acb6f4. Scientific effect: NONE. + diff --git a/TOOLING.md b/TOOLING.md new file mode 100644 index 000000000..b84b774f5 --- /dev/null +++ b/TOOLING.md @@ -0,0 +1,44 @@ +# Math CBZ tool registry + +| Tool | Entrypoint | Scope | Current runtime status | +|---|---|---|---| +| CBZ-MATH-NATIVE-KERNEL-01 | tools/cbz_kernel_gate.py; tools/cbz_kernel_registry.json | Eight native Lean packages, currently 119 source modules; fresh native builds, module kernel replay, independent complete declaration censuses, axiom closure and actual compiled controls | NOT_EVALUATED for this integration | +| Q-CUSP-BINARY64-20261029 | tools/check_cusp_quarantine.py; quarantine/Q-CUSP-BINARY64-20261029.json | One preserved 16-file binary64 packet and its explicitly denied numerical consumers | Integrity/nonconsumption checks only; A3_NOT_PROVEN | + +The native workflow is .github/workflows/cbz-kernel.yml. It supports pull_request, main pushes, workflow_call and workflow_dispatch without a historical head guard. It installs Lean 4.34.1 once, uses Mathlib d13f23b723b8a846827a245b89c10fc7d3f11612 and the exact nine dependency records, and retains evidence under .lake/cbz-kernel/. Its actual positive/empty-module and unused-axiom/sorry/native controls execute before long native builds. Fixture source bytes and immediate control results are retained; later failures cannot turn them into a full-package success. + +Run focused source/control tests from the repository root: + +```sh +python3 -B -S -m unittest discover -s tests -p test_cbz_kernel_gate.py -v +python3 -B -O -S -m unittest discover -s tests -p test_cbz_kernel_gate.py -v +python3 -B -S -m unittest discover -s tests -p test_cusp_quarantine.py -v +python3 -B -O -S -m unittest discover -s tests -p test_cusp_quarantine.py -v +``` + +The auditor has a narrow self-mutation gate. Run `python3 -B -S -m unittest discover -s tests -p test_cbz_kernel_mutations.py -v` (and the same with `-O`) and `python3 -B -S tools/cbz_kernel_mutations.py --output .lake/cbz-kernel/mutations`. The runner requires the unmodified 44-test suite to pass in both modes, then kills all eight declared nonstale guard mutants by their one intended assertion, with zero errors/skips/startup failures. The real Lean preflight also removes theorem-value traversal in one generated auditor and requires the compiled sorry control to expose the false clear result. A compiler failure cannot count as a kill. These are bounded auditor self-tests, not full semantic or all-generated-code qualification. + +Run the native inventory, then actual execution only with the exact pinned runtime and dependency checkouts available: + +```sh +python3 -B -S tools/cbz_kernel_gate.py --inventory +python3 -B -S tools/cbz_kernel_gate.py --execute --expected-commit "$(git rev-parse HEAD)" --timeout 1800 +``` + +Inventory success is SOURCE_INVENTORY_ONLY with kernel_status NOT_EVALUATED. Execution writes a success receipt only after every native package, kernel replay, compiled census, axiom audit, control and final identity recheck passes. A failed or absent phase stays REFUSED/NOT_EVALUATED. The 43 Lean paths outside these eight native packages remain outside this gate's scope. + +Run quarantine integrity and the deliberately denied admission attempt: + +```sh +python3 -B -S tools/check_cusp_quarantine.py +python3 -B -S tools/check_cusp_quarantine.py --consume frontiers/cusp_coefficient_certified_20261001/certificate.py +``` + +The first command must exit 0 with QUARANTINE_INTEGRITY_OK and cbz_certificate_admitted false. The second must exit 1 with REFUSED. An unrelated --consume source must exit 2 with NOT_COVERED and remains uncertified. The existing cusp workflow preserves its numerical replay and mutants as diagnostics; its green result cannot discharge A3. + +Explicit-source callers must treat both exit 1 and exit 2 as non-admission. The validator is opt-in and does not automatically enforce quarantine in other downstream workflows or authenticate every descriptive consumer/reference field. Global consumer isolation and A3 closure are outside its scope. + +Component-local determinant commands and the compiled-inventory quarantine are preserved in frontiers/determinant_moment_20261025/TOOLING.md. Neither this registry nor the all-native gate changes that component's bound inventory or scientific status. + + +Each `--execute` call creates a fresh `.lake/cbz-kernel/executions/attempt-/`. Read `.lake/cbz-kernel/current-execution.json` to locate the current attempt; its success receipt lives inside that directory. A failed attempt records REFUSED without a new success receipt. Previous complete/incomplete attempts and their source/control logs remain unchanged. Top-level reference history is retained separately. The source-inventory initial step and G0 mutation evidence remain separate and are not overwritten by native execution. Repeated mutation commands archive the prior mutation output under `mutations/history/`; an early refusal replaces only the current result, never leaves an old PASS as current. Use distinct output roots/checkouts for concurrent invocations. diff --git a/quarantine/Q-CUSP-BINARY64-20261029.json b/quarantine/Q-CUSP-BINARY64-20261029.json new file mode 100644 index 000000000..c5506e266 --- /dev/null +++ b/quarantine/Q-CUSP-BINARY64-20261029.json @@ -0,0 +1,292 @@ +{ + "schema": "cbz.quarantine/v1", + "id": "Q-CUSP-BINARY64-20261029", + "title": "Cusp c1 binary64 enclosures: A3 arithmetic certification unavailable", + "classification": "QUARANTINED", + "layer_a": "A3", + "layer_a_status": "A3_NOT_PROVEN", + "cbz_certificate_admitted": false, + "source_snapshot": { + "repository": "d6g8k5htny-coder/Math-", + "commit": "8151f592918a845bf19eb8eafaf8444540a32734", + "packet_path": "frontiers/cusp_coefficient_certified_20261001", + "packet_object": "CL-CU-CUSP-COEFFICIENT-20261001-v1", + "manifest": { + "path": "frontiers/cusp_coefficient_certified_20261001/SOURCE_FILES.json", + "git_blob": "e9624bdeb78e9fe37f8fbacf45958b9b93f1cf95", + "sha256": "605481bd178e8d0dca68183601f6a99d66f25631717cae9c6a1f4b06e97f4911", + "bytes": 3645 + } + }, + "source_files": [ + { + "path": "frontiers/cusp_coefficient_certified_20261001/ERRATUM_20261013.md", + "git_blob": "a9c3f95a6e31cd1924f4952d6092d848bd80f8ef", + "sha256": "c6e4d0ae3854b27f31b7165ccc376d070c85093a7e442d8b951744013b9b0be1", + "bytes": 8430 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/NOTE.md", + "git_blob": "b2866871c10cd0a0def41e10bdaf5ecbef18241c", + "sha256": "9c74117f6b7ff2054fcfb5ddcfb4c8ad4a3a1278c201faafc5e98e7612abfc0c", + "bytes": 27264 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/README.md", + "git_blob": "7840312a485ce480149424430ec2508bb0852086", + "sha256": "14e427b7b9c0b2b823192e37cb2728036adae493dfdebef78d04b24232bf5bdf", + "bytes": 1104 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/RESULTS.json", + "git_blob": "8bbd0b0c69f6b29849fb2e3a3b2ad86974130987", + "sha256": "2de0a2381eb2f73b3f2ed7367c78d28856067b271f9e3484384c199a24cacdbe", + "bytes": 5350 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/SOURCE_FILES.json", + "git_blob": "e9624bdeb78e9fe37f8fbacf45958b9b93f1cf95", + "sha256": "605481bd178e8d0dca68183601f6a99d66f25631717cae9c6a1f4b06e97f4911", + "bytes": 3645 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/SOURCE_MAP.json", + "git_blob": "7e9092f185c55efe22bc9587be5cdf2f5ef89bd1", + "sha256": "306b39a011472e6c86642c1226f8605f4b4ec9b01308e0c7b0233c24023f1390", + "bytes": 3336 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/certificate.py", + "git_blob": "7a4ba3e80acb3bb2423429e4808138574303b82d", + "sha256": "7472ac07d96210801b4070771713b0732bafb2cc479dd74d733eebc097b71838", + "bytes": 18392 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/consts.py", + "git_blob": "5cac30c3bf086697b978f1161191764121298fd4", + "sha256": "5265668c0f489137d6362d230d7f2df0dfb25632abdadc0934a2c89c8594759e", + "bytes": 4462 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/controls.py", + "git_blob": "5e41d95cf30ab47581ad15e78577a80a9d7e5384", + "sha256": "e2d59dfa162947e02d3ba696e5fb89aa926d2a658d4252f0ec1d0e6806ec3ddc", + "bytes": 8690 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/cusp.py", + "git_blob": "fba24e5ee979ac23c6c00935af6ba1d1ecb09590", + "sha256": "695038fb8de5c7f13fd481384a29117df297c4d7125b7b761ee4114e7d0f19fc", + "bytes": 7686 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/cx.py", + "git_blob": "29e3a4a8a46f065346592320e0c6bb65c6ccb331", + "sha256": "af2a32b3cf6b3826520ac3a14bc4238143447c5e3697ad0355d8a55e6b9aacd1", + "bytes": 4716 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/d3.py", + "git_blob": "bae664536aac0f673cd8cd211d8637b6ba34c50c", + "sha256": "eafa1a6cf76cbdd9338f315377522aa3c23b361216c77bcd5e27ef610f57b0f7", + "bytes": 11136 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/elem.py", + "git_blob": "99ad3332b40daa1eee50106dbaa8b4b726cd5ae6", + "sha256": "65490f314fd731ced8d893d137ed5d7a516cf3cf36ba68cf77d7845805c55fb0", + "bytes": 9825 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/gauss.py", + "git_blob": "71f0b5709d5867497a5a1da1c08de48c30d68976", + "sha256": "51cd9e56f1858f711bee0a4554727d847f22a0796e85c77be58b4e74f2278eb0", + "bytes": 6228 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/ia.py", + "git_blob": "cf4bbfa16f577fe65f4ab5fb3621943fa63cf9fa", + "sha256": "6d048d58c6ab18f21c0609fc888ca73497a60e234217bb4f7a309a1502fccc9e", + "bytes": 8930 + }, + { + "path": "frontiers/cusp_coefficient_certified_20261001/side24.py", + "git_blob": "31da88a031f3df682d1411415bbc1a9a7f591850", + "sha256": "85c330d82623dc89effed5a09b8d15a8986688f5eacc922f8b9b87754f9eef35", + "bytes": 10043 + } + ], + "not_proven_boundary": [ + "A3-admissible certified numerical intervals for Gaussian cusp c1 of Math-#207 CU.2 in d=1,2,3.", + "A3-admissible numerical bounds derived from those intervals: I_cand=(3^(1/4)/2)c1, I_cand-c1, c1/c_(d,ref), and c1/c_(d,24).", + "Absolute torus c1 intervals obtained by combining the unadmitted reference intervals with conditional transfer inequalities, including the packet L>=24 claims and the cusp_torus_transfer inherited_interval outputs for L>=10." + ], + "mathematical_arithmetic_gap": "certificate.py explicitly uses outward-rounded IEEE binary64 interval arithmetic from ia.py/elem.py/cx.py. The current Layer A3 prohibits floating-point mathematical bound certification. No exact-rational or verified-real replacement establishes these published endpoints in this record. Replay equality and seeded mutant rejection do not discharge that arithmetic certificate gap.", + "not_a_verdict": [ + "This quarantine does not prove any quoted interval false.", + "It does not classify or refute the analytic Mellin reduction, Theorem CU, symbolic coefficient identities, or conditional transfer inequalities.", + "Exact-rational transfer algebra does not independently establish its inherited reference interval." + ], + "attempted": [ + { + "date": "2026-10-29", + "action": "Inspected exact source certificate.py, ia.py, SOURCE_FILES.json, RESULTS.json and declared consumers at the recorded commit.", + "outcome": "Binary64 certification path confirmed; no A3-admissible replacement found in the scoped packet." + }, + { + "date": "2026-10-29", + "action": "Preserved all 16 source files and original replay/mutant commands.", + "outcome": "Diagnostic reproducibility retained; no endpoint promoted or numerically recomputed by the quarantine checker." + } + ], + "resumption_cost": { + "class": "substantial arithmetic proof and implementation work; no reliable time estimate", + "required": [ + "Replace all certifying basic, elementary and complex arithmetic with exact rational or verified-real bounds.", + "Re-establish constants, quadrature, analytic continuation and tail bounds, then prove published decimal rounding from exact endpoints.", + "Run sound positive, negative and mutation controls and bind exact source identities.", + "Reconcile every inherited numerical consumer before any CBZ admission." + ] + }, + "isolation": { + "packet_bytes": "preserved verbatim", + "replay_role": "diagnostic only", + "certificate_admission": "denied for this packet, identical source copies and the named inherited numerical artifacts", + "analytic_transfer_scope": "not reclassified by this arithmetic quarantine", + "global_A3_audit": false, + "closed_consumer_boundary": "No cusp dependency is declared in Math claims/LANDING_CLAIMS.json at this baseline. This is not a census of external main statuses." + }, + "denied_certificate_sources": [ + "frontiers/cusp_coefficient_certified_20261001", + "frontiers/cusp_torus_transfer_20261001/RESULTS.json", + "frontiers/cusp_torus_transfer_20261001/transfer.py", + "frontiers/c2_torus_transfer_20261001/NOTE.md", + "frontiers/c2_torus_transfer_20261001/SOURCE_MAP.json", + "frontiers/c2_exact_20261001/NOTE.md", + "frontiers/third_order_coefficient_20261001/NOTE.md", + "frontiers/third_order_coefficient_20261001/README.md", + "frontiers/third_order_coefficient_20261001/SOURCES.json", + "frontiers/remainder_vanishing_20260930/ERRATUM_20261004.md" + ], + "numerical_consumers": [ + { + "source": { + "path": "frontiers/cusp_torus_transfer_20261001/transfer.py", + "git_blob": "de48ca6c7e3637001b510d9b9aab0d789a76de70", + "sha256": "49acaca69d437aebed4547a802430b4b2906d5c96827dabb4b622e96f3190b32", + "bytes": 9677 + }, + "outputs": { + "path": "frontiers/cusp_torus_transfer_20261001/RESULTS.json", + "git_blob": "f044f2b2da19c756a8aa14831f7aa85e03e018a5", + "sha256": "1ca1b76e5ad6a55083fb72b533106311e751aafd9f9e4c3173de413f3aa66b43", + "bytes": 2955 + }, + "scope": "inherited_interval transcribes peer decimals; conditional_absolute_c1 outputs inherit this unadmitted reference. Exact relative covariance-transfer algebra is separate." + }, + { + "source": { + "path": "frontiers/c2_torus_transfer_20261001/NOTE.md", + "git_blob": "5ce5bad2a1073b9b425fc4c5e6eed5527d39eaf2", + "sha256": "6d15dccc847d9457ff5d77d6286179fa87505b5d0570fea7996366bb2ba79da3", + "bytes": 21673 + }, + "manifest": { + "path": "frontiers/c2_torus_transfer_20261001/SOURCE_MAP.json", + "git_blob": "5365bc2d8e89f6dd0cb473caa3334f910b70a6bb", + "sha256": "56fae2a5c2aad309bec346cde15e8df968ea75d48b1ae194f3d1e4d0dc35629a", + "bytes": 7513 + }, + "scope": "NOTE section 0 and [CU-results] explicitly consume the c1/c interval. The c2 transfer computation is a distinct claim, not refuted here." + }, + { + "source": { + "path": "frontiers/third_order_coefficient_20261001/NOTE.md", + "git_blob": "fa44893404bceafb2956409b1d544de5397199a0", + "sha256": "cbb59eb8df5d492c5183e110219703559307441b0d9fb281434b5193e3ef8078", + "bytes": 47631 + }, + "scope": "c1/c numerical display/table and certification wording inherit #219. README says no numerical input is consumed by the c2 checker; no algorithmic dependency is invented." + }, + { + "source": { + "path": "frontiers/c2_exact_20261001/NOTE.md", + "git_blob": "a2798b87674ed5fc0d2144697e77ccb9b185b4ab", + "sha256": "598fc86a7c6b21bad438ef087e5aa7521f0fae08e25fa4f40f9b2ba635846dbb", + "bytes": 14480 + }, + "scope": "quoted c1/c correction; its own c2 exact formulas are not refuted by this Q." + }, + { + "source": { + "path": "frontiers/remainder_vanishing_20260930/ERRATUM_20261004.md", + "git_blob": "0ffb10311e0d683e7e3ba57cc01f21696948b8e2", + "sha256": "1d058a6f66ed48bc7c74d8c529addb143d6397be050c9d28d9b97436af164961", + "bytes": 5581 + }, + "scope": "quoted c1/c correction ratio. No new proof failure is inferred for its analytic remainder statement." + } + ], + "adjacent_shared_arithmetic": [ + { + "source": { + "path": "frontiers/c2_exact_20261001/ia.py", + "git_blob": "cf4bbfa16f577fe65f4ab5fb3621943fa63cf9fa", + "sha256": "6d048d58c6ab18f21c0609fc888ca73497a60e234217bb4f7a309a1502fccc9e", + "bytes": 8930 + }, + "scope": "byte-identical arithmetic engine; separate certification exposure, not a blanket verdict on that packet" + }, + { + "source": { + "path": "frontiers/c2_exact_20261001/elem.py", + "git_blob": "99ad3332b40daa1eee50106dbaa8b4b726cd5ae6", + "sha256": "65490f314fd731ced8d893d137ed5d7a516cf3cf36ba68cf77d7845805c55fb0", + "bytes": 9825 + }, + "scope": "byte-identical arithmetic engine; separate certification exposure, not a blanket verdict on that packet" + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/ia.py", + "git_blob": "cf4bbfa16f577fe65f4ab5fb3621943fa63cf9fa", + "sha256": "6d048d58c6ab18f21c0609fc888ca73497a60e234217bb4f7a309a1502fccc9e", + "bytes": 8930 + }, + "scope": "byte-identical arithmetic engine; separate certification exposure, not a blanket verdict on that packet" + } + ], + "surfaces": { + "canonical_index": "PROOF_INDEX.md", + "diagnostic_workflow": ".github/workflows/cusp-coefficient-certified.yml", + "other_workflow_references": [ + { + "path": ".github/workflows/cusp-torus-transfer.yml", + "git_blob": "d4ca448f576b463518d470d7ad53b190c2f359d5", + "sha256": "c1d6431f74edf97a30c9761359da9b6e1e44138e47a96015c0ff4381195e174d", + "bytes": 1876 + }, + { + "path": ".github/workflows/c2-torus-transfer.yml", + "git_blob": "e8c11afdc19eba9e9090aa7dca8ab130e411c833", + "sha256": "c353a0346e72bf672fe0fed0bd54bc41f19ab8bbdf986def55550404903ab8d1", + "bytes": 3957 + }, + { + "path": ".github/workflows/third-order-coefficient.yml", + "git_blob": "be6c402b9dd8d8b581c14e4bfbb040b2948317a9", + "sha256": "1c931a7a4f1f44aefa08321c329e224b016eac73c32b0f8c968a2f7e5b392868", + "bytes": 6594 + } + ], + "historical_availability_index": { + "path": "docs/integration/2026-10-23-postcut-proof-sources.md", + "git_blob": "a1008e928c56cb360509db0f894b5fafae435df3", + "sha256": "d0e34f44e505c928604b5382def98559bd1a029be62102af1c14c3ed928513e8", + "bytes": 63129 + }, + "historical_packet_labels": "retained verbatim; they do not override this A3 admission denial" + }, + "owner": null, + "maintenance": 0 +} diff --git a/tests/test_cbz_kernel_gate.py b/tests/test_cbz_kernel_gate.py new file mode 100644 index 000000000..c563beb1a --- /dev/null +++ b/tests/test_cbz_kernel_gate.py @@ -0,0 +1,333 @@ +"""CBZ native gate refusals: omitted source, forged census, stale output and bad child exit.""" +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch + +TOOL = Path(__file__).resolve().parents[1] / "tools" / "cbz_kernel_gate.py" +gate = None +if TOOL.exists(): + spec = importlib.util.spec_from_file_location("cbz_kernel_gate", TOOL) + gate = importlib.util.module_from_spec(spec) + spec.loader.exec_module(gate) + +BASE = """CBZ|MODULE|s4d|2|2 +CBZ|DECL|s4d|s4d/s74|theorem +CBZ|DECL|s4d|s4d/s64|def +CBZ|AXIOMS| +CBZ|END|1|2|3 +""" +NATIVE = """CBZ|MODULE|s4d|2|2 +CBZ|DECL|s4d|s756e7573656443425a4e6174697665|theorem +CBZ|DECL|s4d|s756e7573656443425a4e6174697665/s5f6e6174697665/s6e61746976655f646563696465/s61785f31375f33|axiom +CBZ|AXIOMS|s756e7573656443425a4e6174697665/s5f6e6174697665/s6e61746976655f646563696465/s61785f31375f33 +CBZ|END|1|2|3 +""" + +class NativeGateTests(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(gate, "CBZ native gate is not implemented") + + def project(self, root, lake='name = "fixture"\n[[lean_lib]]\nname = "M"\n'): + p = root / "formal" + p.mkdir() + (p / "lakefile.toml").write_text(lake) + (p / "lean-toolchain").write_text("leanprover/lean4:v4.34.1\n") + (p / "lake-manifest.json").write_text(json.dumps({"packages": []})) + return p + + def test_orphan_native_module_is_included_even_without_an_import(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (p / "M.lean").write_text("def x : Nat := 1\n") + (p / "Orphan.lean").write_text("theorem hidden : True := True.intro\n") + report = gate.project_inventory(root, "formal") + self.assertEqual([x["module"] for x in report["modules"]], ["M", "Orphan"]) + + def test_srcdir_is_removed_from_actual_module_identity(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root, 'name = "fixture"\n[[lean_lib]]\nname = "Inputs"\nsrcDir = "inputs"\nroots = ["M"]\n') + (p / "inputs").mkdir() + (p / "inputs/M.lean").write_text("def x : Nat := 1\n") + report = gate.project_inventory(root, "formal") + self.assertEqual(report["modules"][0]["module"], "M") + self.assertEqual(report["modules"][0]["path"], "inputs/M.lean") + + def test_two_source_paths_cannot_shadow_one_module(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root, 'name = "fixture"\n[[lean_lib]]\nname = "M"\n[[lean_lib]]\nname = "Inputs"\nsrcDir = "inputs"\n') + (p / "M.lean").write_text("def x : Nat := 1\n") + (p / "inputs").mkdir();(p / "inputs/M.lean").write_text("def x : Nat := 2\n") + with self.assertRaisesRegex(gate.GateError, "duplicate module"): + gate.project_inventory(root, "formal") + + def test_source_symlink_is_refused(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (root / "external").write_text("def x : Nat := 1\n") + (p / "M.lean").symlink_to(root / "external") + with self.assertRaisesRegex(gate.GateError, "symlink"): + gate.project_inventory(root, "formal") + + def test_source_directory_symlink_cannot_hide_a_module(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (p / "M.lean").write_text("def x : Nat := 1\n") + external = root / "external";external.mkdir() + (external / "Hidden.lean").write_text("axiom hidden : False\n") + (p / "hidden").symlink_to(external, target_is_directory=True) + with self.assertRaisesRegex(gate.GateError, "symlink"): + gate.project_inventory(root, "formal") + + def test_unreadable_source_directory_is_refused_even_for_privileged_runner(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (p / "M.lean").write_text("def x : Nat := 1\n") + hidden = p / "hidden";hidden.mkdir() + (hidden / "Hidden.lean").write_text("axiom hidden : False\n") + hidden.chmod(0) + try: + with self.assertRaisesRegex(gate.GateError, "unreadable|inaccessible"): + gate.project_inventory(root, "formal") + finally: + hidden.chmod(0o700) + + def test_invalid_utf8_native_source_is_refused_at_inventory(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (p / "M.lean").write_bytes(b"def x := 1\n\xff") + with self.assertRaisesRegex(gate.GateError, "UTF-8"): + gate.project_inventory(root, "formal") + + def test_native_module_system_source_is_refused_until_sidecars_are_qualified(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (p / "M.lean").write_text("module\npublic def x : Nat := 1\n") + with self.assertRaisesRegex(gate.GateError, "module-system"): + gate.project_inventory(root, "formal") + + def test_absolute_or_parent_project_escape_is_refused(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) / "own";root.mkdir() + outside = self.project(Path(d)) + (outside / "M.lean").write_text("def x : Nat := 1\n") + for relative in (str(outside), "../formal"): + with self.subTest(relative=relative), self.assertRaisesRegex(gate.GateError, "project path|escape"): + gate.project_inventory(root, relative) + + def test_root_cache_is_explicitly_excluded(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root) + (p / "M.lean").write_text("def x : Nat := 1\n") + (p / ".lake/packages").mkdir(parents=True) + (p / ".lake/packages/Dependency.lean").write_text("axiom external : False\n") + report = gate.project_inventory(root, "formal") + self.assertEqual([x["module"] for x in report["modules"]], ["M"]) + self.assertEqual(report["excluded_cache_dirs"], [".lake"]) + + def test_missing_declared_library_root_cannot_pass_inventory(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);p = self.project(root, 'name = "fixture"\n[[lean_lib]]\nname = "M"\nroots = ["Missing"]\n') + (p / "M.lean").write_text("def x : Nat := 1\n") + with self.assertRaisesRegex(gate.GateError, "root"): + gate.project_inventory(root, "formal") + + def test_tracked_native_module_cannot_be_omitted_from_filesystem_census(self): + snapshot = {"projects": [{"project": "formal", "modules": [{"path": "M.lean"}]}]} + with self.assertRaisesRegex(gate.GateError, "coverage"): + gate.require_tracked_coverage(snapshot, {"formal/M.lean", "formal/hidden/Hidden.lean"}) + + def test_valid_compiled_census_preserves_total_and_every_declaration(self): + r = gate.parse_audit(BASE, ["M"]) + self.assertEqual(r["declaration_count"], 2) + self.assertEqual(r["module_counts"], {"M": 2}) + self.assertEqual(sorted(x["name"] for x in r["declarations"]), ["M.d", "M.t"]) + + def test_omitted_registered_module_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "module"): + gate.parse_audit(BASE, ["M", "Omitted"]) + + def test_independent_census_disagreement_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "census"): + gate.parse_audit(BASE.replace("s4d|2|2", "s4d|2|1"), ["M"]) + + def test_duplicate_constant_cannot_satisfy_count(self): + with self.assertRaisesRegex(gate.GateError, "duplicate"): + gate.parse_audit(BASE.replace("s4d/s64", "s4d/s74"), ["M"]) + + def test_missing_terminal_marker_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "END"): + gate.parse_audit(BASE.replace("CBZ|END|1|2|3\n", ""), ["M"]) + + def test_false_terminal_total_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "count"): + gate.parse_audit(BASE.replace("END|1|2|3", "END|1|1|3"), ["M"]) + + def test_unrecognized_protocol_record_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "protocol"): + gate.parse_audit(BASE + "CBZ|MADE_UP|green\n", ["M"]) + + def test_unused_custom_axiom_is_refused_even_with_empty_union(self): + with self.assertRaisesRegex(gate.GateError, "axiom"): + gate.parse_audit(BASE.replace("s4d/s64|def", "s4d/s64|axiom"), ["M"]) + + def test_unsafe_definition_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "unsafe"): + gate.parse_audit(BASE.replace("s4d/s64|def", "s4d/s64|unsafe"), ["M"]) + + def test_transitive_sorry_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "sorryAx"): + gate.parse_audit(BASE.replace("CBZ|AXIOMS|", "CBZ|AXIOMS|s736f7272794178"), ["M"]) + + def test_native_reduce_axiom_is_refused(self): + with self.assertRaisesRegex(gate.GateError, "Lean.ofReduceBool"): + gate.parse_audit(BASE.replace("CBZ|AXIOMS|", "CBZ|AXIOMS|s4c65616e/s6f66526564756365426f6f6c"), ["M"]) + + def test_pinned_native_generated_axiom_control_is_qualified_only_as_expected_refusal(self): + result = gate.validate_control(NATIVE, "M", "native") + self.assertEqual(result["forbidden_axioms"], ["unusedCBZNative._native.native_decide.ax_17_3"]) + + def test_native_control_cannot_accept_an_unrelated_generated_axiom(self): + with self.assertRaises(gate.GateError): + gate.validate_control(NATIVE.replace("s61785f31375f33", "s61785f6f74686572"), "M", "native") + + def test_native_control_requires_the_actual_named_theorem(self): + with self.assertRaises(gate.GateError): + gate.validate_control(NATIVE.replace("s756e7573656443425a4e6174697665|theorem", "s756e7573656443425a4e6174697665|def"), "M", "native") + + def test_module_single_component_alias_cannot_impersonate_dotted_module(self): + text = BASE.replace("CBZ|MODULE|s4d|", "CBZ|MODULE|s412e42|").replace("CBZ|DECL|s4d|", "CBZ|DECL|s412e42|") + with self.assertRaisesRegex(gate.GateError, "module"): + gate.parse_audit(text, ["A.B"]) + + def committed_repo(self, root): + subprocess.run(["git", "init", "--quiet", str(root)], check=True) + (root / "M.lean").write_text("def x : Nat := 1\n") + subprocess.run(["git", "-C", str(root), "add", "M.lean"], check=True) + subprocess.run(["git", "-C", str(root), "-c", "user.name=CBZ test", "-c", "user.email=cbz-test@example.invalid", "commit", "--quiet", "-m", "fixture"], check=True) + return subprocess.check_output(["git", "-C", str(root), "rev-parse", "HEAD"], text=True).strip() + + def test_assume_unchanged_cannot_hide_bytes_from_commit_attestation(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);head = self.committed_repo(root) + subprocess.run(["git", "-C", str(root), "update-index", "--assume-unchanged", "M.lean"], check=True) + (root / "M.lean").write_text("def x : Nat := 999\n") + self.assertEqual(subprocess.check_output(["git", "-C", str(root), "status", "--porcelain"], text=True), "") + with self.assertRaisesRegex(gate.GateError, "HEAD blob"): + gate.attest_sources(root, head, {"M.lean"}) + + def test_matching_commit_bytes_receive_canonical_blob_attestation(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);head = self.committed_repo(root) + report = gate.attest_sources(root, head, {"M.lean"}) + self.assertEqual(report["files"], 1) + self.assertEqual(report["commit"], head) + + def test_dependency_clean_label_cannot_hide_changed_tracked_sources(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);dependency = root / "formal/.lake/packages/mathlib" + dependency.mkdir(parents=True) + head = self.committed_repo(dependency) + subprocess.run(["git", "-C", str(dependency), "update-index", "--assume-unchanged", "M.lean"], check=True) + (dependency / "M.lean").write_text("def x : Nat := 999\n") + with self.assertRaisesRegex(gate.GateError, "HEAD blob"): + gate.share_dependencies(root, {"projects": [{"project": "formal"}]}, {"mathlib": head}) + + def test_standard_core_axiom_is_the_explicit_exception(self): + r = gate.parse_audit(BASE.replace("CBZ|AXIOMS|", "CBZ|AXIOMS|s70726f70657874"), ["M"]) + self.assertEqual(r["axioms"], ["propext"]) + + def test_quoted_single_component_cannot_impersonate_standard_axiom(self): + # This encodes one string component, not the two-component core Name. + with self.assertRaisesRegex(gate.GateError, "forbidden transitive axiom"): + gate.parse_audit(BASE.replace("CBZ|AXIOMS|", "CBZ|AXIOMS|s436c6173736963616c2e63686f696365"), ["M"]) + + def test_terminal_marker_cannot_precede_more_protocol_records(self): + text = BASE.replace("CBZ|END|1|2|3\n", "") + with self.assertRaisesRegex(gate.GateError, "terminal"): + gate.parse_audit("CBZ|END|1|2|3\n" + text, ["M"]) + + def test_negative_control_refuses_missing_axiom_report(self): + text = BASE.replace("CBZ|AXIOMS|\n", "") + with self.assertRaises(gate.GateError): + gate.validate_control(text, "M", "unused_axiom") + + def test_negative_control_refuses_unrelated_parser_failure(self): + with self.assertRaises(gate.GateError): + gate.validate_control(BASE + "CBZ|MADE_UP|axiom\n", "M", "unused_axiom") + + def test_negative_control_must_name_its_actual_forbidden_axiom(self): + text = BASE.replace("CBZ|AXIOMS|", "CBZ|AXIOMS|s736f7272794178") + with self.assertRaises(gate.GateError): + gate.validate_control(text, "M", "native") + + def test_negative_sorry_control_accepts_only_complete_refusal(self): + text = BASE.replace("CBZ|AXIOMS|", "CBZ|AXIOMS|s736f7272794178") + result = gate.validate_control(text, "M", "sorry") + self.assertEqual(result["forbidden_axioms"], ["sorryAx"]) + + def test_empty_project_is_refused_but_empty_aggregator_is_visible(self): + empty = "CBZ|MODULE|s4d|0|0\nCBZ|AXIOMS|\nCBZ|END|1|0|0\n" + with self.assertRaisesRegex(gate.GateError, "empty"): + gate.parse_audit(empty, ["M"]) + r = gate.parse_audit(BASE.replace("CBZ|AXIOMS|", "CBZ|MODULE|s52|0|0\nCBZ|AXIOMS|").replace("END|1|2|3", "END|2|2|3"), ["M", "R"]) + self.assertEqual(r["module_counts"]["R"], 0) + + def test_source_hash_change_prevents_reusing_snapshot(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) / "M.lean";p.write_text("def x := 1\n") + before = gate.digest(p);p.write_text("def x := 2\n") + with self.assertRaisesRegex(gate.GateError, "changed"): + gate.require_unchanged({"M.lean": before}, Path(d)) + + def test_fresh_native_build_removes_old_objects_keeps_dependencies(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d);(p / ".lake/build/lib/lean").mkdir(parents=True) + (p / ".lake/build/lib/lean/Old.olean").write_text("old") + (p / ".lake/packages").mkdir() + (p / ".lake/packages/keep").write_text("dependency") + gate.fresh_build_directory(p) + self.assertFalse((p / ".lake/build").exists()) + self.assertEqual((p / ".lake/packages/keep").read_text(), "dependency") + + def test_symlink_build_directory_is_refused_before_removal(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d);(p / ".lake").mkdir();(p / "victim").mkdir() + (p / ".lake/build").symlink_to(p / "victim", target_is_directory=True) + with self.assertRaisesRegex(gate.GateError, "symlink"): + gate.fresh_build_directory(p) + self.assertTrue((p / "victim").is_dir()) + + def test_real_child_failure_retains_evidence_and_raises(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) + with self.assertRaisesRegex(gate.GateError, "exit 7"): + gate.run_logged([sys.executable, "-c", "import sys; print('actual failure'); sys.exit(7)"], "bad", p, p, 5) + self.assertEqual(json.loads((p / "bad.json").read_text())["returncode"], 7) + self.assertIn("actual failure", (p / "bad.stdout").read_text()) + + def test_real_child_success_retains_output_digest(self): + with tempfile.TemporaryDirectory() as d: + p = Path(d) + r = gate.run_logged([sys.executable, "-c", "print('actual success')"], "ok", p, p, 5) + self.assertEqual(r["returncode"], 0) + self.assertEqual(r["stdout_sha256"], gate.digest(p / "ok.stdout")) + + def test_git_identity_ignores_inherited_foreign_repository_selectors(self): + with tempfile.TemporaryDirectory() as d: + own, foreign = Path(d) / "own", Path(d) / "foreign" + own.mkdir();foreign.mkdir() + subprocess.run(["git", "init", "--quiet", str(own)], check=True) + subprocess.run(["git", "init", "--quiet", str(foreign)], check=True) + with patch.dict(os.environ, {"GIT_DIR": str(foreign / ".git"), "GIT_WORK_TREE": str(foreign)}): + actual = gate.git_output(own, "rev-parse", "--show-toplevel") + self.assertEqual(Path(actual), own) + +if __name__ == "__main__": + unittest.main() + diff --git a/tests/test_cbz_kernel_mutations.py b/tests/test_cbz_kernel_mutations.py new file mode 100644 index 000000000..a21dfebe4 --- /dev/null +++ b/tests/test_cbz_kernel_mutations.py @@ -0,0 +1,136 @@ +"""The mutation harness must accept only intended assertion kills, never broken tests.""" +import importlib.util +import contextlib +import io +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +PATH = Path(__file__).resolve().parents[1] / "tools/cbz_kernel_mutations.py" +harness = None +if PATH.exists(): + spec = importlib.util.spec_from_file_location("cbz_kernel_mutations", PATH) + harness = importlib.util.module_from_spec(spec) + spec.loader.exec_module(harness) + +SELECTOR = "test_cbz_kernel_gate.NativeGateTests.test_target" +KILL = """FAIL: test_target (test_cbz_kernel_gate.NativeGateTests.test_target) +AssertionError: guard escaped +Ran 1 test in 0.001s +FAILED (failures=1) +""" + +class MutationHarnessTests(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(harness, "kernel mutation harness is not implemented") + + def test_exact_assertion_failure_is_a_kill(self): + result = harness.suite_result(1, KILL) + harness.require_kill(result, SELECTOR) + self.assertEqual(result["assertion_failures"], 1) + + def test_clean_success_is_not_a_mutant_kill(self): + result = harness.suite_result(0, "Ran 1 test in 0.001s\nOK\n") + with self.assertRaises(harness.MutationError): + harness.require_kill(result, SELECTOR) + + def test_test_errors_are_not_kills(self): + text = KILL.replace("FAIL:", "ERROR:").replace("failures=1", "errors=1") + with self.assertRaises(harness.MutationError): + harness.require_kill(harness.suite_result(1, text), SELECTOR) + + def test_zero_tests_and_missing_summaries_are_not_kills(self): + for text in ("Ran 0 tests in 0.000s\nOK\n", "Traceback: startup crash\n"): + with self.subTest(text=text), self.assertRaises(harness.MutationError): + harness.require_kill(harness.suite_result(1, text), SELECTOR) + + def test_skipped_tests_are_not_kills(self): + text = KILL.replace("failures=1", "failures=1, skipped=1") + with self.assertRaises(harness.MutationError): + harness.require_kill(harness.suite_result(1, text), SELECTOR) + + def test_unrelated_assertion_does_not_kill_declared_mutant(self): + text = KILL.replace("test_target", "test_other") + with self.assertRaises(harness.MutationError): + harness.require_kill(harness.suite_result(1, text), SELECTOR) + + def test_timeout_or_launch_failure_is_not_a_kill(self): + for code in (124, 127, -9): + with self.subTest(code=code), self.assertRaises(harness.MutationError): + harness.require_kill(harness.suite_result(code, KILL), SELECTOR) + + def test_baseline_requires_all_44_healthy_tests(self): + harness.require_baseline(harness.suite_result(0, "Ran 44 tests in 0.1s\nOK\n")) + for text in ("Ran 0 tests in 0.1s\nOK\n", "Ran 43 tests in 0.1s\nOK\n", + "Ran 44 tests in 0.1s\nOK (skipped=1)\n"): + with self.subTest(text=text), self.assertRaises(harness.MutationError): + harness.require_baseline(harness.suite_result(0, text)) + + def test_stale_duplicate_or_noop_anchor_is_not_a_valid_mutation(self): + for source, before, after in (("x=1\n", "missing", "x=2"), + ("x=1\nx=1\n", "x=1", "x=2"), + ("x=1\n", "x=1", "x=1")): + with self.subTest(source=source), self.assertRaises(harness.MutationError): + harness.apply_mutation(source, before, after) + + def test_mutant_must_be_syntactically_valid_before_test_execution(self): + self.assertEqual(harness.apply_mutation("x=1\n", "x=1", "x=2"), "x=2\n") + with self.assertRaises(harness.MutationError): + harness.apply_mutation("x=1\n", "x=1", "def invalid(") + + def test_early_failure_replaces_current_pass_and_preserves_it_as_history(self): + with tempfile.TemporaryDirectory() as d: + output = Path(d) / "mutations";output.mkdir() + (output / "result.json").write_text('{"status":"PASS","synthetic_test":true}\n') + with patch.object(harness, "CASES", []), contextlib.redirect_stderr(io.StringIO()): + result = harness.main(["--output", str(output)]) + self.assertEqual(result, 1) + self.assertEqual(json.loads((output / "result.json").read_text())["status"], "REFUSED") + self.assertTrue(any(json.loads(p.read_text()).get("synthetic_test") + for p in (output / "history").rglob("result.json"))) + + def kernel(self): + path = PATH.with_name("cbz_kernel_gate.py") + spec = importlib.util.spec_from_file_location("cbz_kernel_custody_test", path) + module = importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + return module + + def test_two_execution_attempts_preserve_receipt_logs_and_g0_evidence(self): + kernel = self.kernel() + with tempfile.TemporaryDirectory() as d: + output = Path(d);(output / "mutations").mkdir() + (output / "mutations/result.json").write_text('{"status":"PASS","synthetic_test":true}\n') + first = kernel.begin_execution(output) + (first / "receipt.json").write_text('{"synthetic_test":true}\n') + (first / "control.log").write_text("first actual-attempt log fixture\n") + kernel.finish_execution(output, first, "PASS") + second = kernel.begin_execution(output) + kernel.finish_execution(output, second, "REFUSED") + self.assertNotEqual(first, second) + self.assertTrue((first / "receipt.json").is_file()) + self.assertEqual((first / "control.log").read_text(), "first actual-attempt log fixture\n") + self.assertFalse((second / "receipt.json").exists()) + self.assertEqual(json.loads((output / "current-execution.json").read_text())["status"], "REFUSED") + self.assertTrue(json.loads((output / "mutations/result.json").read_text())["synthetic_test"]) + + def test_failed_execution_cannot_leave_a_current_success_reference(self): + kernel = self.kernel() + with tempfile.TemporaryDirectory() as d: + root = Path(d);output = root / "evidence" + first = kernel.begin_execution(output) + (first / "receipt.json").write_text('{"synthetic_test":true}\n') + kernel.finish_execution(output, first, "PASS") + with contextlib.redirect_stderr(io.StringIO()): + result = kernel.main(["--execute", "--root", str(root), "--output", str(output), + "--expected-commit", "not-a-commit"]) + self.assertEqual(result, 1) + current = json.loads((output / "current-execution.json").read_text()) + self.assertEqual(current["status"], "REFUSED") + self.assertFalse((output / current["execution"] / "receipt.json").exists()) + self.assertTrue((first / "receipt.json").is_file()) + +if __name__ == "__main__": + unittest.main() + diff --git a/tests/test_cusp_quarantine.py b/tests/test_cusp_quarantine.py new file mode 100644 index 000000000..c10e81a40 --- /dev/null +++ b/tests/test_cusp_quarantine.py @@ -0,0 +1,183 @@ +"""One-packet A3 quarantine boundary controls; no arithmetic certification.""" +from __future__ import annotations + +import json +import hashlib +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "tools/check_cusp_quarantine.py" +PACKET = "frontiers/cusp_coefficient_certified_20261001" +RECORD = "quarantine/Q-CUSP-BINARY64-20261029.json" +QID = "Q-CUSP-BINARY64-20261029" + + +class CuspQuarantine(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="cusp-quarantine-") + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + shutil.copytree(ROOT / PACKET, self.root / PACKET) + (self.root / "PROOF_INDEX.md").write_bytes((ROOT / "PROOF_INDEX.md").read_bytes()) + target = self.root / RECORD + target.parent.mkdir(parents=True) + if (ROOT / RECORD).is_file(): + target.write_bytes((ROOT / RECORD).read_bytes()) + + def cli(self, *args): + flags = ["-B", "-S"] + ["-O"] * sys.flags.optimize + env = {key: value for key, value in os.environ.items() + if key not in {"PYTHONHOME", "PYTHONPATH", "PYTHONOPTIMIZE"}} + return subprocess.run( + [sys.executable, *flags, str(SCRIPT), "--root", str(self.root), *args], + cwd=self.root, env=env, capture_output=True, text=True, timeout=10, + check=False, + ) + + def report(self, result): + self.assertTrue(result.stdout.startswith("{"), result) + self.assertEqual(result.stderr, "", result) + return json.loads(result.stdout) + + def change_record(self, callback): + path = self.root / RECORD + doc = json.loads(path.read_text()) if path.is_file() else {} + callback(doc) + path.write_text(json.dumps(doc, indent=2) + "\n") + + def refused(self, diagnostic, *args): + result = self.cli(*args) + self.assertEqual(result.returncode, 1, result) + doc = self.report(result) + self.assertFalse(doc["cbz_certificate_admitted"]) + self.assertTrue(any(diagnostic in item for item in doc["problems"]), doc) + + def test_record_integrity_never_certifies_arithmetic(self): + result = self.cli() + self.assertEqual(result.returncode, 0, result) + doc = self.report(result) + self.assertEqual(doc["status"], "QUARANTINE_INTEGRITY_OK") + self.assertEqual(doc["layer_a_status"], "A3_NOT_PROVEN") + self.assertFalse(doc["cbz_certificate_admitted"]) + self.assertEqual(doc["preserved_packet_files"], 16) + + def test_packet_cannot_be_consumed_as_cbz_certificate(self): + self.refused("quarantined numerical source", "--consume", PACKET + "/certificate.py") + + def test_normalized_packet_alias_cannot_evade_denial(self): + for path in ("./" + PACKET + "/RESULTS.json", + "frontiers/unused/../cusp_coefficient_certified_20261001/ia.py"): + with self.subTest(path=path): + self.refused("quarantined numerical source", "--consume", path) + + def test_inherited_absolute_intervals_cannot_be_consumed(self): + self.refused( + "quarantined numerical source", "--consume", + "frontiers/cusp_torus_transfer_20261001/RESULTS.json", + ) + + def test_renamed_packet_copy_cannot_evade_denial(self): + path = self.root / "mirror/replay.py" + path.parent.mkdir() + path.write_bytes((self.root / PACKET / "certificate.py").read_bytes()) + self.refused("quarantined numerical source", "--consume", "mirror/replay.py") + + def test_unrelated_source_is_not_silently_certified(self): + result = self.cli("--consume", "formal/Basic.lean") + self.assertEqual(result.returncode, 2, result) + doc = self.report(result) + self.assertEqual(doc["status"], "NOT_COVERED") + self.assertFalse(doc["cbz_certificate_admitted"]) + + def test_missing_record_and_empty_source_inventory_fail_closed(self): + path = self.root / RECORD + if path.is_file(): + path.unlink() + self.refused("missing quarantine record") + + def test_empty_packet_source_inventory_cannot_pass(self): + self.change_record(lambda doc: doc.update(source_files=[])) + self.refused("exact packet inventory") + + def test_record_cannot_admit_certificate_or_drop_denials(self): + self.change_record(lambda doc: doc.update(cbz_certificate_admitted=True)) + self.refused("certificate admission must remain false") + self.change_record(lambda doc: doc.update(cbz_certificate_admitted=False, + denied_certificate_sources=[])) + self.refused("denied source inventory") + + def test_owner_and_maintenance_are_explicit(self): + self.change_record(lambda doc: doc.update(owner="invented owner", maintenance=1)) + self.refused("owner must remain unassigned") + self.change_record(lambda doc: doc.update(owner=None)) + self.refused("maintenance must remain zero") + + def test_packet_bytes_and_tree_are_preserved(self): + path = self.root / PACKET / "ia.py" + path.write_bytes(path.read_bytes() + b"\n# changed\n") + self.refused("packet source identity mismatch") + path = self.root / PACKET / "extra.py" + path.write_text("pass\n") + self.refused("packet tree differs") + + def test_manifest_cannot_rebind_itself_to_modified_packet(self): + changed = self.root / PACKET / "ia.py" + changed.write_bytes(changed.read_bytes() + b"\n# altered arithmetic\n") + def identity(path): + raw = path.read_bytes() + return {"bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(), + "git_blob": hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()} + path = self.root / PACKET / "SOURCE_FILES.json" + manifest = json.loads(path.read_text()) + for row in manifest["files"]: + if row["path"] == "ia.py": + row.update(identity(changed)) + path.write_text(json.dumps(manifest) + "\n") + def rebind_record(doc): + for row in doc["source_files"]: + if row["path"] in (PACKET + "/ia.py", PACKET + "/SOURCE_FILES.json"): + row.update(identity(self.root / row["path"])) + doc["source_snapshot"]["manifest"].update(identity(path)) + self.change_record(rebind_record) + self.refused("frozen packet manifest identity") + + def test_index_must_explicitly_classify_the_quarantine(self): + (self.root / "PROOF_INDEX.md").write_text("# historical index without classification\n") + self.refused("canonical index quarantine") + + def test_index_denial_must_be_boolean_false(self): + path = self.root / "PROOF_INDEX.md" + path.write_text(path.read_text().replace('"cbz_certificate_admitted":false', + '"cbz_certificate_admitted":0')) + self.refused("canonical index quarantine") + + def test_source_byte_count_must_remain_an_exact_integer(self): + self.change_record(lambda doc: doc["source_files"][0].update( + bytes=float(doc["source_files"][0]["bytes"]))) + self.refused("exact packet inventory") + + def test_snapshot_manifest_identity_cannot_disagree_with_frozen_source(self): + self.change_record(lambda doc: doc["source_snapshot"]["manifest"].update(git_blob="0" * 40)) + self.refused("snapshot manifest identity") + + def test_duplicate_record_members_fail_before_overwrite(self): + path = self.root / RECORD + raw = path.read_text() if path.is_file() else "{}" + raw = raw.rstrip().removesuffix("}") + ',"cbz_certificate_admitted":true,"cbz_certificate_admitted":false}' + path.write_text(raw) + self.refused("duplicate JSON member") + + def test_empty_or_escaping_consumer_paths_do_not_pass(self): + for path in ("", "../outside.py", "/tmp/certificate.py"): + with self.subTest(path=path): + self.refused("unsafe consumer path", "--consume", path) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/cbz_kernel_gate.py b/tools/cbz_kernel_gate.py new file mode 100644 index 000000000..363c2eb12 --- /dev/null +++ b/tools/cbz_kernel_gate.py @@ -0,0 +1,829 @@ +#!/usr/bin/env python3 +"""Fresh native Lean kernel/axiom evidence. Never promotes scientific status.""" +from __future__ import annotations +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import sys +import time +import tomllib +import uuid + +PROJECTS = ( + "formal", + "specifications/lean_statements_20261010", + "specifications/lean_statement_proofs_20261011", + "frontiers/cap_first_exit_lean_20261002", + "frontiers/determinant_moment_20261025", + "frontiers/source_smooth_realization_20261011", + "frontiers/source_lifetime_realization_20261017", + "frontiers/source_derivative_gaussian_20261025", +) +ALLOWED_AXIOMS = frozenset({"propext", "Classical.choice", "Quot.sound"}) +ALLOWED_AXIOM_NAMES = frozenset({("propext",), ("Classical", "choice"), ("Quot", "sound")}) +TOOLCHAIN = "leanprover/lean4:v4.34.1" +LEAN_COMMIT = "5045d0056413266e57c625dcd7c365b10e377c52" +MATHLIB_REV = "d13f23b723b8a846827a245b89c10fc7d3f11612" +MODULE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*") +SAFE_KINDS = frozenset({"theorem", "def", "inductive", "ctor", "rec"}) + +class GateError(ValueError): + pass + +class AuditRefused(GateError): + def __init__(self, bad_axioms, bad_declarations, declarations=()): + self.bad_axioms = set(bad_axioms) + self.bad_declarations = list(bad_declarations) + self.declarations = list(declarations) + details = [] + if self.bad_axioms: + details.append("forbidden transitive axiom: " + ", ".join(sorted(render_name(v) for v in self.bad_axioms))) + details.extend("forbidden compiled declaration kind: " + row["kind"] + " " + row["name"] for row in self.bad_declarations) + super().__init__("; ".join(details)) + +def require(ok, message): + if not ok: + raise GateError(message) + +def digest(path): + h = hashlib.sha256() + with Path(path).open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + h.update(block) + return h.hexdigest() + +def write_json(path, value): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + require(not path.is_symlink(), "symlink evidence destination: " + str(path)) + temp = path.with_name(path.name + ".tmp") + require(not temp.is_symlink(), "symlink temporary evidence destination") + temp.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") + temp.replace(path) + +def begin_execution(output): + """Fresh attempt directory; prior successes/failures and separate G0 evidence survive.""" + output = Path(output) + require(not output.is_symlink(), "symlink execution output") + output.mkdir(parents=True, exist_ok=True) + runs = output / "executions" + require(not runs.is_symlink(), "symlink execution history") + runs.mkdir(exist_ok=True) + history = output / "reference-history" + for name in ("receipt.json", "current-execution.json", "result.json"): + old = output / name + if old.exists() or old.is_symlink(): + require(not history.is_symlink(), "symlink reference history") + history.mkdir(exist_ok=True) + old.replace(history / (uuid.uuid4().hex + "-" + name)) + run = runs / ("attempt-" + uuid.uuid4().hex) + run.mkdir() + state = {"status": "RUNNING", "execution": run.relative_to(output).as_posix()} + write_json(output / "current-execution.json", state) + write_json(output / "result.json", state) + return run + +def finish_execution(output, run, status): + output = Path(output) + relative = Path(run).relative_to(output).as_posix() if run is not None else None + current_path = output / "current-execution.json" + current = json.loads(current_path.read_text()) if current_path.is_file() else {} + # Skip an already-replaced reference; same-output callers must serialize. + # This check is not an atomic concurrency lock. + if relative is not None and current.get("execution") != relative: + return + state = {"status": status, "execution": relative} + write_json(current_path, state) + write_json(output / "result.json", state) + +def project_inventory(repo, relative): + repo = Path(repo).resolve() + selected = Path(relative) + require(not selected.is_absolute() and selected.parts and ".." not in selected.parts + and selected.as_posix() == relative, "unsafe project path or escape: " + relative) + root = repo / selected + for ancestor in [repo, *[repo.joinpath(*selected.parts[:i]) for i in range(1, len(selected.parts) + 1)]]: + require(not ancestor.is_symlink(), "symlink project ancestor: " + str(ancestor)) + require(root.resolve().is_relative_to(repo), "native project escape") + require(root.is_dir() and not root.is_symlink(), "missing or symlink project: " + relative) + config = {} + for name in ("lean-toolchain", "lakefile.toml", "lake-manifest.json"): + p = root / name + require(p.is_file() and not p.is_symlink(), "missing or symlink project configuration: " + str(p)) + config[name] = digest(p) + require((root / "lean-toolchain").read_text().strip() == TOOLCHAIN, "unexpected Lean toolchain: " + relative) + lake = tomllib.loads((root / "lakefile.toml").read_text()) + libs = lake.get("lean_lib", []) + require(libs and all(isinstance(v.get("name"), str) and MODULE.fullmatch(v["name"]) for v in libs), + "missing or malformed native library inventory") + src_dirs = {Path(v.get("srcDir", ".")) for v in libs} + require(all(not p.is_absolute() and ".." not in p.parts for p in src_dirs), "unsafe native srcDir") + require(all(".lake" not in p.parts for p in src_dirs), "native srcDir cannot use the excluded .lake cache") + src_dirs = sorted(src_dirs, key=lambda p: len(p.parts), reverse=True) + modules = [] + names = set() + paths, excluded_cache_dirs = native_source_files(root) + for p in paths: + rel = p.relative_to(root) + require(not p.is_symlink() and not any(q.is_symlink() for q in p.parents if q != root.parent), + "symlink native Lean source: " + str(rel)) + src = next((d for d in src_dirs if rel.is_relative_to(d)), None) + require(src is not None, "unmapped native Lean source: " + str(rel)) + name = ".".join(rel.relative_to(src).with_suffix("").parts) + require(MODULE.fullmatch(name) is not None, "invalid native module identity: " + name) + require(name not in names, "duplicate module identity: " + name) + names.add(name) + modules.append({"module": name, "path": rel.as_posix(), "sha256": digest(p), "bytes": p.stat().st_size}) + require(modules, "empty native source inventory: " + relative) + for library in libs: + roots = library.get("roots", [library["name"]]) + require(isinstance(roots, list) and roots and all(isinstance(v, str) and MODULE.fullmatch(v) for v in roots), + "malformed declared native library roots") + for declared in roots: + require(any(name == declared or name.startswith(declared + ".") for name in names), + "missing declared native library root: " + declared) + lock = json.loads((root / "lake-manifest.json").read_text()) + return {"project": relative, "modules": sorted(modules, key=lambda x: x["module"]), + "libraries": [v["name"] for v in libs], "configuration_sha256": config, + "dependency_records": lock.get("packages", []), "excluded_cache_dirs": excluded_cache_dirs} + +def native_source_files(root): + """Visit every source directory explicitly; traversal errors are never an empty census.""" + paths, excluded = [], [] + readable = stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH + executable = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH + def walk(directory): + try: + mode = directory.lstat().st_mode + require(stat.S_ISDIR(mode) and not stat.S_ISLNK(mode), "symlink or non-directory source path: " + str(directory)) + require(mode & readable and mode & executable, "unreadable or inaccessible source directory: " + str(directory)) + with os.scandir(directory) as scan: + entries = sorted(scan, key=lambda e: e.name) + for entry in entries: + path = Path(entry.path) + mode = entry.stat(follow_symlinks=False).st_mode + require(not stat.S_ISLNK(mode), "symlink source entry: " + str(path)) + if directory == root and entry.name == ".lake": + require(stat.S_ISDIR(mode), "native .lake cache must be a directory") + excluded.append(".lake") + continue + if stat.S_ISDIR(mode): + walk(path) + else: + require(stat.S_ISREG(mode), "nonregular native source entry: " + str(path)) + if path.suffix == ".lean": + require(mode & readable, "unreadable native source file: " + str(path)) + try: + text = path.read_bytes().decode("utf-8") + except UnicodeDecodeError as exc: + raise GateError("native source is not UTF-8: " + str(path)) from exc + # Conservative source preflight; the compiled module-header check + # below is authoritative even if future syntax evades this spelling. + require(re.search(r"(?m)^\s*module(?:\s|$)", text) is None, + "native module-system sidecars are not qualified: " + str(path)) + paths.append(path) + except OSError as exc: + raise GateError("inaccessible native source traversal: " + str(directory) + ": " + str(exc)) from exc + walk(root) + return sorted(paths), excluded + +def require_tracked_coverage(snapshot, tracked): + prefixes = [row["project"] + "/" for row in snapshot["projects"]] + expected = {p for p in tracked if p.endswith(".lean") and any(p.startswith(prefix) for prefix in prefixes)} + observed = {row["project"] + "/" + module["path"] for row in snapshot["projects"] for module in row["modules"]} + require(expected == observed, "native tracked/filesystem Lean coverage mismatch: missing=" + + repr(sorted(expected - observed)) + " extra=" + repr(sorted(observed - expected))) + +def require_unchanged(snapshot, root): + for relative, expected in snapshot.items(): + p = Path(root) / relative + require(p.is_file() and not p.is_symlink() and digest(p) == expected, "source changed: " + relative) + +def fresh_build_directory(project): + project = Path(project) + lake = project / ".lake" + require(not lake.is_symlink(), "symlink native .lake directory") + build = lake / "build" + require(not build.is_symlink(), "symlink native build directory") + if build.exists(): + require(build.is_dir(), "native build path is not a directory") + shutil.rmtree(build) + +def decode_name(encoded): + require(isinstance(encoded, str) and encoded, "empty encoded declaration name") + parts = [] + for component in encoded.split("/"): + if component.startswith("s"): + raw = component[1:] + require(bool(raw) and len(raw) % 2 == 0 and re.fullmatch("[0-9a-f]+", raw), "malformed encoded string name") + try: + value = bytes.fromhex(raw).decode("utf-8") + except (ValueError, UnicodeDecodeError) as exc: + raise GateError("malformed encoded UTF-8 name") from exc + parts.append(value) + elif component.startswith("n") and re.fullmatch("0|[1-9][0-9]*", component[1:]): + parts.append(int(component[1:])) + else: + raise GateError("malformed encoded declaration name") + return tuple(parts) + +def render_name(parts): + return ".".join(str(p) for p in parts) + +def parse_audit(text, expected_modules): + require(len(expected_modules) == len(set(expected_modules)) and expected_modules, "invalid expected module inventory") + require(all(MODULE.fullmatch(m) for m in expected_modules), "invalid expected native module name") + expected_names = {tuple(m.split(".")) for m in expected_modules} + counts = {} + declarations = [] + names = set() + axioms = None + terminal = None + for line in text.splitlines(): + if not line.startswith("CBZ|"): + continue + require(terminal is None, "protocol record after terminal END marker") + fields = line.split("|") + tag = fields[1] if len(fields) > 1 else "" + if tag == "MODULE" and len(fields) == 5: + name = decode_name(fields[2]) + require(name not in counts, "duplicate audited module") + require(fields[3].isdigit() and fields[4].isdigit(), "malformed module count") + first, second = int(fields[3]), int(fields[4]) + require(first == second, "independent compiled census disagreement: " + render_name(name)) + counts[name] = first + elif tag == "DECL" and len(fields) == 5: + module = decode_name(fields[2]) + encoded_name = decode_name(fields[3]) + name = render_name(encoded_name) + require(encoded_name not in names, "duplicate compiled declaration") + names.add(encoded_name) + declarations.append({"module": render_name(module), "_module": module, + "encoded_module": fields[2], "name": name, "encoded_name": fields[3], "kind": fields[4]}) + elif tag == "AXIOMS" and len(fields) == 3: + require(axioms is None, "duplicate axiom closure") + encoded = [] if not fields[2] else [decode_name(v) for v in fields[2].split(",")] + require(len(encoded) == len(set(encoded)), "duplicate transitive axiom") + axioms = encoded + elif tag == "END" and len(fields) == 5: + require(terminal is None and all(v.isdigit() for v in fields[2:]), "malformed or duplicate END") + terminal = tuple(int(v) for v in fields[2:]) + else: + raise GateError("unrecognized CBZ audit protocol record: " + line) + require(terminal is not None, "missing END audit marker") + require(axioms is not None, "missing transitive axiom closure") + require(set(counts) == expected_names, "compiled module inventory differs from registered native sources") + require(terminal[:2] == (len(counts), len(declarations)), "terminal audit count mismatch") + require(len(declarations) > 0, "empty project declaration inventory") + require(terminal[2] >= len(declarations), "transitive closure count is smaller than declaration count") + for module, expected_count in counts.items(): + require(sum(x["_module"] == module for x in declarations) == expected_count, "per-module declaration count mismatch") + for row in declarations: + require(row["_module"] in counts, "declaration outside native module inventory") + declarations = [{k: v for k, v in row.items() if k != "_module"} for row in declarations] + bad = set(axioms) - ALLOWED_AXIOM_NAMES + bad_declarations = [row for row in declarations if row["kind"] not in SAFE_KINDS] + if bad or bad_declarations: + raise AuditRefused(bad, bad_declarations, declarations) + return {"declaration_count": len(declarations), "module_counts": {render_name(k): v for k, v in counts.items()}, + "declarations": declarations, "axioms": sorted(render_name(v) for v in axioms), "closure_count": terminal[2], + "protocol_sha256": hashlib.sha256("\n".join(x for x in text.splitlines() if x.startswith("CBZ|")).encode()).hexdigest()} + +def command_environment(): + env = dict(os.environ) + # Local identity checks must inspect the supplied checkout, even when the caller + # inherited a foreign Git selector or a command-line configuration injection. + for name in list(env): + if name in {"GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", + "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_REPLACE_REF_BASE"} or name.startswith("GIT_CONFIG"): + env.pop(name) + env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_SYSTEM=os.devnull, + GIT_NO_REPLACE_OBJECTS="1", GIT_OPTIONAL_LOCKS="0", GIT_TERMINAL_PROMPT="0") + env.pop("LEAN_PATH", None) + return env + +def run_logged(command, label, out, cwd, timeout): + out = Path(out) + out.mkdir(parents=True, exist_ok=True) + require(re.fullmatch("[A-Za-z0-9_.-]+", label), "unsafe command log label") + stdout, stderr = out / (label + ".stdout"), out / (label + ".stderr") + require(not stdout.is_symlink() and not stderr.is_symlink(), "symlink command log") + env = command_environment() + start = time.monotonic() + with stdout.open("wb") as so, stderr.open("wb") as se: + try: + proc = subprocess.run(command, cwd=cwd, env=env, stdout=so, stderr=se, timeout=timeout) + code = proc.returncode + except subprocess.TimeoutExpired: + code = 124 + except OSError as exc: + se.write(str(exc).encode()) + code = 127 + result = {"argv": [str(v) for v in command], "cwd": str(cwd), "returncode": code, + "elapsed_seconds": time.monotonic() - start, "timeout_seconds": timeout, + "stdout_sha256": digest(stdout), "stderr_sha256": digest(stderr)} + write_json(out / (label + ".json"), result) + require(code == 0, label + ": child exit " + str(code)) + return result + +def audit_source(modules): + require(modules and len(modules) == len(set(modules)) and all(MODULE.fullmatch(m) for m in modules), + "unsafe or duplicate generated audit module") + imports = "\n".join("import " + m for m in modules) + names = ", ".join(chr(96) + m for m in modules) + return imports + "\nimport Lean\n" + r""" +open Lean Elab Command +set_option maxRecDepth 100000 +set_option maxHeartbeats 0 +namespace CBZInternalAudit +def hex (s : String) : String := + s.toUTF8.foldl (fun acc b => acc ++ (if b.toNat < 16 then "0" else "") ++ String.ofList (Nat.toDigits 16 b.toNat)) "" +def join (a b : String) : String := if a.isEmpty then b else a ++ "/" ++ b +def enc : Name → String + | .anonymous => "" + | .str p s => join (enc p) ("s" ++ hex s) + | .num p k => join (enc p) ("n" ++ toString k) +def kind (ci : ConstantInfo) : String := + if ci.isUnsafe then "unsafe" else + match ci with + | .thmInfo _ => "theorem" + | .defnInfo v => if v.safety == .safe then "def" else "partial" + | .axiomInfo _ => "axiom" + | .opaqueInfo _ => "opaque" + | .inductInfo _ => "inductive" + | .ctorInfo _ => "ctor" + | .recInfo _ => "rec" + | .quotInfo _ => "quot" +structure St where + visited : NameSet := {} + axioms : NameSet := {} + missing : NameSet := {} +partial def collect (env : Environment) (c : Name) : StateM St Unit := do + unless (← get).visited.contains c do + modify fun s => { s with visited := s.visited.insert c } + let expr (e : Expr) : StateM St Unit := e.getUsedConstants.forM (collect env) + match env.find? c with + | some (.axiomInfo v) => modify (fun s => { s with axioms := s.axioms.insert c }) *> expr v.type + | some (.defnInfo v) => expr v.type *> expr v.value + | some (.thmInfo v) => expr v.type *> expr v.value + | some (.opaqueInfo v) => expr v.type *> expr v.value + | some (.quotInfo _) => pure () + | some (.ctorInfo v) => expr v.type + | some (.recInfo v) => expr v.type + | some (.inductInfo v) => expr v.type *> v.ctors.forM (collect env) + | none => modify fun s => { s with missing := s.missing.insert c } +end CBZInternalAudit +run_cmd do + let env := (← getEnv).setExporting false + let modules : Array Name := #[""" + names + r"""] + let constants := env.constants.toList + let mut audited : Array Name := #[] + for modName in modules do + let some idx := env.getModuleIdx? modName + | throwError "missing native module {modName}" + let data := env.header.moduleData[idx]! + if data.isModule then + throwError "CBZ module-system sidecars are not qualified: {modName}" + let table := data.constants + let headerNames := (table.map (·.name)).qsort Name.lt + let originNames := (constants.filterMap fun (name, _) => + if env.getModuleIdxFor? name == some idx then some name else none).toArray.qsort Name.lt + unless headerNames == originNames do + throwError "independent compiled census disagreement {modName}: {headerNames.size} versus {originNames.size}" + liftIO <| IO.println s!"CBZ|MODULE|{CBZInternalAudit.enc modName}|{headerNames.size}|{originNames.size}" + for name in originNames do + if (env.checked.get.find? name).isNone then + throwError "missing checked kernel declaration {name}" + let some ci := env.find? name | throwError "missing declaration {name}" + liftIO <| IO.println s!"CBZ|DECL|{CBZInternalAudit.enc modName}|{CBZInternalAudit.enc name}|{CBZInternalAudit.kind ci}" + audited := audited.push name + let (_, closure) := (audited.forM (CBZInternalAudit.collect env)).run {} + unless closure.missing.isEmpty do + throwError "missing transitive closure declaration {closure.missing.toArray}" + let axioms := (closure.axioms.toArray.map CBZInternalAudit.enc).qsort (· < ·) + liftIO <| IO.println s!"CBZ|AXIOMS|{",".intercalate axioms.toList}" + liftIO <| IO.println s!"CBZ|END|{modules.size}|{audited.size}|{closure.visited.size}" +""" + +def native_snapshot(repo): + reports = [project_inventory(repo, p) for p in PROJECTS] + binding = {} + for r in reports: + for f in r["modules"]: + binding[r["project"] + "/" + f["path"]] = f["sha256"] + for name, sha in r["configuration_sha256"].items(): + binding[r["project"] + "/" + name] = sha + return {"schema_version": 1, "status": "SOURCE_INVENTORY_ONLY", "scientific_effect": "NONE", + "projects": reports, "project_count": len(reports), "module_count": sum(len(p["modules"]) for p in reports), + "source_binding": binding, "kernel_status": "NOT_EVALUATED"} + +def git_output(repo, *args): + result = subprocess.run(["git", "--no-replace-objects", "-C", str(repo), *args], + text=True, capture_output=True, env=command_environment()) + require(result.returncode == 0, "git identity check failed: " + result.stderr.strip()) + return result.stdout.strip() + +def git_tree_entries(repo, commit): + require(re.fullmatch("[0-9a-f]{40}", commit or ""), "canonical tree requires an exact commit") + result = subprocess.run(["git", "--no-replace-objects", "--literal-pathspecs", "-C", str(repo), + "ls-tree", "-r", "-z", "--full-tree", commit], + capture_output=True, env=command_environment()) + require(result.returncode == 0, "cannot read canonical Git tree") + entries = {} + for record in result.stdout.split(b"\0"): + if not record: + continue + try: + metadata, raw_path = record.split(b"\t", 1) + mode, kind, blob = metadata.decode("ascii").split(" ") + path = raw_path.decode("utf-8") + except (ValueError, UnicodeError) as exc: + raise GateError("malformed canonical Git tree record") from exc + require(path not in entries and re.fullmatch("[0-9a-f]{40}", blob), "duplicate or malformed Git tree entry") + entries[path] = {"mode": mode, "kind": kind, "blob": blob} + require(entries, "empty canonical Git tree") + return entries + +def attest_sources(repo, commit, paths, entries=None): + """Bind actual consumed bytes to commit blobs; index flags/status cannot substitute.""" + repo = Path(repo).resolve() + entries = git_tree_entries(repo, commit) if entries is None else entries + rows = [] + for relative in sorted(paths): + pure = Path(relative) + require(not pure.is_absolute() and ".." not in pure.parts and pure.as_posix() == relative, + "unsafe consumed source path") + entry = entries.get(relative) + require(entry is not None and entry["kind"] == "blob" and entry["mode"] in {"100644", "100755"}, + "unsupported or missing HEAD blob source mode: " + relative) + path = repo / pure + require(path.is_file() and not any(p.is_symlink() for p in [path, *path.parents] if p != repo.parent), + "missing or symlink HEAD blob source: " + relative) + data = path.read_bytes() + blob = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest() + require(blob == entry["blob"], "consumed bytes differ from HEAD blob: " + relative) + rows.append({"path": relative, "git_blob": blob, "sha256": hashlib.sha256(data).hexdigest(), "mode": entry["mode"]}) + return {"commit": commit, "files": len(rows), "source_records": rows, + "records_sha256": hashlib.sha256(json.dumps(rows, sort_keys=True).encode()).hexdigest()} + +def dependency_pins(snapshot): + expected = None + for project in snapshot["projects"]: + records = project["dependency_records"] + require(isinstance(records, list), "malformed native dependency lock") + pins = {} + for record in records: + if record.get("type") == "path": + require(project["project"] == "specifications/lean_statement_proofs_20261011" + and record.get("name") == "universal_law_specifications" + and record.get("dir") == "../lean_statements_20261010", "unexpected path dependency") + continue + require(record.get("type") == "git" and isinstance(record.get("name"), str) + and re.fullmatch("[0-9a-f]{40}", record.get("rev", "")), "invalid Git dependency lock") + require(record["name"] not in pins, "duplicate dependency lock") + pins[record["name"]] = record["rev"] + require(pins.get("mathlib") == MATHLIB_REV, "unexpected Mathlib revision") + require(expected is None or pins == expected, "native projects have inconsistent dependency revisions") + expected = pins + return expected + +def share_dependencies(repo, snapshot, pins): + shared = Path(repo) / "formal/.lake/packages" + verified = {} + for name, revision in pins.items(): + path = shared / name + require(path.is_dir() and git_output(path, "rev-parse", "HEAD") == revision, "dependency checkout differs from pinned revision: " + name) + require(not git_output(path, "status", "--porcelain", "--untracked-files=normal"), "dirty dependency checkout: " + name) + entries = git_tree_entries(path, revision) + attestation = attest_sources(path, revision, set(entries), entries) + verified[name] = {"revision": revision, "path": str(path.resolve()), "tracked_source_attestation": attestation, + "compiled_cache_trust": "Pinned dependency cache accepted; dependency objects are not claimed freshly rebuilt or independently source-qualified."} + for report in snapshot["projects"]: + packages = Path(repo) / report["project"] / ".lake/packages" + if packages == shared: + continue + require(not packages.is_symlink(), "symlink packages root") + packages.mkdir(parents=True, exist_ok=True) + for name in pins: + dest = packages / name + target = shared / name + if dest.exists() or dest.is_symlink(): + require(dest.resolve() == target.resolve(), "pre-existing unrelated dependency materialization: " + str(dest)) + else: + dest.symlink_to(target.resolve(), target_is_directory=True) + return verified + +def import_names(text): + # Actual native compilation remains authoritative for unsupported import syntax. + clean = re.sub(r"/-.*?-/", "", text, flags=re.S) + result = [] + for line in clean.splitlines(): + line = line.split("--", 1)[0].strip() + if line.startswith("import ") or line.startswith("public import "): + names = line.removeprefix("public ").removeprefix("import ").split() + require(all(MODULE.fullmatch(n) for n in names), "unsupported native import syntax") + result.extend(names) + return result + +def compile_missing(project, modules, out, timeout): + by_name = {m["module"]: m for m in modules} + done = set() + active = set() + def visit(name): + if name in done: + return + require(name not in active, "cyclic native imports: " + name) + active.add(name) + row = by_name[name] + for dep in import_names((project / row["path"]).read_text()): + if dep in by_name: + visit(dep) + obj = project / ".lake/build/lib/lean" / (name.replace(".", "/") + ".olean") + if not obj.is_file(): + obj.parent.mkdir(parents=True, exist_ok=True) + run_logged(["lake", "env", "lean", "-o", str(obj), row["path"]], "orphan-" + name, out, project, timeout) + require(obj.is_file() and not obj.is_symlink(), "native module did not produce fresh object: " + name) + active.remove(name) + done.add(name) + for name in by_name: + visit(name) + +def validate_control(text, module, label): + try: + parse_audit(text, [module]) + except AuditRefused as exc: + expected = {"sorry": {("sorryAx",)}} + if label == "unused_axiom": + require(len(exc.bad_declarations) == 1 and exc.bad_declarations[0]["kind"] == "axiom" + and decode_name(exc.bad_declarations[0]["encoded_name"]) == ("unusedCBZPremise",) + and exc.bad_axioms == {("unusedCBZPremise",)}, "unused-axiom control refused for an unrelated finding") + elif label == "native": + # Lean 4.34.1 Native.lean: nativeEqTrue adds a generated axiom via + # mkAuxDeclName (`_native ++ `native_decide ++ `ax). CoreM appends + # positive elaboration indices. This is qualified by a real hosted fixture; + # no concrete helper name is claimed observed before that execution. + require(len(exc.bad_declarations) == 1 and exc.bad_declarations[0]["kind"] == "axiom", + "native control must expose its one generated axiom") + name = decode_name(exc.bad_declarations[0]["encoded_name"]) + require(len(name) == 4 and name[:3] == ("unusedCBZNative", "_native", "native_decide") + and isinstance(name[3], str) and re.fullmatch(r"ax_[1-9][0-9]*(?:_[1-9][0-9]*)*", name[3]), + "native control refused an unrelated generated axiom") + require(exc.bad_axioms == {name}, "native control closure differs from its generated axiom") + require(any(row["kind"] == "theorem" and decode_name(row["encoded_name"]) == ("unusedCBZNative",) + for row in exc.declarations), "native control omitted its actual theorem") + else: + require(label in expected and exc.bad_axioms == expected[label] and not exc.bad_declarations, + "negative control refused for an unrelated forbidden declaration or axiom: " + label) + return {"outcome": "REJECTED_EXPECTED_FORBIDDEN_DECLARATION_OR_AXIOM", "diagnostic": str(exc), + "forbidden_axioms": sorted(render_name(v) for v in exc.bad_axioms)} + raise GateError("negative control escaped: " + label) + +def generated_theorem_value_mutation(project, out, timeout, module): + """A real compiled sorry fixture must expose omitted theorem-value traversal.""" + original = audit_source([module]) + before = "| some (.thmInfo v) => expr v.type *> expr v.value" + after = "| some (.thmInfo v) => expr v.type" + require(original.count(before) == 1, "stale generated-auditor theorem-value mutation") + path = out / "MutatedTheoremValueAudit.lean" + path.write_text(original.replace(before, after, 1)) + run = run_logged(["lake", "env", "lean", str(path)], "generated-theorem-value-mutant", out, project, timeout) + require(not (out / "generated-theorem-value-mutant.stderr").read_text().strip(), + "generated auditor mutant produced unexpected diagnostics") + text = (out / "generated-theorem-value-mutant.stdout").read_text() + # The deliberately broken collector must run and parse, then the compiled sorry + # control must detect its false clear result. A Lean crash is never a mutation kill. + accepted = parse_audit(text, [module]) + require("sorryAx" not in accepted["axioms"], "generated theorem-value mutant did not remove the intended dependency") + try: + validate_control(text, module, "sorry") + except GateError as exc: + require(type(exc) is GateError and str(exc) == "negative control escaped: sorry", + "generated auditor mutant failed for an unrelated reason") + diagnostic = str(exc) + else: + raise GateError("generated theorem-value mutant was not detected by the compiled control") + result = {"id": "omit_generated_theorem_value_traversal", "outcome": "KILLED_BY_COMPILED_SORRY_CONTROL", + "scope": "One actual generated Lean collector mutation; not a general generated-code mutation certificate.", + "mutation_location_count": 1, "baseline_source_sha256": hashlib.sha256(original.encode()).hexdigest(), + "mutant_source_sha256": digest(path), "command": run, + "mutated_audit_report": accepted, "control_diagnostic": diagnostic} + write_json(out / "generated-theorem-value-result.json", result) + return result + +def negative_controls(project, out, timeout): + out.mkdir(parents=True, exist_ok=True) + # Exercise the generated Lean API and the empty-aggregator case before any long build. + positive = project / ".lake/CBZControl_positive.lean" + empty = project / ".lake/CBZControl_empty.lean" + positive.write_text("import Lean\ndef cbzValidValue : Nat := 2\ntheorem cbzValidProof : cbzValidValue = 2 := rfl\n") + empty.write_text("import CBZControl_positive\n") + retained = out / "sources" + retained.mkdir(parents=True, exist_ok=True) + positive_sources = {source.name: digest(source) for source in (positive, empty)} + for source in (positive, empty): + shutil.copyfile(source, retained / source.name) + positive_objects = {} + target = project / ".lake/build/lib/lean" + target.mkdir(parents=True, exist_ok=True) + for source in (positive, empty): + module = source.stem + run_logged(["lake", "env", "lean", "--root=" + str(project / ".lake"), + "-o", str(target / (module + ".olean")), str(source)], + "positive-" + module + "-compile", out, project, timeout) + positive_objects[module] = digest(target / (module + ".olean")) + run_logged(["lake", "env", "leanchecker", module], "positive-" + module + "-kernel", out, project, timeout) + baseline = out / "PositiveAudit.lean" + baseline.write_text(audit_source([positive.stem, empty.stem])) + run_logged(["lake", "env", "lean", str(baseline)], "positive-audit", out, project, timeout) + positive_report = parse_audit((out / "positive-audit.stdout").read_text(), [positive.stem, empty.stem]) + require(positive_report["module_counts"][empty.stem] == 0, "empty-aggregator positive control is not empty") + require({"cbzValidValue", "cbzValidProof"} <= {r["name"] for r in positive_report["declarations"]}, + "positive control omitted its actual named declarations") + positive_sources_after = {source.name: digest(source) for source in (positive, empty)} + positive_objects_after = {name: digest(target / (name + ".olean")) for name in positive_objects} + require(positive_sources_after == positive_sources and positive_objects_after == positive_objects, + "positive fixture source or object changed during preflight") + positive_report.update(sources_before=positive_sources, sources_after=positive_sources_after, + objects_before=positive_objects, objects_after=positive_objects_after) + write_json(out / "positive-result.json", positive_report) + cases = { + "unused_axiom": ("axiom unusedCBZPremise : False\n", "axiom"), + "sorry": ("private theorem unusedCBZProof : True := by sorry\n", "sorryAx"), + "native": ("theorem unusedCBZNative : (2 : Nat) + 2 = 4 := by native_decide\n", "Lean.ofReduceBool"), + } + reports = {"positive": positive_report} + for label, (body, expected) in cases.items(): + module = "CBZControl_" + label + path = project / ".lake" / (module + ".lean") + path.write_text("import Lean\n" + body) + source_before = digest(path) + shutil.copyfile(path, retained / path.name) + obj = project / ".lake/build/lib/lean" / (module + ".olean") + run_logged(["lake", "env", "lean", "--root=" + str(project / ".lake"), "-o", str(obj), str(path)], + "control-" + label + "-compile", out, project, timeout) + object_before = digest(obj) + run_logged(["lake", "env", "leanchecker", module], "control-" + label + "-kernel", out, project, timeout) + audit = out / ("ControlAudit_" + label + ".lean") + audit.write_text(audit_source([module])) + run_logged(["lake", "env", "lean", str(audit)], "control-" + label + "-audit", out, project, timeout) + text = (out / ("control-" + label + "-audit.stdout")).read_text() + reports[label] = validate_control(text, module, label) + source_after, object_after = digest(path), digest(obj) + require(source_before == source_after and object_before == object_after, + "negative fixture source or object changed during preflight: " + label) + reports[label].update(source_before=source_before, source_after=source_after, + object_before=object_before, object_after=object_after) + write_json(out / (label + "-result.json"), reports[label]) + if label == "sorry": + reports["generated_theorem_value_mutation"] = generated_theorem_value_mutation(project, out, timeout, module) + require(digest(path) == source_before and digest(obj) == object_before, + "compiled sorry fixture changed during generated-auditor mutation") + write_json(out / "controls-result.json", reports) + return reports + +def execute(repo, out, expected_commit, timeout): + require(re.fullmatch("[0-9a-f]{40}", expected_commit or ""), "execute requires a full expected commit") + require(git_output(repo, "rev-parse", "HEAD") == expected_commit, "tested commit differs from expected commit") + require(not git_output(repo, "status", "--porcelain", "--untracked-files=no"), "tracked source worktree is dirty") + snapshot = native_snapshot(repo) + tree_entries = git_tree_entries(repo, expected_commit) + tracked = set(tree_entries) + require(set(snapshot["source_binding"]) <= tracked, "untracked native proof/configuration source") + require_tracked_coverage(snapshot, tracked) + gate_files = {"tools/cbz_kernel_gate.py", "tools/cbz_kernel_registry.json", + "tests/test_cbz_kernel_gate.py", ".github/workflows/cbz-kernel.yml", + "tools/cbz_kernel_mutations.py", "tests/test_cbz_kernel_mutations.py"} + require(gate_files <= tracked, "untracked CBZ gate implementation/configuration") + require(Path(__file__).resolve() == (Path(repo) / "tools/cbz_kernel_gate.py").resolve(), + "running CBZ gate differs from the tested checkout") + gate_binding = {name: digest(Path(repo) / name) for name in gate_files} + canonical_binding = attest_sources(repo, expected_commit, set(snapshot["source_binding"]) | gate_files, tree_entries) + for relative in set(snapshot["source_binding"]) | gate_files: + dest = out / "sources" / relative + dest.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(Path(repo) / relative, dest) + write_json(out / "source-inventory.json", snapshot) + pins = dependency_pins(snapshot) + for row in snapshot["projects"]: + fresh_build_directory(Path(repo) / row["project"]) + dependencies = share_dependencies(repo, snapshot, pins) + run_logged(["lake", "env", "lean", "--version"], "lean-version", out, Path(repo) / "formal", timeout) + version = (out / "lean-version.stdout").read_text().strip() + require(re.fullmatch(r"Lean \(version 4\.34\.1, [^()\r\n]+, commit " + LEAN_COMMIT + r", Release\)", version), + "unexpected actual Lean runtime: " + version) + run_logged(["lake", "env", "lean", "--print-prefix"], "lean-prefix", out, Path(repo) / "formal", timeout) + prefix = Path((out / "lean-prefix.stdout").read_text().strip()) + runtime = {name: {"path": str(prefix / "bin" / name), "sha256": digest(prefix / "bin" / name)} + for name in ("lean", "lake", "leanchecker")} + controls = negative_controls(Path(repo) / "formal", out / "controls", timeout) + reports = [] + object_binding = {} + progress = {"projects": [{"project": row["project"], "status": "NOT_EVALUATED"} for row in snapshot["projects"]]} + write_json(out / "progress.json", progress) + for index, row in enumerate(snapshot["projects"]): + progress["projects"][index]["status"] = "RUNNING" + write_json(out / "progress.json", progress) + project = Path(repo) / row["project"] + logs = out / ("project-" + str(index)) + logs.mkdir(parents=True) + run_logged(["lake", "build"], "native-default-build", logs, project, timeout) + run_logged(["lake", "build", *row["libraries"]], "all-native-libraries-build", logs, project, timeout) + compile_missing(project, row["modules"], logs, timeout) + objects = {} + for module in row["modules"]: + name = module["module"] + obj = project / ".lake/build/lib/lean" / (name.replace(".", "/") + ".olean") + before = digest(obj) + run_logged(["lake", "env", "leanchecker", name], "kernel-" + name, logs, project, timeout) + require(digest(obj) == before, "compiled object changed during kernel replay: " + name) + objects[name] = {"sha256": before, "bytes": obj.stat().st_size} + object_binding[obj.relative_to(repo).as_posix()] = before + names = [m["module"] for m in row["modules"]] + audit = logs / "Environment.lean" + audit.write_text(audit_source(names)) + run_logged(["lake", "env", "lean", str(audit)], "environment", logs, project, timeout) + report = parse_audit((logs / "environment.stdout").read_text(), names) + require_unchanged(snapshot["source_binding"], repo) + report.update(project=row["project"], objects=objects, audit_source_sha256=digest(audit)) + write_json(logs / "audit-report.json", report) + reports.append(report) + progress["projects"][index]["status"] = "KERNEL_AND_AXIOM_AUDIT_PASSED" + write_json(out / "progress.json", progress) + print(json.dumps({"project": row["project"], "modules": len(names), "declarations": report["declaration_count"], "status": "KERNEL_AND_AXIOM_AUDIT_PASSED"}), flush=True) + require_unchanged(snapshot["source_binding"], repo) + require_unchanged(gate_binding, repo) + require_unchanged(object_binding, repo) + require(attest_sources(repo, expected_commit, set(snapshot["source_binding"]) | gate_files) == canonical_binding, + "canonical consumed source attestation changed") + require(git_output(repo, "rev-parse", "HEAD") == expected_commit, "tested checkout HEAD changed during execution") + require(native_snapshot(repo)["source_binding"] == snapshot["source_binding"], "native source inventory changed") + require(not git_output(repo, "status", "--porcelain", "--untracked-files=no"), "tracked source changed during native execution") + share_dependencies(repo, snapshot, pins) + receipt = {"schema_version": 1, "status": "KERNEL_AND_AXIOM_AUDIT_PASSED", "scientific_effect": "NONE", + "checked_commit": expected_commit, "checked_tree": git_output(repo, "rev-parse", "HEAD^{tree}"), + "repository": os.environ.get("GITHUB_REPOSITORY"), "run_id": os.environ.get("GITHUB_RUN_ID"), + "run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"), "lean_version": version, "runtime": runtime, + "dependency_checkouts": dependencies, "dependency_objects_rebuilt_from_source": False, + "allowed_axioms": sorted(ALLOWED_AXIOMS), "projects": reports, "negative_controls": controls, + "source_inventory_sha256": digest(out / "source-inventory.json"), + "gate_source_binding": gate_binding, + "canonical_source_attestation": canonical_binding, + "scope": "Eight native packages only; no semantic or scientific-status closure."} + write_json(out / "receipt.json", receipt) + return receipt + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + action = p.add_mutually_exclusive_group(required=True) + action.add_argument("--inventory", action="store_true") + action.add_argument("--execute", action="store_true") + p.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) + p.add_argument("--output", type=Path, default=Path(".lake/cbz-kernel")) + p.add_argument("--expected-commit") + p.add_argument("--timeout", type=int, default=1800, help="Actual timeout for each compiler/audit command") + args = p.parse_args(argv) + repo = args.root.resolve() + out = args.output if args.output.is_absolute() else repo / args.output + require(not out.is_symlink(), "symlink evidence output") + out.mkdir(parents=True, exist_ok=True) + run = out + try: + if args.execute: + run = begin_execution(out) + require(args.timeout > 0, "nonpositive command timeout") + if args.inventory: + result = native_snapshot(repo) + dependency_pins(result) + write_json(out / "source-inventory.json", result) + else: + result = execute(repo, run, args.expected_commit, args.timeout) + write_json(run / "result.json", {"status": result["status"], "scientific_effect": "NONE"}) + if args.execute: + finish_execution(out, run, result["status"]) + print(json.dumps({k: v for k, v in result.items() if k in ("status", "project_count", "module_count", "kernel_status", "checked_commit")}, sort_keys=True)) + return 0 + except (GateError, OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as exc: + if run != out: + (run / "receipt.json").unlink(missing_ok=True) + if (run / "progress.json").is_file(): + progress = json.loads((run / "progress.json").read_text()) + for row in progress["projects"]: + if row["status"] == "RUNNING": + row.update(status="REFUSED", reason=str(exc)) + write_json(run / "progress.json", progress) + write_json(run / "result.json", {"status": "REFUSED", "scientific_effect": "NONE", "reason": str(exc), + "kernel_status": "NOT_ESTABLISHED"}) + if args.execute: + finish_execution(out, run if run != out else None, "REFUSED") + print("CBZ kernel gate REFUSED: " + str(exc), file=sys.stderr) + return 1 + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/tools/cbz_kernel_mutations.py b/tools/cbz_kernel_mutations.py new file mode 100644 index 000000000..f8ca1e131 --- /dev/null +++ b/tools/cbz_kernel_mutations.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Eight bounded source-guard mutations; crashes/errors/skips never count as kills.""" +from __future__ import annotations +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import uuid + +ROOT = Path(__file__).resolve().parents[1] +TOOL = Path("tools/cbz_kernel_gate.py") +TEST = Path("tests/test_cbz_kernel_gate.py") +EXPECTED_BASELINE_TESTS = 44 +CASES = [ + ("independent_census", + 'require(first == second, "independent compiled census disagreement: " + render_name(name))', + 'require(True, "independent compiled census disagreement: " + render_name(name))', + "test_independent_census_disagreement_is_refused"), + ("unused_custom_axiom", + 'bad_declarations = [row for row in declarations if row["kind"] not in SAFE_KINDS]', + 'bad_declarations = []', + "test_unused_custom_axiom_is_refused_even_with_empty_union"), + ("unsafe_definition", + 'SAFE_KINDS = frozenset({"theorem", "def", "inductive", "ctor", "rec"})', + 'SAFE_KINDS = frozenset({"theorem", "def", "inductive", "ctor", "rec", "unsafe"})', + "test_unsafe_definition_is_refused"), + ("transitive_sorry", + 'bad = set(axioms) - ALLOWED_AXIOM_NAMES', + 'bad = set()', + "test_transitive_sorry_is_refused"), + ("head_blob_binding", + 'require(blob == entry["blob"], "consumed bytes differ from HEAD blob: " + relative)', + 'require(True, "consumed bytes differ from HEAD blob: " + relative)', + "test_assume_unchanged_cannot_hide_bytes_from_commit_attestation"), + ("source_subdirectory_omission", + 'if stat.S_ISDIR(mode):\n walk(path)', + 'if stat.S_ISDIR(mode):\n continue', + "test_unreadable_source_directory_is_refused_even_for_privileged_runner"), + ("terminal_completeness", + 'require(terminal is not None, "missing END audit marker")', + 'if terminal is None:\n terminal = (len(counts), len(declarations), len(declarations))', + "test_missing_terminal_marker_is_refused"), + ("native_control_nontheorem", + 'require(any(row["kind"] == "theorem" and decode_name(row["encoded_name"]) == ("unusedCBZNative",)\n for row in exc.declarations), "native control omitted its actual theorem")', + 'require(True, "native control omitted its actual theorem")', + "test_native_control_requires_the_actual_named_theorem"), +] + +class MutationError(ValueError): + pass + +def require(condition, message): + if not condition: + raise MutationError(message) + +def sha(data): + return hashlib.sha256(data).hexdigest() + +def suite_result(returncode, output): + runs = re.findall(r"^Ran ([0-9]+) tests? in .+$", output, re.M) + summaries = re.findall(r"^(?:OK(?: \([^\n]*\))?|FAILED \([^\n]*\))$", output, re.M) + valid = len(runs) == 1 and len(summaries) == 1 + summary = summaries[0] if valid else "" + counts = dict(re.findall(r"(failures|errors|skipped)=([0-9]+)", summary)) + return {"returncode": returncode, "valid_protocol": valid, + "tests_run": int(runs[0]) if valid else 0, + "assertion_failures": int(counts.get("failures", 0)), + "test_errors": int(counts.get("errors", 0)), + "tests_skipped": int(counts.get("skipped", 0)), + "failing_tests": re.findall(r"^FAIL: [^\n]* \(([^\n)]+)\)$", output, re.M), + "error_tests": re.findall(r"^ERROR: [^\n]* \(([^\n)]+)\)$", output, re.M), + "has_assertion_error": "AssertionError" in output, + "summary": summary} + +def require_baseline(result): + require(result["valid_protocol"] and result["returncode"] == 0 + and result["tests_run"] == EXPECTED_BASELINE_TESTS + and result["assertion_failures"] == result["test_errors"] == result["tests_skipped"] == 0 + and not result["failing_tests"] and not result["error_tests"] + and result["summary"].startswith("OK"), "unmodified 44-test baseline is not healthy") + +def require_kill(result, selector): + require(result["valid_protocol"] and result["returncode"] == 1 and result["tests_run"] == 1 + and result["assertion_failures"] == 1 and result["test_errors"] == 0 + and result["tests_skipped"] == 0 and result["failing_tests"] == [selector] + and not result["error_tests"] and result["has_assertion_error"], + "mutant was not killed by its one intended assertion; errors/skips/crashes are not kills") + +def apply_mutation(source, before, after): + require(before != after and source.count(before) == 1, "stale, duplicate or no-op mutation anchor") + changed = source.replace(before, after, 1) + require(changed != source, "unchanged mutation") + try: + compile(changed, "", "exec") + except SyntaxError as exc: + raise MutationError("mutant does not compile") from exc + return changed + +def run_suite(work, output, label, mode, selector=None): + command = [sys.executable, "-B", "-S", *(["-O"] if mode == "optimized" else [])] + if selector: + command += ["-m", "unittest", selector, "-v"] + cwd = work / "tests" + else: + command += ["-m", "unittest", "discover", "-s", "tests", "-p", TEST.name, "-v"] + cwd = work + environment = {k: v for k, v in os.environ.items() + if k not in {"PYTHONHOME", "PYTHONPATH", "PYTHONOPTIMIZE", "PYTHONSTARTUP", "PYTHONINSPECT"}} + environment["PYTHONDONTWRITEBYTECODE"] = "1" + try: + child = subprocess.run(command, cwd=cwd, env=environment, capture_output=True, text=True, timeout=60) + stdout, stderr, code = child.stdout, child.stderr, child.returncode + except subprocess.TimeoutExpired as exc: + def text(value): + return value.decode("utf-8", "backslashreplace") if isinstance(value, bytes) else value or "" + stdout, stderr, code = text(exc.stdout), text(exc.stderr), 124 + except OSError as exc: + stdout, stderr, code = "", str(exc), 127 + path = output / (label + "-" + mode + ".log") + path.write_text(stdout + stderr) + result = suite_result(code, stdout + stderr) + result.update(command=command, cwd=str(cwd), log=path.name, log_sha256=sha(path.read_bytes())) + return result + +def execute(output): + require(not output.is_symlink(), "symlink mutation output") + if output.exists() and any(output.iterdir()): + previous = output.with_name(output.name + ".previous-" + uuid.uuid4().hex) + output.replace(previous) + output.mkdir(parents=True) + (output / "history").mkdir() + previous.replace(output / "history" / previous.name) + else: + output.mkdir(parents=True, exist_ok=True) + report = {"schema_version": 1, "status": "RUNNING", "scope": "Eight Python source guards only; generated Lean mutation is executed by the real control preflight.", + "source_binding": None, "expected_baseline_tests": EXPECTED_BASELINE_TESTS, + "declared_mutants": len(CASES), "baselines": {}, "mutants": []} + output.mkdir(parents=True, exist_ok=True) + def retain(): + (output / "result.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + retain() + try: + require(CASES and len({c[0] for c in CASES}) == len(CASES), "empty or duplicate declared mutation inventory") + source = (ROOT / TOOL).read_text() + tests = (ROOT / TEST).read_bytes() + binding = {"tool_sha256": sha(source.encode()), "test_sha256": sha(tests)} + report["source_binding"] = binding + retain() + # Check every declared location before running; a stale case is never dropped. + mutated = {name: apply_mutation(source, before, after) for name, before, after, _ in CASES} + with tempfile.TemporaryDirectory(prefix="cbz-kernel-mutations-") as temp: + work = Path(temp) + (work / TOOL.parent).mkdir() + (work / TEST.parent).mkdir() + (work / TOOL).write_text(source) + (work / TEST).write_bytes(tests) + for mode in ("normal", "optimized"): + result = run_suite(work, output, "baseline", mode) + report["baselines"][mode] = result + retain() + require_baseline(result) + for name, before, after, method in CASES: + selector = "test_cbz_kernel_gate.NativeGateTests." + method + row = {"id": name, "selector": selector, "mutation_location_count": 1, + "mutated_source_sha256": sha(mutated[name].encode()), "runs": {}} + report["mutants"].append(row) + (work / TOOL).write_text(mutated[name]) + try: + for mode in ("normal", "optimized"): + result = run_suite(work, output, name, mode, selector) + row["runs"][mode] = result + retain() + require_kill(result, selector) + row["outcome"] = "KILLED_BY_INTENDED_ASSERTION_IN_BOTH_MODES" + finally: + (work / TOOL).write_text(source) + retain() + require(sha((ROOT / TOOL).read_bytes()) == binding["tool_sha256"] + and sha((ROOT / TEST).read_bytes()) == binding["test_sha256"], + "auditor source/test changed during mutation execution") + report.update(status="PASS", killed_mutants=len(report["mutants"]), + threshold="All eight declared nonstale mutants killed in both modes; zero errors/skips/startup failures") + retain() + return report + except (MutationError, OSError, ValueError, TypeError) as exc: + report.update(status="REFUSED", reason=str(exc)) + retain() + raise + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=Path(".lake/cbz-kernel/mutations")) + args = parser.parse_args(argv) + output = args.output if args.output.is_absolute() else ROOT / args.output + try: + report = execute(output) + except (MutationError, OSError, ValueError, TypeError) as exc: + print("CBZ kernel mutation gate REFUSED: " + str(exc), file=sys.stderr) + return 1 + print(json.dumps({"status": report["status"], "declared_mutants": report["declared_mutants"], + "killed_mutants": report["killed_mutants"], "scope": report["scope"]})) + return 0 + +if __name__ == "__main__": + raise SystemExit(main()) + diff --git a/tools/cbz_kernel_registry.json b/tools/cbz_kernel_registry.json new file mode 100644 index 000000000..810f762c7 --- /dev/null +++ b/tools/cbz_kernel_registry.json @@ -0,0 +1,65 @@ +{ + "schema_version": 1, + "tool_id": "CBZ-MATH-NATIVE-KERNEL-01", + "entrypoint": "tools/cbz_kernel_gate.py", + "workflow": ".github/workflows/cbz-kernel.yml", + "tests": "tests/test_cbz_kernel_gate.py", + "status": "CANDIDATE_NOT_HOSTED_EXECUTED", + "scientific_effect": "NONE", + "runtime": { + "lean": "leanprover/lean4:v4.34.1", + "lean_commit": "5045d0056413266e57c625dcd7c365b10e377c52", + "mathlib": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "python": "3.11.16" + }, + "inventory_command": "python3 -B -S tools/cbz_kernel_gate.py --inventory", + "execution_command": "python3 -B -S tools/cbz_kernel_gate.py --execute --expected-commit \"$GITHUB_SHA\"", + "scope": "All native Lean sources in the eight fixed package roots; explicit srcDir mappings; no proof, bound or scientific status changes.", + "outputs": ".lake/cbz-kernel/", + "failure_behavior": "REFUSED terminal result; no success receipt; retain actual command exits and stdout/stderr.", + "success_requirements": [ + "exact source checkout and pinned dependency commits", + "all native project build directories freshly removed", + "native library builds and standalone orphan modules", + "standalone leanchecker on every inventoried module", + "independent compiled header/environment-origin census agreement", + "every native declaration in checked kernel environment", + "all-declaration transitive axiom closure inside explicit core set", + "compiled unused-axiom, sorry and native_decide controls refused for exact forbidden findings", + "final source and dependency identity readback" + ], + "allowed_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "not_established": [ + "local or hosted Lean execution before the workflow runs", + "mathematical semantic alignment", + "all Mathlib objects rebuilt from source", + "all Lean files outside the eight native package roots", + "parent theorem or scientific status closure" + ], + "mutation_entrypoint": "tools/cbz_kernel_mutations.py", + "mutation_tests": "tests/test_cbz_kernel_mutations.py", + "mutation_command": "python3 -B -S tools/cbz_kernel_mutations.py --output .lake/cbz-kernel/mutations", + "mutation_threshold": { + "unmodified_baseline_tests_per_mode": 44, + "declared_python_source_mutants": 8, + "modes": [ + "normal", + "optimized" + ], + "required": "Every nonstale compiling mutant must yield exactly its intended assertion failure, positive count, zero errors/skips/startup failures; stale cases refuse.", + "actual_generated_lean_mutants": 1, + "generated_threshold": "Omitting theorem-value traversal must compile/run and be detected by the compiled sorry control before long native builds." + }, + "execution_custody": { + "attempts": "Fresh executions/attempt-/ directory per --execute call", + "current_reference": "current-execution.json", + "receipt": "receipt.json inside the referenced execution directory", + "prior_attempts": "Preserved complete/incomplete; never reused or overwritten", + "g0_mutations": "Separate mutations/result.json; prior mutation outputs retained under mutations/history/", + "failure": "New current reference is REFUSED with no new success receipt; earlier receipts/logs remain historical." + } +} diff --git a/tools/check_cusp_quarantine.py b/tools/check_cusp_quarantine.py new file mode 100644 index 000000000..780cf30fd --- /dev/null +++ b/tools/check_cusp_quarantine.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""One source-bound cusp quarantine boundary, not a general A3 certifier.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import posixpath +import re + +QID = "Q-CUSP-BINARY64-20261029" +BASE = "8151f592918a845bf19eb8eafaf8444540a32734" +PACKET = "frontiers/cusp_coefficient_certified_20261001" +RECORD = "quarantine/" + QID + ".json" +MANIFEST_BLOB = "e9624bdeb78e9fe37f8fbacf45958b9b93f1cf95" +DENIED = frozenset(( + PACKET, + "frontiers/cusp_torus_transfer_20261001/RESULTS.json", + "frontiers/cusp_torus_transfer_20261001/transfer.py", + "frontiers/c2_torus_transfer_20261001/NOTE.md", + "frontiers/c2_torus_transfer_20261001/SOURCE_MAP.json", + "frontiers/c2_exact_20261001/NOTE.md", + "frontiers/third_order_coefficient_20261001/NOTE.md", + "frontiers/third_order_coefficient_20261001/README.md", + "frontiers/third_order_coefficient_20261001/SOURCES.json", + "frontiers/remainder_vanishing_20260930/ERRATUM_20261004.md", +)) + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON member " + ascii(key)) + result[key] = value + return result + + +def strict_json(raw): + return json.loads(raw, object_pairs_hook=unique_object) + + +def blob(raw): + return hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest() + + +def regular(root, relative): + path = root / relative + if not path.is_file() or any(p.is_symlink() for p in [path, *path.parents] + if p != root and root in p.parents): + raise ValueError("regular local source required: " + relative) + return path.read_bytes() + + +def normalized_consumer(value): + if (not isinstance(value, str) or not value or value.startswith("/") + or "\\" in value or ":" in value or "\0" in value): + raise ValueError("unsafe consumer path: " + ascii(value)) + result = posixpath.normpath(value) + if result == ".." or result.startswith("../"): + raise ValueError("unsafe consumer path: " + ascii(value)) + return result + + +def audit(root): + record_path = root / RECORD + if not record_path.is_file(): + raise ValueError("missing quarantine record: " + RECORD) + doc = strict_json(regular(root, RECORD)) + if not isinstance(doc, dict) or doc.get("schema") != "cbz.quarantine/v1" or doc.get("id") != QID: + raise ValueError("unsupported quarantine record") + if (doc.get("classification") != "QUARANTINED" or doc.get("layer_a") != "A3" + or doc.get("layer_a_status") != "A3_NOT_PROVEN"): + raise ValueError("quarantine A3 classification must remain explicit") + if doc.get("cbz_certificate_admitted") is not False: + raise ValueError("certificate admission must remain false") + if doc.get("owner") is not None: + raise ValueError("owner must remain unassigned") + if type(doc.get("maintenance")) is not int or doc["maintenance"] != 0: + raise ValueError("maintenance must remain zero") + for field in ("title", "mathematical_arithmetic_gap"): + if not isinstance(doc.get(field), str) or not doc[field].strip(): + raise ValueError("nonempty quarantine field required: " + field) + boundary = doc.get("not_proven_boundary") + if not isinstance(boundary, list) or not boundary or not all(isinstance(x, str) and x.strip() for x in boundary): + raise ValueError("not-proven boundary must be nonempty") + snapshot = doc.get("source_snapshot") + if (not isinstance(snapshot, dict) or snapshot.get("commit") != BASE + or snapshot.get("packet_path") != PACKET): + raise ValueError("quarantine source snapshot must remain exact") + denied = doc.get("denied_certificate_sources") + if (not isinstance(denied, list) or not all(isinstance(x, str) for x in denied) + or len(denied) != len(DENIED) or set(denied) != DENIED): + raise ValueError("denied source inventory must remain exact") + raw = regular(root, PACKET + "/SOURCE_FILES.json") + if blob(raw) != MANIFEST_BLOB: + raise ValueError("frozen packet manifest identity mismatch") + manifest = strict_json(raw) + entries = manifest["files"] + names = [entry["path"] for entry in entries] + if any(Path(name).name != name for name in names) or len(names) != 15 or len(set(names)) != 15: + raise ValueError("frozen packet manifest inventory mismatch") + expected_names = set(names) | {"SOURCE_FILES.json"} + if {p.name for p in (root / PACKET).iterdir()} != expected_names: + raise ValueError("packet tree differs from frozen manifest") + expected = {} + for name in sorted(expected_names): + data = regular(root, PACKET + "/" + name) + row = {"path": PACKET + "/" + name, "git_blob": blob(data), + "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)} + expected[row["path"]] = row + for entry in entries: + actual = expected[PACKET + "/" + entry["path"]] + if any(actual[key] != entry[key] for key in ("git_blob", "sha256", "bytes")): + raise ValueError("packet source identity mismatch: " + entry["path"]) + sources = doc.get("source_files") + if (not isinstance(sources, list) or len(sources) != 16 + or any(not isinstance(x, dict) or not isinstance(x.get("path"), str) + or type(x.get("bytes")) is not int for x in sources) + or {x["path"] for x in sources} != set(expected) + or any(x != expected[x["path"]] for x in sources)): + raise ValueError("exact packet inventory required in quarantine record") + if snapshot.get("manifest") != expected[PACKET + "/SOURCE_FILES.json"]: + raise ValueError("snapshot manifest identity mismatch") + index = (root / "PROOF_INDEX.md").read_text(encoding="utf-8") + matches = re.findall(r"", index) + wanted = {"id": QID, "classification": "QUARANTINED", + "layer_a_status": "A3_NOT_PROVEN", "cbz_certificate_admitted": False, "record": RECORD} + entry = strict_json(matches[0]) if len(matches) == 1 else None + if (not isinstance(entry, dict) or entry != wanted + or entry.get("cbz_certificate_admitted") is not False): + raise ValueError("canonical index quarantine classification mismatch") + return {x["git_blob"] for x in sources} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) + parser.add_argument("--consume", action="append", default=[], + help="test explicit numerical-certificate source admission; unrelated sources are NOT_COVERED") + args = parser.parse_args(argv) + report = {"quarantine_id": QID, "scope": "one-packet quarantine integrity and explicit source admission only", + "layer_a_status": "A3_NOT_PROVEN", "cbz_certificate_admitted": False, + "status": "QUARANTINE_INTEGRITY_OK", "preserved_packet_files": 0, "problems": []} + try: + root = args.root.resolve() + known_blobs = audit(root) + report["preserved_packet_files"] = 16 + for value in args.consume: + path = normalized_consumer(value) + denied = path in DENIED or path.startswith(PACKET + "/") + if not denied and (root / path).exists(): + denied = blob(regular(root, path)) in known_blobs + if denied: + report["problems"].append("quarantined numerical source: " + path) + except (ValueError, OSError) as exc: + report["problems"].append(str(exc)) + if report["problems"]: + report["status"] = "REFUSED" + code = 1 + elif args.consume: + report["status"] = "NOT_COVERED" + code = 2 + else: + code = 0 + print(json.dumps(report, indent=2, sort_keys=True)) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) From 0a631dea171071398c05a877f858c5e5997a7753 Mon Sep 17 00:00:00 2001 From: Dylan Roy <249851642+d6g8k5htny-coder@users.noreply.github.com> Date: Thu, 29 Oct 2026 15:04:33 -0500 Subject: [PATCH 2/2] Preserve hosted refusal and report exact compiled census differences Keep strict header/origin equality. Qualify the diagnostic against actual compiled core controls and retain the failed hosted evidence. --- DECISIONS.md | 15 ++++++++++++++ GOVERNANCE.md | 4 +++- STATUS.md | 9 ++++++++- TOOLING.md | 3 +++ tools/cbz_kernel_gate.py | 4 +++- tools/cbz_kernel_registry.json | 36 +++++++++++++++++++++++++++++++++- 6 files changed, 67 insertions(+), 4 deletions(-) diff --git a/DECISIONS.md b/DECISIONS.md index 907c6d525..180c4472a 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -33,3 +33,18 @@ The first hosted native attempt40933241149 at tested merge80bdeac2c7a88b51da13a8 ## 2026-10-29T19:04:15.984661+00:00: preserve current C8 wrapper integration (Phase 2, Layer C) Compose the fixed native gate against e877242cf68fb24c605066f16dd07f513ee75a1d, preserving all five current C8 wrapper engineering files. They change no Lean source or package configuration. No history rewrite, required-check change or mathematical promotion is performed. + + +## 2026-10-29T19:53:31.221784+00:00: preserve second hosted census refusal (Phase3, LayerC) + +Observe actual run40938100721/tested merge7db34c265162dc2538720729ac6212355e4e3e6d. G0 and first two native projects passed in their exact scope; the third refused SpecificationProofs.P15Hazard header/origin census46versus45. Retain artifact12927120552/SHA2566c4fd6359a7e57732468077121ea32cf749024d6d9f160a9a40ffb58b1413eb6 and all actual logs. Correct current surfaces from NOT_EVALUATED to REFUSED; no all-native green, missing-declaration skip or source-success transfer. Investigate exact imported-name identity and enrich diagnostics before any soundness-changing repair. Reversible source/docs only. + + +## 2026-10-29T20:00:31.938206+00:00: separate observed regression success from kernel failure (Phase3, LayerC) + +Native full-suite40938100424/job123674068758 records tested merge7db34c265162dc2538720729ac6212355e4e3e6d/tree203e1b48c2961eb29db415fb2a5f4c12f49428b3 and1149tests in each mode, bareOK/zero unittestskips. Preserve raw decodedlog SHA256b368ac0e1beb8ef3902fb4c249be593c7ece17dcbdfb19eef94a432a80209a90. Do not transfer it to a repaired successor or infer kernel/full-federation/CBZ acceptance. C8 binary64 replay remains diagnostic even when green. Reversible documentary observation. + + +## 2026-10-29T20:04:00.518048+00:00: name the strict census mismatch (Phase3, LayerC) + +Add exact header-only/origin-only Name arrays to the existing generated Lean refusal. Keep the same equality gate and all declarations; do not relax for unexamined imported duplicates.52gate controls normal/O and9critical Python mutants per mode pass. Actual pinned-core preflight passes all positive/empty and negative controls and catches the generated theorem-value mutation. An actual forced-origin-omission fixture exits1 with empty stderr and exact header-only[cbzValidValue]/origin-only[] evidence. Gate SHA256a0ba2b3a8d724e8a2b9b945373c9a8004f2e9982a5400d99ba1dfb7619b06e08;26runtime hashes stable. Preserve all previous receipts; source/debug improvement only, no whole-native success. Reversible. diff --git a/GOVERNANCE.md b/GOVERNANCE.md index f6af98b8c..fd49fa312 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -12,7 +12,7 @@ That checker is opt-in. Other downstream workflows do not automatically enforce Integration source base: 74565f013575b7b05ecfc4034cd5d638ee355353, tree 19b3e91bad1a4d7f5a21b1ea5e273fd300acb6f4. The determinant engineering changes from Math-#528 and their component GOVERNANCE.md, TOOLING.md, STATUS.md and QUARANTINE.json are preserved. The generic native gate does not invent the determinant component's missing compiled_inventory binding or clear its quarantine. -Current native execution status is NOT_EVALUATED. Test counts, old receipts, source scans and workflow success outside the exact audited source/scope do not supply missing kernel evidence. Scientific effect: NONE. +Current all-native execution is REFUSED; full scope is NOT_ESTABLISHED. Test counts, old receipts, source scans and workflow success outside the exact audited source/scope do not supply missing kernel evidence. Scientific effect: NONE. Auditor self-testing is bounded and fail-closed: the declared Python guard mutants require intended assertion kills with healthy positive baselines and no errors/skips; the generated theorem-value collector mutation requires actual Lean execution and detection by the compiled sorry fixture. Missing, stale or unexecuted mutation evidence cannot qualify the auditor. @@ -20,3 +20,5 @@ Auditor self-testing is bounded and fail-closed: the declared Python guard mutan Execution custody is append-only by attempt: fresh execution subdirectories preserve previous complete and incomplete logs/receipts, while a separate current reference states the new outcome. G0 mutation evidence stays separate. An early failure invalidates current success without destroying historical evidence. Layer B dependency metadata rule (2026-10-29): attest the literal Git payload of only the three exact catalogued noncompiler links at their pinned package revisions; never follow them. All Lean, configuration, gate and unknown symlinks remain refused. Link path/mode/blob/payload/hash/role and target_followed=false are explicit receipt records. Complete pinned-tree census and adverse controls support this narrow handling; it grants no broader source or dependency-object qualification. + +A partial hosted attempt is not a whole-scope success. Preserve each project result and the exact failing compiled census; require a new actual final full-scope run after repair. Source-pinned first-project evidence is historical to that tested merge and is not transferred to a successor. diff --git a/STATUS.md b/STATUS.md index f09725b7e..20de5c918 100644 --- a/STATUS.md +++ b/STATUS.md @@ -4,7 +4,7 @@ This is a technical execution/quarantine ledger for the registered tools. It gra | Item | Current status | Missing evidence or boundary | |---|---|---| -| Eight native packages / 119 source modules | NOT_EVALUATED under the new gate | Actual source-pinned fresh native builds, every-module kernel replay, full independent compiled censuses, transitive axiom closure and compiled controls | +| Eight native packages / 119 source modules | REFUSED at the second hosted attempt; full scope NOT_ESTABLISHED | Run40938100721 verified the first two projects, then refused the project2 compiled-census mismatch; remaining projects and final source/object readback are unqualified | | Cusp binary64 coefficient packet | QUARANTINED; A3_NOT_PROVEN | Exact rational/verified-real bound certification and source-bound reconciliation of the denied numerical consumers | | Determinant component gate from Math-#528 | QUARANTINED | Existing compiled_inventory is null; package-specific bound census and repaired-gate execution remain unestablished | | Native module-system sidecars | NOT_QUALIFIED | New module sources and compiled isModule headers are refused by this gate | @@ -24,3 +24,10 @@ Integration base read and source-verified: 74565f013575b7b05ecfc4034cd5d638ee355 ## First actual native attempt and bounded repair Run40933241149, tested merge80bdeac2c7a88b51da13a81d47d458c0d474f0c6, passed auditor controls and Lean installation, then REFUSED before proof builds on a legitimate Batteries documentation symlink. Its174-file/630934-byte artifact12924216223 is retained. The repair enumerates three exact reviewed Batteries/Mathlib metadata links without dereference; all source/configuration and unknown links remain refused. The fixed source has52 kernel controls plus13 harness controls per mode,9/9 Python mutants killed per mode, and an actual compiled-control preflight. The complete eight-project run at the fixed source is NOT_EVALUATED. + + +## Second actual native attempt + +Run40938100721 at feature headfdc723e3d0c0fd7b1f270aad611ac511561c108b tested merge7db34c265162dc2538720729ac6212355e4e3e6d. G0 passed. The formal project (9modules,116declarations) and statement project (6modules,590declarations) each produced kernel/axiom results; project2 then REFUSED because SpecificationProofs.P15Hazard compiled header/origin censuses differ (46versus45). This is a hard refusal, not all-native success. Its366-file/745675-byte artifact12927120552, SHA2566c4fd6359a7e57732468077121ea32cf749024d6d9f160a9a40ffb58b1413eb6, is retained. Diagnosis must account explicitly for actual imported declaration identity; no missing declaration may be silently removed or treated as verified. + +The separate full-regression job in run40938100424 at tested merge7db34c265162dc2538720729ac6212355e4e3e6d/tree203e1b48c2961eb29db415fb2a5f4c12f49428b3 completed1149 root tests normally and1149 with-O, both bareOK and zero unittest skips. This qualifies those two regression executions at that tree; it does not override the separate kernel audit refusal or qualify a later source. The original C8 replay40938100491 also succeeded diagnostically and does not establish A3 exact-bound certification. diff --git a/TOOLING.md b/TOOLING.md index 1b92540d3..99538191c 100644 --- a/TOOLING.md +++ b/TOOLING.md @@ -44,3 +44,6 @@ Component-local determinant commands and the compiled-inventory quarantine are p Each `--execute` call creates a fresh `.lake/cbz-kernel/executions/attempt-/`. Read `.lake/cbz-kernel/current-execution.json` to locate the current attempt; its success receipt lives inside that directory. A failed attempt records REFUSED without a new success receipt. Previous complete/incomplete attempts and their source/control logs remain unchanged. Top-level reference history is retained separately. The source-inventory initial step and G0 mutation evidence remain separate and are not overwritten by native execution. Repeated mutation commands archive the prior mutation output under `mutations/history/`; an early refusal replaces only the current result, never leaves an old PASS as current. Use distinct output roots/checkouts for concurrent invocations. + + +Latest actual attempt: run40938100721 at tested merge7db34c265162dc2538720729ac6212355e4e3e6d refused on project2 P15Hazard compiled census46versus45 after two project results. Artifact12927120552 (745675bytes; SHA2566c4fd6359a7e57732468077121ea32cf749024d6d9f160a9a40ffb58b1413eb6) preserves the failure. The eight-project tool remains unqualified until actual full-scope success. diff --git a/tools/cbz_kernel_gate.py b/tools/cbz_kernel_gate.py index ea9a6f5e7..07bd1a2ce 100644 --- a/tools/cbz_kernel_gate.py +++ b/tools/cbz_kernel_gate.py @@ -411,7 +411,9 @@ def kind (ci : ConstantInfo) : String := let originNames := (constants.filterMap fun (name, _) => if env.getModuleIdxFor? name == some idx then some name else none).toArray.qsort Name.lt unless headerNames == originNames do - throwError "independent compiled census disagreement {modName}: {headerNames.size} versus {originNames.size}" + let headerOnly := headerNames.filter fun name => !originNames.contains name + let originOnly := originNames.filter fun name => !headerNames.contains name + throwError "independent compiled census disagreement {modName}: {headerNames.size} versus {originNames.size}; header-only {headerOnly}; origin-only {originOnly}" liftIO <| IO.println s!"CBZ|MODULE|{CBZInternalAudit.enc modName}|{headerNames.size}|{originNames.size}" for name in originNames do if (env.checked.get.find? name).isNone then diff --git a/tools/cbz_kernel_registry.json b/tools/cbz_kernel_registry.json index 90af0b0cc..5b609b8fa 100644 --- a/tools/cbz_kernel_registry.json +++ b/tools/cbz_kernel_registry.json @@ -4,7 +4,7 @@ "entrypoint": "tools/cbz_kernel_gate.py", "workflow": ".github/workflows/cbz-kernel.yml", "tests": "tests/test_cbz_kernel_gate.py", - "status": "HOSTED_ATTEMPT_REFUSED_REQUALIFICATION_PENDING", + "status": "HOSTED_SECOND_ATTEMPT_REFUSED_CENSUS_DIAGNOSIS_ACTIVE", "scientific_effect": "NONE", "runtime": { "lean": "leanprover/lean4:v4.34.1", @@ -99,5 +99,39 @@ "prior_attempts": "Preserved complete/incomplete; never reused or overwritten", "g0_mutations": "Separate mutations/result.json; prior mutation outputs retained under mutations/history/", "failure": "New current reference is REFUSED with no new success receipt; earlier receipts/logs remain historical." + }, + "second_hosted_attempt": { + "run_id": "40938100721", + "job_id": "123673915168", + "feature_head": "fdc723e3d0c0fd7b1f270aad611ac511561c108b", + "checked_merge_commit": "7db34c265162dc2538720729ac6212355e4e3e6d", + "result": "REFUSED_AT_PROJECT_2_COMPILED_CENSUS", + "reason": "SpecificationProofs.P15Hazard header/origin census46versus45; no full-scope or final readback evidence.", + "completed_project_results": [ + { + "project": "formal", + "modules": 9, + "declarations": 116 + }, + { + "project": "specifications/lean_statements_20261010", + "modules": 6, + "declarations": 590 + } + ], + "artifact": { + "id": "12927120552", + "bytes": 745675, + "files": 366, + "sha256": "6c4fd6359a7e57732468077121ea32cf749024d6d9f160a9a40ffb58b1413eb6" + } + }, + "census_diagnostic_successor": { + "policy": "Strict header/origin equality remains unchanged; refusal now prints both exact Name differences. No missing declaration excluded.", + "gate_sha256": "a0ba2b3a8d724e8a2b9b945373c9a8004f2e9982a5400d99ba1dfb7619b06e08", + "local_self_tests_per_mode": 52, + "declared_python_mutants_killed_per_mode": 9, + "actual_core_preflight": "Positive/empty and three negative compiled controls passed; generated theorem-value mutation caught; forced origin omission explicitly reports cbzValidValue and refuses.", + "all_native_status": "NOT_ESTABLISHED; new actual hosted diagnostic run required" } }