diff --git a/.github/workflows/c2-interval-audit.yml b/.github/workflows/c2-interval-audit.yml index 649c7735f..2ebc64b82 100644 --- a/.github/workflows/c2-interval-audit.yml +++ b/.github/workflows/c2-interval-audit.yml @@ -4,6 +4,7 @@ name: Independent c2 interval audit pull_request: paths: - 'reviews/c2_interval_audit_20261001/**' + - 'tools/cbz_c2_oracle_qualification/**' - '.github/workflows/c2-interval-audit.yml' workflow_dispatch: @@ -39,3 +40,25 @@ jobs: cmp RESULTS.json "$RUNNER_TEMP/c2-normal.json" python -B -S verify.py git diff --exit-code + - name: Qualify the pinned exact oracle and source mutation runner + env: + PYTHONDONTWRITEBYTECODE: '1' + run: | + set -euo pipefail + evidence="$(mktemp -d "$RUNNER_TEMP/c2-oracle-qualification.XXXXXX")" + echo "C2_QUALIFICATION_EVIDENCE=$evidence" >> "$GITHUB_ENV" + mkdir -p "$evidence/source/reviews" "$evidence/source/tools" + cp -R reviews/c2_interval_audit_20261001 "$evidence/source/reviews/" + cp -R tools/cbz_c2_oracle_qualification "$evidence/source/tools/" + python -B -S tools/cbz_c2_oracle_qualification/test_runner.py -v 2>&1 | tee "$evidence/runner-normal.log" + python -B -O -S tools/cbz_c2_oracle_qualification/test_runner.py -v 2>&1 | tee "$evidence/runner-optimized.log" + python -B -S tools/cbz_c2_oracle_qualification/run_mutations.py --evidence-dir "$evidence/normal" 2>&1 | tee "$evidence/cut-normal.log" + python -B -O -S tools/cbz_c2_oracle_qualification/run_mutations.py --evidence-dir "$evidence/optimized" 2>&1 | tee "$evidence/cut-optimized.log" + - name: Retain exact oracle qualification source and evidence + if: always() && env.C2_QUALIFICATION_EVIDENCE != '' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: c2-oracle-qualification-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.C2_QUALIFICATION_EVIDENCE }} + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/c8-elder-failure-coefficient.yml b/.github/workflows/c8-elder-failure-coefficient.yml index 80937702d..6752581d0 100644 --- a/.github/workflows/c8-elder-failure-coefficient.yml +++ b/.github/workflows/c8-elder-failure-coefficient.yml @@ -1,10 +1,19 @@ -name: C8 elder-failure coefficient (certified replay) +name: C8 elder-failure replay (A3 quarantine; diagnostics only) 'on': pull_request: paths: - 'frontiers/c8_elder_failure_coefficient_20261001/**' - '.github/workflows/c8-elder-failure-coefficient.yml' + - 'quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json' + - 'tools/check_c8_quarantine.py' + - 'tools/c8_quarantine_mutations.py' + - 'tools/c8_quarantine_registry.json' + - 'tests/test_c8_quarantine.py' + - 'tests/test_c8_quarantine_mutations.py' + - 'tests/test_c8_quarantine_workflow.py' + - 'docs/cbz/C8_QUARANTINE.md' + - 'PROOF_INDEX.md' - 'frontiers/c6_cluster_coefficients_numerics_20260930/NOTE.md' - 'frontiers/c6_cluster_coefficients_numerics_20260930/RESULTS.json' - 'frontiers/local_elder_geometry_20260930/PROOF.md' @@ -17,7 +26,51 @@ permissions: contents: read jobs: + quarantine-boundary: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 + with: + python-version: '3.11.16' + - name: Enforce the opt-in C8 boundary and test its source guards + run: | + set -euo pipefail + mkdir -p .lake/c8-quarantine + python -B -S -m unittest discover -s tests -p test_c8_quarantine_mutations.py -v + python -B -O -S -m unittest discover -s tests -p test_c8_quarantine_mutations.py -v + python -B -S -m unittest discover -s tests -p test_c8_quarantine_workflow.py -v + python -B -O -S -m unittest discover -s tests -p test_c8_quarantine_workflow.py -v + python -B -S tools/c8_quarantine_mutations.py --output .lake/c8-quarantine/mutations + python -B -S tools/check_c8_quarantine.py > .lake/c8-quarantine/integrity.json + rc=0 + python -B -S tools/check_c8_quarantine.py --consume-output /results/k=1/J_fail > .lake/c8-quarantine/denied.json || rc=$? + test "$rc" -eq 1 + rc=0 + python -B -S tools/check_c8_quarantine.py --consume-output '/results/k=1/parts/E[2T]' > .lake/c8-quarantine/exact-witness.json || rc=$? + test "$rc" -eq 2 + python -B -S - <<'PY' + import json, pathlib + root = pathlib.Path('.lake/c8-quarantine') + for name, status in [('integrity', 'QUARANTINE_INTEGRITY_OK'), ('denied', 'REFUSED'), ('exact-witness', 'NOT_COVERED')]: + doc = json.loads((root / (name + '.json')).read_text()) + if doc['status'] != status or doc['cbz_certificate_admitted'] is not False: + raise ValueError('invalid nonadmission result: ' + name) + PY + - name: Preserve current and historical boundary evidence + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: c8-quarantine-${{ github.run_id }}-${{ github.run_attempt }} + path: .lake/c8-quarantine/ + include-hidden-files: true + if-no-files-found: error + retention-days: 90 certified-replay: + needs: quarantine-boundary runs-on: ubuntu-latest timeout-minutes: 150 strategy: diff --git a/.github/workflows/cbz-kernel.yml b/.github/workflows/cbz-kernel.yml new file mode 100644 index 000000000..ce39b315e --- /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 replay, raw imported-record census and compiled 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..cf5d6562c --- /dev/null +++ b/DECISIONS.md @@ -0,0 +1,77 @@ +# 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. + + +## 2026-10-29T19:04:15.984661+00:00: exact dependency metadata links (Phase 2, Layer B) + +The first hosted native attempt40933241149 at tested merge80bdeac2c7a88b51da13a81d47d458c0d474f0c6 refused before proof builds on Batteries docs/README.md. Preserve its failure,174-file artifact12924216223 (630934bytes; SHA256b319f068e05980750d3803944da42d2c54a336ecec8ee4accbbc6f5d19784094) and original eight-mutant/44-test records. Inspect every tree of all nine pinned dependencies. Handle only three exact reviewed noncompiler aliases by package, revision, path, mode, Git blob and raw readlink payload; never follow the target. Preserve refusal for unknown or Lean/config/gate/ancestor links. Record every link payload and its limited role; omit nothing silently. The fixed52-test baseline and13 harness methods pass per mode;9/9 Python mutations are killed per mode and the actual generated Lean mutation is detected. The full eight-project run remains unqualified. This reversible source repair is registered in tools/cbz_kernel_registry.json and TOOLING.md. + +## 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. + + +### 2026-10-29 — precise C8 arithmetic quarantine + +Preserve all eleven original C8 files, existing tests and both diagnostic replay blocks. Install a source-pinned opt-in boundary for106 unadmitted numerical pairs, with three exact Fraction exceptions and owner=null/maintenance=0. Require the bounded 13-mutant cut, healthy 41-method baselines and every-CLI protocol health. Retain the first refused cut and subsequent actual receipts. Preserve the separate C2 exact witness; do not infer global isolation, analytic refutation or new theorem/kernel/A8 admission. + + +- 2026-10-29 · CBZ tool qualification · Layer B, enforcing A8 · Added external C2 oracle qualification and a finite 12-source-mutant inventory after the prior 38-method replay lacked genuine source mutation. Preserved 22 original review/source-packet files and oracle SHA256 `b462b1b24613f74abd66042e0f347f69423595e9a1aedf1c6b45197425afe075`. Normal/optimized Python 3.12.14: original 38, external 25, runner 12 all pass; 12/12 mutants killed per mode by intended assertions. Preserved runner-missing RED, subcase-classification RED, newly-added-case omission RED and post-pin source-change RED before their fixes. Missing computed keys remain an external admission check, not an invented new guard in the original `results()`. Reversible additive engineering tool only; no source mathematical statement, packet byte or parent/kernel/federation status changed. Evidence: component registry/README and source-bound candidate receipt. Root append is offered for the canonical writer; this lane did not edit shared Math530 documents or publish. +- 2026-10-29 · CI admission · Layer B, enforcing A8 · Added explicit C2 qualification CI commands because nested tools tests are outside root tests discovery. Preserved original source-authentication run block verbatim, added only tool path eligibility plus qualification/evidence steps, and explicitly retained evidence for30 days. Local exact-step replay passed; no hosted success is inferred. Canonical integration remains with the root writer; no source authentication is inferred from local-only packet verification. + + +## 2026-10-29T20:14:06.248242+00:00: union additive arithmetic boundaries (Phase2, LayerB/C) + +Compose C8 ten-file frozen candidatebb45fec81de4a751000c1ac8f33da372cf3eceba and C2 six-file frozen vectorc60491320b160a85fb77306fd39e35bb8bac47c419b7283cf4f4bc8ba663bcf2 on the current kernel/cusp source. PROOF_INDEX additions share the same initial hunk; preserve the full existing index and CUSP marker and insert the distinct C8 boundary rather than replacing either. Preserve all original33 C8/C2/review packet files and both C8 replay blocks plus C2 authenticated59a block. No Lean/bound/source-assumption changes; narrow tools remain explicit about unqualified global isolation/semantics. Current kernel diagnostic0a631 is still executing; do not transfer it to this uncommitted union. Reversible. + + +## 2026-10-29T20:25:46.522468+00:00: preserve named alias refusal and adverse evidence (Phase3, LayerA/C) + +Diagnostic40945793449 identifies header-onlyUniversalLaw.Spec.P15.block.eq_1 in P15Hazard and no origin-onlyname. Retain exact366file artifact12930262595/SHA256c6b81d8163211c75bcb87ab72323bccf296f55e8b62bbc61a561bb8695535e99. Actual pinned-core6compile/kernel probes independently demonstrate benign identical aliases and unsafe selected-environment-only auditing: earlier raw sorryAx/customaxiom/axiomkind can be hidden by a later same-name validtheorem. Keep current strictrefusal; prototype explicit raw-version proof/type/declaration traversal before repairing. No filter/subset/union shortcut. No closure or successor evidence transfer. Reversible source/docs only. + +- 2026-10-29 · Layer B enforcing A8 · Reproduced C2 probe fixture-phase false kills without retracting prior genuine source-mutant observations. Added lifecycle regressions first (six intended RED assertion failures, zero errors; stale-output guard already passed). Require complete supported setup/body-entry/body-exit/teardown/cleanup plus real BODY AssertionError events and typed counter provenance. The original oracle and12 source mutations are preserved. Current44 component methods and fresh12/12 phase-sealed cuts pass normally/optimized; prior receipts retain their historical source cut and are not silently upgraded. No new arithmetic engine, mathematical scope, source-authentication claim or hosted result is inferred. + +- 2026-10-29 · Layer B enforcing A8 · Reproduced and repaired C8 fixture-phase false kills and stale observation reuse. Added eight regressions before production changes (eight RED assertion failures, zero errors). Extended the reviewed Math phase-wrapper pattern with body exit, successful fixture/cleanup counters and per-test event provenance; preserved all13 mutation anchors and the checker/packet. Current scoped suite66 methods passes in both modes, including22 harness controls; a fresh phase-sealed13/13 cut passes in each mode. Old14-control/cut observations remain historical. No canonical ledger overwrite, mathematical source change, local candidate commit or GitHub write in this lane. + +[2026-10-29T21:02:53.692743+00:00] [Phase 2] [Layer B] Composed the C8/C2 lifecycle-qualified mutation runners from frozen vector f77984cee059e4457e72bc3b168dc5f9c92b3be6a1286ac4b7ea8fed202489d7; all ten preimages and postimages matched. Preserve earlier cuts as historical; fixture assertions/stale records cannot award a current kill. Protected checker/oracle bytes and original numerical packets remain unchanged. Reversible. Evidence: infra-discovery/lifecycle-repair/REPAIR_RECEIPT.json (root execution evidence; hosted NOT_EVALUATED). + +[2026-10-29T21:10:29.701033+00:00] [Phase 2] [Layer B] Replaced selected-name-only axiom closure with raw imported record traversal keyed by module/constant-table indices, reconciled solely by exact theorem payload aliases. The independent foreign-helper counterexample is retained; no test, bound or proof was weakened. Five frozen code/test/workflow blobs match candidate gate de98c85e6d1cbab7e6adcaa922fe114fb5b9ed3d303122d342ea7ebcc98eda1a; merged registry preserves prior hosted refusals. Reversible. Evidence: kernel-review/duplicate-probes/frozen-candidate/COMPONENT_DELTA.json and candidate-preflight/execution-envelope.json; whole-native hosted status NOT_ESTABLISHED. diff --git a/GOVERNANCE.md b/GOVERNANCE.md new file mode 100644 index 000000000..f819180c8 --- /dev/null +++ b/GOVERNANCE.md @@ -0,0 +1,40 @@ +# 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 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 designated actual method-body AssertionErrors, completed supported lifecycle, healthy positive baselines and no errors/skips; the generated theorem-value and foreign-version collector mutations each require actual Lean execution, complete false-clear protocols and detection by their exact 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. + +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. + + +### C8 arithmetic quarantine boundary — 2026-10-29 + +Register CBZ-MATH-C8-QUARANTINE-01 as a bounded opt-in integrity/source-admission checker. It binds the unchanged eleven-file C8 packet, denies 106 numerical interval outputs, and distinguishes three Fraction witnesses without admitting a certificate. Global downstream isolation, descriptive consumer metadata, analytic theory, kernel/theorem closure and the separate C2 oracle's A8 qualification are outside its success scope. Shared ia.py bytes alone do not quarantine C2. + + +### C2 finite oracle qualification registry + +CBZ-C2-ORACLE-QUALIFICATION: `tools/cbz_c2_oracle_qualification/REGISTRY.json`; five self-contained source/test/docs files and existing C2 workflow wiring. Purpose: exact nine-expression witness and selected critical source-guard self-tests. Run the commands in the component README; original38, external25 and current runner19 controls pass per mode, all12 declared mutants killed per mode under the body-phase contract below. The earlier runner12 cut remains historical. Original oracle/packet bytes are fixed; full-engine, kernel, scientific and federation claims remain false. Owner:none; maintenance:zero. New toolsource/declaredcut changes require complete selfqualification. Source case omission and source-pin races are refused by the campaign. + +Exact imported-declaration coverage rule: never replace raw module census with a union/subset checked only via selected env.find. Actual pinned-core counterexamples show a nonselected raw sorry/custom-axiom proof can be hidden by a selected valid same-name theorem. Any alias handling must preserve and audit every relevant raw ConstantInfo version; no proof value or declaration kind may disappear through name deduplication. + +## 2026-10-29T21:02:53.692743+00:00: Mutation classification + +The bounded C8 and C2 mutation qualifications require measured designated method-body AssertionErrors, completed supported setup/body/teardown/cleanup and fresh child records. Lifecycle failures, stale output, skips and process failures refuse qualification. Their registries document exact finite domains and reproduction commands; this does not award global A8. Current source cuts observed C8 66 controls/mode and 13/13 mutants/mode; C2 44 controls/mode and 12/12 mutants/mode. Earlier receipts remain historical. diff --git a/PROOF_INDEX.md b/PROOF_INDEX.md index 6b406a44a..b38036710 100644 --- a/PROOF_INDEX.md +++ b/PROOF_INDEX.md @@ -2,6 +2,20 @@ 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. +## C8 arithmetic quarantine + +**[Q-C8-ELDER-FAILURE-BINARY64-20261029](quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json): QUARANTINED, A3_NOT_PROVEN.** The unchanged C8 packet has 106 unadmitted binary64 numerical interval leaves and three separately checked exact rational E[2T] witnesses. The opt-in checker enforces this precise boundary without certifying the analytic theory, all consumers or global isolation. The nine C2 supplied-expression endpoints have a separate exact-rational witness; shared ia.py bytes do not quarantine them. + + + +## 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..bc90de053 --- /dev/null +++ b/STATUS.md @@ -0,0 +1,52 @@ +# 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 | Raw-record repair locally qualified; whole scope NOT_ESTABLISHED | Prior hosted attempts refused at project2. Their first-project outputs used the older selected-only collector; a fresh all-native run of the repaired collector and final source/object readback are required | +| 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. + +The current collector traverses every reachable imported raw ConstantInfo version by module/record identity. It reconciles native census differences only with explicit identical theorem payload aliases, retaining separate raw-record and unique-name counts. Different valid proof payloads conservatively refuse. The frozen local cut passed66 gate controls and17 harness controls per mode, all9 declared Python mutants per mode, actual pinned-core alias/raw-version controls, and both generated collector mutants. These finite controls do not qualify all119 native modules or dependency cache objects. Prior selected-only collector results remain historical observations. + +## 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. + + +## 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. + + +### C8 bounded arithmetic quarantine — 2026-10-29 + +Q-C8-ELDER-FAILURE-BINARY64-20261029 is A3_NOT_PROVEN with certificate admission denied for its 106 listed numeric pairs. Three exact E[2T] Fraction witnesses remain separate and nonadmitting. The current source-bound candidate passed 41 core,22 harness and 3 workflow methods per mode and all 13 declared mutants in both modes, requiring measured intended body assertions and completed fixtures. The earlier 14-harness cut remains historical evidence. Full C8 numerical replay and hosted qualification of this change remain NOT_EVALUATED. Other workflows/global isolation and generic auditor soundness are not established here. + + +### C2 exact-oracle bounded tool qualification + +Original oracle and both packets remain unchanged. The external25-case baseline and19runner controls pass in each mode;12/12 declared source mutants are killed per mode with measured intended body assertions, completed fixtures and zero errors/skips. The earlier 12-runner cut remains historical evidence. The composed C8/C2/cusp focused suite passed128 methods normally and128 optimized, zero skips; this is not the full regression suite. This is finite source-tool evidence for the nine supplied closed forms, not Gaussian interpretation, all arithmetic, kernel or federation closure. Hosted execution of the added CI step is NOT_EVALUATED. + +### How to verify the added arithmetic boundaries + +C8 integrity: `python -B -S tools/check_c8_quarantine.py`. C8 self-verification: `python -B -S tools/c8_quarantine_mutations.py --output /tmp/c8-cut-NEW`. C2 self-verification: `python -B -S tools/cbz_c2_oracle_qualification/test_runner.py -v`, then `python -B -S tools/cbz_c2_oracle_qualification/run_mutations.py --evidence-dir /tmp/c2-cut-NEW`; repeat with-O and new output paths. Complete scopes and commands are in TOOLING.md and the component registries. No integrity/mutation success admits an excluded certificate. + + +Latest strict diagnostic attempt40945793449 at tested mergea22a0e395f108e85116f03b5a9813042afbd4829 REFUSED on P15Hazard46versus45, naming header-only`UniversalLaw.Spec.P15.block.eq_1` and no origin-only name. Artifact12930262595/SHA256c6b81d8163211c75bcb87ab72323bccf296f55e8b62bbc61a561bb8695535e99 is retained. Imported generated-theorem coalescing must be handled without hiding any raw theorem proof or axiom declaration. Current whole-native kernel status remains NOT_ESTABLISHED. diff --git a/TOOLING.md b/TOOLING.md new file mode 100644 index 000000000..7153de29e --- /dev/null +++ b/TOOLING.md @@ -0,0 +1,66 @@ +# 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-NEW`. The runner requires all66 baseline method bodies to pass in both modes, then kills all nine declared nonstale guard mutants by their designated actual body AssertionError, with completed supported lifecycle and zero errors/skips/startup failures. Its17 harness controls reject fixture failures and stale observations. The real Lean preflight separately compiles and runs theorem-value-omission and foreign-raw-version-omission collectors; both must emit complete false-clear protocols and be caught by their exact compiled sorry control. A compiler failure cannot count as a kill. These are bounded auditor self-tests, not full semantic or all-generated-code qualification. + +The raw-record collector builds and independently checks the full imported module/ConstantInfo index. Native raw declarations are direct roots; each referenced Name reaches every imported version. The only permitted native aliases have identical theorem constructor, name, level parameters, type and proof expressions under Expr.equal, and TheoremVal.all, with a raw owner witness and selected checked declaration. Raw/unique closure counts and aliases are explicit protocol-v2 fields. Missing records, unsupported module sidecars and different proof payloads refuse. Dependency cache objects remain trusted inputs rather than freshly rebuilt dependencies. + +Dependency attestation covers every tracked Git entry. Its only symlink exceptions are three independently inspected aliases at the exact registered package, revision, path, Git blob and raw link payload: Batteries documentation README and two inactive Mathlib Python benchmark aliases. It hashes and enumerates the link payload without following its target, and records that limited role. These aliases are not gate compiler inputs; unknown links/revisions and all native Lean/configuration/gate source links or symlinked ancestors remain refused. + +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. + + +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. + + +### CBZ-MATH-C8-QUARANTINE-01 + +Use [tools/check_c8_quarantine.py](tools/check_c8_quarantine.py), [registry](tools/c8_quarantine_registry.json) and [scope/commands](docs/cbz/C8_QUARANTINE.md). Run `python -B -S tools/check_c8_quarantine.py` for integrity only; use `--consume` or `--consume-output` for explicit nonadmission. Denied sources/106 outputs return1; exact 3 witnesses and unrelated inputs return2 NOT_COVERED. + +Run `python -B -S tools/c8_quarantine_mutations.py --output .lake/c8-quarantine/mutations` after the normal/optimized harness and workflow tests. The source-bound cut requires healthy unchanged 41-method baselines, all 13 intended assertion kills per mode, and independent health for every CLI call. The14 harness controls reject startup/input-dependent crashes, invalid JSON/typed structure, errors/skips, multiple failures and stale evidence. Original legacy replay blocks stay diagnostic and byte-preserved. Receipts alone do not establish global A8/A3 or theorem closure. + + +- **CBZ-C2-ORACLE-QUALIFICATION:** `tools/cbz_c2_oracle_qualification/REGISTRY.json` and sibling README. External qualification preserves original C2 oracle SHA256 `b462b1b24613f74abd66042e0f347f69423595e9a1aedf1c6b45197425afe075` and both original packets. Observed Python 3.12.14 normal/optimized: original 38 methods; external 25-case complete baseline; runner 12 controls; 12/12 actual source mutants killed at intended assertions with zero mutant errors/skips. Runner rejects surviving, startup/input-dependent crash, stale, wrong-assertion, skipped and incomplete-case evidence as kills, and refuses a source changed after its pin read. Exact scope is nine supplied closed-form enclosures plus declared finite operation guards/remainders; no Gaussian derivation, full engine proof, kernel, semantic or federation certificate. Owner: none; maintenance: zero. Replay commands and new-output-path requirement are in the component README. +- CI command coverage: `.github/workflows/c2-interval-audit.yml` preserves original59a authentication and run bytes, adds tool-directory PR eligibility, and runs the runner controls and full finite cuts in normal/optimized modes. The exact added shell body passed locally; hosted qualification remains NOT_EVALUATED until an actual run is observed. An always-after-started-step artifact retains copied source/evidence for30 days with the repository's existing pinned upload action. + +- C2 oracle qualification now requires phase-sealed current-source evidence. The original oracle remains SHA256 `b462b1b24613f74abd66042e0f347f69423595e9a1aedf1c6b45197425afe075`; its25 external test method bodies and22 packet files are unchanged. Current19 runner controls reject setup/teardown/cleanup assertions as kills and retain genuine BODY assertions, typed event-counter provenance and stale-output refusal. The standalone44-method component passes in both modes; fresh12/12 source-mutant cuts pass with every25-case baseline body attested. Earlier12-control observations remain historical. Existing CI commands discover all19 current controls automatically; hosted execution of this repair remains NOT_EVALUATED. Scope stays the nine supplied closed forms and declared finite checks, with no broader analytic/kernel/federation certificate. + +- C8 lifecycle repair supersedes the earlier14-control collector for current qualification. The C8 checker remains SHA256 `ee09075645f68e73a30037457a3c535825a8dd369e4de73680753fe92cab11b4`; packet and41 core tests are unchanged. The repaired harness has22 controls and requires typed `unittest.body-phase/v1` evidence: complete setup, actual body entry/exit, successful teardown/cleanup and matching failure-event counters. Only the designated BODY AssertionError kills; CLI health must belong to that selected body. Actual setup/teardown/cleanup assertions now refuse in normal/optimized Python, genuine body kills remain valid, and reused observation paths refuse before launch. Fresh current-source cuts again kill13/13 mutants in both modes. Earlier cuts remain historical without retroactive lifecycle attestation. Scope remains the C8 quarantine boundary; no arithmetic/kernel/global isolation or CBZ admission. diff --git a/docs/cbz/C8_QUARANTINE.md b/docs/cbz/C8_QUARANTINE.md new file mode 100644 index 000000000..8c0f3392e --- /dev/null +++ b/docs/cbz/C8_QUARANTINE.md @@ -0,0 +1,31 @@ +# C8 numerical quarantine boundary + +`CBZ-MATH-C8-QUARANTINE-01` registers `tools/check_c8_quarantine.py`, its [machine registry](../../tools/c8_quarantine_registry.json), [record](../../quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json), and the C8 workflow. Scientific effect is NONE; owner is null and maintenance is zero. + +The record binds all eleven unchanged files of `frontiers/c8_elder_failure_coefficient_20261001` at `e877242cf68fb24c605066f16dd07f513ee75a1d`. It lists 106 unadmitted binary64 interval pairs for reference planar near-cluster coefficients, the declared compact-band elder-failure constant, numeric planar torus transfer and reference-only conditional d=3 outputs. The three E[2T] pairs independently contain `199/9`, `1355/36` and `20957/288` by exact Fraction formula and decimal comparison. No legacy enclosure is asserted false and no analytic theorem is refuted. + +The checker validates that exact packet, the 106/3 output partition, required classification and canonical index marker. Descriptive consumer/reference metadata is not fully revalidated. Other workflows are not automatically isolated. Shared ia.py bytes alone do not deny the separate C2 exact arithmetic witness or any unrelated source. C2 auditor A8 qualification is not awarded by this tool. + +Run from the repository root with standard-library Python: + + python -B -S tools/check_c8_quarantine.py + python -B -S -m unittest discover -s tests -p test_c8_quarantine.py -v + python -B -O -S -m unittest discover -s tests -p test_c8_quarantine.py -v + python -B -S -m unittest discover -s tests -p test_c8_quarantine_mutations.py -v + python -B -O -S -m unittest discover -s tests -p test_c8_quarantine_mutations.py -v + python -B -S tools/c8_quarantine_mutations.py --output .lake/c8-quarantine/mutations + +Default exit0 means QUARANTINE_INTEGRITY_OK with A3_NOT_PROVEN and admitted=false. `--consume` accepts a repository-relative source path. `--consume-output` accepts one canonical JSON pointer into the frozen C8 results. All 106 denied paths return1 REFUSED. The three exact witnesses and unrelated inputs return2 NOT_COVERED, always nonadmitting. For example: + + python -B -S tools/check_c8_quarantine.py --consume-output /results/k=1/J_fail + python -B -S tools/check_c8_quarantine.py --consume-output '/results/k=1/parts/E[2T]' + +The bounded mutation cut requires the unchanged 41-method suite to pass in both interpreter modes and all thirteen declared source mutants to fail exactly their intended assertion. A direct unittest collector records failures, subtest failures/errors and skips. Every test CLI invocation has independent exit/stderr/JSON/structure health recorded before assertions; crashes and malformed responses never count as kills, including after a healthy benign smoke. Source inputs, mutants, per-call health and logs are retained. Rerunning the mutation command archives prior complete/incomplete output under history/ and writes a new current RUNNING/PASS/REFUSED result. Use distinct output paths for concurrent callers. + +The lifecycle repair requires `unittest.body-phase/v1` evidence for every selected test: successful setup, actual body entry and exit, successful teardown and completion of every cleanup, with typed per-test failure/error counters bound to the observed events. Only the designated BODY AssertionError may kill a mutant; setup, teardown or cleanup assertions refuse even when their ID, exit and CLI health otherwise match. Unsupported custom internal unittest lifecycles refuse. CLI health is attributed to its actual selected test/body. The harness now has22 controls, including actual fixture-phase cases in each Python mode and a genuine body-kill positive control. Direct observation path reuse is refused before launch, preserving the prior bytes rather than reading stale JSON after a startup failure. The earlier14-control/13-mutant observation remains historical; only a fresh source-bound cut with this lifecycle schema qualifies the repaired source. + +Current implementation state: opt-in boundary only. Full C8 numerical replay is NOT_EVALUATED for this change; the original replay and five-mutant run blocks remain byte-identical and execute in the workflow after the new boundary controls. No universal auditor, kernel, theorem, finite-lifetime or global A3 closure follows. + +## Decision ledger + +- 2026-10-29: Preserve the eleven-file C8 packet and all original tests. Deny its 106 listed numerical certificates, retain the three exact rational exceptions, and preserve the exact C2 witness. Adopt the explicit opt-in source/output boundary with bounded source mutation controls. Keep consumer narratives and global isolation outside the integrity-success scope. diff --git a/quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json b/quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json new file mode 100644 index 000000000..f5bcc0588 --- /dev/null +++ b/quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json @@ -0,0 +1,1765 @@ +{ + "schema": "cbz.quarantine/v1", + "id": "Q-C8-ELDER-FAILURE-BINARY64-20261029", + "title": "C8 near-cluster and elder-failure binary64 enclosures: A3 arithmetic certification unavailable", + "record_state": "OPT_IN_GATE_INSTALLED", + "classification": "QUARANTINED", + "layer_a": "A3", + "layer_a_status": "A3_NOT_PROVEN", + "cbz_certificate_admitted": false, + "source_snapshot": { + "repository": "d6g8k5htny-coder/Math-", + "commit": "e877242cf68fb24c605066f16dd07f513ee75a1d", + "packet_path": "frontiers/c8_elder_failure_coefficient_20261001", + "packet_object": "CL-C8-ELDER-FAILURE-COEFFICIENT-20261001-v1", + "manifest": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/SOURCE_FILES.json", + "git_blob": "1efc243fa447e7162644b939b2cd2200270e9874", + "sha256": "446fa632ec3055ce53587357fb47588041eab7829dbfe44438f0d5b3bab7e209", + "bytes": 2284 + } + }, + "source_files": [ + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/NOTE.md", + "git_blob": "9903dd6f6b2514069bef78399b3d90201280911e", + "sha256": "de50468afe0cae0bd2147a79e1b5b45a9f57ade5a81a9a99fd95aaaccc826c7c", + "bytes": 27438 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/README.md", + "git_blob": "68ac15054b26ab4e0b9021859727be3385b6dbbd", + "sha256": "63313f05a155a5b93db70c82c16eca7ab98c4f1311ddc770dffc5ccb2db85031", + "bytes": 1906 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/RESULTS.json", + "git_blob": "670297d08e516b5c3456fef278abb8ce454cfd79", + "sha256": "73bd816e0b48d9740c02d58f32fda99a110e4634222760e17c9c98df64b4d870", + "bytes": 9040 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/SOURCE_FILES.json", + "git_blob": "1efc243fa447e7162644b939b2cd2200270e9874", + "sha256": "446fa632ec3055ce53587357fb47588041eab7829dbfe44438f0d5b3bab7e209", + "bytes": 2284 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/SOURCE_MAP.json", + "git_blob": "f48177918014d3b09fe40e810695c986b1a30af5", + "sha256": "ab8a34556de2c309d5a379bd17b047159622dc111bf78ecf818f6dd9e339c4c9", + "bytes": 6451 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/boxes.py", + "git_blob": "f6b42e2a0bf0021d85ded2bd19a77205455a5aa0", + "sha256": "5d6a9cfca33ed5140065bfd02a630a77596adf8c0b45ed6edb0032005754f9db", + "bytes": 28396 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/certificate.py", + "git_blob": "0cbecb81eefceb11499bce4d78386a46d879cd51", + "sha256": "4d19857f5ba5cebf9dae8320680618abb23cbe6c1e674803ea95f99c96a56c10", + "bytes": 31193 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/controls.py", + "git_blob": "39613832228583a9eb81d3eb2a1ee12e2b791d39", + "sha256": "d275ee5a120c3246e0c1a6dc5cd8bc8fbe738069c64448894efe3feebb7dd1f1", + "bytes": 5593 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/ia.py", + "git_blob": "cf4bbfa16f577fe65f4ab5fb3621943fa63cf9fa", + "sha256": "6d048d58c6ab18f21c0609fc888ca73497a60e234217bb4f7a309a1502fccc9e", + "bytes": 8930 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/test_replay_metadata.py", + "git_blob": "f943d6a1f3f5faf7a708818b78d7e6c74174d49c", + "sha256": "047f3692f840a7a3dd4993f0fa22bf5402cbd01bb01ba28010931186762c7df3", + "bytes": 2803 + }, + { + "path": "frontiers/c8_elder_failure_coefficient_20261001/torus.py", + "git_blob": "4a448b2f30e8f1157b758bc9ae5c9c258e112db8", + "sha256": "c5e3496d62dd7dcb544a72722982221654b9e6de100d5cf36640ca4abd67d279", + "bytes": 9778 + } + ], + "not_proven_boundary": [ + "For K(z)=exp(-|z|^2/2) in d=2: certified J_fail,J_1,J_2, J_2/J_fail and 2J_2/(J_1+2J_2) at k=1/2,1,2; p_b(0)/z_0, alpha_1, alpha_2=nu(2) and a_fail at b=0,1 and those gaps.", + "The reference planar band integral C_fail^{B,K}=const*I_b*I_k on B=[0,1],K=[1/2,2], and its supporting quadrature/box/tail numerical bounds.", + "The numerical Lemma T covariance, chi-square, expectation and density-ratio bounds and resulting planar torus intervals for every L>=10 and every frame.", + "The reference-only d=3 constants, b=0 pointwise coefficients and band C_fail^(3),{B,K}, conditional on the packet Math-#175/#184 interfaces. No d=3 torus transfer is claimed by this packet." + ], + "mathematical_arithmetic_gap": "certificate.py certify/derived/document propagate floating interval endpoints from ia.py and boxes.py/torus.py and emit certified=true. Directed one-ulp binary64 operations and Decimal publication do not themselves discharge Layer A3 exact-bound certification. No exact-rational or verified-real replacement for the 106 listed leaves was located in the scoped source/consumer census. Rational subexpressions and seeded mutant rejection do not establish those remaining bounds.", + "evidence": [ + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/NOTE.md", + "git_blob": "9903dd6f6b2514069bef78399b3d90201280911e", + "sha256": "de50468afe0cae0bd2147a79e1b5b45a9f57ade5a81a9a99fd95aaaccc826c7c", + "bytes": 27438, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 23, + "line_end": 81, + "finding": "Reference/torus tables, exact band and conditional d=3 statement boundaries." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/NOTE.md", + "git_blob": "9903dd6f6b2514069bef78399b3d90201280911e", + "sha256": "de50468afe0cae0bd2147a79e1b5b45a9f57ade5a81a9a99fd95aaaccc826c7c", + "bytes": 27438, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 272, + "line_end": 324, + "finding": "Planar torus scope and binary64 arithmetic policy." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/NOTE.md", + "git_blob": "9903dd6f6b2514069bef78399b3d90201280911e", + "sha256": "de50468afe0cae0bd2147a79e1b5b45a9f57ade5a81a9a99fd95aaaccc826c7c", + "bytes": 27438, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 383, + "line_end": 399, + "finding": "Conditional identification, compact grids/band, no finite-r or rate scope." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/certificate.py", + "git_blob": "0cbecb81eefceb11499bce4d78386a46d879cd51", + "sha256": "4d19857f5ba5cebf9dae8320680618abb23cbe6c1e674803ea95f99c96a56c10", + "bytes": 31193, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 316, + "line_end": 352, + "finding": "certify returns raw floats from adaptive boxes, tails and transfers." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/certificate.py", + "git_blob": "0cbecb81eefceb11499bce4d78386a46d879cd51", + "sha256": "4d19857f5ba5cebf9dae8320680618abb23cbe6c1e674803ea95f99c96a56c10", + "bytes": 31193, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 387, + "line_end": 468, + "finding": "derived propagates intervals and document emits certified=true." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/boxes.py", + "git_blob": "f6b42e2a0bf0021d85ded2bd19a77205455a5aa0", + "sha256": "5d6a9cfca33ed5140065bfd02a630a77596adf8c0b45ed6edb0032005754f9db", + "bytes": 28396, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 80, + "line_end": 154, + "finding": "Library root values are seeds; final certifying sign/bracket checks are still binary64." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/torus.py", + "git_blob": "4a448b2f30e8f1157b758bc9ae5c9c258e112db8", + "sha256": "c5e3496d62dd7dcb544a72722982221654b9e6de100d5cf36640ca4abd67d279", + "bytes": 9778, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 129, + "line_end": 185, + "finding": "Torus regressions, chi-square and derived deviation bounds use binary64 interval operations." + }, + { + "source": { + "path": "frontiers/c8_elder_failure_coefficient_20261001/ia.py", + "git_blob": "cf4bbfa16f577fe65f4ab5fb3621943fa63cf9fa", + "sha256": "6d048d58c6ab18f21c0609fc888ca73497a60e234217bb4f7a309a1502fccc9e", + "bytes": 8930, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 1, + "line_end": 57, + "finding": "Binary64 pairs and nextafter-widened elementary operations." + } + ], + "denied_output_count": 106, + "denied_outputs": [ + { + "path": [ + "results", + "k=0.5", + "J_fail" + ], + "json_pointer": "/results/k=0.5/J_fail", + "interval": [ + "36.78305814", + "36.78680021" + ] + }, + { + "path": [ + "results", + "k=0.5", + "J_1" + ], + "json_pointer": "/results/k=0.5/J_1", + "interval": [ + "35.67360980", + "35.68065110" + ] + }, + { + "path": [ + "results", + "k=0.5", + "J_2" + ], + "json_pointer": "/results/k=0.5/J_2", + "interval": [ + "1.106148894", + "1.109448563" + ] + }, + { + "path": [ + "results", + "k=0.5", + "share_J2_over_Jfail" + ], + "json_pointer": "/results/k=0.5/share_J2_over_Jfail", + "interval": [ + "0.03006918240", + "0.03016194161" + ] + }, + { + "path": [ + "results", + "k=0.5", + "near_palm_excess" + ], + "json_pointer": "/results/k=0.5/near_palm_excess", + "interval": [ + "0.05837775723", + "0.05856276965" + ] + }, + { + "path": [ + "results", + "k=0.5", + "parts", + "E[2(B_-)^3]" + ], + "json_pointer": "/results/k=0.5/parts/E[2(B_-)^3]", + "interval": [ + "8.357431233", + "8.357432938" + ] + }, + { + "path": [ + "results", + "k=0.5", + "parts", + "E[V] boxes" + ], + "json_pointer": "/results/k=0.5/parts/E[V] boxes", + "interval": [ + "18.57553740", + "18.58052069" + ] + }, + { + "path": [ + "results", + "k=0.5", + "parts", + "E[H_2] boxes" + ], + "json_pointer": "/results/k=0.5/parts/E[H_2] boxes", + "interval": [ + "1.474865193", + "1.479264750" + ] + }, + { + "path": [ + "results", + "k=0.5", + "parts", + "tail bound" + ], + "json_pointer": "/results/k=0.5/parts/tail bound", + "interval": [ + "0", + "1.475969601E-9" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=0", + "p_b(0)/z_0" + ], + "json_pointer": "/results/k=0.5/coefficients/b=0/p_b(0)~1z_0", + "interval": [ + "0.03134386261", + "0.03134386889" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=0", + "alpha_1" + ], + "json_pointer": "/results/k=0.5/coefficients/b=0/alpha_1", + "interval": [ + "1.118148836", + "1.118369538" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=0", + "alpha_2" + ], + "json_pointer": "/results/k=0.5/coefficients/b=0/alpha_2", + "interval": [ + "0.03467098246", + "0.03477440682" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=0", + "a_fail = alpha_1 + alpha_2" + ], + "json_pointer": "/results/k=0.5/coefficients/b=0/a_fail = alpha_1 + alpha_2", + "interval": [ + "1.152923236", + "1.153040528" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=1", + "p_b(0)/z_0" + ], + "json_pointer": "/results/k=0.5/coefficients/b=1/p_b(0)~1z_0", + "interval": [ + "0.008974028845", + "0.008974030641" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=1", + "alpha_1" + ], + "json_pointer": "/results/k=0.5/coefficients/b=1/alpha_1", + "interval": [ + "0.3201360354", + "0.3201992242" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=1", + "alpha_2" + ], + "json_pointer": "/results/k=0.5/coefficients/b=1/alpha_2", + "interval": [ + "0.009926613082", + "0.009956224403" + ] + }, + { + "path": [ + "results", + "k=0.5", + "coefficients", + "b=1", + "a_fail = alpha_1 + alpha_2" + ], + "json_pointer": "/results/k=0.5/coefficients/b=1/a_fail = alpha_1 + alpha_2", + "interval": [ + "0.3300922578", + "0.3301258393" + ] + }, + { + "path": [ + "results", + "k=1", + "J_fail" + ], + "json_pointer": "/results/k=1/J_fail", + "interval": [ + "172.8463609", + "172.8602041" + ] + }, + { + "path": [ + "results", + "k=1", + "J_1" + ], + "json_pointer": "/results/k=1/J_1", + "interval": [ + "169.5839525", + "169.6070816" + ] + }, + { + "path": [ + "results", + "k=1", + "J_2" + ], + "json_pointer": "/results/k=1/J_2", + "interval": [ + "3.253121786", + "3.262409093" + ] + }, + { + "path": [ + "results", + "k=1", + "share_J2_over_Jfail" + ], + "json_pointer": "/results/k=1/share_J2_over_Jfail", + "interval": [ + "0.01881938142", + "0.01887461645" + ] + }, + { + "path": [ + "results", + "k=1", + "near_palm_excess" + ], + "json_pointer": "/results/k=1/near_palm_excess", + "interval": [ + "0.03694156081", + "0.03705188358" + ] + }, + { + "path": [ + "results", + "k=1", + "parts", + "E[2(B_-)^3]" + ], + "json_pointer": "/results/k=1/parts/E[2(B_-)^3]", + "interval": [ + "5.876020762", + "5.876021946" + ] + }, + { + "path": [ + "results", + "k=1", + "parts", + "E[V] boxes" + ], + "json_pointer": "/results/k=1/parts/E[V] boxes", + "interval": [ + "14.10054776", + "14.10515341" + ] + }, + { + "path": [ + "results", + "k=1", + "parts", + "E[H_2] boxes" + ], + "json_pointer": "/results/k=1/parts/E[H_2] boxes", + "interval": [ + "1.084373928", + "1.087469698" + ] + }, + { + "path": [ + "results", + "k=1", + "parts", + "tail bound" + ], + "json_pointer": "/results/k=1/parts/tail bound", + "interval": [ + "0", + "3.232088888E-10" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=0", + "p_b(0)/z_0" + ], + "json_pointer": "/results/k=1/coefficients/b=0/p_b(0)~1z_0", + "interval": [ + "0.007835965654", + "0.007835967222" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=0", + "alpha_1" + ], + "json_pointer": "/results/k=1/coefficients/b=0/alpha_1", + "interval": [ + "1.328854160", + "1.329035399" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=0", + "alpha_2" + ], + "json_pointer": "/results/k=1/coefficients/b=0/alpha_2", + "interval": [ + "0.02549135313", + "0.02556412816" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=0", + "a_fail = alpha_1 + alpha_2" + ], + "json_pointer": "/results/k=1/coefficients/b=0/a_fail = alpha_1 + alpha_2", + "interval": [ + "1.354418283", + "1.354526758" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=1", + "p_b(0)/z_0" + ], + "json_pointer": "/results/k=1/coefficients/b=1/p_b(0)~1z_0", + "interval": [ + "0.002243507211", + "0.002243507661" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=1", + "alpha_1" + ], + "json_pointer": "/results/k=1/coefficients/b=1/alpha_1", + "interval": [ + "0.3804628584", + "0.3805147487" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=1", + "alpha_2" + ], + "json_pointer": "/results/k=1/coefficients/b=1/alpha_2", + "interval": [ + "0.007298402918", + "0.007319239058" + ] + }, + { + "path": [ + "results", + "k=1", + "coefficients", + "b=1", + "a_fail = alpha_1 + alpha_2" + ], + "json_pointer": "/results/k=1/coefficients/b=1/a_fail = alpha_1 + alpha_2", + "interval": [ + "0.3877820960", + "0.3878131531" + ] + }, + { + "path": [ + "results", + "k=2", + "J_fail" + ], + "json_pointer": "/results/k=2/J_fail", + "interval": [ + "1111.982273", + "1112.030781" + ] + }, + { + "path": [ + "results", + "k=2", + "J_1" + ], + "json_pointer": "/results/k=2/J_1", + "interval": [ + "1103.129655", + "1103.205691" + ] + }, + { + "path": [ + "results", + "k=2", + "J_2" + ], + "json_pointer": "/results/k=2/J_2", + "interval": [ + "8.825088654", + "8.852620061" + ] + }, + { + "path": [ + "results", + "k=2", + "share_J2_over_Jfail" + ], + "json_pointer": "/results/k=2/share_J2_over_Jfail", + "interval": [ + "0.007936011924", + "0.007961115375" + ] + }, + { + "path": [ + "results", + "k=2", + "near_palm_excess" + ], + "json_pointer": "/results/k=2/near_palm_excess", + "interval": [ + "0.01574666826", + "0.01579686122" + ] + }, + { + "path": [ + "results", + "k=2", + "parts", + "E[2(B_-)^3]" + ], + "json_pointer": "/results/k=2/parts/E[2(B_-)^3]", + "interval": [ + "5.093426722", + "5.093427745" + ] + }, + { + "path": [ + "results", + "k=2", + "parts", + "E[V] boxes" + ], + "json_pointer": "/results/k=2/parts/E[V] boxes", + "interval": [ + "14.80440892", + "14.80843560" + ] + }, + { + "path": [ + "results", + "k=2", + "parts", + "E[H_2] boxes" + ], + "json_pointer": "/results/k=2/parts/E[H_2] boxes", + "interval": [ + "0.7354240545", + "0.7377183383" + ] + }, + { + "path": [ + "results", + "k=2", + "parts", + "tail bound" + ], + "json_pointer": "/results/k=2/parts/tail bound", + "interval": [ + "0", + "2.004587614E-10" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=0", + "p_b(0)/z_0" + ], + "json_pointer": "/results/k=2/coefficients/b=0/p_b(0)~1z_0", + "interval": [ + "0.001958991413", + "0.001958991806" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=0", + "alpha_1" + ], + "json_pointer": "/results/k=2/coefficients/b=0/alpha_1", + "interval": [ + "2.161021739", + "2.161170692" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=0", + "alpha_2" + ], + "json_pointer": "/results/k=2/coefficients/b=0/alpha_2", + "interval": [ + "0.01728827462", + "0.01734220843" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=0", + "a_fail = alpha_1 + alpha_2" + ], + "json_pointer": "/results/k=2/coefficients/b=0/a_fail = alpha_1 + alpha_2", + "interval": [ + "2.178363944", + "2.178458970" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=1", + "p_b(0)/z_0" + ], + "json_pointer": "/results/k=2/coefficients/b=1/p_b(0)~1z_0", + "interval": [ + "0.0005608768028", + "0.0005608769151" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=1", + "alpha_1" + ], + "json_pointer": "/results/k=2/coefficients/b=1/alpha_1", + "interval": [ + "0.6187198961", + "0.6187625424" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=1", + "alpha_2" + ], + "json_pointer": "/results/k=2/coefficients/b=1/alpha_2", + "interval": [ + "0.004949788004", + "0.004965229734" + ] + }, + { + "path": [ + "results", + "k=2", + "coefficients", + "b=1", + "a_fail = alpha_1 + alpha_2" + ], + "json_pointer": "/results/k=2/coefficients/b=1/a_fail = alpha_1 + alpha_2", + "interval": [ + "0.6236851249", + "0.6237123314" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "R_3(0) = (32 + 28 sqrt2)/17" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/R_3(0) = (32 + 28 sqrt2)~117", + "interval": [ + "4.211645446", + "4.211646289" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "const_3" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/const_3", + "interval": [ + "0.006583316240", + "0.006583317557" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "I_b^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/I_b^(3)", + "interval": [ + "1.513649011", + "1.513683082" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "C_fail^(3),{B,K}" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/C_fail^(3),{B,K}", + "interval": [ + "0.004405817806", + "0.004416745237" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=0.5, b=0", + "alpha_1^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=0.5, b=0/alpha_1^(3)", + "interval": [ + "4.709246927", + "4.710176443" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=0.5, b=0", + "alpha_2^(3) = nu^(3)(2)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=0.5, b=0/alpha_2^(3) = nu^(3)(2)", + "interval": [ + "0.1460219000", + "0.1464574868" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=0.5, b=0", + "a_fail^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=0.5, b=0/a_fail^(3)", + "interval": [ + "4.855704384", + "4.856198372" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=1, b=0", + "alpha_1^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=1, b=0/alpha_1^(3)", + "interval": [ + "5.596663133", + "5.597426446" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=1, b=0", + "alpha_2^(3) = nu^(3)(2)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=1, b=0/alpha_2^(3) = nu^(3)(2)", + "interval": [ + "0.1073605521", + "0.1076670548" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=1, b=0", + "a_fail^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=1, b=0/a_fail^(3)", + "interval": [ + "5.704330166", + "5.704787020" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=2, b=0", + "alpha_1^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=2, b=0/alpha_1^(3)", + "interval": [ + "9.101458278", + "9.102085610" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=2, b=0", + "alpha_2^(3) = nu^(3)(2)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=2, b=0/alpha_2^(3) = nu^(3)(2)", + "interval": [ + "0.07281209039", + "0.07303924044" + ] + }, + { + "path": [ + "results", + "d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)", + "k=2, b=0", + "a_fail^(3)" + ], + "json_pointer": "/results/d=3 (conditional on Math-#175 (L1) and Math-#184 Theorem 1)/k=2, b=0/a_fail^(3)", + "interval": [ + "9.174497503", + "9.174897715" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "jet covariance deviation delta (order <= 6)" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/jet covariance deviation delta (order <= 6)", + "interval": [ + "0", + "2.850266693E-14" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "chi^2 bound" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/chi^2 bound", + "interval": [ + "0", + "2.878353120E-23" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "|J^L - J| bound (all k, J_fail and J_2)" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/|J^L - J| bound (all k, J_fail and J_2)", + "interval": [ + "0", + "1.247240771E-7" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "(pi_0 p_b(0))^L / (pi_0 p_b(0))^ref" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/(pi_0 p_b(0))^L ~1 (pi_0 p_b(0))^ref", + "interval": [ + "0.9999998999", + "1.000000101" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "J_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/J_fail", + "interval": [ + "36.78305802", + "36.78680034" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "J_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/J_2", + "interval": [ + "1.106148770", + "1.109448688" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=0", + "p_b(0)/z_0" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=0/p_b(0)~1z_0", + "interval": [ + "0.03134386261", + "0.03134386889" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=0", + "alpha_1" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=0/alpha_1", + "interval": [ + "1.118148828", + "1.118369546" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=0", + "alpha_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=0/alpha_2", + "interval": [ + "0.03467097855", + "0.03477441073" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=0", + "a_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=0/a_fail", + "interval": [ + "1.152923232", + "1.153040532" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=1", + "p_b(0)/z_0" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=1/p_b(0)~1z_0", + "interval": [ + "0.008974028845", + "0.008974030641" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=1", + "alpha_1" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=1/alpha_1", + "interval": [ + "0.3201360332", + "0.3201992265" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=1", + "alpha_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=1/alpha_2", + "interval": [ + "0.009926611963", + "0.009956225523" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=0.5", + "b=1", + "a_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=0.5/b=1/a_fail", + "interval": [ + "0.3300922567", + "0.3301258404" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "J_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/J_fail", + "interval": [ + "172.8463608", + "172.8602042" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "J_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/J_2", + "interval": [ + "3.253121661", + "3.262409218" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=0", + "p_b(0)/z_0" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=0/p_b(0)~1z_0", + "interval": [ + "0.007835965654", + "0.007835967222" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=0", + "alpha_1" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=0/alpha_1", + "interval": [ + "1.328854158", + "1.329035401" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=0", + "alpha_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=0/alpha_2", + "interval": [ + "0.02549135216", + "0.02556412914" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=0", + "a_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=0/a_fail", + "interval": [ + "1.354418282", + "1.354526759" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=1", + "p_b(0)/z_0" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=1/p_b(0)~1z_0", + "interval": [ + "0.002243507211", + "0.002243507661" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=1", + "alpha_1" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=1/alpha_1", + "interval": [ + "0.3804628579", + "0.3805147493" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=1", + "alpha_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=1/alpha_2", + "interval": [ + "0.007298402638", + "0.007319239338" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=1", + "b=1", + "a_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=1/b=1/a_fail", + "interval": [ + "0.3877820958", + "0.3878131534" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "J_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/J_fail", + "interval": [ + "1111.982273", + "1112.030781" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "J_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/J_2", + "interval": [ + "8.825088529", + "8.852620186" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=0", + "p_b(0)/z_0" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=0/p_b(0)~1z_0", + "interval": [ + "0.001958991413", + "0.001958991806" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=0", + "alpha_1" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=0/alpha_1", + "interval": [ + "2.161021738", + "2.161170692" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=0", + "alpha_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=0/alpha_2", + "interval": [ + "0.01728827438", + "0.01734220867" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=0", + "a_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=0/a_fail", + "interval": [ + "2.178363944", + "2.178458970" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=1", + "p_b(0)/z_0" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=1/p_b(0)~1z_0", + "interval": [ + "0.0005608768028", + "0.0005608769151" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=1", + "alpha_1" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=1/alpha_1", + "interval": [ + "0.6187198960", + "0.6187625426" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=1", + "alpha_2" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=1/alpha_2", + "interval": [ + "0.004949787934", + "0.004965229804" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "k=2", + "b=1", + "a_fail" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/k=2/b=1/a_fail", + "interval": [ + "0.6236851248", + "0.6237123315" + ] + }, + { + "path": [ + "results", + "torus model, every L >= 10, every frame (Lemma T)", + "C_fail^{B,K}" + ], + "json_pointer": "/results/torus model, every L >= 10, every frame (Lemma T)/C_fail^{B,K}", + "interval": [ + "0.002724454687", + "0.002731151043" + ] + }, + { + "path": [ + "results", + "C_fail", + "I_k" + ], + "json_pointer": "/results/C_fail/I_k", + "interval": [ + "0.4421366818", + "0.4432233938" + ] + }, + { + "path": [ + "results", + "C_fail", + "I_k boxes" + ], + "json_pointer": "/results/C_fail/I_k boxes", + "interval": [ + "0.4421366818", + "0.4432233938" + ] + }, + { + "path": [ + "results", + "C_fail", + "I_k tail bound" + ], + "json_pointer": "/results/C_fail/I_k tail bound", + "interval": [ + "0", + "1.296653887E-11" + ] + }, + { + "path": [ + "results", + "C_fail", + "int_K W(k) dk" + ], + "json_pointer": "/results/C_fail/int_K W(k) dk", + "interval": [ + "0.009075577556", + "0.009075579412" + ] + }, + { + "path": [ + "results", + "C_fail", + "const" + ], + "json_pointer": "/results/C_fail/const", + "interval": [ + "0.008250963314", + "0.008250964965" + ] + }, + { + "path": [ + "results", + "C_fail", + "I_b" + ], + "json_pointer": "/results/C_fail/I_b", + "interval": [ + "0.7468240581", + "0.7468242075" + ] + }, + { + "path": [ + "results", + "C_fail", + "C_fail^{B,K}" + ], + "json_pointer": "/results/C_fail/C_fail^{B,K}", + "interval": [ + "0.002724454695", + "0.002731151035" + ] + } + ], + "exact_rational_exceptions": [ + { + "path": [ + "results", + "k=0.5", + "parts", + "E[2T]" + ], + "interval": [ + "22.11110889", + "22.11111333" + ], + "exact_value": "199/9", + "identity": "6*(6*k + 1/(4*k) + 5/(216*k^3))", + "k": "1/2", + "method": "Exact Fraction formula and exact decimal containment; no binary64 execution." + }, + { + "path": [ + "results", + "k=1", + "parts", + "E[2T]" + ], + "interval": [ + "37.63888512", + "37.63889266" + ], + "exact_value": "1355/36", + "identity": "6*(6*k + 1/(4*k) + 5/(216*k^3))", + "k": "1", + "method": "Exact Fraction formula and exact decimal containment; no binary64 execution." + }, + { + "path": [ + "results", + "k=2", + "parts", + "E[2T]" + ], + "interval": [ + "72.76735383", + "72.76736839" + ], + "exact_value": "20957/288", + "identity": "6*(6*k + 1/(4*k) + 5/(216*k^3))", + "k": "2", + "method": "Exact Fraction formula and exact decimal containment; no binary64 execution." + } + ], + "exception_scope": "The three E[2T] exact strings and their published interval pairs are independently checked by integer/Fraction formula and decimal containment only. This does not establish any other integrand, tail, expectation or physical-law identification.", + "not_a_verdict": [ + "No quoted enclosure is asserted mathematically false.", + "No analytic root reduction, Gaussian-integral identity, conditional asymptotic theorem, torus transfer inequality or existing review verdict is refuted by this arithmetic admission decision.", + "Timing, process counts, adaptive split heuristics, library root seeds and floating/Monte Carlo comparisons are not separately classified as mathematical bound certificates.", + "The nine C2 supplied-expression endpoints have a distinct exact rational witness; the common ia.py bytes do not make that witness a universal engine or C8 certificate." + ], + "attempted": [ + { + "date": "2026-10-29", + "action": "Bound all 11 packet files and three shared-engine paths to e877 Git blobs; traced certificate and torus output assembly and all direct-reference hits across 4028 canonical blobs.", + "outcome": "109 interval leaves found; three exact rational E[2T] exceptions checked, remaining 106 lack an inspected A3-admissible replacement." + }, + { + "date": "2026-10-29", + "action": "Traced known numerical displays and inspected current Math landing/graph plus Main c93 status/projection sources.", + "outcome": "PD quotes the enclosure but does not use it in its rate proof; QS A3.10 explicitly attempts no numeric value. No CLOSED dependency established in those inspected surfaces." + } + ], + "resumption_cost": { + "class": "substantial arithmetic proof and implementation work; no reliable time estimate", + "required": [ + "Replace or independently certify all load-bearing basic/elementary/root sign, Gaussian moments, Taylor boxes, tail and band-integration computations using exact rationals or verified reals.", + "Establish exact decimal endpoints, including all numeric planar-torus deviation bounds, and preserve the reference-only d=3 conditional boundary.", + "Run meaningful positive/negative/mutation controls and bind every source/result identity before any CBZ admission.", + "Reconcile the quoted numerical displays and actual consuming workflows without promoting existential analytic statements or imported premises." + ] + }, + "isolation": { + "packet_bytes": "preserved verbatim; no packet/test/workflow mutation by this task", + "replay_role": "legacy diagnostic evidence only; C8 full replay NOT_EVALUATED in this task", + "certificate_admission": "denied for these 106 numerical leaves and their restated numeric certification claims; exact rational exceptions above remain distinct", + "analytic_transfer_scope": "not reclassified by this arithmetic quarantine", + "enforcement_status": "Opt-in C8 source/output checker plus this packet workflow boundary checks. Default success is integrity only; explicit denied106 outputs return1, exact3 witnesses and unrelated inputs return2 without admission. Other workflows and global downstream isolation are not enforced.", + "global_A3_audit": false, + "closed_consumer_boundary": "No declared dependency in inspected Math landing10-claim manifest or D0-D7 graph. Main c93 hypergraph assigns the C8 unit orphan/OPEN, bound=false and credit=0. This is not a complete federation/catalog transitive audit." + }, + "denied_certificate_sources": [ + "frontiers/c8_elder_failure_coefficient_20261001", + "frontiers/c8_elder_failure_coefficient_20261001/RESULTS.json", + "frontiers/c8_elder_failure_coefficient_20261001/certificate.py", + "frontiers/c8_elder_failure_coefficient_20261001/boxes.py", + "frontiers/c8_elder_failure_coefficient_20261001/torus.py" + ], + "numerical_consumers": [ + { + "source": { + "path": "frontiers/planar_compact_k_chain_20261006/PD/PROOF.md", + "git_blob": "27893c7d28579f485787a7a45127a9124c719652", + "sha256": "7da0f672ab30a91a6e5787583326f0b14397a4addbb9e07b162cd2a3143e0e98", + "bytes": 14294, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 105, + "line_end": 105, + "scope": "Quotes C_fail in [0.0027244,0.0027312] and L>=10 scope as #217 claim. The rate proof uses an existential/integral-defined coefficient, not these endpoint values; no new analytic theorem quarantine." + }, + { + "source": { + "path": "frontiers/planar_compact_k_chain_20261006/PD/CLAIM.md", + "git_blob": "64cbe23e82f97842b6146a68842aa5923d77f881", + "sha256": "71da3c4362280817fabcddb65c7bf7803d84b8b94916c4b428308f9a065b2784", + "bytes": 1814, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 24, + "line_end": 24, + "scope": "Restates #217 certifies C_fail but supplies no numeric endpoint input to the proof." + } + ], + "non_numeric_references": [ + { + "source": { + "path": "frontiers/qs_d3_soft_layer_chain_20261005/A3_10/PROOF.md", + "git_blob": "f92830484ed0d7e8e582058bc564f547317963e0", + "sha256": "98fd6832e6003e5317072c8088482cc9facd68133d373f8497800b539d27dc07", + "bytes": 21069, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 70, + "line_end": 71, + "scope": "No numerical value is attempted; explicitly says #217 planar enclosure is planar." + }, + { + "source": { + "path": "frontiers/c2_exact_20261001/NOTE.md", + "git_blob": "a2798b87674ed5fc0d2144697e77ccb9b185b4ab", + "sha256": "598fc86a7c6b21bad438ef087e5aa7521f0fae08e25fa4f40f9b2ba635846dbb", + "bytes": 14480, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "line_start": 167, + "line_end": 170, + "scope": "Shared arithmetic provenance only; C2 endpoint certification has the separate exact oracle." + }, + { + "source": { + "path": "docs/integration/2026-10-23-postcut-proof-sources.md", + "git_blob": "a1008e928c56cb360509db0f894b5fafae435df3", + "sha256": "d0e34f44e505c928604b5382def98559bd1a029be62102af1c14c3ed928513e8", + "bytes": 63129, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + }, + "scope": "Availability index quotes original packet kind; not mathematical admission or a numerical algorithm input." + } + ], + "surfaces": { + "canonical_index": "PROOF_INDEX.md", + "diagnostic_workflow": ".github/workflows/c8-elder-failure-coefficient.yml", + "workflow_line_start": 64, + "workflow_line_end": 83, + "workflow_scope": "The workflow runs integrity/source-mutation controls before retained full legacy replay/mutant commands. Replay is diagnostic, never CBZ mathematical admission.", + "historical_workflow_at_source_snapshot": { + "path": ".github/workflows/c8-elder-failure-coefficient.yml", + "git_blob": "80937702d0a57d025ffdc812e9497c30fe7a125b", + "sha256": "3f040049aa445768598ac172df90363bfb6f20e0d023ea3ff143c4d8fc18f9f8", + "bytes": 3770, + "snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d" + } + }, + "owner": null, + "maintenance": 0 +} 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_c8_quarantine.py b/tests/test_c8_quarantine.py new file mode 100644 index 000000000..dec615ee5 --- /dev/null +++ b/tests/test_c8_quarantine.py @@ -0,0 +1,329 @@ +"""Bounded C8 quarantine controls; integrity success never grants admission.""" +from fractions import Fraction as F +import importlib.util +import hashlib +import json +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_c8_quarantine.py" +PACKET = "frontiers/c8_elder_failure_coefficient_20261001" +QID = "Q-C8-ELDER-FAILURE-BINARY64-20261029" +RECORD = "quarantine/" + QID + ".json" +EXACT = {"k=0.5": "199/9", "k=1": "1355/36", "k=2": "20957/288"} +CLI_HEALTH = [] + + +def observe_cli(child): + """Independent child health before semantic assertions; no crashed CLI is a kill.""" + errors = [] + if child.returncode not in (0, 1, 2):errors.append("unexpected exit") + if child.stderr:errors.append("unexpected stderr") + def unique(items): + value = {} + for key, item in items: + if key in value:raise ValueError("duplicate JSON member") + value[key] = item + return value + try: + doc = json.loads(child.stdout, object_pairs_hook=unique, + parse_constant=lambda v: (_ for _ in ()).throw(ValueError("nonfinite JSON"))) + valid = (isinstance(doc, dict) and doc.get("status") in {"QUARANTINE_INTEGRITY_OK", "REFUSED", "NOT_COVERED"} + and type(doc.get("cbz_certificate_admitted")) is bool + and isinstance(doc.get("scientific_effect"), str) + and all(isinstance(doc.get(k), str) and doc[k] for k in ("quarantine_id", "scope", "layer_a_status")) + and all(type(doc.get(k)) is int and doc[k] >= 0 + for k in ("preserved_packet_files", "denied_output_count", "exact_exception_count")) + and isinstance(doc.get("problems"), list) and all(isinstance(v, str) for v in doc["problems"]) + and isinstance(doc.get("source_decisions"), list) and isinstance(doc.get("output_decisions"), list)) + if valid: + for field, key in (("source_decisions", "source"), ("output_decisions", "output")): + valid = valid and all(isinstance(v, dict) and isinstance(v.get(key), str) + and isinstance(v.get("decision"), str) for v in doc[field]) + valid = valid and all(v.get("decision") != "EXACT_RATIONAL_WITNESS_ONLY" or isinstance(v.get("exact_value"), str) + for v in doc["output_decisions"]) + if not valid:errors.append("invalid report structure") + except (ValueError, TypeError): + errors.append("invalid JSON") + row = {"returncode": child.returncode, "healthy": not errors, "problems": errors, + "stdout_sha256": hashlib.sha256(child.stdout.encode()).hexdigest(), + "stderr_sha256": hashlib.sha256(child.stderr.encode()).hexdigest()} + CLI_HEALTH.append(row) + return row + + +def pointer(path): + return "/" + "/".join(x.replace("~", "~0").replace("/", "~1") for x in path) + + +class C8Quarantine(unittest.TestCase): + def setUp(self): + self.assertTrue(SCRIPT.is_file(), "C8 quarantine tool is missing") + temp = tempfile.TemporaryDirectory(prefix="c8-quarantine-") + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + shutil.copytree(ROOT / PACKET, self.root / PACKET) + (self.root / "PROOF_INDEX.md").write_bytes((ROOT / "PROOF_INDEX.md").read_bytes()) + record = self.root / RECORD + record.parent.mkdir() + if (ROOT / RECORD).is_file(): + record.write_bytes((ROOT / RECORD).read_bytes()) + + def cli(self, *args, root=None): + flags = ["-B", "-S", *(["-O"] if sys.flags.optimize else [])] + env = {k: v for k, v in os.environ.items() if k not in {"PYTHONHOME", "PYTHONPATH", "PYTHONOPTIMIZE"}} + try: + child = subprocess.run([sys.executable, *flags, str(SCRIPT), "--root", str(root or self.root), *args], + env=env, capture_output=True, text=True, timeout=15) + except (OSError, subprocess.TimeoutExpired, UnicodeError) as exc: + CLI_HEALTH.append({"healthy": False, "problems": [type(exc).__name__]}) + raise + observe_cli(child) + return child + + def report(self, child): + self.assertEqual(child.stderr, "", child) + result = json.loads(child.stdout) + self.assertIs(result["cbz_certificate_admitted"], False) + self.assertEqual(result["scientific_effect"], "NONE") + return result + + def refused(self, diagnostic, *args, root=None): + child = self.cli(*args, root=root) + self.assertEqual(child.returncode, 1, child) + result = self.report(child) + self.assertEqual(result["status"], "REFUSED") + self.assertTrue(any(diagnostic in v for v in result["problems"]), result) + return result + + def change(self, callback): + path = self.root / RECORD + value = json.loads(path.read_text()) + callback(value) + path.write_text(json.dumps(value) + "\n") + + def pairs(self): + rows = {} + def walk(value, path): + if isinstance(value, dict): + for key, item in value.items(): + walk(item, path + [key]) + elif isinstance(value, list) and len(value) == 2 and all(isinstance(x, str) for x in value): + rows[pointer(path)] = value + walk(json.loads((self.root / PACKET / "RESULTS.json").read_text())["results"], ["results"]) + self.assertEqual(len(rows), 109) + exceptions = {pointer(["results", k, "parts", "E[2T]"]) for k in EXACT} + return rows, exceptions + + def test_integrity_success_does_not_admit_arithmetic(self): + child = self.cli();self.assertEqual(child.returncode, 0, child) + result = self.report(child) + self.assertEqual(result["status"], "QUARANTINE_INTEGRITY_OK") + self.assertEqual(result["layer_a_status"], "A3_NOT_PROVEN") + self.assertEqual((result["preserved_packet_files"], result["denied_output_count"], result["exact_exception_count"]), (11, 106, 3)) + + def test_all_106_published_denied_outputs_are_mechanically_denied(self): + rows, exceptions = self.pairs();denied = set(rows) - exceptions + args = [x for p in sorted(denied) for x in ("--consume-output", p)] + child = self.cli(*args);self.assertEqual(child.returncode, 1, child) + result = self.report(child) + self.assertEqual({d["output"] for d in result["output_decisions"] if d["decision"] == "DENIED"}, denied) + self.assertEqual(len(result["output_decisions"]), 106) + + def test_three_fraction_witnesses_remain_explicitly_nonadmitting(self): + rows, exceptions = self.pairs() + args = [x for p in sorted(exceptions) for x in ("--consume-output", p)] + child = self.cli(*args);self.assertEqual(child.returncode, 2, child) + result = self.report(child);self.assertEqual(result["status"], "NOT_COVERED") + self.assertEqual(len(result["output_decisions"]), 3) + for d in result["output_decisions"]: + self.assertEqual(d["decision"], "EXACT_RATIONAL_WITNESS_ONLY") + lo, hi = map(F, rows[d["output"]]);exact = F(d["exact_value"]) + self.assertLessEqual(lo, exact);self.assertLessEqual(exact, hi) + self.assertIn(str(exact), EXACT.values()) + + def test_mixed_exception_and_denied_output_refuses(self): + self.refused("quarantined numerical output", "--consume-output", "/results/k=1/parts/E[2T]", + "--consume-output", "/results/k=1/J_fail") + + def test_unknown_output_is_not_coverage_or_admission(self): + child = self.cli("--consume-output", "/results/not-present") + self.assertEqual(child.returncode, 2, child) + self.assertEqual(self.report(child)["output_decisions"][0]["decision"], "NOT_COVERED") + + def test_packet_and_normalized_source_aliases_refuse(self): + for name in (PACKET, "./" + PACKET + "/RESULTS.json", "frontiers/unused/../c8_elder_failure_coefficient_20261001/certificate.py"): + with self.subTest(name=name): + self.refused("quarantined numerical source", "--consume", name) + + def test_direct_packet_source_refuses(self): + self.refused("quarantined numerical source", "--consume", PACKET + "/RESULTS.json") + + def test_renamed_c8_result_copy_cannot_evade_denial(self): + dest = self.root / "mirror/results.json";dest.parent.mkdir() + dest.write_bytes((self.root / PACKET / "RESULTS.json").read_bytes()) + self.refused("quarantined numerical source", "--consume", "mirror/results.json") + + def test_shared_ia_or_c2_source_is_not_quarantined_by_byte_equality(self): + for name in ("frontiers/c2_exact_20261001/ia.py", "mirror/shared_ia.py"): + dest = self.root / name;dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes((self.root / PACKET / "ia.py").read_bytes()) + child = self.cli("--consume", name);self.assertEqual(child.returncode, 2, child) + self.assertEqual(self.report(child)["source_decisions"][0]["decision"], "NOT_COVERED") + + def test_unrelated_analytic_proof_is_not_certified_or_refuted(self): + child = self.cli("--consume", "frontiers/planar_compact_k_chain_20261006/PD/PROOF.md") + self.assertEqual(child.returncode, 2, child) + self.assertEqual(self.report(child)["status"], "NOT_COVERED") + + def test_missing_record_refuses(self): + (self.root / RECORD).unlink();self.refused("missing quarantine record") + + def test_record_admission_must_be_typed_false(self): + for value in (True, 0): + self.change(lambda d: d.update(cbz_certificate_admitted=value)) + self.refused("admission must remain false") + + def test_classification_and_isolation_limits_cannot_be_promoted(self): + self.change(lambda d: d.update(layer_a_status="A3_PROVEN"));self.refused("A3 classification") + + def test_owner_and_maintenance_cannot_be_invented(self): + self.change(lambda d: d.update(owner="invented"));self.refused("owner must remain unassigned") + self.change(lambda d: d.update(owner=None, maintenance=True));self.refused("maintenance must remain zero") + + def test_source_snapshot_is_exact(self): + self.change(lambda d: d["source_snapshot"].update(commit="0" * 40));self.refused("source snapshot") + + def test_empty_or_duplicated_source_inventory_refuses(self): + self.change(lambda d: d.update(source_files=[]));self.refused("packet inventory") + + def test_source_byte_count_requires_an_integer(self): + self.change(lambda d: d["source_files"][0].update(bytes=float(d["source_files"][0]["bytes"]))) + self.refused("packet inventory") + + def test_packet_changes_and_extra_files_refuse(self): + path = self.root / PACKET / "ia.py";path.write_bytes(path.read_bytes() + b"\n# altered\n") + self.refused("packet source identity") + (self.root / PACKET / "extra.py").write_text("pass\n");self.refused("packet tree differs") + + def test_refreshed_manifest_cannot_rebind_changed_sources(self): + changed = self.root / PACKET / "ia.py";changed.write_bytes(changed.read_bytes() + b"\n# altered\n") + def ident(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()} + manifest = self.root / PACKET / "SOURCE_FILES.json";doc = json.loads(manifest.read_text()) + for row in doc["files"]: + if row["path"] == "ia.py":row.update(ident(changed)) + manifest.write_text(json.dumps(doc) + "\n") + def rebind(d): + for row in d["source_files"]: + if row["path"] in (PACKET + "/ia.py", PACKET + "/SOURCE_FILES.json"):row.update(ident(self.root / row["path"])) + d["source_snapshot"]["manifest"].update(ident(manifest)) + self.change(rebind);self.refused("frozen packet manifest") + + def test_changed_source_cannot_rebind_only_quarantine_metadata(self): + p = self.root / PACKET / "ia.py";raw = p.read_bytes() + b"\n# changed\n";p.write_bytes(raw) + def rebind(d): + for row in d["source_files"]: + if row["path"] == PACKET + "/ia.py": + row.update(bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest(), + git_blob=hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()) + self.change(rebind);self.refused("packet source identity") + + def test_denied_inventory_cannot_be_emptied(self): + self.change(lambda d: d.update(denied_outputs=[]));self.refused("denied output inventory") + + def test_denied_inventory_cannot_duplicate_or_change_an_endpoint(self): + self.change(lambda d: d["denied_outputs"].__setitem__(0, d["denied_outputs"][1]));self.refused("denied output inventory") + + def test_exact_exceptions_cannot_be_removed(self): + self.change(lambda d: d.update(exact_rational_exceptions=[]));self.refused("exact rational exception") + + def test_false_exact_rational_witness_refuses(self): + self.change(lambda d: d["exact_rational_exceptions"][0].update(exact_value="1"));self.refused("exact rational exception") + + def test_fraction_checker_rejects_a_false_endpoint(self): + spec = importlib.util.spec_from_file_location("c8_exact_control", SCRIPT) + module = importlib.util.module_from_spec(spec);spec.loader.exec_module(module) + results = json.loads((self.root / PACKET / "RESULTS.json").read_text()) + results["results"]["k=1"]["parts"]["E[2T]"] = ["1", "1"] + with self.assertRaisesRegex(ValueError, "exact rational containment"): + module.exact_exceptions(results) + + def test_denied_interval_endpoints_cannot_be_rewritten(self): + self.change(lambda d: d["denied_outputs"][0].update(interval=["1", "1"])) + self.refused("denied output inventory") + + def test_global_isolation_is_not_claimed_by_integrity_success(self): + self.change(lambda d: d["isolation"].update(global_A3_audit=True)) + self.refused("limited opt-in scope") + + def test_mathematical_boundary_cannot_be_emptied(self): + self.change(lambda d: d.update(not_proven_boundary=[]));self.refused("nonempty mathematical boundary") + + def test_snapshot_manifest_cannot_disagree_with_source(self): + self.change(lambda d: d["source_snapshot"]["manifest"].update(git_blob="0" * 40)) + self.refused("snapshot manifest identity") + + def test_denial_sources_and_global_isolation_scope_are_exact(self): + self.change(lambda d: d.update(denied_certificate_sources=[]));self.refused("denied source inventory") + + def test_missing_or_promoted_index_marker_refuses(self): + (self.root / "PROOF_INDEX.md").write_text("# No C8 quarantine marker\n") + self.refused("canonical index quarantine") + + def test_index_boolean_false_cannot_be_replaced_by_zero(self): + p = self.root / "PROOF_INDEX.md";p.write_text(p.read_text().replace('"cbz_certificate_admitted":false', '"cbz_certificate_admitted":0')) + self.refused("canonical index quarantine") + + def test_duplicate_json_members_refuse(self): + p = self.root / RECORD;raw = p.read_text().rstrip();p.write_text(raw[:-1] + ',"cbz_certificate_admitted":false}') + self.refused("duplicate JSON member") + + def test_invalid_utf8_and_nonfinite_json_refuse(self): + p = self.root / RECORD;p.write_bytes(b'\xff');self.refused("UTF-8") + p.write_text('{"bad":NaN}');self.refused("nonfinite JSON") + + def test_symlink_source_or_packet_ancestor_refuses(self): + p = self.root / PACKET / "ia.py";raw = p.read_bytes();p.unlink() + target = self.root / "outside-ia.py";target.write_bytes(raw);p.symlink_to(target) + self.refused("regular local source") + + def test_symlink_record_and_index_refuse(self): + p = self.root / RECORD;raw = p.read_bytes();p.unlink();target = self.root / "record.json";target.write_bytes(raw);p.symlink_to(target) + self.refused("regular local source") + + def test_symlink_packet_directory_cannot_hide_sources(self): + p = self.root / PACKET;target = self.root / "external-packet";p.rename(target);p.symlink_to(target, target_is_directory=True) + self.refused("regular local source") + + def test_symlink_index_refuses(self): + p = self.root / "PROOF_INDEX.md";raw = p.read_bytes();p.unlink();target = self.root / "index.md";target.write_bytes(raw);p.symlink_to(target) + self.refused("regular local source") + + def test_symlink_checkout_root_refuses(self): + with tempfile.TemporaryDirectory() as d: + alias = Path(d) / "alias";alias.symlink_to(self.root, target_is_directory=True) + self.refused("symlink checkout", root=alias) + + def test_unreadable_source_refuses_even_for_privileged_runner(self): + p = self.root / PACKET / "ia.py";p.chmod(0) + try:self.refused("unreadable local source") + finally:p.chmod(0o644) + + def test_unsafe_source_paths_and_output_pointers_refuse(self): + for name in ("", "../outside", "/tmp/source", "a\\b", "x:y"): + with self.subTest(name=name):self.refused("unsafe consumer path", "--consume", name) + for name in ("", "results/a", "/results/~2", "/results/a~"): + with self.subTest(name=name):self.refused("invalid output pointer", "--consume-output", name) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_c8_quarantine_mutations.py b/tests/test_c8_quarantine_mutations.py new file mode 100644 index 000000000..efe0c7a36 --- /dev/null +++ b/tests/test_c8_quarantine_mutations.py @@ -0,0 +1,223 @@ +"""Mutation custody and child-health controls; a crashed CLI never kills a mutant.""" +import contextlib +import importlib.util +import io +import json +from pathlib import Path +import tempfile +import unittest +import sys +import ast +from unittest.mock import patch + +PATH = Path(__file__).resolve().parents[1] / "tools/c8_quarantine_mutations.py" +h = None +if PATH.exists(): + spec = importlib.util.spec_from_file_location("c8_mutation_harness", PATH) + h = importlib.util.module_from_spec(spec);spec.loader.exec_module(h) +SELECTOR = "test_c8_quarantine.C8Quarantine.test_unknown_output_is_not_coverage_or_admission" + + +class HarnessControls(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(h, "C8 mutation harness is missing") + + def result(self): + return {"returncode": 1, "tests_run": 1, "failures": [{"id": SELECTOR, "kind": "AssertionError"}], + "errors": [], "skipped": [], "expected_failures": [], "unexpected_successes": [], + "selected_ids": [SELECTOR], "lifecycle": self.lifecycle([SELECTOR], [SELECTOR]), + "cli_health": [{"healthy": True, "test_id": SELECTOR, "phase": "body"}], "smoke": {"healthy": True}} + + def lifecycle(self, ids, failures): + rows=[] + for identity in ids: + rows.append({"id":identity,"supported":True,"setup_entered":1,"setup_completed":1, + "body_entered":1,"body_exited":1,"teardown_entered":1,"teardown_completed":1, + "cleanup_entered":0,"cleanup_completed":0,"failure_count":failures.count(identity),"error_count":0}) + return {"schema":"unittest.body-phase/v1","tests":rows,"events":[{ + "id":identity,"phase":"body","kind":"failure","exception":"AssertionError","assertion":True} + for identity in failures]} + + def test_intended_assertion_is_the_only_accepted_kill(self): + h.check_run(self.result(), 1, SELECTOR) + + def test_success_errors_skips_wrong_selector_and_zero_are_not_kills(self): + changes = [{"returncode": 0}, {"errors": [{"id": SELECTOR}]}, {"skipped": [SELECTOR]}, + {"tests_run": 0}, {"failures": [{"id": "other", "kind": "AssertionError"}]}, + {"failures": [{"id": SELECTOR, "kind": "RuntimeError"}]}] + for change in changes: + with self.subTest(change=change), self.assertRaises(h.MutationError): + result = self.result();result.update(change);h.check_run(result, 1, SELECTOR) + + def test_all_cli_health_is_required_even_after_a_healthy_smoke(self): + result = self.result();result["cli_health"].append({"healthy": False}) + with self.assertRaisesRegex(h.MutationError, "unhealthy CLI"): + h.check_run(result, 1, SELECTOR) + + def test_zero_cli_calls_do_not_qualify_a_cli_control(self): + result = self.result();result["cli_health"] = [] + with self.assertRaises(h.MutationError):h.check_run(result, 1, SELECTOR) + + def test_healthy_baseline_requires_all_41_methods_and_no_errors_or_skips(self): + result = self.result();result.update(returncode=0, tests_run=41, failures=[]) + tree=ast.parse((h.ROOT/h.TEST).read_text()) + names=sorted(n.name for c in tree.body if isinstance(c,ast.ClassDef) and c.name=="C8Quarantine" + for n in c.body if isinstance(n,ast.FunctionDef) and n.name.startswith("test_")) + ids=["test_c8_quarantine.C8Quarantine."+name for name in names] + result.update(selected_ids=ids,lifecycle=self.lifecycle(ids,[])) + h.check_run(result, 41) + result["tests_run"] = 40 + with self.assertRaises(h.MutationError):h.check_run(result, 41) + + def test_stale_noop_duplicate_and_noncompiling_mutations_refuse(self): + for source, before, after in (("x=1", "missing", "x=2"), ("x=1", "x=1", "x=1"), + ("x=1\nx=1", "x=1", "x=2"), ("x=1", "x=1", "def invalid(")): + with self.subTest(before=before), self.assertRaises(h.MutationError):h.apply_mutation(source, before, after) + + def actual(self, replacement, method): + with tempfile.TemporaryDirectory() as d: + root = Path(d);work = root / "work";out = root / "out";out.mkdir() + h.materialize(work) + source = (work / h.TOOL).read_text() + (work / h.TOOL).write_text(replacement(source)) + return h.run_suite(work, out, "probe", "optimized" if sys.flags.optimize else "normal", method) + + def test_input_dependent_invalid_json_cannot_fake_an_assertion_kill(self): + def bad(source): + return 'import sys\n' + source.replace(' raise SystemExit(main())', + ' if "--consume-output" in sys.argv:\n print("not-json"); raise SystemExit(1)\n raise SystemExit(main())') + result = self.actual(bad, SELECTOR) + self.assertTrue(result["smoke"]["healthy"]) + self.assertEqual((len(result["failures"]), len(result["errors"])), (1, 0)) + with self.assertRaisesRegex(h.MutationError, "unhealthy CLI"):h.check_run(result, 1, SELECTOR) + + def test_input_dependent_runtime_crash_cannot_fake_an_assertion_kill(self): + def bad(source): + return 'import sys\n' + source.replace(' raise SystemExit(main())', + ' if "--consume-output" in sys.argv:\n raise RuntimeError("input-dependent crash")\n raise SystemExit(main())') + result = self.actual(bad, SELECTOR) + self.assertTrue(result["smoke"]["healthy"]) + self.assertEqual((len(result["failures"]), len(result["errors"])), (1, 0)) + with self.assertRaisesRegex(h.MutationError, "unhealthy CLI"):h.check_run(result, 1, SELECTOR) + + def test_input_dependent_malformed_counter_structure_is_not_a_kill(self): + def bad(source): + return source.replace(' print(json.dumps(report, indent=2, sort_keys=True))', + ' if args.consume_output:\n report["denied_output_count"] = "not-an-integer"\n print(json.dumps(report, indent=2, sort_keys=True))').replace(' code = 2', ' code = 1') + result = self.actual(bad, SELECTOR) + self.assertTrue(result["smoke"]["healthy"]) + with self.assertRaisesRegex(h.MutationError, "unhealthy CLI"):h.check_run(result, 1, SELECTOR) + + def test_startup_crash_never_counts_as_a_kill(self): + result = self.actual(lambda s: 'raise RuntimeError("startup crash")\n' + s, SELECTOR) + with self.assertRaisesRegex(h.MutationError, "unhealthy CLI"):h.check_run(result, 1, SELECTOR) + + def test_healthy_semantic_false_clear_is_an_actual_assertion_kill(self): + selector = "test_c8_quarantine.C8Quarantine.test_all_106_published_denied_outputs_are_mechanically_denied" + result = self.actual(lambda s: s.replace('if path in checked["denied"]:', 'if False:'), selector) + h.check_run(result, 1, selector) + self.assertTrue(all(v["healthy"] for v in result["cli_health"])) + + def test_subtest_failures_are_counted_and_multiple_failures_do_not_qualify(self): + selector = "test_c8_quarantine.C8Quarantine.test_packet_and_normalized_source_aliases_refuse" + result = self.actual(lambda s: s.replace('if denied:\n report["problems"]', + 'if False:\n report["problems"]'), selector) + self.assertEqual(len(result["failures"]), 3) + with self.assertRaises(h.MutationError):h.check_run(result, 1, selector) + + def test_subtest_runtime_error_is_retained_and_never_qualifies(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);work = root / "work";out = root / "out";out.mkdir();h.materialize(work) + path = work / h.TEST;source = path.read_text() + start = source.index(' def test_unknown_output_is_not_coverage_or_admission(self):') + end = source.index('\n def ', start + 5) + source = source[:start] + ' def test_unknown_output_is_not_coverage_or_admission(self):\n with self.subTest(probe=True):\n raise RuntimeError("subtest crash")\n' + source[end:] + path.write_text(source);result = h.run_suite(work, out, "error-probe", "normal", SELECTOR) + self.assertEqual(result["errors"], [{"id": SELECTOR, "kind": "RuntimeError"}]) + with self.assertRaises(h.MutationError):h.check_run(result, 1, SELECTOR, 0) + + def test_early_refusal_preserves_prior_receipt_and_clears_current_pass(self): + with tempfile.TemporaryDirectory() as d: + out = Path(d) / "mutations";out.mkdir();(out / "result.json").write_text('{"status":"PASS","synthetic":true}\n') + with patch.object(h, "CASES", []), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(h.main(["--output", str(out)]), 1) + self.assertEqual(json.loads((out / "result.json").read_text())["status"], "REFUSED") + self.assertTrue(any(json.loads(p.read_text()).get("synthetic") for p in (out / "history").rglob("result.json"))) + + def fixture_probe(self, phase, minimum=1): + with tempfile.TemporaryDirectory() as d: + root = Path(d);work = root / "work";out = root / "out";out.mkdir();h.materialize(work) + method = ("test_fraction_checker_rejects_a_false_endpoint" if minimum == 0 + else "test_unknown_output_is_not_coverage_or_admission") + selector = "test_c8_quarantine.C8Quarantine." + method + marker = root / "body-entered" + extra = '\n_original_setup=C8Quarantine.setUp\n_original_body=C8Quarantine.' + method + '\n' + extra += 'def _body(self):\n Path(' + repr(str(marker)) + ').write_text("entered")\n _original_body(self)\n' + if phase == "body":extra += ' self.fail("body assertion control")\n' + extra += 'C8Quarantine.' + method + '=_body\n' + if phase == "setup": + extra += 'def _fixture(self):\n _original_setup(self)\n' + if minimum:extra += ' self.cli()\n' + extra += ' self.fail("setup assertion control")\nC8Quarantine.setUp=_fixture\n' + elif phase == "teardown": + extra += 'def _fixture(self):\n self.fail("teardown assertion control")\nC8Quarantine.tearDown=_fixture\n' + elif phase == "cleanup": + extra += 'def _fixture(self):\n _original_setup(self)\n self.addCleanup(self.fail,"cleanup assertion control")\nC8Quarantine.setUp=_fixture\n' + path = work / h.TEST;path.write_text(path.read_text() + extra) + result = h.run_suite(work, out, "fixture", "optimized" if sys.flags.optimize else "normal", selector) + return result, selector, marker.exists() + + def test_setup_assertion_is_not_an_intended_body_kill(self): + result, selector, entered = self.fixture_probe("setup") + self.assertFalse(entered);self.assertTrue(all(v["healthy"] for v in result["cli_health"])) + with self.assertRaises(h.MutationError):h.check_run(result, 1, selector) + + def test_teardown_assertion_is_not_an_intended_body_kill(self): + result, selector, entered = self.fixture_probe("teardown") + self.assertTrue(entered) + with self.assertRaises(h.MutationError):h.check_run(result, 1, selector) + + def test_cleanup_assertion_is_not_an_intended_body_kill(self): + result, selector, entered = self.fixture_probe("cleanup") + self.assertTrue(entered) + with self.assertRaises(h.MutationError):h.check_run(result, 1, selector) + + def test_fraction_setup_without_cli_is_not_an_intended_body_kill(self): + result, selector, entered = self.fixture_probe("setup", 0) + self.assertFalse(entered) + with self.assertRaises(h.MutationError):h.check_run(result, 1, selector, 0) + + def test_genuine_body_assertion_records_completed_fixture_and_body(self): + result, selector, entered = self.fixture_probe("body") + self.assertTrue(entered);h.check_run(result, 1, selector) + self.assertIn("lifecycle", result) + self.assertEqual(result["lifecycle"]["events"], [{"id": selector, "phase": "body", "kind": "failure", + "exception":"AssertionError","assertion":True}]) + self.assertEqual(result["lifecycle"]["tests"][0]["body_exited"], 1) + + def test_missing_baseline_body_evidence_refuses(self): + result = self.result();result["lifecycle"] = {"schema": "unittest.body-phase/v1", "tests": [], "events": []} + with self.assertRaises(h.MutationError):h.check_run(result, 1, SELECTOR) + + def test_phase_counter_provenance_is_required(self): + for target,key,value in (("test","body_entered",True),("test","body_exited",0), + ("test","failure_count",0),("event","phase","cleanup"),("event","assertion",False)): + with self.subTest(key=key): + result=self.result();result["lifecycle"]["tests" if target=="test" else "events"][0][key]=value + with self.assertRaises(h.MutationError):h.check_run(result,1,SELECTOR) + + def test_stale_observation_cannot_survive_a_later_startup_failure(self): + with tempfile.TemporaryDirectory() as d: + root=Path(d);work=root/"work";out=root/"out";out.mkdir();h.materialize(work) + source=(work/h.TOOL).read_text();(work/h.TOOL).write_text(source.replace(' code = 2',' code = 0')) + mode="optimized" if sys.flags.optimize else "normal" + first=h.run_suite(work,out,"reuse",mode,SELECTOR);h.check_run(first,1,SELECTOR) + receipt=out/("reuse-"+mode+".json");original=receipt.read_bytes() + path=work/h.TEST;path.write_text('raise RuntimeError("startup control")\n'+path.read_text()) + with self.assertRaises(h.MutationError): + second=h.run_suite(work,out,"reuse",mode,SELECTOR);h.check_run(second,1,SELECTOR) + self.assertEqual(receipt.read_bytes(),original) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_c8_quarantine_workflow.py b/tests/test_c8_quarantine_workflow.py new file mode 100644 index 000000000..7984daa28 --- /dev/null +++ b/tests/test_c8_quarantine_workflow.py @@ -0,0 +1,48 @@ +"""C8 workflow wiring and custody of the two original diagnostic run blocks.""" +import hashlib +import json +from pathlib import Path +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +class WorkflowControls(unittest.TestCase): + def test_all_registered_quarantine_commands_run_before_legacy_replay(self): + text = (ROOT / ".github/workflows/c8-elder-failure-coefficient.yml").read_text() + self.assertIn("A3 quarantine", text) + for command in ("python -B -S -m unittest discover -s tests -p test_c8_quarantine_mutations.py -v", + "python -B -O -S -m unittest discover -s tests -p test_c8_quarantine_mutations.py -v", + "python -B -S tools/c8_quarantine_mutations.py", + "python -B -S tools/check_c8_quarantine.py", + "--consume-output /results/k=1/J_fail"): + self.assertIn(command, text) + self.assertLess(text.index(command), text.index("Self-test, full replay against RESULTS.json, mutants")) + self.assertIn("needs: quarantine-boundary", text) + self.assertIn("if: always()", text) + self.assertIn("include-hidden-files: true", text) + + def test_both_original_replay_blocks_are_byte_preserved(self): + expected = set(json.loads((ROOT / "tools/c8_quarantine_registry.json").read_text())["legacy_run_block_sha256"]) + self.assertEqual(len(expected), 2) + lines = (ROOT / ".github/workflows/c8-elder-failure-coefficient.yml").read_text().splitlines(keepends=True) + actual = set() + for i, line in enumerate(lines): + if line.strip() != "run: |":continue + indent = len(line) - len(line.lstrip());j = i + 1 + while j < len(lines) and (not lines[j].strip() or len(lines[j]) - len(lines[j].lstrip()) > indent):j += 1 + actual.add(hashlib.sha256("".join(lines[i + 1:j]).encode()).hexdigest()) + self.assertLessEqual(expected, actual) + + def test_registry_declares_nonadmission_and_bounded_source_controls(self): + r = json.loads((ROOT / "tools/c8_quarantine_registry.json").read_text()) + self.assertEqual(r["scientific_effect"], "NONE") + self.assertIs(r["global_isolation_established"], False) + self.assertIs(r["cbz_certificate_admitted"], False) + self.assertEqual((r["denied_outputs"], r["exact_rational_witnesses"]), (106, 3)) + self.assertEqual((r["core_methods_per_mode"], r["harness_methods_per_mode"], r["declared_mutants"]), (41, 22, 13)) + self.assertIn("every CLI", r["mutation_threshold"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_cbz_kernel_gate.py b/tests/test_cbz_kernel_gate.py new file mode 100644 index 000000000..e8833ed1b --- /dev/null +++ b/tests/test_cbz_kernel_gate.py @@ -0,0 +1,521 @@ +"""CBZ native gate refusals: omitted source, forged census, stale output and bad child exit.""" +import importlib.util +import hashlib +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|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|2|3 +""" +ALIASED = """CBZ|MODULE|s41|1|1 +CBZ|DECL|s41|s536861726564|theorem +CBZ|MODULE|s42|1|0 +CBZ|DECL|s42|s536861726564|theorem +CBZ|ALIAS|s42|s536861726564|s41 +CBZ|AXIOMS| +CBZ|END|2|2|3|1|2 +""" + +def encoded(name): + return "/".join("s" + component.encode().hex() for component in name.split(".")) + +FOREIGN = "\n".join([ + "CBZ|MODULE|" + encoded("CBZNativeUsesForeignBad") + "|1|1", + "CBZ|DECL|" + encoded("CBZNativeUsesForeignBad") + "|" + encoded("CBZControlUsesBadHelper") + "|theorem", + "CBZ|MODULE|" + encoded("CBZNativeUsesForeignGood") + "|1|1", + "CBZ|DECL|" + encoded("CBZNativeUsesForeignGood") + "|" + encoded("CBZControlUsesGoodHelper") + "|theorem", + "CBZ|VARIANT|" + encoded("CBZControlSharedHelper"), + "CBZ|AXIOMS|" + encoded("sorryAx"), + "CBZ|END|2|2|8|2|7", ""]) + +FOREIGN_MODULES = ["CBZNativeUsesForeignBad", "CBZNativeUsesForeignGood"] + +class NativeGateTests(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(gate, "CBZ native gate is not implemented") + + def test_exact_theorem_alias_preserves_both_raw_records(self): + try: + report = gate.parse_audit(ALIASED, ["A", "B"]) + except gate.GateError as exc: + self.fail("valid exact theorem alias refused: " + str(exc)) + self.assertEqual(report["declaration_count"], 2) + self.assertEqual(report["unique_declaration_count"], 1) + self.assertEqual(report["module_origin_counts"], {"A": 1, "B": 0}) + self.assertEqual(len(report["aliases"]), 1) + self.assertEqual(report["closure_count"], 3) + self.assertEqual(report["closure_unique_count"], 2) + + def test_external_exact_theorem_owner_is_explicitly_accounted(self): + text = ("CBZ|MODULE|s42|1|0\nCBZ|DECL|s42|s536861726564|theorem\n" + "CBZ|ALIAS|s42|s536861726564|s4d6174686c6962/s58\n" + "CBZ|AXIOMS|\nCBZ|END|1|1|2|1|2\n") + try: + report = gate.parse_audit(text, ["B"]) + except gate.GateError as exc: + self.fail("verified imported owner refused: " + str(exc)) + self.assertEqual(report["aliases"][0]["owner"], "Mathlib.X") + + def test_alias_cannot_replace_a_missing_origin_explanation(self): + with self.assertRaisesRegex(gate.GateError, "census|alias"): + gate.parse_audit(ALIASED.replace("CBZ|ALIAS|s42|s536861726564|s41\n", ""), ["A", "B"]) + + def test_same_module_raw_name_remains_unique(self): + with self.assertRaisesRegex(gate.GateError, "duplicate"): + gate.parse_audit(ALIASED.replace("CBZ|DECL|s42|", "CBZ|DECL|s41|"), ["A", "B"]) + + def test_alias_owner_cannot_be_its_own_module(self): + with self.assertRaisesRegex(gate.GateError, "owner"): + gate.parse_audit(ALIASED.replace("CBZ|ALIAS|s42|s536861726564|s41", "CBZ|ALIAS|s42|s536861726564|s42"), ["A", "B"]) + + def test_duplicate_raw_names_require_one_consistent_owner(self): + with self.assertRaisesRegex(gate.GateError, "owner"): + gate.parse_audit(ALIASED.replace("CBZ|ALIAS|s42|s536861726564|s41", "CBZ|ALIAS|s42|s536861726564|s43"), ["A", "B"]) + + def test_only_theorem_records_may_use_alias_accounting(self): + with self.assertRaisesRegex(gate.GateError, "alias.*theorem"): + gate.parse_audit(ALIASED.replace("CBZ|DECL|s42|s536861726564|theorem", "CBZ|DECL|s42|s536861726564|def"), ["A", "B"]) + + def test_unique_name_total_cannot_impersonate_raw_record_total(self): + with self.assertRaisesRegex(gate.GateError, "unique"): + gate.parse_audit(ALIASED.replace("END|2|2|3|1|2", "END|2|2|3|2|2"), ["A", "B"]) + + def test_closure_unique_total_cannot_exceed_raw_records(self): + with self.assertRaisesRegex(gate.GateError, "unique|closure"): + gate.parse_audit(ALIASED.replace("END|2|2|3|1|2", "END|2|2|3|1|4"), ["A", "B"]) + + def test_alias_protocol_requires_raw_and_unique_terminal_counts(self): + with self.assertRaisesRegex(gate.GateError, "protocol|END|terminal"): + gate.parse_audit(ALIASED.replace("END|2|2|3|1|2", "END|2|2|3"), ["A", "B"]) + + def test_foreign_raw_proof_control_requires_the_hidden_sorry_and_variant(self): + result = gate.validate_raw_variant_control(FOREIGN, FOREIGN_MODULES, "foreign_sorry") + self.assertEqual(result["forbidden_axioms"], ["sorryAx"]) + self.assertEqual(result["raw_variant_names"], ["CBZControlSharedHelper"]) + + def test_foreign_raw_proof_control_cannot_accept_variant_only_refusal(self): + with self.assertRaisesRegex(gate.GateError, "unrelated|incomplete"): + gate.validate_raw_variant_control(FOREIGN.replace("CBZ|AXIOMS|" + encoded("sorryAx"), "CBZ|AXIOMS|"), + FOREIGN_MODULES, "foreign_sorry") + + def test_foreign_control_requires_its_actual_native_theorems(self): + with self.assertRaisesRegex(gate.GateError, "native|unrelated"): + gate.validate_raw_variant_control(FOREIGN.replace(encoded("CBZControlUsesBadHelper"), encoded("unrelated")), + FOREIGN_MODULES, "foreign_sorry") + + def test_nonidentical_raw_payload_is_refused_without_a_forbidden_axiom(self): + with self.assertRaises(gate.AuditRefused) as context: + gate.parse_audit(BASE.replace("CBZ|AXIOMS|", "CBZ|VARIANT|s4d/s74\nCBZ|AXIOMS|"), ["M"]) + self.assertEqual(context.exception.bad_variants, {("M", "t")}) + + 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|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 dependency_link_repo(self, root, relative="docs/README.md", payload="../README.md"): + dependency = root / "formal/.lake/packages/batteries" + dependency.mkdir(parents=True) + self.committed_repo(dependency) + link = dependency / relative + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(payload) + subprocess.run(["git", "-C", str(dependency), "add", relative], check=True) + subprocess.run(["git", "-C", str(dependency), "-c", "user.name=CBZ test", "-c", "user.email=cbz-test@example.invalid", "commit", "--quiet", "-m", "link fixture"], check=True) + head = subprocess.check_output(["git", "-C", str(dependency), "rev-parse", "HEAD"], text=True).strip() + return dependency, head + + def reviewed_link_policy(self, head): + payload = b"../README.md" + return {("batteries", head): {"docs/README.md": { + "git_blob": hashlib.sha1(b"blob 12\0" + payload).hexdigest(), + "payload_hex": payload.hex(), "role": "documentation alias"}}} + + def test_reviewed_dependency_link_payload_is_attested_without_following(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);dependency, head = self.dependency_link_repo(root) + self.assertFalse((dependency / "docs/README.md").exists(), "fixture target must be absent") + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", self.reviewed_link_policy(head), create=True): + result = gate.share_dependencies(root, {"projects": [{"project": "formal"}]}, {"batteries": head}) + report = result["batteries"]["tracked_source_attestation"] + link = next(row for row in report["source_records"] if row["path"] == "docs/README.md") + self.assertEqual(report["symlink_files"], 1) + self.assertEqual(link["mode"], "120000") + self.assertEqual(link["kind"], "symlink_payload") + self.assertEqual(link["payload_hex"], b"../README.md".hex()) + self.assertEqual(link["sha256"], hashlib.sha256(b"../README.md").hexdigest()) + self.assertEqual(link["role"], "documentation alias") + self.assertIs(link["target_followed"], False) + + def test_changed_reviewed_link_target_cannot_hide_behind_clean_git_status(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);dependency, head = self.dependency_link_repo(root) + subprocess.run(["git", "-C", str(dependency), "update-index", "--assume-unchanged", "docs/README.md"], check=True) + link = dependency / "docs/README.md";link.unlink();link.symlink_to("../M.lean") + self.assertEqual(gate.git_output(dependency, "status", "--porcelain"), "") + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", self.reviewed_link_policy(head), create=True): + with self.assertRaisesRegex(gate.GateError, "HEAD blob"): + gate.attest_sources(dependency, head, {"docs/README.md"}, dependency="batteries") + + def test_documentation_symlink_is_refused_by_default(self): + with tempfile.TemporaryDirectory() as d: + dependency, head = self.dependency_link_repo(Path(d)) + with self.assertRaisesRegex(gate.GateError, "source mode"): + gate.attest_sources(dependency, head, {"docs/README.md"}) + + def test_dependency_source_configuration_and_gate_links_remain_refused(self): + for name in ("Hidden.lean", "lakefile.toml", "lakefile.lean", "lake-manifest.json", "lean-toolchain", "tools/cbz_kernel_gate.py"): + with self.subTest(name=name), tempfile.TemporaryDirectory() as d: + root = Path(d);dependency, head = self.dependency_link_repo(root, name) + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", self.reviewed_link_policy(head), create=True): + with self.assertRaisesRegex(gate.GateError, "source mode"): + gate.share_dependencies(root, {"projects": [{"project": "formal"}]}, {"batteries": head}) + + def test_reviewed_metadata_link_with_symlinked_ancestor_is_refused(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d);dependency, head = self.dependency_link_repo(root) + (dependency / "docs").rename(root / "external-docs") + (dependency / "docs").symlink_to(root / "external-docs", target_is_directory=True) + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", self.reviewed_link_policy(head), create=True): + with self.assertRaisesRegex(gate.GateError, "symlink.*ancestor"): + gate.attest_sources(dependency, head, {"docs/README.md"}, dependency="batteries") + + def test_reviewed_metadata_link_must_retain_git_symlink_mode(self): + with tempfile.TemporaryDirectory() as d: + dependency, head = self.dependency_link_repo(Path(d)) + link = dependency / "docs/README.md";link.unlink();link.write_bytes(b"../README.md") + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", self.reviewed_link_policy(head), create=True): + with self.assertRaisesRegex(gate.GateError, "symlink mode"): + gate.attest_sources(dependency, head, {"docs/README.md"}, dependency="batteries") + + def test_metadata_link_review_does_not_transfer_to_another_revision(self): + with tempfile.TemporaryDirectory() as d: + dependency, head = self.dependency_link_repo(Path(d)) + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", self.reviewed_link_policy("0" * 40), create=True): + with self.assertRaisesRegex(gate.GateError, "source mode"): + gate.attest_sources(dependency, head, {"docs/README.md"}, dependency="batteries") + + def test_metadata_link_must_match_the_independently_reviewed_git_blob(self): + with tempfile.TemporaryDirectory() as d: + dependency, head = self.dependency_link_repo(Path(d)) + policy = self.reviewed_link_policy(head) + policy[("batteries", head)]["docs/README.md"]["git_blob"] = "0" * 40 + with patch.object(gate, "DEPENDENCY_METADATA_LINKS", policy, create=True): + with self.assertRaisesRegex(gate.GateError, "reviewed metadata"): + gate.attest_sources(dependency, head, {"docs/README.md"}, dependency="batteries") + + 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|2|3\n", "") + with self.assertRaisesRegex(gate.GateError, "terminal"): + gate.parse_audit("CBZ|END|1|2|3|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|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..a3a92b75e --- /dev/null +++ b/tests/test_cbz_kernel_mutations.py @@ -0,0 +1,183 @@ +"""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) +""" + +def machine_text(text, count=1, failure=True): + ids = [SELECTOR] if count == 1 else ["synthetic.NativeGateTests.test_" + str(i) for i in range(count)] + row = {"schema": "cbz.kernel.mutation-lifecycle/v1", "tests_run": count, "expected_ids": ids, + "body_started": ids, "body_returned": [] if failure else ids, + "failure_events": [{"test": SELECTOR, "phase": "body", "assertion": True}] if failure else [], + "error_events": [], "skipped": 0, "expected_failures": 0, "unexpected_successes": 0} + return text + "CBZM|" + json.dumps(row, sort_keys=True) + "\n" + +KILL = machine_text(KILL) + + +class MutationHarnessTests(unittest.TestCase): + def setUp(self): + self.assertIsNotNone(harness, "kernel mutation harness is not implemented") + + def lifecycle_fixture(self, body, selector=SELECTOR): + with tempfile.TemporaryDirectory() as d: + work = Path(d);(work / "tests").mkdir();output = work / "evidence";output.mkdir() + (work / "tests/test_cbz_kernel_gate.py").write_text( + "import unittest\nclass NativeGateTests(unittest.TestCase):\n" + body) + return harness.run_suite(work, output, "lifecycle", "normal", selector) + + def test_setup_assertion_never_counts_as_selected_body_kill(self): + result = self.lifecycle_fixture( + ' def setUp(self): self.fail("setup sentinel")\n' + ' def test_target(self): raise RuntimeError("body must not execute")\n') + self.assertEqual(result["assertion_failures"], 1) + self.assertEqual(result["test_errors"], 0) + with self.assertRaises(harness.MutationError): + harness.require_kill(result, SELECTOR) + + def test_teardown_assertion_never_counts_as_selected_body_kill(self): + result = self.lifecycle_fixture( + ' def tearDown(self): self.fail("teardown sentinel")\n' + ' def test_target(self): pass\n') + with self.assertRaises(harness.MutationError): + harness.require_kill(result, SELECTOR) + + def test_cleanup_assertion_never_counts_as_selected_body_kill(self): + result = self.lifecycle_fixture( + ' def test_target(self): self.addCleanup(lambda: self.fail("cleanup sentinel"))\n') + with self.assertRaises(harness.MutationError): + harness.require_kill(result, SELECTOR) + + def test_expected_failure_is_not_a_healthy_baseline_body(self): + result = self.lifecycle_fixture( + ' @unittest.expectedFailure\n' + ' def test_target(self): self.fail("expected body failure")\n') + with patch.object(harness, "EXPECTED_BASELINE_TESTS", 1), self.assertRaises(harness.MutationError): + harness.require_baseline(result) + + 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_66_healthy_tests(self): + harness.require_baseline(harness.suite_result(0, machine_text("Ran 66 tests in 0.1s\nOK\n", count=66, failure=False))) + for text in ("Ran 0 tests in 0.1s\nOK\n", "Ran 65 tests in 0.1s\nOK\n", + "Ran 66 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/c8_quarantine_mutations.py b/tools/c8_quarantine_mutations.py new file mode 100644 index 000000000..bb4a3819e --- /dev/null +++ b/tools/c8_quarantine_mutations.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""Bounded C8 source mutations with structured unittest and per-CLI health evidence.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import uuid + +ROOT = Path(__file__).absolute().parents[1] +TOOL = Path("tools/check_c8_quarantine.py") +TEST = Path("tests/test_c8_quarantine.py") +PACKET = Path("frontiers/c8_elder_failure_coefficient_20261001") +RECORD = Path("quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json") +EXPECTED_TESTS = 41 +CASES = [ + ("admission_flag", 'require(doc.get("cbz_certificate_admitted") is False, "certificate admission must remain false")', + 'require(True, "certificate admission must remain false")', "test_record_admission_must_be_typed_false", 1), + ("frozen_manifest", 'require(blob(raw) == MANIFEST_BLOB, "frozen packet manifest identity differs")', + 'require(True, "frozen packet manifest identity differs")', "test_refreshed_manifest_cannot_rebind_changed_sources", 1), + ("source_bytes", 'require(all(actual[k] == entry[k] for k in ("git_blob", "sha256", "bytes")),', + 'require(True,', "test_changed_source_cannot_rebind_only_quarantine_metadata", 1), + ("denied_bijection", 'and {v["json_pointer"] for v in listed} == set(denied)', + 'and True', "test_denied_inventory_cannot_duplicate_or_change_an_endpoint", 1), + ("denied_endpoints", 'and all(v == denied[v["json_pointer"]] for v in listed)', + 'and True', "test_denied_interval_endpoints_cannot_be_rewritten", 1), + ("exact_inventory", 'require(doc.get("exact_rational_exceptions") == exceptions, "exact rational exception inventory differs")', + 'require(True, "exact rational exception inventory differs")', "test_false_exact_rational_witness_refuses", 1), + ("fraction_containment", 'require(F(pair[0]) <= exact <= F(pair[1]), "exact rational containment failed")', + 'require(True, "exact rational containment failed")', "test_fraction_checker_rejects_a_false_endpoint", 0), + ("source_denial", 'if denied:\n report["problems"].append("quarantined numerical source: " + path)', + 'if False:\n report["problems"].append("quarantined numerical source: " + path)', "test_direct_packet_source_refuses", 1), + ("output_denial", 'if path in checked["denied"]:', 'if False:', + "test_all_106_published_denied_outputs_are_mechanically_denied", 1), + ("renamed_copy", 'denied = blob(regular(root, path)) in checked["copied"]', + 'denied = False', "test_renamed_c8_result_copy_cannot_evade_denial", 1), + ("shared_engine_scope", 'COPY_SOURCES = ("RESULTS.json", "certificate.py", "boxes.py", "torus.py")', + 'COPY_SOURCES = ("RESULTS.json", "certificate.py", "boxes.py", "torus.py", "ia.py")', + "test_shared_ia_or_c2_source_is_not_quarantined_by_byte_equality", 1), + ("index_typed_false", 'and entry == wanted and entry.get("cbz_certificate_admitted") is False,', + 'and entry == wanted,', "test_index_boolean_false_cannot_be_replaced_by_zero", 1), + ("unknown_admission", ' code = 2', ' code = 0', "test_unknown_output_is_not_coverage_or_admission", 1), +] + +HELPER = r''' +import importlib.util,json,pathlib,subprocess,sys,unittest +work=pathlib.Path(sys.argv[1]);result_path=pathlib.Path(sys.argv[2]);selector=sys.argv[3] +spec=importlib.util.spec_from_file_location("test_c8_quarantine",work/"tests/test_c8_quarantine.py") +t=importlib.util.module_from_spec(spec);spec.loader.exec_module(t) +try: + cmd=[sys.executable,"-B","-S",*(["-O"] if sys.flags.optimize else []),str(t.SCRIPT),"--root",str(work)] + child=subprocess.run(cmd,capture_output=True,text=True,timeout=15) + smoke=t.observe_cli(child) + smoke["healthy"]=smoke["healthy"] and child.returncode==0 and json.loads(child.stdout).get("status")=="QUARANTINE_INTEGRITY_OK" +except (OSError,subprocess.TimeoutExpired,ValueError,UnicodeError) as exc: + smoke={"healthy":False,"problems":[type(exc).__name__]} +t.CLI_HEALTH.clear() +_PHASE_COUNTERS = ('setup_entered', 'setup_completed', 'body_entered', 'body_exited', + 'teardown_entered', 'teardown_completed', 'cleanup_entered', 'cleanup_completed', + 'failure_count', 'error_count') +_ACTIVE_TEST = None + + +class PhaseResult(unittest.TextTestResult): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.lifecycle = {'schema': 'unittest.body-phase/v1', 'tests': [], 'events': []} + + def startTest(self, test): + global _ACTIVE_TEST + supported = all(getattr(type(test), name) is getattr(unittest.TestCase, name) + for name in ('run', '_callSetUp', '_callTestMethod', '_callTearDown', + '_callCleanup', 'doCleanups')) + row = {'id': test.id(), 'supported': supported, **{name: 0 for name in _PHASE_COUNTERS}} + test._qualification_record = row; test._qualification_phase = 'start' + self.lifecycle['tests'].append(row); _ACTIVE_TEST = test + super().startTest(test) + + def stopTest(self, test): + global _ACTIVE_TEST + _ACTIVE_TEST = None + super().stopTest(test) + + def event(self, test, kind, err): + event = {'id': test.id(), 'phase': getattr(test, '_qualification_phase', 'unknown'), + 'kind': kind, 'exception': err[0].__name__, 'assertion': issubclass(err[0], AssertionError)} + self.lifecycle['events'].append(event) + row = getattr(test, '_qualification_record', None) + if row is not None: row['failure_count' if kind == 'failure' else 'error_count'] += 1 + + def addFailure(self, test, err): + self.event(test, 'failure', err); super().addFailure(test, err) + + def addError(self, test, err): + self.event(test, 'error', err); super().addError(test, err) + + def addSubTest(self, test, subtest, err): + if err is not None: + self.event(test, 'failure' if issubclass(err[0], test.failureException) else 'error', err) + super().addSubTest(test, subtest, err) + + +def install_phases(): + originals = {} + for method, phase, entered, completed in ( + ('_callSetUp', 'setup', 'setup_entered', 'setup_completed'), + ('_callTestMethod', 'body', 'body_entered', 'body_exited'), + ('_callTearDown', 'teardown', 'teardown_entered', 'teardown_completed'), + ('_callCleanup', 'cleanup', 'cleanup_entered', 'cleanup_completed'), + ): + original = getattr(unittest.TestCase, method); originals[method] = original + def tracked(test, *args, _original=original, _phase=phase, _entered=entered, _completed=completed, **kwargs): + test._qualification_phase = _phase + row = getattr(test, '_qualification_record', None) + if row is None: return _original(test, *args, **kwargs) + row[_entered] += 1 + if _phase == 'body': + try: return _original(test, *args, **kwargs) + finally: row[_completed] += 1 + answer = _original(test, *args, **kwargs) + row[_completed] += 1 + return answer + setattr(unittest.TestCase, method, tracked) + return originals + +class Result(PhaseResult): + def __init__(self,*args): + super().__init__(*args);self.bad=[];self.broken=[] + def addFailure(self,test,err): + self.bad.append({"id":test.id(),"kind":err[0].__name__});super().addFailure(test,err) + def addError(self,test,err): + self.broken.append({"id":test.id(),"kind":err[0].__name__});super().addError(test,err) + def addSubTest(self,test,subtest,err): + if err is not None: + target=self.bad if issubclass(err[0],test.failureException) else self.broken + target.append({"id":test.id(),"kind":err[0].__name__}) + super().addSubTest(test,subtest,err) +suite=unittest.TestSuite([t.C8Quarantine(selector.rsplit(".",1)[-1])]) if selector else unittest.defaultTestLoader.loadTestsFromTestCase(t.C8Quarantine) +selected_ids=[test.id() for test in suite] +originals=install_phases() +original_observe=t.observe_cli +def observed_cli(child): + row=original_observe(child) + row.update(test_id=_ACTIVE_TEST.id() if _ACTIVE_TEST is not None else None, + phase=getattr(_ACTIVE_TEST,"_qualification_phase","unknown")) + return row +t.observe_cli=observed_cli +try:r=unittest.TextTestRunner(stream=sys.stderr,verbosity=2,resultclass=Result).run(suite) +finally: + for name,original in originals.items():setattr(unittest.TestCase,name,original) + t.observe_cli=original_observe +report={"tests_run":r.testsRun,"failures":r.bad,"errors":r.broken,"skipped":[x.id() for x,_ in r.skipped],"cli_health":t.CLI_HEALTH,"smoke":smoke,"selected_ids":selected_ids,"lifecycle":r.lifecycle,"expected_failures":[x.id() for x,_ in r.expectedFailures],"unexpected_successes":[x.id() for x in r.unexpectedSuccesses]} +result_path.write_text(json.dumps(report,indent=2)+"\n") +raise SystemExit(0 if r.wasSuccessful() else 1) +''' + + +class MutationError(ValueError): + pass + + +def require(condition, message): + if not condition:raise MutationError(message) + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +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) + try:compile(changed, "", "exec") + except SyntaxError as exc:raise MutationError("noncompiling mutant") from exc + return changed + + +def body_evidence(lifecycle, expected, failure_ids): + counters = {'setup_entered', 'setup_completed', 'body_entered', 'body_exited', + 'teardown_entered', 'teardown_completed', 'cleanup_entered', 'cleanup_completed', + 'failure_count', 'error_count'} + if (not isinstance(lifecycle, dict) or set(lifecycle) != {'schema', 'tests', 'events'} + or lifecycle['schema'] != 'unittest.body-phase/v1' + or not isinstance(expected, list) or not expected + or any(type(value) is not str or not value for value in expected) + or len(expected) != len(set(expected))): return False + rows, events = lifecycle['tests'], lifecycle['events'] + if not isinstance(rows, list) or not isinstance(events, list) or len(rows) != len(expected): return False + if any(not isinstance(row, dict) or set(row) != {'id', 'supported'} | counters for row in rows): return False + if [row['id'] for row in rows] != expected: return False + for row in rows: + if row['supported'] is not True or any(type(row[key]) is not int or row[key] < 0 for key in counters): return False + if any(row[key] != 1 for key in ('setup_entered', 'setup_completed', 'body_entered', 'body_exited', + 'teardown_entered', 'teardown_completed')): return False + if row['cleanup_entered'] != row['cleanup_completed'] or row['error_count'] != 0: return False + if row['failure_count'] != failure_ids.count(row['id']): return False + if len(events) != len(failure_ids): return False + for event, failure_id in zip(events, failure_ids): + if (not isinstance(event, dict) or set(event) != {'id', 'phase', 'kind', 'exception', 'assertion'} + or event['id'] != failure_id or failure_id not in expected + or event['phase'] != 'body' or event['kind'] != 'failure' + or type(event['exception']) is not str or not event['exception'] + or event['assertion'] is not True): return False + return True + + +def check_run(result, count, selector=None, minimum_cli=1): + require(isinstance(result.get("smoke"), dict) and result["smoke"].get("healthy") is True, + "unhealthy CLI smoke; a crash is not a kill") + health = result.get("cli_health") + require(isinstance(health, list) and all(isinstance(v, dict) and v.get("healthy") is True for v in health), + "unhealthy CLI invocation; a crash/invalid JSON is not a kill") + selected=result.get("selected_ids") + require(isinstance(selected,list) and len(selected)==count and len(set(selected))==count + and all(type(value) is str and value.startswith("test_c8_quarantine.C8Quarantine.") for value in selected) + and (selector is None or selected==[selector]), "selected test identity differs") + require(all(v.get("phase")=="body" and v.get("test_id") in selected for v in health), + "CLI health lacks selected-body provenance") + require(len(health) >= minimum_cli, "CLI control did not execute") + failures=result.get("failures") + require(isinstance(failures,list) and all(isinstance(v,dict) and type(v.get("id")) is str for v in failures) + and result.get("expected_failures")==[] and result.get("unexpected_successes")==[] + and body_evidence(result.get("lifecycle"),selected,[v["id"] for v in failures]), + "incomplete lifecycle or non-body assertion; fixtures do not kill mutants") + require(type(result.get("tests_run")) is int and result["tests_run"] == count and count > 0 + and result.get("errors") == [] and result.get("skipped") == [], "test count/errors/skips do not qualify") + if selector: + require(result.get("returncode") == 1 and result.get("failures") == [{"id": selector, "kind": "AssertionError"}], + "mutant lacks its one intended assertion failure") + else: + require(result.get("returncode") == 0 and result.get("failures") == [], "unmodified baseline is not healthy") + + +def materialize(work): + work.mkdir(parents=True) + shutil.copytree(ROOT / PACKET, work / PACKET) + for relative in (TOOL, TEST, RECORD, Path("PROOF_INDEX.md")): + target = work / relative;target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, target) + + +def run_suite(work, output, label, mode, selector=None): + report_path = output / (label + "-" + mode + ".json") + log_path = output / (label + "-" + mode + ".log") + require(not report_path.exists() and not report_path.is_symlink() + and not log_path.exists() and not log_path.is_symlink(), "observation output already exists") + command = [sys.executable, "-B", "-S", *(["-O"] if mode == "optimized" else []), + "-c", HELPER, str(work), str(report_path), selector or ""] + env = {k: v for k, v in os.environ.items() if k not in {"PYTHONHOME", "PYTHONPATH", "PYTHONOPTIMIZE", "PYTHONSTARTUP", "PYTHONINSPECT"}} + env["PYTHONDONTWRITEBYTECODE"] = "1" + try: + child = subprocess.run(command, cwd=work, env=env, capture_output=True, text=True, timeout=60) + stdout, stderr, code = child.stdout, child.stderr, child.returncode + except (OSError, subprocess.TimeoutExpired, UnicodeError) as exc: + stdout, stderr, code = "", type(exc).__name__, 127 + log = output / (label + "-" + mode + ".log");log.write_text(stdout + stderr) + result = json.loads(report_path.read_text()) if report_path.is_file() else {"smoke": {"healthy": False}, "startup_error": True} + result.update(returncode=code, command=command, log=log.name, log_sha256=sha(log.read_bytes())) + report_path.write_text(json.dumps(result, indent=2) + "\n") + 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) + result = {"schema": "cbz.c8-mutation-cut/v1", "status": "RUNNING", "expected_baseline_methods": EXPECTED_TESTS, + "declared_mutants": len(CASES), "source_binding": {}, "baselines": {}, "mutants": [], + "scope": "Declared C8 quarantine guards only; no arithmetic/theorem/global A3 admission."} + def retain():(output / "result.json").write_text(json.dumps(result, indent=2) + "\n") + retain() + try: + require(CASES and len({v[0] for v in CASES}) == len(CASES), "empty or duplicate mutation inventory") + inputs = [TOOL, TEST, RECORD, Path("PROOF_INDEX.md"), Path(__file__).absolute().relative_to(ROOT), + Path("tests/test_c8_quarantine_mutations.py"), + Path("tests/test_c8_quarantine_workflow.py"), Path("tools/c8_quarantine_registry.json"), + Path(".github/workflows/c8-elder-failure-coefficient.yml"), Path("docs/cbz/C8_QUARANTINE.md"), + *[p.relative_to(ROOT) for p in sorted((ROOT / PACKET).iterdir())]] + binding = {p.as_posix(): sha((ROOT / p).read_bytes()) for p in inputs} + result["source_binding"] = binding + source = (ROOT / TOOL).read_text();mutants = {name: apply_mutation(source, before, after) for name, before, after, _, _ in CASES} + sources = output / "sources";sources.mkdir() + (sources / "original.py").write_text(source);shutil.copyfile(ROOT / TEST, sources / TEST.name) + for relative in inputs: + target = sources / relative;target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(ROOT / relative, target) + for name, text in mutants.items():(sources / (name + ".py")).write_text(text) + retain() + with tempfile.TemporaryDirectory(prefix="c8-source-mutations-") as directory: + work = Path(directory) / "repo";materialize(work) + for mode in ("normal", "optimized"): + row = run_suite(work, output, "baseline", mode);result["baselines"][mode] = row;retain() + check_run(row, EXPECTED_TESTS) + for name, before, after, method, minimum in CASES: + selector = "test_c8_quarantine.C8Quarantine." + method + row = {"id": name, "selector": selector, "mutation_locations": 1, + "mutated_source_sha256": sha(mutants[name].encode()), "runs": {}} + result["mutants"].append(row);(work / TOOL).write_text(mutants[name]);retain() + try: + for mode in ("normal", "optimized"): + trial = run_suite(work, output, name, mode, selector);row["runs"][mode] = trial;retain() + check_run(trial, 1, selector, minimum) + row["outcome"] = "KILLED_BY_INTENDED_ASSERTION_BOTH_MODES_WITH_HEALTHY_CLI" + finally:(work / TOOL).write_text(source) + retain() + require(all(sha((ROOT / p).read_bytes()) == digest for p, digest in binding.items()), "source inputs changed during mutation cut") + result.update(status="PASS", killed_mutants=len(CASES));retain();return result + except (ValueError, OSError, KeyError, TypeError) as exc: + result.update(status="REFUSED", reason=str(exc));retain();raise + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=ROOT / ".lake/c8-quarantine/mutations") + args = parser.parse_args(argv) + try:result = execute(args.output.absolute()) + except (ValueError, OSError, KeyError, TypeError) as exc: + print("C8 mutation gate REFUSED: " + str(exc), file=sys.stderr);return 1 + print(json.dumps({"status": result["status"], "declared_mutants": result["declared_mutants"], + "killed_mutants": result["killed_mutants"]}));return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/c8_quarantine_registry.json b/tools/c8_quarantine_registry.json new file mode 100644 index 000000000..258d1766c --- /dev/null +++ b/tools/c8_quarantine_registry.json @@ -0,0 +1,39 @@ +{ + "schema": "cbz.tool/v1", + "id": "CBZ-MATH-C8-QUARANTINE-01", + "entrypoint": "tools/check_c8_quarantine.py", + "record": "quarantine/Q-C8-ELDER-FAILURE-BINARY64-20261029.json", + "source_snapshot": "e877242cf68fb24c605066f16dd07f513ee75a1d", + "scientific_effect": "NONE", + "cbz_certificate_admitted": false, + "global_isolation_established": false, + "scope": "Frozen eleven-file C8 packet, 106 denied output paths, three exact Fraction witnesses and canonical index only; consumer narratives and other workflows are not fully certified or isolated.", + "default_success": "QUARANTINE_INTEGRITY_OK only", + "explicit_consumption": "Denied source/output returns1; exact witness or unrelated source/output returns2 NOT_COVERED. Neither admits a certificate.", + "denied_outputs": 106, + "exact_rational_witnesses": 3, + "preserved_packet_files": 11, + "core_methods_per_mode": 41, + "harness_methods_per_mode": 22, + "workflow_methods_per_mode": 3, + "declared_mutants": 13, + "mutation_threshold": "Healthy unchanged 41-method baseline in both modes with every body entered/exited and complete fixtures; all 13 source mutants yield their designated BODY AssertionError, matching typed event/counter provenance, zero errors/skips/expected failures and healthy selected-body protocol evidence for every CLI invocation. Setup/teardown/cleanup failures and reused observation paths refuse.", + "integrity_command": "python -B -S tools/check_c8_quarantine.py", + "mutation_command": "python -B -S tools/c8_quarantine_mutations.py --output .lake/c8-quarantine/mutations", + "workflow": ".github/workflows/c8-elder-failure-coefficient.yml", + "workflow_role": "Boundary controls precede preserved legacy diagnostic replays; a green replay cannot admit the quarantined numeric pairs.", + "legacy_run_block_sha256": [ + "9184257cac6f9da3aeff53c87923349c3a283eb7360b1c306bbe14823bb2ac89", + "83f52e5e5f43ee72c265b17af9dc73d695540933eb8f4f03b48c9f34a3d7a66e" + ], + "qualification": "Only actual current-source retained receipts establish the stated bounded tests; no static A8, kernel, theorem or global A3 qualification.", + "legacy_full_replay_this_change": "NOT_EVALUATED", + "owner": null, + "maintenance": 0, + "collector_lifecycle_schema": "unittest.body-phase/v1", + "historical_pre_lifecycle_cut": { + "harness_methods_per_mode": 14, + "declared_mutants": 13, + "status": "Historical observed cut; no retroactive lifecycle qualification" + } +} diff --git a/tools/cbz_c2_oracle_qualification/README.md b/tools/cbz_c2_oracle_qualification/README.md new file mode 100644 index 000000000..18310cd9b --- /dev/null +++ b/tools/cbz_c2_oracle_qualification/README.md @@ -0,0 +1,49 @@ +# Exact C2 oracle qualification + +Component ID: CBZ-C2-ORACLE-QUALIFICATION. This is a finite external qualification of `reviews/c2_interval_audit_20261001/oracle.py`, not a new numerical engine. The original oracle, its tests, review packet and source packet remain unchanged. The source pin is SHA256 `b462b1b24613f74abd66042e0f347f69423595e9a1aedf1c6b45197425afe075`, Git blob `094bdf84bc8be7aedb4e50e1b1b3732ce0e6f112`, observed at Math `e877242cf68fb24c605066f16dd07f513ee75a1d`. + +The only mathematical output scope is the nine supplied closed forms for c, c2 and c2/c in dimensions1,2,3. Their identification with Gaussian persistence coefficients, the analytic derivation, full arithmetic-engine correctness, kernel verification, semantic completeness and federation qualification are not established here. The original positive-real Stirling remainder argument remains in the original REVIEW.md; the tests do not replace that argument. + +## Replay from the Math root + +Use Python3 with its standard library only. The observed runtime was Python3.12.14. Every output path below must be new; repeat with different names when preserving another run. + +``` +python3 -B -S tools/cbz_c2_oracle_qualification/test_qualification.py --report-json /tmp/c2-external-normal-NEW.json +python3 -B -O -S tools/cbz_c2_oracle_qualification/test_qualification.py --report-json /tmp/c2-external-optimized-NEW.json +python3 -B -S tools/cbz_c2_oracle_qualification/test_runner.py -v +python3 -B -O -S tools/cbz_c2_oracle_qualification/test_runner.py -v +python3 -B -S tools/cbz_c2_oracle_qualification/run_mutations.py --evidence-dir /tmp/c2-cut-normal-NEW +python3 -B -O -S tools/cbz_c2_oracle_qualification/run_mutations.py --evidence-dir /tmp/c2-cut-optimized-NEW +``` + +Original packet controls remain separate: + +``` +cd reviews/c2_interval_audit_20261001 +python3 -B -S -m unittest -v +python3 -B -O -S -m unittest -v +python3 -B -S verify.py --local-only +``` + +Local-only packet verification does not authenticate unavailable historical upstream Git objects. + +CI wiring is in `.github/workflows/c2-interval-audit.yml`. The original peer-source authentication and run block are preserved verbatim. The tool directory is eligible for pull-request execution. An added step runs all 19 current runner controls and both full declared mutation campaigns in normal/optimized modes, each campaign including its complete 25-case baseline. A new temporary directory retains copied original/tool sources and process evidence. The pinned upload-artifact action runs after a started qualification step even when it fails; retention is explicitly 30 days. Local step replay is recorded separately from any actual hosted result, which is not anticipated here. + +## Verification domain + +The25 external methods check exact inputs/cache aliases, dyadic and decimal outward rounding, interval corners/zero division, integer powers, selected atan/log/exp remainders, radical brackets, Gamma domain/log-Gamma(1)=0, the nine literal endpoint pairs, and results scope/containment. Wrong computed intervals, missing references, incomplete computed keys and falsified published pairs are actually injected with temporary patches. The exp-tail test temporarily uses a finer output grid to expose an omitted positive term; the original source and production240-bit setting remain unchanged. + +The original `results()` raises on false containment and missing references. It does not itself reject a missing computed key. The external qualification assertion independently requires the exact nine-key set; the source-key-omission mutant demonstrates this check. This qualification must not be represented as adding that guard to the preserved original oracle. + +The12 declared mutants change the original oracle source, not expected output data: exact-type guard, dyadic upper rounding, zero-divisor rejection, atan/log/exp remainders, root upper endpoint, Gamma remainder, decimal upper rounding, results containment, missing-reference silent omission and computed-key omission. Each has a literal unique anchor and a named test. The campaign first runs the complete25-case baseline; a test added or removed without updating the inventory causes refusal. Each mutant then runs its explicit intended test. The100% threshold means all12 of this finite inventory, not all possible defects or programs. + +A kill requires an exit1 unittest assertion failure in that exact named method, matching case identity/count and source hash, with no errors, skips, unexpected successes or launch/timeout/source-change failure. Multiple failing subcases are normalized to their real parent method. An exit0 mutant survives; a crash, malformed/missing report, wrong assertion or changed case inventory is INVALID. Baseline failure prevents mutant admission. Stale/ambiguous substitutions and original source-pin changes are refused before a cut executes. The CLI returns0 only for its fully qualified declared cut,1 for a failed cut,2 for refused input. Its output explicitly keeps kernel, semantic and federation certificate flags false. + +Twelve real-process/unit runner controls exercise a passing baseline, intended assertion, survivor, startup crash, input-dependent crash, skipped child, unintended assertion, stale/ambiguous anchors, altered source pin, newly added baseline case, stale campaign and an original changed after its initial pin read. All 12 passed normally and with `-O`. The original 38 methods and the external 25 baseline also passed in both modes; all 12 declared source mutants were killed in both modes. Earlier RED and harness-correction evidence is retained in the candidate receipt. The admitted baseline must match the original pin at execution, and the original must remain unchanged through the completed campaign. + +That12-control cut is historical. The repaired collector now emits `unittest.body-phase/v1`: supported lifecycle, successful setup, actual body entry/exit, successful teardown and completion of every cleanup, plus typed per-test event counters. A kill requires each designated failure to be an actual BODY AssertionError; fixture-phase failures refuse even if their ID and exit match. The complete baseline must attest every body. The current19 runner controls include real setup/teardown/cleanup counterexamples, a genuine body-kill positive, counter-provenance falsifiers and direct stale-output refusal in both modes. Existing probe output remains refused without overwriting its observation. Only new phase-sealed source-bound cuts qualify this repaired source; the prior12 mutant observations are not retroactively relabelled. + +## Ownership and maintenance + +Owner:none. Maintenance:zero; dormant until deliberately edited. Any change to the oracle pin, tests, runner, declared mutations or scope requires another baseline, runner-control and complete declared mutation cut. `REGISTRY.json` records this component's bounded tool entry. No reserved reviewer, approval queue, background process or root-document writer is installed. diff --git a/tools/cbz_c2_oracle_qualification/REGISTRY.json b/tools/cbz_c2_oracle_qualification/REGISTRY.json new file mode 100644 index 000000000..80e7d31dd --- /dev/null +++ b/tools/cbz_c2_oracle_qualification/REGISTRY.json @@ -0,0 +1,42 @@ +{ + "schema": "cbz.component-tool-registry.v1", + "id": "CBZ-C2-ORACLE-QUALIFICATION", + "kind": "external exact-oracle tests and finite source-mutation qualification", + "source_repository": "d6g8k5htny-coder/Math-", + "observed_source_commit": "e877242cf68fb24c605066f16dd07f513ee75a1d", + "oracle_path": "reviews/c2_interval_audit_20261001/oracle.py", + "oracle_git_blob": "094bdf84bc8be7aedb4e50e1b1b3732ce0e6f112", + "oracle_sha256": "b462b1b24613f74abd66042e0f347f69423595e9a1aedf1c6b45197425afe075", + "entrypoint": "tools/cbz_c2_oracle_qualification/run_mutations.py", + "test_suite": "tools/cbz_c2_oracle_qualification/test_qualification.py", + "runner_self_tests": "tools/cbz_c2_oracle_qualification/test_runner.py", + "usage": "See sibling README.md; all evidence paths must be new", + "ci_workflow": ".github/workflows/c2-interval-audit.yml", + "ci_original_authentication_run_block_preserved": true, + "ci_evidence_retention_days": 30, + "hosted_qualification_status": "NOT_EVALUATED", + "observed_runtime": "Python 3.12.14", + "original_tests_per_mode": 38, + "external_baseline_tests_per_mode": 25, + "runner_self_tests_per_mode": 19, + "declared_source_mutants_per_mode": 12, + "required_kills": 12, + "normal_and_optimized_observed": true, + "original_source_and_packet_bytes_preserved": true, + "scope": "Nine supplied closed-form enclosures and selected exact operations/guards/remainders under the explicit finite tests and mutants", + "source_analytic_derivation_revalidated": false, + "kernel_verified": false, + "semantic_completeness": false, + "federation_certificate": false, + "scientific_effect": "NONE", + "owner": "none", + "maintenance": "zero", + "collector_lifecycle_schema": "unittest.body-phase/v1", + "body_kill_contract": "Every selected test has supported complete setup/body-entry/body-exit/teardown/cleanup evidence. Each intended assertion event is a real BODY AssertionError and matches typed per-test event counters. Fixture failures and stale observation reuse never qualify.", + "historical_pre_lifecycle_cut": { + "runner_self_tests_per_mode": 12, + "declared_source_mutants_per_mode": 12, + "status": "Historical observed cut; no retroactive lifecycle qualification" + }, + "current_source_qualification": "Fresh phase-sealed receipt required; previous receipts remain historical" +} diff --git a/tools/cbz_c2_oracle_qualification/run_mutations.py b/tools/cbz_c2_oracle_qualification/run_mutations.py new file mode 100644 index 000000000..a491942a2 --- /dev/null +++ b/tools/cbz_c2_oracle_qualification/run_mutations.py @@ -0,0 +1,208 @@ +"""Finite source-bound C2 oracle qualification; no general arithmetic proof.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys + +HERE = Path(__file__).resolve().parent +DEFAULT_ORACLE = HERE.parents[1] / 'reviews/c2_interval_audit_20261001/oracle.py' +ORACLE_SHA256 = 'b462b1b24613f74abd66042e0f347f69423595e9a1aedf1c6b45197425afe075' +TEST = HERE / 'test_qualification.py' +CASES = ( + 'test_q_exact_rejections', 'test_q_fraction_inputs', 'test_cached_exact_inputs_reject_float_alias', + 'test_enclosure_outward', 'test_enclosure_reversed', 'test_corner_arithmetic', + 'test_division_zero_guard', 'test_power_exact_negative', 'test_atan_remainder', + 'test_log_remainder', 'test_log_domain', 'test_exp_remainder', 'test_exp_zero_reciprocal', + 'test_root_brackets', 'test_root_domain', 'test_gamma_zero_log_at_one', 'test_gamma_domain', + 'test_decimal_outward', 'test_coefficients_nine_contained', 'test_results_table_and_scope', + 'test_results_wrong_interval_rejected', 'test_results_missing_reference_rejected', + 'test_qualification_rejects_missing_computed_key', 'test_results_extra_computed_key_rejected', + 'test_qualification_rejects_falsified_reference', +) +MUTATIONS = ( + ('exact-type-guard', " if type(x) not in (int,F):raise TypeError('exact int/Fraction required')", + ' pass', 'test_q_exact_rejections'), + ('upper-rounding', 'F(ceil(b*SCALE),SCALE)', 'F(floor(b*SCALE),SCALE)', 'test_enclosure_outward'), + ('zero-division-guard', "if b[0]<=0<=b[1]:raise ValueError('division by interval containing zero')", + 'if b[0]<=0<=b[1]:return (F(-999),F(999))', 'test_division_zero_guard'), + ('atan-remainder', 'tail=x**(2*terms+1)/(2*terms+1)', 'tail=F(0)', 'test_atan_remainder'), + ('log-remainder', 'rem=2*u**(2*terms+1)/((2*terms+1)*(1-u*u))', 'rem=F(0)', 'test_log_remainder'), + ('exp-remainder', 'tail=t**(K+1)/factorial(K+1)/(1-t/F(K+2))', 'tail=F(0)', 'test_exp_remainder'), + ('root-upper-endpoint', 'return lo,lo if lo**n==t else F(k+1,SCALE)', + 'return lo,lo', 'test_root_brackets'), + ('gamma-remainder', 'rem=abs(bernoulli(2*K+2))/((2*K+2)*(2*K+1)*y**(2*K+1))', + 'rem=F(0)', 'test_gamma_zero_log_at_one'), + ('decimal-upper-rounding', 'vals=[floor(iv[0]*den),ceil(iv[1]*den)]', + 'vals=[floor(iv[0]*den),floor(iv[1]*den)]', 'test_decimal_outward'), + ('results-containment', " if not ref[0] 1024*1024: raise ValueError('invalid observation') + report = json.loads(path.read_text()) + except (ValueError, OSError, UnicodeError): report = None + classification = classify(report, code, expected_cases, source_hash, intended) + if timed_out or digest(source) != source_hash: classification = 'INVALID' + record = {'classification': classification, 'exit_code': code, 'timed_out': timed_out, + 'source_sha256': source_hash, 'command': command, 'intended_assertion': intended, + 'observation': report, 'stdout_sha256': hashlib.sha256(stdout).hexdigest(), + 'stderr_sha256': hashlib.sha256(stderr).hexdigest()} + (output / 'process.json').write_text(json.dumps(record, sort_keys=True, indent=2) + '\n') + return record + + +def campaign(oracle, output, mutations=MUTATIONS): + source = pinned_source(oracle) + names = [item[0] for item in mutations] + if not names or len(names) != len(set(names)): raise ValueError('unique nonempty mutation inventory required') + prepared = [] + for name, before, after, case in mutations: + if case not in CASES: raise ValueError('unknown intended mutation test') + prepared.append((name, substitute(source, before, after), case)) + output = Path(output).absolute(); output.mkdir(parents=True, exist_ok=False) + baseline = probe(oracle, output / 'baseline') + if baseline['source_sha256'] != ORACLE_SHA256 or digest(oracle) != ORACLE_SHA256: + baseline = {**baseline, 'classification': 'INVALID', 'source_pin_matches': False} + records = [] + if baseline['classification'] == 'PASS': + for name, text, case in prepared: + directory = output / name; directory.mkdir() + mutant = directory / 'oracle.py'; mutant.write_text(text) + record = probe(mutant, directory / 'execution', [case], case) + records.append({'name': name, **record}) + original_unchanged = digest(oracle) == ORACLE_SHA256 + qualified = original_unchanged and baseline['classification'] == 'PASS' and len(records) == len(prepared) and all( + record['classification'] == 'KILLED' for record in records) + result = {'schema': 'c2.oracle.finite-mutation-cut.v1', + 'qualified_in_declared_scope': qualified, 'baseline': baseline, 'mutations': records, + 'declared_mutants': len(prepared), 'killed': sum(r['classification'] == 'KILLED' for r in records), + 'oracle_sha256': ORACLE_SHA256, 'original_source_unchanged': original_unchanged, + 'tests_sha256': digest(TEST), 'runner_sha256': digest(__file__), + 'python': sys.version, 'optimize': sys.flags.optimize, 'scientific_effect': 'NONE', + 'source_analytic_derivation_revalidated': False, 'kernel_verified': False, + 'semantic_completeness': False, 'federation_certificate': False, + 'scope': 'Pinned nine supplied closed forms and explicit finite source mutations only'} + (output / 'REPORT.json').write_text(json.dumps(result, sort_keys=True, indent=2) + '\n') + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--oracle', type=Path, default=DEFAULT_ORACLE) + parser.add_argument('--evidence-dir', type=Path, required=True) + args = parser.parse_args() + try: + result = campaign(args.oracle, args.evidence_dir) + except (OSError, ValueError, UnicodeError) as error: + print(json.dumps({'qualified_in_declared_scope': False, 'error': str(error)}), file=sys.stderr) + return 2 + print(json.dumps({key: result[key] for key in ('qualified_in_declared_scope', 'declared_mutants', 'killed', + 'oracle_sha256', 'semantic_completeness', 'kernel_verified', 'federation_certificate')}, sort_keys=True)) + return 0 if result['qualified_in_declared_scope'] else 1 + + +if __name__ == '__main__': raise SystemExit(main()) diff --git a/tools/cbz_c2_oracle_qualification/test_qualification.py b/tools/cbz_c2_oracle_qualification/test_qualification.py new file mode 100644 index 000000000..16d495941 --- /dev/null +++ b/tools/cbz_c2_oracle_qualification/test_qualification.py @@ -0,0 +1,284 @@ +"""External qualification of the pinned nine-form oracle, not its analytic model.""" +import argparse +from fractions import Fraction as F +import hashlib +import importlib.util +import json +from math import factorial +import os +from pathlib import Path +import sys +import unittest +from unittest import mock + +DEFAULT_ORACLE = Path(__file__).resolve().parents[2] / 'reviews/c2_interval_audit_20261001/oracle.py' +ORACLE = Path(os.environ.get('C2_ORACLE_UNDER_TEST', DEFAULT_ORACLE)) +PAIRS = { + '1.c': ('0.1101103789590410', '0.1101103789590625'), + '1.c2': ('0.2300445802661503', '0.2300445802661998'), + '1.ratio': ('2.089217950577392', '2.089217950578207'), + '2.c': ('0.07340691930602738', '0.07340691930604167'), + '2.c2': ('0.2215244106266632', '0.2215244106267110'), + '2.ratio': ('3.017759261945122', '3.017759261946299'), + '3.c': ('0.04177593184059426', '0.04177593184060272'), + '3.c2': ('0.1612340491269447', '0.1612340491269810'), + '3.ratio': ('3.859496174547095', '3.859496174548665'), +} + + +class OracleQualification(unittest.TestCase): + @classmethod + def setUpClass(cls): + spec = importlib.util.spec_from_file_location('qualified_c2_oracle', ORACLE) + cls.o = importlib.util.module_from_spec(spec) + spec.loader.exec_module(cls.o) + + def assert_table(self, report): + self.assertEqual(set(report['values']), set(PAIRS)) + self.assertEqual(report['scope'], 'independent numerical certification of the nine supplied closed forms only') + self.assertEqual(report['scientific_effect'], 'NONE') + self.assertIs(report['source_analytic_derivation_revalidated'], False) + self.assertIs(report['binary_float_used'], False) + self.assertEqual((report['dyadic_bits'], report['Gamma_shift'], report['Gamma_terms']), (240, 40, 20)) + for key, item in report['values'].items(): + self.assertEqual(tuple(item['published_interval']), PAIRS[key]) + lo, hi = map(F, PAIRS[key]) + a, b = map(F, item['independent_rational_interval']) + self.assertTrue(lo < a <= b < hi, key) + self.assertIs(item['strictly_inside'], True) + + def test_q_exact_rejections(self): + for value in (True, False, 0.5, '1/3', None): + with self.subTest(value=value), self.assertRaises(TypeError): self.o.q(value) + + def test_q_fraction_inputs(self): + for value in (-3, 0, 7, F(1, 3), -F(11, 17)): + self.assertIs(type(self.o.q(value)), F) + self.assertEqual(self.o.q(value), value) + + def test_cached_exact_inputs_reject_float_alias(self): + for function in (self.o.log_bounds, self.o.lngamma_bounds, self.o.gamma_bounds): + function.cache_clear(); function(F(1, 2)) + with self.subTest(function=function.__name__), self.assertRaises(TypeError): function(0.5) + + def test_enclosure_outward(self): + grid = F(1, self.o.SCALE) + for value in (grid / 3, -grid / 3): + lo, hi = self.o.enclosure(value) + self.assertTrue(lo <= value <= hi) + self.assertEqual(hi - lo, grid) + + def test_enclosure_reversed(self): + with self.assertRaises(ValueError): self.o.enclosure(F(2), F(1)) + + def test_corner_arithmetic(self): + a, b = (-F(7, 5), F(2, 3)), (-F(5, 3), -F(1, 7)) + for operation, exact in ((self.o.plus, lambda x, y: x+y), + (self.o.minus, lambda x, y: x-y), + (self.o.times, lambda x, y: x*y), + (self.o.over, lambda x, y: x/y)): + lo, hi = operation(a, b) + for x in a: + for y in b: self.assertTrue(lo <= exact(x, y) <= hi) + + def test_division_zero_guard(self): + for divisor in ((-F(1), F(1)), (F(0), F(1)), (-F(1), F(0))): + with self.subTest(divisor=divisor), self.assertRaises(ValueError): + self.o.over((F(1), F(2)), divisor) + + def test_power_exact_negative(self): + self.assertEqual(self.o.power((F(2), F(2)), -3), (F(1, 8), F(1, 8))) + with self.assertRaises(TypeError): self.o.power((F(2), F(2)), True) + + def test_atan_remainder(self): + lo, hi = self.o.atan_inv(5, terms=1) + self.assertLessEqual(lo, F(74, 375)) + self.assertGreaterEqual(hi, F(1, 5)) + self.assertLess(lo, hi) + + def test_log_remainder(self): + lo, hi = self.o._log_small(F(3, 2), terms=1) + self.assertLessEqual(lo, F(2, 5)) + self.assertGreaterEqual(hi, F(2, 5) + F(2, 375)) + + def test_log_domain(self): + for value in (F(0), -F(1)): + with self.assertRaises(ValueError): self.o.log_bounds(value) + for value in (F(1, 2), F(3)): + with self.assertRaises(ValueError): self.o._log_small(value) + + def test_exp_remainder(self): + # A finer test-only output grid exposes the positive omitted term; + # the oracle's immutable source and production 240-bit setting stay intact. + with mock.patch.object(self.o, 'SCALE', 1 << 2048): + lo, hi = self.o.exp_bounds(F(1, 2)) + positive_partial = sum((F(1, 2)**j / factorial(j) for j in range(102)), F(0)) + self.assertLess(lo, positive_partial) + self.assertGreaterEqual(hi, positive_partial) + + def test_exp_zero_reciprocal(self): + self.assertEqual(self.o.exp_bounds(F(0)), (F(1), F(1))) + lo, hi = self.o.times(self.o.exp_bounds(F(7, 5)), self.o.exp_bounds(-F(7, 5))) + self.assertTrue(lo <= 1 <= hi) + + def test_root_brackets(self): + self.assertEqual(self.o.root_bounds(F(64), 6), (F(2), F(2))) + for value, root in ((F(12), 6), (F(6), 2), (F(7, 3), 3)): + lo, hi = self.o.root_bounds(value, root) + self.assertTrue(lo**root <= value <= hi**root) + self.assertLessEqual(hi-lo, F(1, self.o.SCALE)) + + def test_root_domain(self): + for value, root in ((-F(1), 2), (F(1), 0), (F(1), True)): + with self.assertRaises(ValueError): self.o.root_bounds(value, root) + + def test_gamma_zero_log_at_one(self): + lo, hi = self.o.lngamma_bounds(F(1)) + self.assertTrue(lo <= 0 <= hi, 'Gamma(1)=1 requires log-Gamma(1)=0') + + def test_gamma_domain(self): + for value in (F(0), -F(1, 6)): + with self.assertRaises(ValueError): self.o.gamma_bounds(value) + + def test_decimal_outward(self): + for interval in ((F(1, 3), F(2, 3)), (-F(2, 3), -F(1, 3))): + lo, hi = map(F, self.o.decimal_pair(interval, places=20)) + self.assertTrue(lo <= interval[0] <= interval[1] <= hi) + + def test_coefficients_nine_contained(self): + values = self.o.coefficients() + self.assertEqual(set(values), set(PAIRS)) + self.assertEqual(self.o.PUBLISHED, PAIRS) + for key, (a, b) in values.items(): + lo, hi = map(F, PAIRS[key]) + self.assertTrue(lo < a <= b < hi, key) + self.assertIs(type(a), F); self.assertIs(type(b), F) + + def test_results_table_and_scope(self): + self.assert_table(self.o.results()) + + def test_results_wrong_interval_rejected(self): + wrong = dict(self.o.coefficients()); wrong['1.c'] = (F(2), F(3)) + with mock.patch.object(self.o, 'coefficients', return_value=wrong), self.assertRaises(ArithmeticError): + self.o.results() + + def test_results_missing_reference_rejected(self): + references = dict(PAIRS); del references['1.c'] + with mock.patch.object(self.o, 'PUBLISHED', references), self.assertRaises(KeyError): + self.o.results() + + def test_qualification_rejects_missing_computed_key(self): + incomplete = dict(self.o.coefficients()); del incomplete['1.ratio'] + with mock.patch.object(self.o, 'coefficients', return_value=incomplete): + report = self.o.results() + # The original results() itself does not enforce computed key completeness. + with self.assertRaises(AssertionError): self.assert_table(report) + + def test_results_extra_computed_key_rejected(self): + extra = dict(self.o.coefficients()); extra['extra'] = (F(1), F(1)) + with mock.patch.object(self.o, 'coefficients', return_value=extra), self.assertRaises(KeyError): + self.o.results() + + def test_qualification_rejects_falsified_reference(self): + references = dict(PAIRS); references['1.c'] = ('-1', '1') + with mock.patch.object(self.o, 'PUBLISHED', references): report = self.o.results() + with self.assertRaises(AssertionError): self.assert_table(report) + + +_PHASE_COUNTERS = ('setup_entered', 'setup_completed', 'body_entered', 'body_exited', + 'teardown_entered', 'teardown_completed', 'cleanup_entered', 'cleanup_completed', + 'failure_count', 'error_count') +_ACTIVE_TEST = None + + +class PhaseResult(unittest.TextTestResult): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.lifecycle = {'schema': 'unittest.body-phase/v1', 'tests': [], 'events': []} + + def startTest(self, test): + global _ACTIVE_TEST + supported = all(getattr(type(test), name) is getattr(unittest.TestCase, name) + for name in ('run', '_callSetUp', '_callTestMethod', '_callTearDown', + '_callCleanup', 'doCleanups')) + row = {'id': test.id(), 'supported': supported, **{name: 0 for name in _PHASE_COUNTERS}} + test._qualification_record = row; test._qualification_phase = 'start' + self.lifecycle['tests'].append(row); _ACTIVE_TEST = test + super().startTest(test) + + def stopTest(self, test): + global _ACTIVE_TEST + _ACTIVE_TEST = None + super().stopTest(test) + + def event(self, test, kind, err): + event = {'id': test.id(), 'phase': getattr(test, '_qualification_phase', 'unknown'), + 'kind': kind, 'exception': err[0].__name__, 'assertion': issubclass(err[0], AssertionError)} + self.lifecycle['events'].append(event) + row = getattr(test, '_qualification_record', None) + if row is not None: row['failure_count' if kind == 'failure' else 'error_count'] += 1 + + def addFailure(self, test, err): + self.event(test, 'failure', err); super().addFailure(test, err) + + def addError(self, test, err): + self.event(test, 'error', err); super().addError(test, err) + + def addSubTest(self, test, subtest, err): + if err is not None: + self.event(test, 'failure' if issubclass(err[0], test.failureException) else 'error', err) + super().addSubTest(test, subtest, err) + + +def install_phases(): + originals = {} + for method, phase, entered, completed in ( + ('_callSetUp', 'setup', 'setup_entered', 'setup_completed'), + ('_callTestMethod', 'body', 'body_entered', 'body_exited'), + ('_callTearDown', 'teardown', 'teardown_entered', 'teardown_completed'), + ('_callCleanup', 'cleanup', 'cleanup_entered', 'cleanup_completed'), + ): + original = getattr(unittest.TestCase, method); originals[method] = original + def tracked(test, *args, _original=original, _phase=phase, _entered=entered, _completed=completed, **kwargs): + test._qualification_phase = _phase + row = getattr(test, '_qualification_record', None) + if row is None: return _original(test, *args, **kwargs) + row[_entered] += 1 + if _phase == 'body': + try: return _original(test, *args, **kwargs) + finally: row[_completed] += 1 + answer = _original(test, *args, **kwargs) + row[_completed] += 1 + return answer + setattr(unittest.TestCase, method, tracked) + return originals + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--report-json', type=Path, required=True) + parser.add_argument('--case', action='append') + args = parser.parse_args() + names = args.case or unittest.defaultTestLoader.getTestCaseNames(OracleQualification) + if len(names) != len(set(names)) or any(name not in unittest.defaultTestLoader.getTestCaseNames(OracleQualification) for name in names): + parser.error('unknown or duplicate case') + if args.report_json.exists() or args.report_json.is_symlink(): parser.error('report output already exists') + suite = unittest.TestSuite(OracleQualification(name) for name in names) + identities = [test.id() for test in suite] + originals = install_phases() + try: result = unittest.TextTestRunner(verbosity=2, resultclass=PhaseResult).run(suite) + finally: + for name, original in originals.items(): setattr(unittest.TestCase, name, original) + def identity(test): return getattr(test, 'test_case', test).id() + report = {'schema': 'c2.oracle.qualification-observation.v1', 'test_ids': identities, + 'tests_run': result.testsRun, 'lifecycle': result.lifecycle, + 'expected_failures': [identity(test) for test, _ in result.expectedFailures], 'failures': [identity(test) for test, _ in result.failures], + 'errors': [identity(test) for test, _ in result.errors], + 'skipped': [identity(test) for test, _ in result.skipped], + 'unexpected_successes': [test.id() for test in result.unexpectedSuccesses], + 'was_successful': result.wasSuccessful(), 'oracle_sha256': hashlib.sha256(ORACLE.read_bytes()).hexdigest()} + args.report_json.write_text(json.dumps(report, sort_keys=True, indent=2) + '\n') + return 0 if result.wasSuccessful() else 1 + + +if __name__ == '__main__': raise SystemExit(main()) diff --git a/tools/cbz_c2_oracle_qualification/test_runner.py b/tools/cbz_c2_oracle_qualification/test_runner.py new file mode 100644 index 000000000..5bda622dd --- /dev/null +++ b/tools/cbz_c2_oracle_qualification/test_runner.py @@ -0,0 +1,158 @@ +"""Real-process controls for the finite C2 source-mutator's kill classification.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest +import copy +from unittest import mock + +HERE = Path(__file__).resolve().parent +RUNNER = HERE / 'run_mutations.py' +ORIGINAL = HERE.parents[1] / 'reviews/c2_interval_audit_20261001/oracle.py' + + +class RunnerControls(unittest.TestCase): + def setUp(self): + self.assertTrue(RUNNER.is_file(), 'C2 mutation runner is not supplied') + spec = importlib.util.spec_from_file_location('c2_runner_under_test', RUNNER) + self.runner = importlib.util.module_from_spec(spec); spec.loader.exec_module(self.runner) + self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name); self.source = ORIGINAL.read_text() + + def probe(self, text, case='test_q_fraction_inputs', intended=None): + path = self.root / 'oracle.py'; path.write_text(text) + return self.runner.probe(path, self.root / 'probe', [case], intended) + + def test_valid_baseline_process(self): + result = self.probe(self.source) + self.assertEqual(result['classification'], 'PASS') + self.assertEqual(result['observation']['tests_run'], 1) + + def test_intended_assertion_is_a_kill(self): + text = self.runner.substitute(self.source, " if type(x) not in (int,F):raise TypeError('exact int/Fraction required')", ' pass') + result = self.probe(text, 'test_q_exact_rejections', 'test_q_exact_rejections') + self.assertEqual(result['classification'], 'KILLED') + self.assertEqual(result['observation']['errors'], []) + + def test_surviving_source_is_not_a_kill(self): + result = self.probe(self.source + '\n# surviving control\n', intended='test_q_fraction_inputs') + self.assertEqual(result['classification'], 'SURVIVED') + + def test_startup_crash_is_not_a_kill(self): + result = self.probe("raise RuntimeError('startup control')\n" + self.source, + intended='test_q_fraction_inputs') + self.assertEqual(result['classification'], 'INVALID') + + def test_input_dependent_crash_is_not_a_kill(self): + text = self.runner.substitute(self.source, ' return F(x)', + " if x == F(1,3):raise RuntimeError('input-dependent control')\n return F(x)") + result = self.probe(text, intended='test_q_fraction_inputs') + self.assertEqual(result['classification'], 'INVALID') + self.assertTrue(result['observation']['errors']) + + def test_skip_is_not_a_kill(self): + result = self.probe("import unittest\nraise unittest.SkipTest('skip control')\n" + self.source, + intended='test_q_fraction_inputs') + self.assertEqual(result['classification'], 'INVALID') + + def test_unintended_assertion_is_not_a_kill(self): + text = self.runner.substitute(self.source, " if type(x) not in (int,F):raise TypeError('exact int/Fraction required')", ' pass') + result = self.probe(text, 'test_q_exact_rejections', 'test_root_brackets') + self.assertEqual(result['classification'], 'INVALID') + + def test_stale_or_ambiguous_substitution_is_refused(self): + for text, anchor in ((self.source, 'missing anchor'), ('xx', 'x')): + with self.assertRaisesRegex(ValueError, 'anchor must occur exactly once'): + self.runner.substitute(text, anchor, 'replacement') + + def test_changed_original_pin_is_refused(self): + path = self.root / 'wrong-original.py'; path.write_text(self.source + '\n') + with self.assertRaisesRegex(ValueError, 'oracle source pin mismatch'): + self.runner.pinned_source(path) + + def test_complete_baseline_cannot_omit_a_new_case(self): + driver = self.root / 'qualification.py' + text = self.runner.TEST.read_text().replace( + "if __name__ == '__main__': raise SystemExit(main())", + "OracleQualification.test_added_case = lambda self: None\n" + "if __name__ == '__main__': raise SystemExit(main())") + driver.write_text(text) + with mock.patch.object(self.runner, 'TEST', driver): + result = self.runner.campaign(ORIGINAL, self.root / 'complete-cut') + self.assertFalse(result['qualified_in_declared_scope']) + self.assertEqual(result['baseline']['classification'], 'INVALID') + + def test_stale_campaign_refuses_before_execution(self): + output = self.root / 'stale-cut' + with self.assertRaisesRegex(ValueError, 'anchor must occur exactly once'): + self.runner.campaign(ORIGINAL, output, + [('stale', 'missing anchor', 'replacement', 'test_q_fraction_inputs')]) + self.assertFalse(output.exists()) + + def test_source_changed_after_pin_cannot_qualify(self): + source = self.root / 'changing-original.py'; source.write_text(self.source) + original_pin = self.runner.pinned_source + def changed_after_read(path): + text = original_pin(path) + source.write_text(text + '\n# changed after pin\n') + return text + with mock.patch.object(self.runner, 'pinned_source', changed_after_read): + result = self.runner.campaign(source, self.root / 'changed-cut') + self.assertFalse(result['qualified_in_declared_scope']) + self.assertEqual(result['baseline']['classification'], 'INVALID') + + def fixture_probe(self, phase): + method='test_q_fraction_inputs';marker=self.root/'body-entered' + text=self.source+'\nimport sys as _sys\nfrom pathlib import Path as _Path\n_C=_sys.modules["__main__"].OracleQualification\n_original_body=_C.'+method+'\n' + text+='def _body(self):\n _Path('+repr(str(marker))+').write_text("entered")\n _original_body(self)\n' + if phase=='body':text+=' self.fail("body assertion control")\n' + text+='_C.'+method+'=_body\n' + if phase=='setup':text+='def _fixture(self):\n self.fail("setup assertion control")\n_C.setUp=_fixture\n' + elif phase=='teardown':text+='def _fixture(self):\n self.fail("teardown assertion control")\n_C.tearDown=_fixture\n' + elif phase=='cleanup':text+='def _fixture(self):\n self.addCleanup(self.fail,"cleanup assertion control")\n_C.setUp=_fixture\n' + result=self.probe(text,method,method) + return result,marker.exists() + + def test_setup_assertion_is_not_a_body_kill(self): + result,entered=self.fixture_probe('setup');self.assertFalse(entered) + self.assertEqual(result['classification'],'INVALID') + + def test_teardown_assertion_is_not_a_body_kill(self): + result,entered=self.fixture_probe('teardown');self.assertTrue(entered) + self.assertEqual(result['classification'],'INVALID') + + def test_cleanup_assertion_is_not_a_body_kill(self): + result,entered=self.fixture_probe('cleanup');self.assertTrue(entered) + self.assertEqual(result['classification'],'INVALID') + + def test_genuine_body_kill_has_lifecycle_provenance(self): + result,entered=self.fixture_probe('body');self.assertTrue(entered) + self.assertEqual(result['classification'],'KILLED') + self.assertIn('lifecycle',result['observation']) + self.assertEqual(result['observation']['lifecycle']['events'],[{ + 'id':'__main__.OracleQualification.test_q_fraction_inputs','phase':'body','kind':'failure', + 'exception':'AssertionError','assertion':True}]) + + def test_all_baseline_bodies_are_observed(self): + result=self.probe(self.source) + self.assertIn('lifecycle',result['observation']) + self.assertEqual(result['observation']['lifecycle']['tests'][0]['body_entered'],1) + self.assertEqual(result['observation']['lifecycle']['tests'][0]['body_exited'],1) + + def test_inconsistent_lifecycle_counters_are_invalid(self): + result,_=self.fixture_probe('body') + for target,key,value in (('test','body_entered',True),('test','body_exited',0), + ('test','failure_count',0),('event','phase','cleanup'),('event','assertion',False)): + with self.subTest(key=key): + report=copy.deepcopy(result['observation']) + report['lifecycle']['tests' if target=='test' else 'events'][0][key]=value + self.assertEqual(self.runner.classify(report,1,['test_q_fraction_inputs'],result['source_sha256'], + 'test_q_fraction_inputs'),'INVALID') + + def test_existing_probe_output_cannot_reuse_stale_observation(self): + self.probe(self.source);path=self.root/'probe/observation.json';original=path.read_bytes() + with self.assertRaises(FileExistsError):self.probe('raise RuntimeError("startup control")\n'+self.source) + self.assertEqual(path.read_bytes(),original) + + +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..9e7a6c81b --- /dev/null +++ b/tools/cbz_kernel_gate.py @@ -0,0 +1,1158 @@ +#!/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"}) + +# Complete link census of the nine pinned dependency trees. These exact aliases +# are not compiler inputs to this gate. Never resolve their targets or extend +# this reviewed catalog from checkout contents or an invocation parameter. +DEPENDENCY_METADATA_LINKS = { + ("batteries", "f2effa3d803fda822b1f97b806c47cf2adfbcbc2"): { + "docs/README.md": {"git_blob": "32d46ee883b58d6a383eed06eb98f33aa6530ded", + "payload_hex": "2e2e2f524541444d452e6d64", "role": "documentation alias"}}, + ("mathlib", MATHLIB_REV): { + "scripts/bench/build/fake-root/bin/lean.py": { + "git_blob": "819298943e1a8c331413fb55e2c4bbc98d05e562", "payload_hex": "6c65616e", + "role": "inactive benchmark alias; not gate runtime or compiler input"}, + "scripts/bench/size/run.py": { + "git_blob": "e5224d533ef27b001224859a9b36696846a7e7fe", "payload_hex": "72756e", + "role": "inactive benchmark alias; not gate runtime or compiler input"}}, +} + +class GateError(ValueError): + pass + +class AuditRefused(GateError): + def __init__(self, bad_axioms, bad_declarations, declarations=(), bad_variants=()): + self.bad_axioms = set(bad_axioms) + self.bad_declarations = list(bad_declarations) + self.declarations = list(declarations) + self.bad_variants = set(bad_variants) + 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) + if self.bad_variants: + details.append("nonidentical raw theorem variants: " + ", ".join(sorted(render_name(v) for v in self.bad_variants))) + 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, origins, aliases = {}, {}, {} + declarations, keys, unique_names = [], set(), set() + axioms, terminal = None, None + variants = set() + 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: + module = decode_name(fields[2]) + require(module not in counts, "duplicate audited module") + require(fields[3].isdigit() and fields[4].isdigit(), "malformed module count") + header_count, origin_count = int(fields[3]), int(fields[4]) + require(header_count >= origin_count, "compiled origin count exceeds raw header records") + counts[module], origins[module] = header_count, origin_count + elif tag == "DECL" and len(fields) == 5: + module, name = decode_name(fields[2]), decode_name(fields[3]) + key = (module, name) + require(key not in keys, "duplicate compiled declaration in one module") + keys.add(key) + unique_names.add(name) + declarations.append({"module": render_name(module), "_module": module, "_name": name, + "encoded_module": fields[2], "name": render_name(name), + "encoded_name": fields[3], "kind": fields[4]}) + elif tag == "ALIAS" and len(fields) == 5: + module, name, owner = (decode_name(v) for v in fields[2:]) + key = (module, name) + require(key not in aliases, "duplicate raw theorem alias") + require(owner != module, "alias owner cannot be its own module") + require(MODULE.fullmatch(render_name(owner)) and tuple(render_name(owner).split(".")) == owner, + "malformed alias owner module") + aliases[key] = owner + elif tag == "VARIANT" and len(fields) == 3: + name = decode_name(fields[2]) + require(name not in variants, "duplicate raw variant finding") + variants.add(name) + elif tag == "AXIOMS" and len(fields) == 3: + require(axioms is None, "duplicate axiom closure") + axioms = [] if not fields[2] else [decode_name(v) for v in fields[2].split(",")] + require(len(axioms) == len(set(axioms)), "duplicate transitive axiom") + elif tag == "END" and len(fields) == 7: + require(all(v.isdigit() for v in fields[2:]), "malformed terminal END counts") + 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(declarations, "empty project declaration inventory") + require(terminal[3] == len(unique_names), "native unique-name terminal count mismatch") + require(terminal[2] >= len(declarations), "raw transitive closure count is smaller than declaration record count") + require(terminal[4] >= terminal[3] and terminal[2] >= terminal[4], + "closure unique-name count disagrees with raw closure records") + by_key = {(row["_module"], row["_name"]): row for row in declarations} + for row in declarations: + require(row["_module"] in counts, "declaration outside native module inventory") + for key, owner in aliases.items(): + require(key in by_key and key[0] in counts, "alias does not identify a native raw record") + require(by_key[key]["kind"] == "theorem", "alias requires a theorem raw record") + if owner in counts: + require((owner, key[1]) in by_key and (owner, key[1]) not in aliases, + "alias owner has no original native raw record") + require(by_key[(owner, key[1])]["kind"] == "theorem", "alias owner requires a theorem raw record") + for module, header_count in counts.items(): + rows = [row for row in declarations if row["_module"] == module] + module_aliases = sum(key[0] == module for key in aliases) + require(len(rows) == header_count, "per-module raw declaration count mismatch") + require(header_count == origins[module] + module_aliases, + "independent compiled census disagreement: " + render_name(module)) + for name in unique_names: + rows = [row for row in declarations if row["_name"] == name] + owners = {aliases.get((row["_module"], name), row["_module"]) for row in rows} + require(len(owners) == 1, "duplicate raw declarations have inconsistent owners") + if len(rows) > 1: + require(all(row["kind"] == "theorem" for row in rows), "alias groups require theorem raw records") + public_rows = [{k: v for k, v in row.items() if not k.startswith("_")} for row in declarations] + alias_rows = [{"module": render_name(module), "encoded_module": by_key[(module, name)]["encoded_module"], + "name": render_name(name), "encoded_name": by_key[(module, name)]["encoded_name"], + "owner": render_name(owner)} + for (module, name), owner in aliases.items()] + bad = set(axioms) - ALLOWED_AXIOM_NAMES + bad_declarations = [row for row in public_rows if row["kind"] not in SAFE_KINDS] + if bad or bad_declarations or variants: + raise AuditRefused(bad, bad_declarations, public_rows, variants) + return {"protocol_version": 2, "declaration_count": len(public_rows), + "raw_declaration_count": len(public_rows), "unique_declaration_count": len(unique_names), + "module_counts": {render_name(k): v for k, v in counts.items()}, + "module_origin_counts": {render_name(k): v for k, v in origins.items()}, + "aliases": alias_rows, "declarations": public_rows, + "axioms": sorted(render_name(v) for v in axioms), + "closure_count": terminal[2], "closure_unique_count": terminal[4], + "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" +abbrev RawId := Nat × Nat +abbrev RawIndex := NameMap (Array RawId) +def rawInfo? (env : Environment) (key : RawId) : Option ConstantInfo := do + let data ← env.header.moduleData[key.1]? + data.constants[key.2]? +def exactTheorem (a b : ConstantInfo) : Bool := + match a, b with + | .thmInfo av, .thmInfo bv => + av.name == bv.name && av.levelParams == bv.levelParams && + Expr.equal av.type bv.type && Expr.equal av.value bv.value && av.all == bv.all + | _, _ => false +def importedIndex (env : Environment) : RawIndex := Id.run do + let mut result : RawIndex := {} + for moduleIdx in [:env.header.moduleData.size] do + let data := env.header.moduleData[moduleIdx]! + for constantIdx in [:data.constants.size] do + let ci := data.constants[constantIdx]! + let versions := (result.find? ci.name).getD #[] + result := result.insert ci.name (versions.push (moduleIdx, constantIdx)) + return result +structure St where + visited : Std.HashSet RawId := {} + names : NameSet := {} + axioms : NameSet := {} + missing : NameSet := {} + variants : NameSet := {} + invalidRecord : Bool := false +mutual +partial def collectName (env : Environment) (index : RawIndex) (name : Name) : StateM St Unit := do + modify fun s => { s with names := s.names.insert name } + match index.find? name with + | none => modify fun s => { s with missing := s.missing.insert name } + | some versions => + let selected := env.checked.get.find? name + if selected.isNone then + modify fun s => { s with missing := s.missing.insert name } + for recordId in versions do + match rawInfo? env recordId with + | none => modify fun s => { s with invalidRecord := true } + | some ci => + if ci.name != name then + modify fun s => { s with invalidRecord := true } + if versions.size > 1 then + unless selected.any (exactTheorem ci) do + modify fun s => { s with variants := s.variants.insert name } + collectRecord env index recordId +partial def collectRecord (env : Environment) (index : RawIndex) (recordId : RawId) : StateM St Unit := do + unless (← get).visited.contains recordId do + modify fun s => { s with visited := s.visited.insert recordId } + match rawInfo? env recordId with + | none => modify fun s => { s with invalidRecord := true } + | some ci => + modify fun s => { s with names := s.names.insert ci.name } + let expr (e : Expr) : StateM St Unit := e.getUsedConstants.forM (collectName env index) + match ci with + | .axiomInfo v => modify (fun s => { s with axioms := s.axioms.insert ci.name }) *> expr v.type + | .defnInfo v => expr v.type *> expr v.value + | .thmInfo v => expr v.type *> expr v.value + | .opaqueInfo v => expr v.type *> expr v.value + | .quotInfo _ => pure () + | .ctorInfo v => expr v.type + | .recInfo v => expr v.type + | .inductInfo v => expr v.type *> v.ctors.forM (collectName env index) +end +end CBZInternalAudit +run_cmd do + let env := (← getEnv).setExporting false + let modules : Array Name := #[__CBZ_MODULE_NAMES__] + let index := CBZInternalAudit.importedIndex env + -- Verify index coverage independently from construction, including foreign modules. + let mut expectedRecords : Nat := 0 + for moduleIdx in [:env.header.moduleData.size] do + let data := env.header.moduleData[moduleIdx]! + unless data.constNames == data.constants.map (·.name) do + throwError "raw constNames/constants disagreement in imported module {moduleIdx}" + let mut localNames : NameSet := {} + for constantIdx in [:data.constants.size] do + let ci := data.constants[constantIdx]! + if localNames.contains ci.name then + throwError "duplicate raw declaration inside one module {moduleIdx}: {ci.name}" + localNames := localNames.insert ci.name + let versions := (index.find? ci.name).getD #[] + unless (versions.filter (· == (moduleIdx, constantIdx))).size == 1 do + throwError "raw index omitted or duplicated imported record {moduleIdx}:{constantIdx} {ci.name}" + expectedRecords := expectedRecords + 1 + let mut indexedRecords : Nat := 0 + let mut indexKeys : Std.HashSet CBZInternalAudit.RawId := {} + for (name, versions) in index.toList do + for recordId in versions do + let some ci := CBZInternalAudit.rawInfo? env recordId + | throwError "raw index points outside imported module tables" + unless ci.name == name do + throwError "raw index name disagrees with imported declaration" + if indexKeys.contains recordId then + throwError "raw index repeats an imported record" + indexKeys := indexKeys.insert recordId + indexedRecords := indexedRecords + 1 + unless expectedRecords == indexedRecords do + throwError "raw imported index coverage disagreement {expectedRecords} versus {indexedRecords}" + let constants := env.constants.toList + let mut audited : Array CBZInternalAudit.RawId := #[] + let mut auditedNames : NameSet := {} + let mut aliasProblems : Array Name := #[] + let mut censusProblems : Array String := #[] + 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 headerNames := (data.constants.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 + let headerOnly := headerNames.filter fun name => !originNames.contains name + let originOnly := originNames.filter fun name => !headerNames.contains name + let mut aliasCount : Nat := 0 + liftIO <| IO.println s!"CBZ|MODULE|{CBZInternalAudit.enc modName}|{headerNames.size}|{originNames.size}" + for constantIdx in [:data.constants.size] do + let ci := data.constants[constantIdx]! + let some selected := env.checked.get.find? ci.name + | throwError "missing checked kernel declaration {ci.name}" + let some owner := env.getModuleIdxFor? ci.name + | throwError "missing imported origin for raw native declaration {ci.name}" + audited := audited.push (idx.toNat, constantIdx) + auditedNames := auditedNames.insert ci.name + liftIO <| IO.println s!"CBZ|DECL|{CBZInternalAudit.enc modName}|{CBZInternalAudit.enc ci.name}|{CBZInternalAudit.kind ci}" + if owner != idx then + let versions := (index.find? ci.name).getD #[] + let ownerWitness := versions.any fun key => + key.1 == owner.toNat && (CBZInternalAudit.rawInfo? env key).any (CBZInternalAudit.exactTheorem ci) + if CBZInternalAudit.exactTheorem ci selected && ownerWitness then + let ownerName := env.header.modules[owner]!.module + liftIO <| IO.println s!"CBZ|ALIAS|{CBZInternalAudit.enc modName}|{CBZInternalAudit.enc ci.name}|{CBZInternalAudit.enc ownerName}" + aliasCount := aliasCount + 1 + else + aliasProblems := aliasProblems.push ci.name + else if !originNames.contains ci.name then + censusProblems := censusProblems.push s!"origin-owned raw declaration omitted: {ci.name}" + unless originOnly.isEmpty && headerNames.size == originNames.size + aliasCount do + censusProblems := censusProblems.push s!"independent compiled census disagreement {modName}: {headerNames.size} versus {originNames.size}; header-only {headerOnly}; origin-only {originOnly}" + -- Each native instance is a direct root; its Name also reaches every imported version. + let computation : StateM CBZInternalAudit.St Unit := do + for recordId in audited do + CBZInternalAudit.collectRecord env index recordId + let some ci := CBZInternalAudit.rawInfo? env recordId + | modify fun s => { s with invalidRecord := true } + CBZInternalAudit.collectName env index ci.name + let (_, closure) := computation.run {} + if closure.invalidRecord || !closure.missing.isEmpty then + throwError "missing raw transitive declaration {closure.missing.toArray}; invalid record {closure.invalidRecord}" + if !aliasProblems.isEmpty then + throwError "unverified native theorem alias {aliasProblems}; raw axioms {closure.axioms.toArray}" + if !censusProblems.isEmpty then + throwError "{censusProblems}" + for name in (closure.variants.toArray.map CBZInternalAudit.enc).qsort (· < ·) do + liftIO <| IO.println s!"CBZ|VARIANT|{name}" + 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}|{auditedNames.size}|{closure.names.size}" +""".replace("__CBZ_MODULE_NAMES__", names) + +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, *, dependency=None): + """Bind actual consumed bytes to commit blobs; index flags/status cannot substitute.""" + repo = Path(repo).absolute() + require(not any(p.is_symlink() for p in [repo, *repo.parents]), "symlink source checkout ancestor") + entries = git_tree_entries(repo, commit) if entries is None else entries + metadata_links = DEPENDENCY_METADATA_LINKS.get((dependency, commit), {}) + 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"} + or entry["mode"] == "120000" and relative in metadata_links), + "unsupported or missing HEAD blob source mode: " + relative) + path = repo / pure + ancestors = [repo.joinpath(*pure.parts[:i]) for i in range(1, len(pure.parts))] + require(not any(p.is_symlink() for p in ancestors), "symlink HEAD blob source ancestor: " + relative) + if entry["mode"] == "120000": + reviewed = metadata_links[relative] + require(entry["blob"] == reviewed["git_blob"], "unreviewed metadata Git blob: " + relative) + require(path.is_symlink(), "reviewed metadata link lost Git symlink mode: " + relative) + data = os.readlink(os.fsencode(path)) + link_blob = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest() + require(link_blob == entry["blob"] and data.hex() == reviewed["payload_hex"], + "symlink payload differs from HEAD blob: " + relative) + rows.append({"path": relative, "git_blob": link_blob, "sha256": hashlib.sha256(data).hexdigest(), + "mode": entry["mode"], "kind": "symlink_payload", "payload_hex": data.hex(), + "role": reviewed["role"], "target_followed": False}) + continue + require(path.is_file() and not path.is_symlink(), + "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, + "symlink_files": sum(row.get("kind") == "symlink_payload" for row in 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, dependency=name) + 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: + require(not exc.bad_variants, "negative control refused for unrelated raw payload variants") + 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 validate_raw_variant_control(text, modules, label): + """Require the exact raw-record finding, never an unrelated compile/parser failure.""" + shared = ("CBZControlSharedProof",) + cases = { + "native_sorry": ({("sorryAx",)}, set(), {shared}, {(modules[0], shared, "theorem")}), + "native_axiom": ({shared}, {(shared, "axiom")}, {shared}, {(modules[0], shared, "axiom")}), + "native_custom": ({("CBZControlForeignPremise",)}, set(), {shared}, {(modules[0], shared, "theorem")}), + "different_valid": (set(), set(), {shared}, {(modules[0], shared, "theorem")}), + "foreign_sorry": ({("sorryAx",)}, set(), {("CBZControlSharedHelper",)}, { + ("CBZNativeUsesForeignBad", ("CBZControlUsesBadHelper",), "theorem"), + ("CBZNativeUsesForeignGood", ("CBZControlUsesGoodHelper",), "theorem")}), + } + require(label in cases, "unknown raw-record negative control") + expected_axioms, expected_bad, expected_variants, expected_native = cases[label] + try: + parse_audit(text, modules) + except AuditRefused as exc: + bad = {(decode_name(row["encoded_name"]), row["kind"]) for row in exc.bad_declarations} + actual_native = {(row["module"], decode_name(row["encoded_name"]), row["kind"]) + for row in exc.declarations} + require(exc.bad_axioms == expected_axioms and bad == expected_bad + and exc.bad_variants == expected_variants, + "raw-record control refused for unrelated or incomplete findings: " + label) + require(actual_native == expected_native and len(exc.declarations) == len(expected_native), + "raw-record control omitted or changed its actual native declarations: " + label) + return {"outcome": "REJECTED_EXACT_RAW_RECORD_FINDINGS", "diagnostic": str(exc), + "forbidden_axioms": sorted(render_name(v) for v in exc.bad_axioms), + "raw_variant_names": sorted(render_name(v) for v in exc.bad_variants), + "declarations": exc.declarations, "raw_declaration_count": len(exc.declarations), + "unique_declaration_count": len({decode_name(row["encoded_name"]) for row in exc.declarations})} + raise GateError("raw-record control escaped: " + label) + +def generated_foreign_version_mutation(project, out, timeout, modules): + """A compiled foreign helper must detect selected-only traversal of raw versions.""" + original = audit_source(modules) + before = " for recordId in versions do\n match rawInfo? env recordId with" + after = " for recordId in versions.extract (versions.size - 1) versions.size do\n match rawInfo? env recordId with" + require(original.count(before) == 1, "stale generated-auditor foreign-version mutation") + path = out / "MutatedForeignVersionAudit.lean" + path.write_text(original.replace(before, after, 1)) + run = run_logged(["lake", "env", "lean", str(path)], "generated-foreign-version-mutant", out, project, timeout) + require(not (out / "generated-foreign-version-mutant.stderr").read_text().strip(), + "generated foreign-version mutant produced unexpected diagnostics") + text = (out / "generated-foreign-version-mutant.stdout").read_text() + accepted = parse_audit(text, modules) + require(not accepted["axioms"] and accepted["raw_declaration_count"] == 2 + and accepted["unique_declaration_count"] == 2, + "foreign-version mutation did not produce its intended complete false clear") + try: + validate_raw_variant_control(text, modules, "foreign_sorry") + except GateError as exc: + require(type(exc) is GateError and str(exc) == "raw-record control escaped: foreign_sorry", + "generated foreign-version mutant failed for an unrelated reason") + diagnostic = str(exc) + else: + raise GateError("generated foreign-version mutant was not detected by the compiled control") + result = {"id": "omit_foreign_raw_versions", "outcome": "KILLED_BY_COMPILED_FOREIGN_SORRY_CONTROL", + "scope": "One actual generated collector mutation; imported-index coverage remains active.", + "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-foreign-version-result.json", result) + return result + +def raw_record_controls(project, out, timeout): + """Compiled core fixtures for exact aliases and hidden native/foreign proof payloads.""" + out.mkdir(parents=True, exist_ok=True) + source_root = project / ".lake" + target = source_root / "build/lib/lean" + target.mkdir(parents=True, exist_ok=True) + retained = out / "sources" + retained.mkdir(parents=True, exist_ok=True) + fixtures = { + "CBZAliasGoodA": "import Lean\ntheorem CBZControlSharedProof : True := True.intro\n", + "CBZAliasGoodB": "import Lean\ntheorem CBZControlSharedProof : True := by exact True.intro\n", + "CBZAliasBadSorry": "import Lean\ntheorem CBZControlSharedProof : True := by sorry\n", + "CBZAliasBadAxiom": "import Lean\naxiom CBZControlSharedProof : True\n", + "CBZAliasPremise": "import Lean\naxiom CBZControlForeignPremise : True\n", + "CBZAliasBadCustom": "import CBZAliasPremise\ntheorem CBZControlSharedProof : True := CBZControlForeignPremise\n", + "CBZAliasAlternative": "import Lean\ntheorem CBZControlAlternative : True := True.intro\n", + "CBZAliasDifferent": "import CBZAliasAlternative\ntheorem CBZControlSharedProof : True := CBZControlAlternative\n", + "CBZForeignBad": "import Lean\ntheorem CBZControlSharedHelper : True := by sorry\n", + "CBZForeignGood": "import Lean\ntheorem CBZControlSharedHelper : True := True.intro\n", + "CBZNativeUsesForeignBad": "import CBZForeignBad\ntheorem CBZControlUsesBadHelper : True := CBZControlSharedHelper\n", + "CBZNativeUsesForeignGood": "import CBZForeignGood\ntheorem CBZControlUsesGoodHelper : True := CBZControlSharedHelper\n", + } + before = {} + for module, source in fixtures.items(): + path = source_root / (module + ".lean") + path.write_text(source) + source_before = digest(path) + shutil.copyfile(path, retained / path.name) + obj = target / (module + ".olean") + compile_run = run_logged(["lake", "env", "lean", "--root=" + str(source_root), + "-o", str(obj), str(path)], "raw-" + module + "-compile", out, project, timeout) + require(obj.is_file() and not obj.is_symlink(), "raw fixture omitted object: " + module) + object_before = digest(obj) + kernel_run = run_logged(["lake", "env", "leanchecker", module], "raw-" + module + "-kernel", out, project, timeout) + require(digest(path) == source_before and digest(obj) == object_before, + "raw fixture source or object changed during compile/kernel replay: " + module) + before[module] = {"source_sha256": source_before, "object_sha256": object_before, + "compile": compile_run, "kernel": kernel_run} + + def audit(label, modules, extra_import=None): + source = audit_source(modules) + if extra_import: + source = "import " + modules[0] + "\nimport " + extra_import + "\n" + source.split("\n", 1)[1] + path = out / (label + "Audit.lean") + path.write_text(source) + run_logged(["lake", "env", "lean", str(path)], label + "-audit", out, project, timeout) + require(not (out / (label + "-audit.stderr")).read_text().strip(), + "raw-record audit emitted unexpected diagnostics: " + label) + return (out / (label + "-audit.stdout")).read_text() + + reports = {} + modules = ["CBZAliasGoodA", "CBZAliasGoodB"] + reports["exact_alias"] = parse_audit(audit("exact-alias", modules), modules) + require(reports["exact_alias"]["raw_declaration_count"] == 2 + and reports["exact_alias"]["unique_declaration_count"] == 1 + and len(reports["exact_alias"]["aliases"]) == 1, "identical alias control lost a raw instance") + modules = ["CBZNativeUsesForeignGood"] + reports["foreign_good"] = parse_audit(audit("foreign-good", modules), modules) + require({r["name"] for r in reports["foreign_good"]["declarations"]} == {"CBZControlUsesGoodHelper"}, + "foreign-good control omitted its actual theorem") + for label, module in (("native_sorry", "CBZAliasBadSorry"), ("native_axiom", "CBZAliasBadAxiom"), + ("native_custom", "CBZAliasBadCustom"), ("different_valid", "CBZAliasDifferent")): + reports[label] = validate_raw_variant_control(audit(label, [module], "CBZAliasGoodA"), [module], label) + modules = ["CBZNativeUsesForeignBad", "CBZNativeUsesForeignGood"] + reports["foreign_sorry"] = validate_raw_variant_control(audit("foreign-sorry", modules), modules, "foreign_sorry") + reports["generated_foreign_version_mutation"] = generated_foreign_version_mutation(project, out, timeout, modules) + for module, record in before.items(): + require(digest(source_root / (module + ".lean")) == record["source_sha256"] + and digest(target / (module + ".olean")) == record["object_sha256"], + "raw fixture source or object changed during preflight: " + module) + reports["fixtures"] = before + write_json(out / "raw-record-controls-result.json", reports) + return reports + +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 = "| .thmInfo v => expr v.type *> expr v.value" + after = "| .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") + reports["raw_records"] = raw_record_controls(project, out / "raw-records", timeout) + 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..e5b632181 --- /dev/null +++ b/tools/cbz_kernel_mutations.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Nine bounded source-guard mutations; crashes/errors/skips never count as kills.""" +from __future__ import annotations +import argparse +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +import tempfile +import uuid +import unittest + +ROOT = Path(__file__).resolve().parents[1] +TOOL = Path("tools/cbz_kernel_gate.py") +TEST = Path("tests/test_cbz_kernel_gate.py") +EXPECTED_BASELINE_TESTS = 66 +CASES = [ + ("independent_census", + 'require(header_count == origins[module] + module_aliases,\n "independent compiled census disagreement: " + render_name(module))', + 'require(True, "independent compiled census disagreement: " + render_name(module))', + "test_independent_census_disagreement_is_refused"), + ("unused_custom_axiom", + 'bad_declarations = [row for row in public_rows 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"), + ("dependency_link_payload_binding", + 'require(link_blob == entry["blob"] and data.hex() == reviewed["payload_hex"],\n "symlink payload differs from HEAD blob: " + relative)', + 'require(True, "symlink payload differs from HEAD blob: " + relative)', + "test_changed_reviewed_link_target_cannot_hide_behind_clean_git_status"), + ("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), len(unique_names), len(unique_names))', + "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 _tests(suite): + for item in suite: + if isinstance(item, unittest.TestSuite): + yield from _tests(item) + else: + yield item + +def child_suite(work, selector=None): + """Bespoke collector: failures in fixture lifecycle are never test-body kills.""" + test_path = Path(work) / TEST + spec = importlib.util.spec_from_file_location("test_cbz_kernel_gate", test_path) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + loader = unittest.TestLoader() + suite = loader.loadTestsFromName(selector) if selector else loader.loadTestsFromModule(module) + tests = list(_tests(suite)) + expected = [test.id() for test in tests] + phases, started, returned = {}, [], [] + + def wrap(test, attribute, phase): + original = getattr(test, attribute) + test_id = test.id() + def call(*args, **kwargs): + phases[test_id] = phase + if phase == "body": + started.append(test_id) + value = original(*args, **kwargs) + if phase == "body": + returned.append(test_id) + return value + setattr(test, attribute, call) + + for test in tests: + for attribute, phase in (("_callSetUp", "setup"), ("_callTestMethod", "body"), + ("_callTearDown", "teardown"), ("doCleanups", "cleanup")): + wrap(test, attribute, phase) + + class PhaseResult(unittest.TextTestResult): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.failure_events, self.error_events = [], [] + def event(self, test, error): + return {"test": test.id(), "phase": phases.get(test.id(), "fixture"), + "assertion": issubclass(error[0], AssertionError)} + def addFailure(self, test, error): + self.failure_events.append(self.event(test, error)) + super().addFailure(test, error) + def addError(self, test, error): + self.error_events.append(self.event(test, error)) + super().addError(test, error) + def addSubTest(self, test, subtest, error): + if error is not None: + target = self.failure_events if issubclass(error[0], test.failureException) else self.error_events + target.append(self.event(test, error)) + super().addSubTest(test, subtest, error) + + result = unittest.TextTestRunner(verbosity=2, resultclass=PhaseResult).run(suite) + lifecycle = {"schema": "cbz.kernel.mutation-lifecycle/v1", "tests_run": result.testsRun, + "expected_ids": expected, "body_started": started, "body_returned": returned, + "failure_events": result.failure_events, "error_events": result.error_events, + "skipped": len(result.skipped), "expected_failures": len(result.expectedFailures), + "unexpected_successes": len(result.unexpectedSuccesses)} + print("CBZM|" + json.dumps(lifecycle, sort_keys=True)) + return 0 if result.wasSuccessful() else 1 + +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) + records = re.findall(r"^CBZM\|([^\n]+)$", output, re.M) + valid = len(runs) == len(summaries) == len(records) == 1 + summary = summaries[0] if summaries else "" + counts = {} + if "(" in summary: + for entry in summary.split("(", 1)[1].removesuffix(")").split(","): + if "=" in entry: + key, value = entry.strip().rsplit("=", 1) + if key in {"failures", "errors", "skipped"} and value.isdigit(): + counts[key] = int(value) + lifecycle = {} + if valid: + try: + def unique(pairs): + row = {} + for key, value in pairs: + if key in row: + raise ValueError("duplicate lifecycle key") + row[key] = value + return row + lifecycle = json.loads(records[0], object_pairs_hook=unique) + required = {"schema", "tests_run", "expected_ids", "body_started", "body_returned", + "failure_events", "error_events", "skipped", "expected_failures", "unexpected_successes"} + valid = (isinstance(lifecycle, dict) and set(lifecycle) == required + and lifecycle["schema"] == "cbz.kernel.mutation-lifecycle/v1") + for field in ("tests_run", "skipped", "expected_failures", "unexpected_successes"): + valid = valid and type(lifecycle[field]) is int and lifecycle[field] >= 0 + for field in ("expected_ids", "body_started", "body_returned"): + values = lifecycle[field] + valid = valid and isinstance(values, list) and all(isinstance(v, str) and v for v in values) + valid = valid and len(values) == len(set(values)) + for field in ("failure_events", "error_events"): + values = lifecycle[field] + valid = valid and isinstance(values, list) and all( + isinstance(v, dict) and set(v) == {"test", "phase", "assertion"} + and isinstance(v["test"], str) and v["phase"] in {"setup", "body", "teardown", "cleanup", "fixture"} + and type(v["assertion"]) is bool for v in values) + valid = valid and lifecycle["tests_run"] == int(runs[0]) + valid = valid and len(lifecycle["failure_events"]) == counts.get("failures", 0) + valid = valid and len(lifecycle["error_events"]) == counts.get("errors", 0) + valid = valid and lifecycle["skipped"] == counts.get("skipped", 0) + except (ValueError, TypeError, KeyError): + valid, lifecycle = False, {} + return {"returncode": returncode, "valid_protocol": bool(valid), + "tests_run": int(runs[0]) if len(runs) == 1 else 0, + "assertion_failures": counts.get("failures", 0), "test_errors": counts.get("errors", 0), + "tests_skipped": counts.get("skipped", 0), + "failing_tests": [row["test"] for row in lifecycle.get("failure_events", [])], + "error_tests": [row["test"] for row in lifecycle.get("error_events", [])], + "has_assertion_error": "AssertionError" in output, "summary": summary, + "expected_tests": lifecycle.get("expected_ids", []), + "body_started": lifecycle.get("body_started", []), "body_returned": lifecycle.get("body_returned", []), + "failure_events": lifecycle.get("failure_events", []), "error_events": lifecycle.get("error_events", []), + "expected_failures": lifecycle.get("expected_failures", 0), + "unexpected_successes": lifecycle.get("unexpected_successes", 0)} + +def require_baseline(result): + expected = result["expected_tests"] + require(result["valid_protocol"] and result["returncode"] == 0 + and result["tests_run"] == EXPECTED_BASELINE_TESTS and len(expected) == EXPECTED_BASELINE_TESTS + and result["body_started"] == result["body_returned"] == expected + and result["assertion_failures"] == result["test_errors"] == result["tests_skipped"] == 0 + and result["expected_failures"] == result["unexpected_successes"] == 0 + and not result["failing_tests"] and not result["error_tests"] and result["summary"] == "OK", + "unmodified baseline is not healthy in every declared test body") + +def require_kill(result, selector): + event = {"test": selector, "phase": "body", "assertion": True} + require(result["valid_protocol"] and result["returncode"] == 1 and result["tests_run"] == 1 + and result["assertion_failures"] == 1 and result["test_errors"] == result["tests_skipped"] == 0 + and result["expected_failures"] == result["unexpected_successes"] == 0 + and result["expected_tests"] == result["body_started"] == [selector] + and result["failure_events"] == [event] and not result["error_events"] + and result["failing_tests"] == [selector] and result["has_assertion_error"], + "mutant was not killed by its selected test-body assertion; fixture failures/errors/skips 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 []), + str(Path(__file__).resolve()), "--_child-root", str(work)] + if selector: + command += ["--_child-selector", selector] + 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": "Nine 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), "runner_sha256": sha(Path(__file__).read_bytes())} + 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"] + and sha(Path(__file__).read_bytes()) == binding["runner_sha256"], + "auditor source/test changed during mutation execution") + report.update(status="PASS", killed_mutants=len(report["mutants"]), + threshold="All nine 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")) + parser.add_argument("--_child-root", type=Path, help=argparse.SUPPRESS) + parser.add_argument("--_child-selector", help=argparse.SUPPRESS) + args = parser.parse_args(argv) + if args._child_root is not None: + return child_suite(args._child_root, args._child_selector) + 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..946aca706 --- /dev/null +++ b/tools/cbz_kernel_registry.json @@ -0,0 +1,172 @@ +{ + "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": "RAW_IMPORTED_RECORD_REPAIR_CANDIDATE_HOSTED_UNQUALIFIED", + "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.", + "first_hosted_attempt": { + "run_id": "40933241149", + "job_id": "123656926883", + "checked_merge_commit": "80bdeac2c7a88b51da13a81d47d458c0d474f0c6", + "result": "REFUSED_BEFORE_NATIVE_BUILDS", + "reason": "Regular-only dependency attestation refused the pinned Batteries documentation symlink docs/README.md; fixed candidate requires a new actual hosted run." + }, + "dependency_metadata_links": { + "policy": "Only these exact reviewed package/revision/path/blob/payload tuples; raw link payload attested and enumerated without following targets. All other symlinks and symlinked source ancestors refuse.", + "tree_census": "All nine pinned dependency trees inspected recursively without truncation; three symlinks total.", + "compiler_role": "None in this gate; installed Lean runtime remains separate. Benchmark aliases are inactive.", + "entries": [ + { + "package": "batteries", + "revision": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "path": "docs/README.md", + "git_blob": "32d46ee883b58d6a383eed06eb98f33aa6530ded", + "payload_hex": "2e2e2f524541444d452e6d64", + "role": "documentation alias" + }, + { + "package": "mathlib", + "revision": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "path": "scripts/bench/build/fake-root/bin/lean.py", + "git_blob": "819298943e1a8c331413fb55e2c4bbc98d05e562", + "payload_hex": "6c65616e", + "role": "inactive benchmark alias; not gate runtime or compiler input" + }, + { + "package": "mathlib", + "revision": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "path": "scripts/bench/size/run.py", + "git_blob": "e5224d533ef27b001224859a9b36696846a7e7fe", + "payload_hex": "72756e", + "role": "inactive benchmark alias; not gate runtime or compiler input" + } + ] + }, + "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", + "complete imported raw table/index coverage with exact constNames/ConstantInfo names", + "independent native header/environment-origin census reconciled only by explicit exact theorem aliases", + "every native raw declaration instance directly audited, including coalesced names", + "all reachable raw imported ConstantInfo versions traversed by module/record identity", + "exact theorem payload equality for duplicate reachable names; nonidentical payloads refuse", + "all-record transitive axiom closure inside explicit core set, with raw-record and unique-Name counts separately validated", + "compiled unused-axiom, sorry and native_decide controls refused for exact forbidden findings", + "compiled identical aliases accepted with both raw records; native sorry/axiom/custom and foreign hidden-sorry controls refused for their exact findings", + "final source and dependency identity readback" + ], + "allowed_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ], + "not_established": [ + "all-eight-project native kernel/axiom qualification until a source-bound success receipt exists", + "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": 66, + "declared_python_source_mutants": 9, + "modes": [ + "normal", + "optimized" + ], + "required": "Every baseline test body must execute and return successfully. Every nonstale compiling mutant must yield exactly its selected test-body AssertionError; setup/teardown/cleanup failures, errors, skips and startup failures refuse. Stale cases refuse.", + "actual_generated_lean_mutants": 2, + "generated_threshold": "Theorem-value omission and skipping foreign raw versions must each compile/run with complete false-clear protocol and be caught by their exact 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." + }, + "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" + }, + "third_hosted_attempt": { + "run_id": "40945793449", + "job_id": "123700672950", + "feature_head": "0a631dea171071398c05a877f858c5e5997a7753", + "checked_merge_commit": "a22a0e395f108e85116f03b5a9813042afbd4829", + "result": "REFUSED_AT_PROJECT_2_COMPILED_CENSUS", + "module": "SpecificationProofs.P15Hazard", + "header_count": 46, + "origin_count": 45, + "header_only": [ + "UniversalLaw.Spec.P15.block.eq_1" + ], + "origin_only": [], + "artifact": { + "id": "12930262595", + "bytes": 746874, + "files": 366, + "sha256": "c6b81d8163211c75bcb87ab72323bccf296f55e8b62bbc61a561bb8695535e99" + }, + "qualification": "No all-native success; first two project outcomes are historical TOOL-REPORTED outcomes of the selected-only collector, not new all-record qualification." + }, + "raw_record_repair": { + "protocol_version": 2, + "raw_identity": "Imported module index plus constant-table index; Name alone is never the visited key.", + "exact_alias_policy": "Theorem constructor, name, level parameters, Expr.equal type and proof value, and TheoremVal.all must agree with selected checked CI and a raw owner witness. No general proof-irrelevance alias permission.", + "dependency_policy": "Every reachable raw imported version is traversed, including foreign helpers. Missing names/records and incomplete indexes refuse. Pinned dependency objects remain an explicit cache trust boundary.", + "evidence_scope": "Compiled pinned-core fixture qualification only; all eight real native projects require a fresh hosted successor and final source/object readback.", + "conservative_refusal": "Different valid proof payloads also refuse; no Mathlib-specific bad proof is inferred from generic adversarial controls.", + "historical_collector_limit": "The earlier selected-only collector has a compiled generic foreign-helper counterexample with complete 1/1 native censuses; historical project outcomes do not establish the repaired closure policy.", + "integration_state": "Five code/test/workflow blobs match frozen de98c85e gate cut; registry preserves root diagnostic history and current arithmetic instruments. Fresh hosted all-native execution required." + } +} diff --git a/tools/check_c8_quarantine.py b/tools/check_c8_quarantine.py new file mode 100644 index 000000000..56f37b91d --- /dev/null +++ b/tools/check_c8_quarantine.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""One frozen C8 quarantine boundary. Integrity and exact witnesses never grant admission.""" +from fractions import Fraction as F +import argparse +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import posixpath +import re +import stat + +QID = "Q-C8-ELDER-FAILURE-BINARY64-20261029" +BASE = "e877242cf68fb24c605066f16dd07f513ee75a1d" +PACKET = "frontiers/c8_elder_failure_coefficient_20261001" +RECORD = "quarantine/" + QID + ".json" +MANIFEST_BLOB = "1efc243fa447e7162644b939b2cd2200270e9874" +OBJECT = "CL-C8-ELDER-FAILURE-COEFFICIENT-20261001-v1" +DENIED_SOURCES = (PACKET, PACKET + "/RESULTS.json", PACKET + "/certificate.py", + PACKET + "/boxes.py", PACKET + "/torus.py") +COPY_SOURCES = ("RESULTS.json", "certificate.py", "boxes.py", "torus.py") +MOMENT_IDENTITY = "6*(6*k + 1/(4*k) + 5/(216*k^3))" + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def blob(raw): + return hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest() + + +def unique_object(pairs): + result = {} + for key, value in pairs: + require(key not in result, "duplicate JSON member: " + ascii(key)) + result[key] = value + return result + + +def strict_json(raw): + try: + return json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object, + parse_constant=lambda value: (_ for _ in ()).throw(ValueError("nonfinite JSON: " + value))) + except UnicodeError as exc: + raise ValueError("invalid UTF-8 JSON") from exc + + +def regular(root, relative): + pure = PurePosixPath(relative) + require(not pure.is_absolute() and pure.parts and ".." not in pure.parts + and pure.as_posix() == relative, "unsafe local source path") + for i in range(1, len(pure.parts)): + path = root.joinpath(*pure.parts[:i]) + mode = path.lstat().st_mode + require(stat.S_ISDIR(mode), "regular local source ancestor required: " + relative) + require(mode & 0o444 and mode & 0o111, "unreadable local source ancestor: " + relative) + path = root / relative + mode = path.lstat().st_mode + require(stat.S_ISREG(mode), "regular local source required: " + relative) + require(mode & 0o444, "unreadable local source: " + relative) + return path.read_bytes() + + +def normalized_consumer(value): + require(isinstance(value, str) and value and not value.startswith("/") + and not any(x in value for x in ("\\", ":", "\0")), "unsafe consumer path") + result = posixpath.normpath(value) + require(result != ".." and not result.startswith("../"), "unsafe consumer path") + return result + + +def pointer(path): + return "/" + "/".join(x.replace("~", "~0").replace("/", "~1") for x in path) + + +def canonical_pointer(value): + require(isinstance(value, str) and value.startswith("/results/") + and not re.search(r"~(?![01])", value), "invalid output pointer") + path = [part.replace("~1", "/").replace("~0", "~") for part in value[1:].split("/")] + require(pointer(path) == value, "invalid output pointer") + return value + + +def interval_pairs(document): + rows = {} + def walk(value, path): + if isinstance(value, dict): + for key, item in value.items(): + walk(item, path + [key]) + elif isinstance(value, list) and len(value) == 2 and all(isinstance(v, str) for v in value): + key = pointer(path) + require(key not in rows, "duplicate published output") + rows[key] = {"path": path, "json_pointer": key, "interval": value} + walk(document["results"], ["results"]) + require(len(rows) == 109, "frozen 109-output inventory differs") + return rows + + +def exact_exceptions(document): + result = [] + for k, label in ((F(1, 2), "k=0.5"), (F(1), "k=1"), (F(2), "k=2")): + exact = 6 * (6 * k + F(1) / (4 * k) + F(5) / (216 * k ** 3)) + row = document["results"][label] + pair = row["parts"]["E[2T]"] + require(row["E[2T] exact"] == str(exact), "exact rational identity differs") + require(F(pair[0]) <= exact <= F(pair[1]), "exact rational containment failed") + result.append({"path": ["results", label, "parts", "E[2T]"], "interval": pair, + "exact_value": str(exact), "identity": MOMENT_IDENTITY, "k": str(k), + "method": "Exact Fraction formula and exact decimal containment; no binary64 execution."}) + return result + + +def audit(root): + require((root / RECORD).exists(), "missing quarantine record") + record_raw = regular(root, RECORD) + doc = strict_json(record_raw) + require(isinstance(doc, dict) and doc.get("schema") == "cbz.quarantine/v1" and doc.get("id") == QID, + "unsupported quarantine record") + require(doc.get("classification") == "QUARANTINED" and doc.get("layer_a") == "A3" + and doc.get("layer_a_status") == "A3_NOT_PROVEN", "explicit A3 classification required") + require(doc.get("cbz_certificate_admitted") is False, "certificate admission must remain false") + require(doc.get("owner") is None, "owner must remain unassigned") + require(type(doc.get("maintenance")) is int and doc["maintenance"] == 0, "maintenance must remain zero") + require(isinstance(doc.get("isolation"), dict) and doc["isolation"].get("global_A3_audit") is False, + "limited opt-in scope must remain explicit") + boundary = doc.get("not_proven_boundary") + require(isinstance(boundary, list) and boundary and all(isinstance(v, str) and v.strip() for v in boundary), + "nonempty mathematical boundary required") + for field in ("title", "mathematical_arithmetic_gap"): + require(isinstance(doc.get(field), str) and doc[field].strip(), "nonempty record field: " + field) + snapshot = doc.get("source_snapshot") + require(isinstance(snapshot, dict) and snapshot.get("repository") == "d6g8k5htny-coder/Math-" + and snapshot.get("commit") == BASE and snapshot.get("packet_path") == PACKET + and snapshot.get("packet_object") == OBJECT, "exact source snapshot required") + require(doc.get("denied_certificate_sources") == list(DENIED_SOURCES), "exact denied source inventory required") + raw = regular(root, PACKET + "/SOURCE_FILES.json") + require(blob(raw) == MANIFEST_BLOB, "frozen packet manifest identity differs") + manifest = strict_json(raw) + entries = manifest["files"] + names = [v["path"] for v in entries] + require(len(names) == 10 and len(set(names)) == 10 and all(PurePosixPath(v).name == v for v in names), + "frozen packet manifest inventory differs") + expected_names = set(names) | {"SOURCE_FILES.json"} + require({v.name for v in (root / PACKET).iterdir()} == expected_names, "packet tree differs from frozen manifest") + expected = {} + for name in sorted(expected_names): + data = regular(root, PACKET + "/" + name) + expected[PACKET + "/" + name] = {"path": PACKET + "/" + name, "git_blob": blob(data), + "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)} + for entry in entries: + actual = expected[PACKET + "/" + entry["path"]] + require(all(actual[k] == entry[k] for k in ("git_blob", "sha256", "bytes")), + "packet source identity differs: " + entry["path"]) + sources = doc.get("source_files") + require(isinstance(sources, list) and len(sources) == 11 + and all(isinstance(v, dict) and isinstance(v.get("path"), str) and type(v.get("bytes")) is int for v in sources) + and {v["path"] for v in sources} == set(expected) + and all(v == expected[v["path"]] for v in sources), "exact packet inventory required") + require(snapshot.get("manifest") == expected[PACKET + "/SOURCE_FILES.json"], "snapshot manifest identity differs") + document = strict_json(regular(root, PACKET + "/RESULTS.json")) + pairs = interval_pairs(document) + exceptions = exact_exceptions(document) + exact = {pointer(v["path"]): v for v in exceptions} + denied = {key: value for key, value in pairs.items() if key not in exact} + listed = doc.get("denied_outputs") + require(type(doc.get("denied_output_count")) is int and doc["denied_output_count"] == 106 + and isinstance(listed, list) and len(listed) == 106 + and all(isinstance(v, dict) and isinstance(v.get("json_pointer"), str) for v in listed) + and {v["json_pointer"] for v in listed} == set(denied) + and all(v == denied[v["json_pointer"]] for v in listed), "exact denied output inventory required") + require(doc.get("exact_rational_exceptions") == exceptions, "exact rational exception inventory differs") + index = regular(root, "PROOF_INDEX.md").decode("utf-8") + matches = re.findall(r"", index) + entry = strict_json(matches[0].encode()) if len(matches) == 1 else None + wanted = {"id": QID, "classification": "QUARANTINED", "layer_a_status": "A3_NOT_PROVEN", + "cbz_certificate_admitted": False, "record": RECORD} + require(isinstance(entry, dict) and entry == wanted and entry.get("cbz_certificate_admitted") is False, + "canonical index quarantine classification differs") + copied = {expected[PACKET + "/" + name]["git_blob"] for name in COPY_SOURCES} + return {"denied": denied, "exact": exact, "copied": copied, + "record_sha256": hashlib.sha256(record_raw).hexdigest(), "packet_manifest_git_blob": MANIFEST_BLOB} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path(__file__).absolute().parents[1]) + parser.add_argument("--consume", action="append", default=[]) + parser.add_argument("--consume-output", action="append", default=[]) + args = parser.parse_args(argv) + report = {"quarantine_id": QID, "status": "QUARANTINE_INTEGRITY_OK", "scientific_effect": "NONE", + "layer_a_status": "A3_NOT_PROVEN", "cbz_certificate_admitted": False, + "scope": "C8 packet, exact 106 denial paths, three Fraction witnesses and canonical index only; descriptive consumer metadata and global downstream isolation are not certified.", + "preserved_packet_files": 0, "denied_output_count": 0, "exact_exception_count": 0, + "source_decisions": [], "output_decisions": [], "problems": []} + try: + root = args.root.absolute() + require(".." not in root.parts and not any(p.is_symlink() for p in (root, *root.parents)), "symlink checkout or unsafe root") + checked = audit(root) + report.update(preserved_packet_files=11, denied_output_count=len(checked["denied"]), + exact_exception_count=len(checked["exact"]), record_sha256=checked["record_sha256"], + packet_manifest_git_blob=checked["packet_manifest_git_blob"]) + for value in args.consume: + path = normalized_consumer(value) + denied = path in DENIED_SOURCES or path.startswith(PACKET + "/") + if not denied and ((root / path).exists() or (root / path).is_symlink()): + denied = blob(regular(root, path)) in checked["copied"] + report["source_decisions"].append({"source": path, "decision": "DENIED" if denied else "NOT_COVERED"}) + if denied: + report["problems"].append("quarantined numerical source: " + path) + for value in args.consume_output: + path = canonical_pointer(value) + if path in checked["denied"]: + report["output_decisions"].append({"output": path, "decision": "DENIED"}) + report["problems"].append("quarantined numerical output: " + path) + elif path in checked["exact"]: + report["output_decisions"].append({"output": path, "decision": "EXACT_RATIONAL_WITNESS_ONLY", + "exact_value": checked["exact"][path]["exact_value"]}) + else: + report["output_decisions"].append({"output": path, "decision": "NOT_COVERED"}) + except (ValueError, OSError, KeyError, TypeError) as exc: + report["problems"].append(str(exc)) + if report["problems"]: + report["status"] = "REFUSED" + code = 1 + elif args.consume or args.consume_output: + 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()) 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())