# Formal proofs, protocols, and interop

> Audit Lean 4 and TorchLean declarations for Status.formal claims, verify statistical protocols with the Experimental Protocol Compiler, and export in-toto, DSSE, and CycloneDX 1.7 ML-BOMs.

Source: https://kucinglabs.com/docs/formal-interop
Markdown: https://kucinglabs.com/docs/formal-interop.md

## Lean 4 and TorchLean formal theorem adapters (CLAIM 6)

Linking a paper proof by file name breaks when someone edits a lemma or adds `sorry`. `arah.claim.theorems` pins `.lean` source files, toolchains, and lake manifests by SHA-256 hash inside a 10 MiB read cap (`DEFAULT_MAX_FILE_BYTES`).

`LeanTheoremAdapter` parses declarations and checks `#print axioms` against `ALLOWED_STANDARD_AXIOMS` (`propext`, `Classical.choice`, `Quot.sound`), forbidding `sorryAx`. `TorchLeanAdapter` binds finite-precision network proofs to `network_digest`, `dtype`, `input_domain_digest`, and `property_name`. `promote_formal_claim` serves as the sole bridge to `Status.formal` and rejects unsealed, stale, or dirty-axiom receipts.

**Register, audit, promote to Status.formal, and detect file staleness**

```python
from pathlib import Path
import tempfile
import arah
from arah.claim import TheoremLinkStatus, promote_formal_claim

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    lean_file = root / "AffineBound.lean"
    lean_file.write_text("theorem affine_gap_bound : True := trivial\n", encoding="utf-8")
    toolchain = root / "lean-toolchain"
    toolchain.write_text("leanprover/lean4:v4.14.0\n", encoding="utf-8")
    manifest = root / "lake-manifest.json"
    manifest.write_text('{"version": "1.1.0", "packages": []}\n', encoding="utf-8")

    adapter = arah.LeanTheoremAdapter()
    tref = adapter.check_registered(
        lean_file, "affine_gap_bound", toolchain_path=toolchain, manifest_path=manifest, repo_root_id="demo"
    )
    receipt = adapter.verify_audit_output(
        tref,
        build_exit_code=0,
        axioms_output="'affine_gap_bound' depends on axioms: [propext, Classical.choice, Quot.sound]",
        current_file_sha256=tref.file_sha256,
    )
    formal_claim = promote_formal_claim("Affine gap bounded over R", arah.Exactness.exact, receipt)
    assert receipt.status is TheoremLinkStatus.audited and formal_claim.status is arah.Status.formal

    # Any edit to the .lean file marks the receipt stale
    lean_file.write_text("theorem affine_gap_bound : True := by trivial\n", encoding="utf-8")
    assert adapter.check_staleness(receipt, lean_file) is TheoremLinkStatus.stale
```

## Experimental Protocol Compiler

A sound statistical test fails if an author peeks at raw gate scores or reuses holdout items. `arah.claim.protocol` checks execution transcripts (`ProtocolStep` sequences) against a declared `ProtocolSpec` and emits a verifier-sealed `ProtocolComplianceCertificate`.

- `ProtocolKind`: `fresh_batches`, `decision_only_reuse`, `thresholdout_budgeted`, `final_holdout_only`.
- `GuaranteeType`: `online_fdr`, `fwer`, `bounded_risk`, `fresh_holdout` (non-interchangeable).
- `ActorRole`: `author`, `evaluator`, `dashboard`, `operator`. `InfoChannel`: `practice`, `gate_raw`, `gate_decision`, `calibration`, `holdout`.

| Violation code | Failure caught |
| --- | --- |
| `protocol.raw_gate_leak` | Author reads continuous `gate_raw` scores under a protocol that permits only coarse `gate_decision` outputs |
| `protocol.item_reuse_or_rebundle` | Repeated `item_digests` across tiers or across batches marked fresh |
| `protocol.human_feedback_leak` | Dashboard or operator feedback enters authoring proposals before artifact freeze |
| `protocol.holdout_contamination` | Holdout queries exceed `max_holdout_queries` or occur before later proposals |
| `protocol.calibration_reuse` | An author reads calibration data during a proposal, then reuses those items as fresh calibration |
| `protocol.decision_budget_or_channel_violation` | Gate decisions exceed `max_gate_decisions` or write unauthorized channels |
| `claim.protocol_invalid` | Protocol and guarantee mismatch, or invalid error budget `alpha` |

## Supply-chain provenance interop (CLAIM 7)

`arah.claim.interop` exports deterministic JSON provenance artifacts with zero hand-typed metrics and zero fabricated licenses. Use `export_in_toto_statement` plus `wrap_dsse_envelope` / `verify_dsse_envelope` (`dsse_pae`) for signed attestations, `export_cyclonedx_ml_bom` for CycloneDX 1.7 ML-BOMs, `export_hf_model_card` for `ReportGuard`-checked model cards, and `export_claim_graph` for machine-readable claim graphs.

**Sign in-toto DSSE envelopes, emit CycloneDX 1.7 ML-BOM, model card, and claim graph**

```python
import hashlib
import hmac
import arah
from arah.claim import (
    ARAH_CLAIM_GRAPH_SCHEMA,
    LedgerRecord,
    export_claim_graph,
    export_hf_model_card,
    verify_dsse_envelope,
    wrap_dsse_envelope,
)

model_sha = hashlib.sha256(b"demo-weights").hexdigest()
donor_sha = hashlib.sha256(b"donor-weights").hexdigest()
claim = arah.exact("Linear map matches reference")

statement = arah.export_in_toto_statement(
    "model.safetensors", model_sha, manifest_payload={"schema": "arah.manifest.v1"}, claims=[claim], donor_digests=[donor_sha]
)
key = b"local-test-signing-key"
envelope = wrap_dsse_envelope(
    statement, sign_fn=lambda pae: hmac.new(key, pae, hashlib.sha256).digest(), keyid="key-1"
)
unwrapped = verify_dsse_envelope(
    envelope, lambda pae, sig: hmac.compare_digest(hmac.new(key, pae, hashlib.sha256).digest(), sig)
)
assert unwrapped["subject"][0]["digest"]["sha256"] == model_sha

bom = arah.export_cyclonedx_ml_bom(
    "demo-model", "1.0.0", model_sha, donor_components=[{"name": "upstream-donor", "sha256": donor_sha}], claims=[claim]
)
donor_comp = next(c for c in bom["components"] if c["name"] == "upstream-donor")
assert bom["specVersion"] == "1.7" and "licenses" not in donor_comp

rec = LedgerRecord("eval_1", model_sha, {"err": 0.0}, arah.Status.heuristic, "fresh-to-author")
card = export_hf_model_card("demo-model", arah.ReportGuard([rec]), "Error={{record:eval_1.err}}.", declared_claims=("eval_1",), tags=("arah-v1",))
graph = export_claim_graph([claim], artifacts=[{"name": "model.safetensors", "sha256": model_sha}])
assert "Error=0." in card and graph["schema"] == ARAH_CLAIM_GRAPH_SCHEMA
```
