diff --git a/README.md b/README.md
index e28196b..43adf2f 100644
--- a/README.md
+++ b/README.md
@@ -93,7 +93,7 @@ Run the full Tier 2 oracle gates and Family `A` to `D` graders. On Linux, `lake
## What is not proved
- Passing Tier 2 oracles proves only the machine-checked properties enforced by each checker. Whether a theorem statement matches human intent remains a Tier 1 human specification judgment.
-- `datasets/scripts/grade_item.py` grades Family C items by deterministic structural claim-tier and `meta["bar_status"]` replay rather than re-running Lean compilation on prose-only reports.
+- `datasets/scripts/grade_item.py` grades Family C items by deterministic structural claim-tier and `meta["bar_status"]` replay. The `bar_check` replay pins `spec_meta.statements` and does not emit an identity scaffold. It does not re-run Lean compilation. `verdict_audit` items, including `PUB-C-V02`, check a verdict JSON block and do not use the Family C Lean repair path.
- Live `8` GiB RTX 3080 `T-C5` telemetry (`stack/results/final/ux582hs_rtx3080_tc5_live_receipt.json`) measured Windows 11 NVIDIA Optimus (`driver 566.07`, `0 MiB` idle WDDM VRAM), while bare-metal Linux kernel execution on `UX582HS` remains tracked separately.
## What you must trust
diff --git a/bin/bootstrap-deps b/bin/bootstrap-deps
index 4a7d967..9f7f8e5 100755
--- a/bin/bootstrap-deps
+++ b/bin/bootstrap-deps
@@ -30,7 +30,7 @@ from mcproof.lineage import ( # noqa: E402
def _clone_at_exact_sha(url: str, commit: str, dest: Path) -> None:
- if not COMMIT_RE.match(commit):
+ if not COMMIT_RE.fullmatch(commit):
raise ValueError(f"refusing non-40-hex commit pin {commit!r} for {url}")
if (dest / ".git").exists():
head = subprocess.run(
diff --git a/datasets/README.md b/datasets/README.md
index a4871bc..18d3e57 100644
--- a/datasets/README.md
+++ b/datasets/README.md
@@ -26,7 +26,7 @@ All 144 `PUB-` prompts stay strictly inside four reserved public subtopics so th
- **Family A (`formal_proof`, 24 compile / 12 validation)**: stock-`Init` Lean `v4.35.0` proofs and `WeakStatement` vacuous-hypothesis traps checked across all six kernels of `lake comparator --paranoid`, `leanchecker`, `collectAxioms`, and `soko` `lean4_auditor.py`.
- **Family B (`code`, 24 compile / 12 validation)**: exact `int` and `Fraction` Python certificate verifiers (`def verify(inst, cert) -> bool`) audited for distinct AST alpha-skeletons, zero `float` or `/` coercion, zero `assert` under `mde guard --code-audit`, clean `python3 -O -B -W error` execution, and 100% planted-bug mutation kills (`>= 80%` floor).
-- **Family C (`formal_proof`, 24 compile / 12 validation)**: epistemic claim-tier hygiene and refusal traps checked by `mcproof`, `mission/bar/check.py`, `formal-claims-audit/scripts/check_verdicts.py`, and `f0/scripts/gate.py`.
+- **Family C (`formal_proof`, 24 compile / 12 validation)**: epistemic claim-tier hygiene and refusal traps checked by `mcproof`, `mission/bar/check.py`, `formal-claims-audit/scripts/check_verdicts.py`, and `f0/scripts/gate.py`. The `bar_check` oracle is the one that builds a Lean project from pinned `spec_meta.statements`. `PUB-C-V02` is a `verdict_audit` item and does not use that path.
- **Family D (`formal_proof`, 24 compile / 12 validation)**: mixed-register technical notes combining plain prose (`check-prose.py` and `--dupes`), `
` protection, full 40-character verdict SHAs, kernel-checked Lean 4 blocks, and mandatory boundary sections.
## Re-check Commands
diff --git a/datasets/SHA256SUMS b/datasets/SHA256SUMS
index d7f80d6..8baa97f 100644
--- a/datasets/SHA256SUMS
+++ b/datasets/SHA256SUMS
@@ -1,4 +1,4 @@
-a584a5b6254aae9dbf800643dcea3c9786a93198ee6975adea00fcc0eaa56007 README.md
+42b9a50198da3641a98deefcc754bca2ce474b453918ea7a274c4ffd73f1f2c9 README.md
067059259c5d2238a8ab3f6a6b01ebcedeed2dc0d19d2f7a02a3e170f52f7f31 compile.jsonl
6d3918122d61d92e74752b4a26f70dbc3e5786657df596b54e54a384cb1c9140 harnesses/family_a/PUB-A-C01.json
3e5993ed8ed763e630129fe2426eadea2e0c03dc48d705de8dcbe75a4faedcec harnesses/family_a/PUB-A-C02.json
@@ -146,7 +146,7 @@ dfc1d7b0f63c89861c06453993d6aec79249231272f3200a0c3e378a7131658c harnesses/fami
011e0e35a21fe2cd7e54bb9c4efed1e8208923d35a1110e4ff18b7ce1f51631a harnesses/family_d/PUB-D-V12.json
ba2e9b277eeb8d9ea5965b27d73ca8efc6c55c732ad800ee2bdfea41266eeeae hybrid_k0.jsonl
93a27e6c37e501153ff5837abaebec10ff80a85b84dc9c15897809687d822142 manifest.json
-1c774b9040622baf59c4d0ca2ab3e49807131d83b66cdb6aa16387ddaf8113e7 scripts/grade_item.py
+cd97d19a0c6b773636fb2fab15bd3dff10fcfe242d32aa77b69e8f0d20d05556 scripts/grade_item.py
f5cb4f7d69da62e4be17a4947049b89928d1ea82c1a2a93dd7d7851ee623611d targets/family_a/PUB-A-C01.lean
7e688d533d3e502b272bfe1b166d6eceaa7f635ac4c511ca7a1449b591257f69 targets/family_a/PUB-A-C02.lean
f1f8e95c36306ca5a9abc45cee000ffe7d783d8f012eb3e9a47e583e6fbee82b targets/family_a/PUB-A-C03.lean
diff --git a/datasets/scripts/grade_item.py b/datasets/scripts/grade_item.py
index 20b73b1..6548a85 100755
--- a/datasets/scripts/grade_item.py
+++ b/datasets/scripts/grade_item.py
@@ -4,9 +4,11 @@
Delegates primary Family A/B/C/D checks to `bin/mcproof` and runs structural
claim/metadata replay (`mission/bar/check.py` README/bar.toml consistency,
verdict JSON field checks, and `f0/scripts/gate.py` feed schema checks) for
-Family C items when `--id` is supplied. Note: Family C audits prose/metadata
-alignment and claim-tier honesty, whereas Lean 4 theorem proving is tested in
-Family A and Family D.
+Family C items when `--id` is supplied. A `bar_check` replay pins
+`spec_meta.statements` and does not emit an identity scaffold. It does not
+compile Lean. A `verdict_audit` item, including `PUB-C-V02`, checks a verdict
+JSON block and does not build a Lean project. Lean 4 theorem proving is tested
+in Family A and Family D.
"""
from __future__ import annotations
@@ -51,6 +53,17 @@ def _resolve_deps_root() -> Path:
MCPROOF_BIN = _resolve_mcproof_bin()
DEPS_ROOT = _resolve_deps_root()
+if str(REPO_ROOT / "src") not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT / "src"))
+
+from mcproof.repair_loop import ( # noqa: E402
+ _family_c_lakefile,
+ _family_c_root_source,
+ _family_c_spec_source,
+ _family_c_statement_headers,
+ _family_c_code_under_proof,
+)
+
def _load_item(item_id: str) -> dict[str, Any]:
for name in ("compile.jsonl", "validation.jsonl"):
@@ -83,41 +96,35 @@ def _run_family_c_structural_replay(harness: dict[str, Any], completion_text: st
errs: list[str] = []
if otype == "bar_check":
+ pkg = str(meta["pkg"])
+ thms = list(meta["theorem_names"])
+ headers = _family_c_statement_headers(meta, thms)
+ if headers is None:
+ return False, [
+ "target_statements_absent: spec_meta.statements must pin the header of every theorem_names entry"
+ ]
bar_tpl = DEPS_ROOT / "mission" / "bar" / "template"
bar_chk = DEPS_ROOT / "mission" / "bar" / "check.py"
if not bar_tpl.is_dir() or not bar_chk.is_file():
return False, [f"missing_mission_dep_under_{DEPS_ROOT.name}__run_bin_bootstrap_deps"]
- pkg = str(meta["pkg"])
- thms = list(meta["theorem_names"])
readme_body = re.sub(r"(?im)^Claim-Tier:[^\n]*\n+", "", completion_text, count=1)
# Take bar_status strictly from harness metadata; candidate prose cannot self-promote status.
bar_status = str(meta["bar_status"])
+ code_toml = ", ".join(json.dumps(name) for name in _family_c_code_under_proof(pkg, meta))
with tempfile.TemporaryDirectory(prefix="mcproof_ds_bar_") as td:
root = Path(td)
shutil.copytree(bar_tpl, root, dirs_exist_ok=True)
(root / "Clamp.lean").unlink(missing_ok=True)
shutil.rmtree(root / "Clamp", ignore_errors=True)
- (root / f"{pkg}.lean").write_text(f"namespace {pkg}\ndef op (x : Nat) : Nat := x\nend {pkg}\n", encoding="utf-8")
+ (root / f"{pkg}.lean").write_text(_family_c_root_source(pkg, meta), encoding="utf-8")
(root / pkg).mkdir(exist_ok=True)
- spec_lines = [f"import {pkg}", f"namespace {pkg}.Spec"]
- proof_lines = [f"import {pkg}", f"namespace {pkg}.Spec"]
- for tfull in thms:
- tshort = tfull.split(".")[-1]
- spec_lines.append(f"theorem {tshort} (x : Nat) : {pkg}.op x = x := by sorry")
- proof_lines.append(f"theorem {tshort} (x : Nat) : {pkg}.op x = x := rfl")
- spec_lines.append(f"end {pkg}.Spec\n")
- proof_lines.append(f"end {pkg}.Spec\n")
- (root / pkg / "Spec.lean").write_text("\n".join(spec_lines), encoding="utf-8")
- (root / pkg / "Proofs.lean").write_text("\n".join(proof_lines), encoding="utf-8")
- (root / "Main.lean").write_text(f'import {pkg}\ndef main : IO Unit := IO.println s!"{{{pkg}.op 1}}"\n', encoding="utf-8")
- (root / "lakefile.toml").write_text(
- f'name = "{pkg.lower()}"\nversion = "0.1.0"\ndefaultTargets = ["{pkg}"]\n\n'
- f'[[lean_lib]]\nname = "{pkg}"\n\n'
- f'[[lean_lib]]\nname = "{pkg}.Spec"\n\n'
- f'[[lean_lib]]\nname = "{pkg}.Proofs"\n\n'
- f'[[lean_exe]]\nname = "{pkg.lower()}"\nroot = "Main"\n',
+ (root / pkg / "Spec.lean").write_text(_family_c_spec_source(pkg, headers), encoding="utf-8")
+ (root / pkg / "Proofs.lean").write_text(f"import {pkg}\n", encoding="utf-8")
+ (root / "Main.lean").write_text(
+ f'import {pkg}\ndef main : IO Unit := IO.println "ok"\n',
encoding="utf-8",
)
+ (root / "lakefile.toml").write_text(_family_c_lakefile(pkg), encoding="utf-8")
(root / "comparator.json").write_text(
json.dumps(
{
@@ -134,7 +141,7 @@ def _run_family_c_structural_replay(harness: dict[str, Any], completion_text: st
(root / "bar.toml").write_text(
f'[project]\nname = "{pkg.lower()}"\nstatus = "{bar_status}"\npage = "README.md"\n'
f'spec_authors = ["example-author"]\nentry_points = ["Main.lean"]\n\n'
- f'[spec]\nfiles = ["SPEC.md", "{pkg}/Spec.lean"]\ncode = ["{pkg}.op"]\n\n'
+ f'[spec]\nfiles = ["SPEC.md", "{pkg}/Spec.lean"]\ncode = [{code_toml}]\n\n'
f'[tests]\nresults = "tests/TEST-RESULTS.md"\ncommand = "{meta["test_cmd"]}"\nfiles = ["tests/run_tests.py"]\n',
encoding="utf-8",
)
diff --git a/docs/CONTINUITY.md b/docs/CONTINUITY.md
index 5fda783..e386f55 100644
--- a/docs/CONTINUITY.md
+++ b/docs/CONTINUITY.md
@@ -91,3 +91,15 @@ python3 verification/build_final_receipt.py
1. **Multi-layer `blk.28..31` `TangentBetaEdit` live serving promotion:** Wire 4-layer `TangentBetaEdit` (`weft` `c33bbf4f`) into live `warp-modeld` Stage 1 to 4 admission and measure multi-turn `k = 1..4` pass curves with `blk.28..31` non-uniform depth allocation (`alpha_l*` proportional to `R_l^2 / (gamma_l^2 * rho_l)`).
2. **Concrete graph-hypothesis coupling for `Mcproof.TransitionBounds`:** Mechanize finite-table checkers discharging projection and cut-capacity hypotheses directly inside Lean `v4.35.0` alongside Python `verify_dual_product_parity`.
+
+## D11 Family C real-Lean repair turn (2026-11-20)
+- **Defect closed in `src/mcproof/repair_loop.py`:** the public Family C scorer parsed `says_verified` from candidate prose and rebuilt an identity `rfl` scaffold while running the comparator with `--no-lean`. Candidate Lean never compiled, and prose could self-promote `bar_status`.
+- **What uses the Lean path:** `_run_family_c_real_lean_turn` runs only when `oracle_type` is `bar_check`. Public `bar_check` items include `PUB-C-V01` (`CrtPair`) and `PUB-C-C01` (`ModInv`). `bar_status` comes from harness `spec_meta`. A spoofed verified claim yields `FAMILY_C_STATUS_SELF_ATTESTATION`. Missing lean blocks and `sorry` or `admit` fail closed before `lake`.
+- **What does not use it:** `PUB-C-V02` is `oracle_type: verdict_audit` in `datasets/harnesses/family_c/PUB-C-V02.json`. That path checks a fenced verdict JSON block. It does not build a Lean project, does not hash a theorem statement, and does not call `lake`. A solve of `PUB-C-V02` is a verdict-audit result. It is not evidence that this Lean path accepted a proof.
+- **Statement pin:** `spec_meta.statements` supplies the target header for each fully-qualified theorem name. The guard hashes that header. It does not hash `op x = x`. A fully qualified `rfl` of the identity fails with `FAMILY_C_STATEMENT_MISMATCH`. A missing header fails with `FAMILY_C_TARGET_STATEMENT_ABSENT` and is not replaced by an identity scaffold.
+- **`defaultTargets`:** the generated project targets `["{pkg}", "{pkg}.Spec", "{pkg}.Proofs"]`, so `lake build` compiles the candidate proofs. The old `["{pkg}"]` list left broken proofs uncompiled.
+- **Lean evidence in this lane:** `test_family_c_known_bad_proof_reaches_lake_build` states the pinned headers and closes them with `exact Nat.noSuchLemma`. The turn records `LAKE_BUILD_FAILED` and keeps the compiler `file:line:column` tail.
+- **Skip rule:** that test skips only when `lean` and `lake` are absent, and the skip reason says the lake path was not exercised. `test_family_c_lean_error_text_reaches_next_turn_prompt` only checks `format_diagnostics` on a hand-written finding. It does not run `lake`.
+- **`datasets/scripts/grade_item.py`:** the structural bar replay writes those same pinned headers into `Spec.lean`. It does not write an identity `op` or an identity `rfl` proof. `defaultTargets` includes the spec and proofs libraries. Harnesses that omit `statements`, which is every frozen `bar_check` file today, fail closed with `target_statements_absent`. This replay still does not compile Lean.
+- **Known wart:** `verify_lean4_project_comparator` still keeps only the last 6 `lake build` lines. The repair turn records its own `lake build` first and keeps lines that contain `.lean:line:column`, so a failed candidate proof does not depend on that truncated tail.
+- **Envelope:** this section describes the code on this branch. This lane did not re-run the public validation split, and it did not touch the vault or the sealed holdout.
diff --git a/src/mcproof/__init__.py b/src/mcproof/__init__.py
index 5215eeb..3c9e7b9 100644
--- a/src/mcproof/__init__.py
+++ b/src/mcproof/__init__.py
@@ -60,6 +60,7 @@
compute_candidate_state_hash,
compute_failure_signature,
default_inference_oracle,
+ evaluate_early_stop_eligibility,
format_diagnostics,
make_llama_server_generator,
retrieve_plane1_excerpt,
@@ -67,6 +68,7 @@
run_repair_item,
run_repair_split,
sanitize_oracle_diagnostics,
+ summarize_oracle_grader_gap,
)
__version__ = "0.2.0"
@@ -93,6 +95,7 @@
"compute_candidate_state_hash",
"compute_failure_signature",
"default_inference_oracle",
+ "evaluate_early_stop_eligibility",
"find_forbidden_control_bytes",
"format_diagnostics",
"grade_family_completion",
@@ -119,6 +122,7 @@
"run_verdicts_oracle",
"sanitize_oracle_diagnostics",
"scrub_challenge_artifacts",
+ "summarize_oracle_grader_gap",
"verify_dual_product_parity",
"verify_lean4_project_comparator",
"verify_lean4_source",
diff --git a/src/mcproof/domain_protocol.py b/src/mcproof/domain_protocol.py
index ad42143..187413e 100644
--- a/src/mcproof/domain_protocol.py
+++ b/src/mcproof/domain_protocol.py
@@ -29,6 +29,7 @@
import sys
import tempfile
from typing import Any, Callable, Mapping, Protocol, Sequence, runtime_checkable
+import unicodedata
from .repair_loop import (
MAX_RETRIEVAL_TOKENS_HARD_CAP,
@@ -42,8 +43,12 @@
MAX_CERT_ABS_INT = 10**60
STRICT_RATIONAL_RE = re.compile(r"^-?[0-9]+(?:/[1-9][0-9]*)?$")
SHA256_64_RE = re.compile(r"^[0-9a-f]{64}$")
-# Zero-width and word-joiner marks. Unicode whitespace is rejected separately.
-_CITATION_INVISIBLE_CHARS = frozenset("\u200b\u200c\u200d\u2060\ufeff")
+# Blank-looking filler / ignorable codepoints whose Unicode category is Lo/So/Mn/Cf
+# (e.g. Braille Pattern Blank U+2800, Hangul Filler U+3164, Halfwidth Hangul Filler U+FFA0).
+_CITATION_INVISIBLE_CHARS = frozenset(
+ "\u034f\u115f\u1160\u17b4\u17b5\u180e\u200b\u200c\u200d\u2060\u2800\u3164\ufeff\uffa0"
+)
+_INVISIBLE_UNICODE_CATEGORIES = frozenset({"Cc", "Cf", "Cn", "Cs", "Mn", "Zl", "Zp", "Zs"})
NON_VERIFIED_SUBTIERS: frozenset[str] = frozenset(
{
"LINT_PASS",
@@ -420,9 +425,19 @@ def run_restricted_sandbox_cell(
preimport_mods = [m for m in allowed_sorted if m != "__future__"]
preamble_lines: list[str] = []
if injected_globals:
- for key in sorted(injected_globals.keys()):
- if re.match(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$", key):
- preamble_lines.append(f"_ns[{key!r}] = {injected_globals[key]!r}")
+ for key in sorted(injected_globals.keys(), key=repr):
+ if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", key):
+ return {
+ "ok": False,
+ "returncode": 2,
+ "timed_out": False,
+ "ast_rejected": True,
+ "violations": [f"invalid_injected_global_key:{key!r}"],
+ "timeout_sec": capped_timeout,
+ "stdout": "",
+ "stderr": f"invalid injected_globals key {key!r}",
+ }
+ preamble_lines.append(f"_ns[{key!r}] = {injected_globals[key]!r}")
with tempfile.TemporaryDirectory(prefix="mcproof_sandbox_") as tmp_dir:
if os.name != "nt":
@@ -595,13 +610,34 @@ def audit_portfolio_bounds(
"""Audit portfolio lower/upper bound records, closing `F-07` caller-bound inflation and bound inversions."""
findings: list[dict[str, str]] = []
triaged: list[dict[str, Any]] = []
- for row in items:
+ if not isinstance(items, Sequence) or isinstance(items, (str, bytes)) or len(items) == 0:
+ return {
+ "passed": False,
+ "epistemic_status": "REJECTED",
+ "items": [],
+ "findings": [{"rule": "CERT_PORTFOLIO_EMPTY", "message": "Portfolio bounds list must be a non-empty sequence."}],
+ }
+ for idx, row in enumerate(items):
+ if not isinstance(row, Mapping):
+ findings.append(_type_finding(f"items[{idx}]", "an object", row))
+ triaged.append({"id": f"item_{idx}", "epistemic_status": "REJECTED", "caller_bounds_verified": False})
+ continue
iid = str(row.get("id", "unknown"))
p_floor = row.get("proven_floor")
s_known = row.get("shortest_known")
l_rec = row.get("live_record")
-
- if p_floor is not None and s_known is not None and int(p_floor) > int(s_known):
+ raw_row_status = row.get("epistemic_status")
+ row_bad_type = False
+ for bname, bval in (("proven_floor", p_floor), ("shortest_known", s_known), ("live_record", l_rec)):
+ if bval is not None and not _is_count(bval):
+ findings.append(_type_finding(f"{iid}.{bname}", "a non-negative integer", bval))
+ row_bad_type = True
+ if raw_row_status is not None and not isinstance(raw_row_status, str):
+ findings.append(_type_finding(f"{iid}.epistemic_status", "a string", raw_row_status))
+ row_bad_type = True
+ if row_bad_type:
+ status = "REJECTED_INVALID_BOUND_TYPE"
+ elif p_floor is not None and s_known is not None and p_floor > s_known:
findings.append(
{
"rule": "CERT_F07_INCONSISTENT_PORTFOLIO_BOUNDS",
@@ -609,7 +645,7 @@ def audit_portfolio_bounds(
}
)
status = "REJECTED_INCONSISTENT_PORTFOLIO_BOUNDS"
- elif s_known is not None and l_rec is not None and int(s_known) > int(l_rec):
+ elif s_known is not None and l_rec is not None and s_known > l_rec:
findings.append(
{
"rule": "CERT_F07_INCONSISTENT_PORTFOLIO_BOUNDS",
@@ -617,8 +653,16 @@ def audit_portfolio_bounds(
}
)
status = "REJECTED_INCONSISTENT_PORTFOLIO_BOUNDS"
+ elif p_floor is not None and l_rec is not None and p_floor > l_rec:
+ findings.append(
+ {
+ "rule": "CERT_F07_INCONSISTENT_PORTFOLIO_BOUNDS",
+ "message": f"{iid}: proven_floor ({p_floor}) > live_record ({l_rec})",
+ }
+ )
+ status = "REJECTED_INCONSISTENT_PORTFOLIO_BOUNDS"
elif iid not in registered_verified_ids:
- if str(row.get("epistemic_status", "")).upper() in ("VERIFIED", "PROVEN"):
+ if isinstance(raw_row_status, str) and raw_row_status.strip().upper() in ("VERIFIED", "PROVEN"):
findings.append(
{
"rule": "CERT_F07_UNVERIFIED_CALLER_BOUNDS",
@@ -640,13 +684,36 @@ def audit_portfolio_bounds(
def _citation_text_visible(value: str) -> bool:
- """True when `value` has a printable character that is not whitespace or invisible."""
+ """True when `value` contains at least one visible, non-blank, non-format character."""
return any(
- ch.isprintable() and not ch.isspace() and ch not in _CITATION_INVISIBLE_CHARS
+ ch.isprintable()
+ and not ch.isspace()
+ and ch not in _CITATION_INVISIBLE_CHARS
+ and unicodedata.category(ch) not in _INVISIBLE_UNICODE_CATEGORIES
for ch in value
)
+def _witness_value_valid(value: Any, *, _depth: int = 0) -> bool:
+ """True iff `value` is a non-empty, non-blank exact witness element (no bool/float/None/empty containers)."""
+ if _depth > 16:
+ return False
+ if value is None or type(value) is bool or isinstance(value, float):
+ return False
+ if type(value) is int:
+ return True
+ if isinstance(value, str):
+ return _citation_text_visible(value)
+ if isinstance(value, list):
+ return len(value) > 0 and all(_witness_value_valid(elem, _depth=_depth + 1) for elem in value)
+ if isinstance(value, Mapping):
+ return len(value) > 0 and all(
+ isinstance(k, str) and _citation_text_visible(k) and _witness_value_valid(v, _depth=_depth + 1)
+ for k, v in value.items()
+ )
+ return False
+
+
def _known_citation_findings(cert: Mapping[str, Any]) -> list[dict[str, str]]:
"""Require a KNOWN citation. Proof digests and `tcb_pins` are not one.
@@ -724,6 +791,130 @@ def _known_citation_findings(cert: Mapping[str, Any]) -> list[dict[str, str]]:
return findings
+_CERT_FLAG_FIELDS: tuple[str, ...] = (
+ "includes_hidden_state",
+ "caller_bounds_verified",
+ "differential_match",
+ "unverified_caller_claim",
+ "valid_winning_witness",
+ "valid_winning_route",
+ "truncated_by_budget",
+ "exact_optimum_reached",
+ "complete_space",
+ "complete_domain_closed",
+ "impl_invariant_checked",
+ "impl_goal_parity_checked",
+ "obs_projection_injective",
+)
+_CERT_COUNT_FIELDS: tuple[str, ...] = (
+ "step_consistency_violations",
+ "open_transitions",
+ "proven_floor",
+)
+# These two may be null, which means the same as leaving the key out.
+_CERT_OPTIONAL_COUNT_FIELDS: tuple[str, ...] = ("max_bound", "witness_cost", "certified_lower_bound")
+_CERT_TEXT_FIELDS: tuple[str, ...] = (
+ "epistemic_status",
+ "prior_status",
+ "evidence_kind",
+ "proof_mode",
+ "state_hash_mode",
+ "certificate_kind",
+ "witness_or_proof_sha256",
+ "instance_sha256",
+ "canonical_instance_sha256",
+)
+_CERT_ORACLE_LIST_FIELDS: tuple[str, ...] = ("oracles_checked", "engines_verified", "checkers_executed")
+_CERT_CONTROL_FLAG_FIELDS: tuple[str, ...] = ("oracle_invoked", "unexpectedly_passed", "seed_equals_target")
+
+
+def _type_finding(path: str, expected: str, value: Any) -> dict[str, str]:
+ shown = repr(value)
+ if len(shown) > 40:
+ shown = shown[:37] + "..."
+ return {
+ "rule": "CERT_FIELD_TYPE_INVALID",
+ "message": f"{path} must be {expected} (got {type(value).__name__} {shown}).",
+ }
+
+
+def _is_count(value: Any) -> bool:
+ """True for a non-negative `int`. A `bool` is not a count."""
+ return type(value) is int and value >= 0
+
+
+def _certificate_type_findings(cert: Mapping[str, Any]) -> list[dict[str, str]]:
+ """Check the type of every field the auditor reads, before any value is compared.
+
+ The value checks test `is False`, truthiness or `int()`. A flag written as the
+ string "false" or as 0, or a count written as a negative number, slips past them.
+ """
+ findings: list[dict[str, str]] = []
+ for key in _CERT_FLAG_FIELDS:
+ if key in cert and type(cert[key]) is not bool:
+ findings.append(_type_finding(key, "a boolean", cert[key]))
+ for key in _CERT_COUNT_FIELDS:
+ if key in cert and not _is_count(cert[key]):
+ findings.append(_type_finding(key, "a non-negative integer", cert[key]))
+ for key in _CERT_OPTIONAL_COUNT_FIELDS:
+ if cert.get(key) is not None and not _is_count(cert[key]):
+ findings.append(_type_finding(key, "a non-negative integer or null", cert[key]))
+ for key in _CERT_TEXT_FIELDS:
+ if key in cert and not isinstance(cert[key], str):
+ findings.append(_type_finding(key, "a string", cert[key]))
+ if "tcb_pins" in cert:
+ pins = cert["tcb_pins"]
+ if not isinstance(pins, Mapping):
+ findings.append(_type_finding("tcb_pins", "an object", pins))
+ else:
+ if "tcb_manifest_verified" in pins and type(pins["tcb_manifest_verified"]) is not bool:
+ findings.append(_type_finding("tcb_pins.tcb_manifest_verified", "a boolean", pins["tcb_manifest_verified"]))
+ for key in ("checker_sha256", "checker_auditor_py_sha256"):
+ if pins.get(key) is not None and not isinstance(pins[key], str):
+ findings.append(_type_finding(f"tcb_pins.{key}", "a string", pins[key]))
+ if "must_fail_controls" in cert:
+ controls = cert["must_fail_controls"]
+ if not isinstance(controls, list):
+ findings.append(_type_finding("must_fail_controls", "a list of strings", controls))
+ else:
+ for idx, name in enumerate(controls):
+ if not isinstance(name, str):
+ findings.append(_type_finding(f"must_fail_controls[{idx}]", "a string", name))
+ if "control_records" in cert:
+ records = cert["control_records"]
+ if not isinstance(records, list):
+ findings.append(_type_finding("control_records", "a list of objects", records))
+ else:
+ for idx, rec in enumerate(records):
+ if not isinstance(rec, Mapping):
+ findings.append(_type_finding(f"control_records[{idx}]", "an object", rec))
+ continue
+ if "name" in rec and (not isinstance(rec["name"], str) or not _citation_text_visible(rec["name"])):
+ findings.append(_type_finding(f"control_records[{idx}].name", "a non-empty string", rec["name"]))
+ for key in _CERT_CONTROL_FLAG_FIELDS:
+ if key in rec and type(rec[key]) is not bool:
+ findings.append(_type_finding(f"control_records[{idx}].{key}", "a boolean", rec[key]))
+ for okey in _CERT_ORACLE_LIST_FIELDS:
+ if okey in cert:
+ olist = cert[okey]
+ if not isinstance(olist, list):
+ findings.append(_type_finding(okey, "a list of non-empty strings", olist))
+ else:
+ for idx, entry in enumerate(olist):
+ if not isinstance(entry, str) or not _citation_text_visible(entry):
+ findings.append(_type_finding(f"{okey}[{idx}]", "a non-empty string", entry))
+ for wkey in ("witness", "winning_witness"):
+ if wkey in cert and cert[wkey] is not None:
+ wval = cert[wkey]
+ if not isinstance(wval, (str, list)):
+ findings.append(_type_finding(wkey, "a string, list, or null", wval))
+ elif isinstance(wval, list):
+ for idx, elem in enumerate(wval):
+ if not _witness_value_valid(elem):
+ findings.append(_type_finding(f"{wkey}[{idx}]", "a non-blank exact step value", elem))
+ return findings
+
+
def audit_transition_certificate(
cert: Mapping[str, Any],
*,
@@ -735,7 +926,19 @@ def audit_transition_certificate(
A KNOWN certificate carries `citation`: `source` and `reference` are non-empty
strings, and `artifact_sha256` is a lowercase 64-hex digest of the cited artifact.
"""
- findings: list[dict[str, str]] = []
+ if not isinstance(cert, Mapping):
+ return {
+ "passed": False,
+ "epistemic_status": "REJECTED",
+ "finding_count": 1,
+ "findings": [
+ {
+ "rule": "CERT_NOT_AN_OBJECT",
+ "message": f"Certificate must be a JSON object (got {type(cert).__name__}).",
+ }
+ ],
+ }
+ findings: list[dict[str, str]] = _certificate_type_findings(cert)
status = str(cert.get("epistemic_status", "")).strip().upper()
proof_mode = str(cert.get("proof_mode", "")).strip().lower()
@@ -789,7 +992,7 @@ def audit_transition_certificate(
}
)
else:
- clean_names = [str(c).strip() for c in controls if str(c).strip()]
+ clean_names = [c.strip() for c in controls if isinstance(c, str) and _citation_text_visible(c)]
if len(clean_names) != len(controls) or len(set(clean_names)) != len(clean_names):
findings.append(
{
@@ -797,10 +1000,15 @@ def audit_transition_certificate(
"message": "must_fail_controls contains empty or duplicate control identifiers.",
}
)
- for crec in cert.get("control_records") or []:
+ seen_control_names: set[str] = set()
+ raw_crecs = cert.get("control_records")
+ for crec in (raw_crecs if isinstance(raw_crecs, list) else []):
if not isinstance(crec, Mapping):
continue
- cname = str(crec.get("name", "unnamed_control"))
+ raw_cname = crec.get("name")
+ cname = raw_cname.strip() if isinstance(raw_cname, str) and _citation_text_visible(raw_cname) else "unnamed_control"
+ if isinstance(raw_cname, str) and _citation_text_visible(raw_cname):
+ seen_control_names.add(cname)
if crec.get("unexpectedly_passed") is True:
findings.append(
{
@@ -808,26 +1016,46 @@ def audit_transition_certificate(
"message": f"Negative control {cname!r} unexpectedly passed.",
}
)
- if crec.get("oracle_invoked") is False or crec.get("seed_equals_target") is True:
+ if (
+ crec.get("oracle_invoked") is False
+ or crec.get("seed_equals_target") is True
+ or ("oracle_invoked" not in crec)
+ or ("unexpectedly_passed" not in crec)
+ ):
findings.append(
{
"rule": "CERT_A6_TAUTOLOGICAL_CONTROL",
- "message": f"Negative control {cname!r} is tautological (zero oracle invocation or pre-seeded at target).",
+ "message": f"Negative control {cname!r} is tautological or omits oracle_invoked/unexpectedly_passed.",
+ }
+ )
+ if isinstance(controls, list) and len(controls) > 0:
+ expected_cnames = {c.strip() for c in controls if isinstance(c, str) and _citation_text_visible(c)}
+ missing_cnames = sorted(expected_cnames - seen_control_names)
+ if missing_cnames:
+ findings.append(
+ {
+ "rule": "CERT_A6_CONTROL_COVERAGE_INCOMPLETE",
+ "message": f"control_records omits must_fail_controls entries: {missing_cnames}.",
}
)
- # F-01: Optimistic differential boolean without >=2 independent replay engines
- oracles = cert.get("oracles_checked") or cert.get("engines_verified") or cert.get("checkers_executed") or []
- if cert.get("differential_match") is True and (not isinstance(oracles, list) or len(oracles) < 2):
- findings.append(
- {
- "rule": "CERT_SINGLE_ORACLE_DIFFERENTIAL",
- "message": "differential_match=True requires >=2 independent verification engines.",
- }
- )
+ # F-01: Optimistic differential boolean without >=2 distinct independent replay engines
+ if cert.get("differential_match") is True:
+ present_okeys = [okey for okey in _CERT_ORACLE_LIST_FIELDS if okey in cert]
+ if not present_okeys or any(
+ not isinstance(cert[okey], list)
+ or len({e.strip() for e in cert[okey] if isinstance(e, str) and _citation_text_visible(e)}) < 2
+ for okey in present_okeys
+ ):
+ findings.append(
+ {
+ "rule": "CERT_SINGLE_ORACLE_DIFFERENTIAL",
+ "message": "differential_match=True requires >=2 distinct independent verification engines.",
+ }
+ )
# F-02: Partial-projection state hash missing hidden state bits
- if cert.get("includes_hidden_state") is False or cert.get("state_hash_mode") in ("observable_projection_only", "ascii_only", "rendered_board_only"):
+ if cert.get("includes_hidden_state") is False or str(cert.get("state_hash_mode", "")).strip().lower() in ("observable_projection_only", "ascii_only", "rendered_board_only"):
findings.append(
{
"rule": "CERT_PARTIAL_STATE_PROJECTION",
@@ -846,12 +1074,16 @@ def audit_transition_certificate(
}
)
else:
- chk_sha = str(pins.get("checker_sha256") or pins.get("checker_auditor_py_sha256") or "")
- if not pins.get("tcb_manifest_verified", False) or not SHA256_64_RE.fullmatch(chk_sha):
+ present_chk_keys = [k for k in ("checker_sha256", "checker_auditor_py_sha256") if k in pins]
+ chk_valid = bool(present_chk_keys) and all(
+ isinstance(pins[k], str) and bool(SHA256_64_RE.fullmatch(pins[k])) and pins[k] != "0" * 64
+ for k in present_chk_keys
+ )
+ if pins.get("tcb_manifest_verified") is not True or not chk_valid:
findings.append(
{
"rule": "CERT_TCB_MANIFEST_UNLOCKED",
- "message": "TCB pins must verify SHA256SUMS and bind a 64-hex checker/auditor SHA-256.",
+ "message": "TCB pins must verify SHA256SUMS and bind non-zero 64-hex checker/auditor SHA-256(s).",
}
)
@@ -868,39 +1100,67 @@ def audit_transition_certificate(
}
)
- # F-04: Unwitnessed or mismatched-length `proven_floor` claimed as `VERIFIED`
- if "proven_floor" in cert:
- p_floor = int(cert["proven_floor"])
- max_b = cert.get("max_bound")
- if max_b is not None and p_floor > int(max_b):
+ # F-04: Unwitnessed or mismatched-length `proven_floor` claimed as `VERIFIED`.
+ # A certificate that says `exact_optimum_reached: false`, or that carries a witness
+ # key with no witness in it, fails whether or not `proven_floor` is present.
+ p_floor = cert.get("proven_floor") if _is_count(cert.get("proven_floor")) else None
+ max_b = cert.get("max_bound") if _is_count(cert.get("max_bound")) else None
+ if p_floor is not None and max_b is not None and p_floor > max_b:
+ findings.append(
+ {
+ "rule": "CERT_FLOOR_EXCEEDS_MAX_BOUND",
+ "message": f"proven_floor ({p_floor}) exceeds search max_bound ({max_b}).",
+ }
+ )
+ if status in ("VERIFIED", "PROVEN"):
+ present_wkeys = [wk for wk in ("witness", "winning_witness") if wk in cert]
+ witness_claimed = "proven_floor" in cert or bool(present_wkeys)
+ valid_witnesses = [
+ cert[wk]
+ for wk in present_wkeys
+ if isinstance(cert[wk], (str, list)) and _witness_value_valid(cert[wk])
+ ]
+ all_present_nonempty = bool(present_wkeys) and len(valid_witnesses) == len(present_wkeys)
+ if cert.get("exact_optimum_reached") is False or (witness_claimed and not all_present_nonempty):
findings.append(
{
- "rule": "CERT_FLOOR_EXCEEDS_MAX_BOUND",
- "message": f"proven_floor ({p_floor}) exceeds search max_bound ({max_b}).",
+ "rule": "CERT_UNWITNESSED_VERIFIED_OPTIMUM",
+ "message": "Unwitnessed lower bound must carry status LOWER_BOUND_UNWITNESSED, never VERIFIED/PROVEN.",
}
)
- if status == "VERIFIED":
- witness = cert.get("witness") if "witness" in cert else cert.get("winning_witness")
+ elif p_floor is not None:
witness_cost = cert.get("witness_cost")
- if witness_cost is None and isinstance(witness, str):
- witness_cost = len(witness)
- if cert.get("exact_optimum_reached") is False or not witness:
- findings.append(
- {
- "rule": "CERT_UNWITNESSED_VERIFIED_OPTIMUM",
- "message": "Unwitnessed lower bound must carry status LOWER_BOUND_UNWITNESSED, never VERIFIED.",
- }
- )
- elif witness_cost is not None and int(witness_cost) != p_floor:
+ if witness_cost is not None:
+ if _is_count(witness_cost) and witness_cost != p_floor:
+ findings.append(
+ {
+ "rule": "CERT_WITNESS_FLOOR_MISMATCH",
+ "message": f"Witness cost {witness_cost} != claimed proven_floor {p_floor}.",
+ }
+ )
+ else:
+ for wval in valid_witnesses:
+ if len(wval) != p_floor:
+ findings.append(
+ {
+ "rule": "CERT_WITNESS_FLOOR_MISMATCH",
+ "message": f"Witness cost {len(wval)} != claimed proven_floor {p_floor}.",
+ }
+ )
+ break
+
+ # Instance digest format & mismatch checks (fail closed on blank/newline/all-zero)
+ for ikey in ("instance_sha256", "canonical_instance_sha256"):
+ if ikey in cert and isinstance(cert[ikey], str):
+ ival = cert[ikey]
+ if not SHA256_64_RE.fullmatch(ival) or ival == "0" * 64:
findings.append(
{
- "rule": "CERT_WITNESS_FLOOR_MISMATCH",
- "message": f"Witness cost {witness_cost} != claimed proven_floor {p_floor}.",
+ "rule": "CERT_INSTANCE_DIGEST_MALFORMED",
+ "message": f"{ikey} must be a non-zero lowercase 64-hex SHA-256 digest.",
}
)
-
- # Instance mismatch & step-consistency violations
- if cert.get("instance_sha256") and cert.get("canonical_instance_sha256"):
+ if "instance_sha256" in cert and "canonical_instance_sha256" in cert:
if cert.get("instance_sha256") != cert.get("canonical_instance_sha256"):
findings.append(
{
@@ -908,7 +1168,7 @@ def audit_transition_certificate(
"message": "Certificate instance_sha256 does not match canonical target instance.",
}
)
- if int(cert.get("step_consistency_violations", 0)) > 0:
+ if _is_count(cert.get("step_consistency_violations")) and cert["step_consistency_violations"] > 0:
findings.append(
{
"rule": "CERT_STEP_INCONSISTENCY",
@@ -920,7 +1180,7 @@ def audit_transition_certificate(
incomplete_graph = (
cert.get("complete_space") is False
or cert.get("complete_domain_closed") is False
- or int(cert.get("open_transitions", 0)) > 0
+ or (_is_count(cert.get("open_transitions")) and cert["open_transitions"] > 0)
)
if (
proof_mode == "inductive_potential"
@@ -960,7 +1220,7 @@ def audit_transition_certificate(
# F-08: Missing, malformed non-64-hex, or unregistered witness_or_proof_sha256 (fail closed, NEON-D5)
if status in ("VERIFIED", "PROVEN"):
w_sha = str(cert.get("witness_or_proof_sha256", ""))
- if not SHA256_64_RE.fullmatch(w_sha):
+ if not SHA256_64_RE.fullmatch(w_sha) or w_sha == "0" * 64:
findings.append(
{
"rule": "CERT_INVALID_WITNESS_SHA256",
@@ -1045,12 +1305,30 @@ def _parse_exact_rational(val: Any, *, max_abs_int: int = MAX_CERT_ABS_INT) -> F
def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]:
"""Verify exact rational LP dual lower-bound (`bounds`) or Farkas (`infeasible`) certificates."""
- mode = str(cert.get("mode", "bounds")).strip().lower()
+ if not isinstance(cert, Mapping):
+ return {
+ "passed": False,
+ "epistemic_status": "REJECTED",
+ "findings": [{"rule": "LP_CERT_NOT_AN_OBJECT", "message": f"LP certificate must be a JSON object (got {type(cert).__name__})."}],
+ }
+ raw_mode = cert.get("mode", "bounds")
+ if not isinstance(raw_mode, str):
+ return {
+ "passed": False,
+ "epistemic_status": "REJECTED",
+ "findings": [{"rule": "LP_CERT_MALFORMED", "message": "mode must be a string"}],
+ }
+ mode = raw_mode.strip().lower()
findings: list[dict[str, str]] = []
try:
- matrix_a = [[_parse_exact_rational(x) for x in row] for row in cert["A"]]
- rhs_b = [_parse_exact_rational(x) for x in cert["b"]]
- dual_y = [_parse_exact_rational(x) for x in cert["y"]]
+ raw_a, raw_b, raw_y = cert["A"], cert["b"], cert["y"]
+ if not isinstance(raw_a, list) or not isinstance(raw_b, list) or not isinstance(raw_y, list):
+ raise TypeError("A, b, and y must be lists")
+ if any(not isinstance(row, list) for row in raw_a):
+ raise TypeError("each row of A must be a list")
+ matrix_a = [[_parse_exact_rational(x) for x in row] for row in raw_a]
+ rhs_b = [_parse_exact_rational(x) for x in raw_b]
+ dual_y = [_parse_exact_rational(x) for x in raw_y]
except (KeyError, TypeError, ValueError) as exc:
return {
"passed": False,
@@ -1060,6 +1338,12 @@ def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]:
m_rows = len(matrix_a)
n_cols = len(matrix_a[0]) if m_rows > 0 else 0
+ if m_rows == 0 or n_cols == 0:
+ return {
+ "passed": False,
+ "epistemic_status": "REJECTED",
+ "findings": [{"rule": "LP_CERT_EMPTY_SYSTEM", "message": "LP constraint matrix A must have >= 1 row and >= 1 column."}],
+ }
if len(rhs_b) != m_rows or len(dual_y) != m_rows or any(len(r) != n_cols for r in matrix_a):
return {
"passed": False,
@@ -1076,7 +1360,10 @@ def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]:
if mode == "bounds":
try:
- cost_c = [_parse_exact_rational(x) for x in cert["c"]]
+ raw_c = cert["c"]
+ if not isinstance(raw_c, list):
+ raise TypeError("c must be a list")
+ cost_c = [_parse_exact_rational(x) for x in raw_c]
claimed_lb = _parse_exact_rational(cert["claimed_lower_bound"])
except (KeyError, TypeError, ValueError) as exc:
return {
diff --git a/src/mcproof/lean_harness.py b/src/mcproof/lean_harness.py
index 0c5e74a..36a1e6d 100644
--- a/src/mcproof/lean_harness.py
+++ b/src/mcproof/lean_harness.py
@@ -9,12 +9,14 @@
from pathlib import Path
import re
import shutil
+import stat
import subprocess
import sys
import tempfile
-from typing import Any, Sequence
+from typing import Any, Mapping, Sequence
+import uuid
-from .paths import dep_repo, elan_bin_dir, find_lean_tool, repo_root
+from .paths import dep_repo, deps_dir, elan_bin_dir, find_lean_tool, repo_root
STANDARD_AXIOMS: frozenset[str] = frozenset({"propext", "Classical.choice", "Quot.sound"})
SORRY_WARNING_RE = re.compile(r"warning:.*declaration uses [`']sorry[`']")
@@ -59,11 +61,30 @@
),
),
(
+ # `attribute [init]` is not `@[init]`. It still runs when the module is imported.
+ # The marker may sit mid-line or be split across a newline (`attribute\n[init]`).
+ "FORBIDDEN_INIT_ATTRIBUTE",
+ re.compile(r"attribute\s*\[[^\]]*\b(?:builtin_init|init)\b"),
+ ),
+ (
+ # Not only at the start of a line. A mid-line `#eval` still runs during elaboration.
"FORBIDDEN_EVAL_COMMAND",
- re.compile(r"(?m)^[ \t]*#(?:eval|reduce|check|print|synth)\b"),
+ re.compile(r"#(?:eval|reduce|check|print|synth)\b"),
),
)
+# A hit here means the candidate would run code during compile or import.
+# Callers return before any Lean process. Sorry, axiom, and vacuous lints still
+# reach the kernel so those checks stay in place.
+COMPILE_BLOCKING_LINT_RULES = frozenset({
+ "FORBIDDEN_INIT_ATTRIBUTE",
+ "FORBIDDEN_EVAL_COMMAND",
+ "METAPROGRAM_ESCAPE",
+ "SYNTAX_OVERRIDE_DECL",
+ "UNSOUND_IMPLEMENTED_BY",
+ "UNVERIFIED_NATIVE_EVAL",
+})
+
COMPARATOR_ORDERED_KERNELS: tuple[tuple[str, str, str], ...] = (
("lean-paranoid", "Running Lean paranoid kernel on solution", "Lean paranoid kernel accepts the solution"),
("lean4lean", "Running lean4lean kernel on solution", "lean4lean kernel accepts the solution"),
@@ -79,46 +100,252 @@
)
-def linux_bwrap_functional(*, timeout_sec: float = 5.0) -> bool:
- """Return True when Linux `bwrap` runs a minimal sandbox and can create `lake comparator`'s `/run/user` session dir."""
+class CandidateSandboxUnavailable(RuntimeError):
+ """`bwrap` cannot confine a candidate Lean run. Callers must not fall back to the host."""
+
+
+# Host trees that must not be visible. `/run` hides ssh-agent and API sockets.
+# `/agent` and `/workspace` hide the checkout, including `.git/config`.
+_SANDBOX_SYS_RO = ("/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc")
+_SANDBOX_TMPFS = ("/tmp", "/run", "/home", "/root", "/agent", "/workspace", "/opt", "/var")
+_SANDBOX_CPU_SEC = 600
+# `RLIMIT_NPROC` counts every thread of this uid. 8192 is enough for `lake build`.
+_SANDBOX_NOFILE = 4096
+_SANDBOX_NPROC = 8192
+_SANDBOX_PROBE_SOCKS = ("/run/cursor/api.sock", "/run/host-services/ssh-auth.sock")
+_BWRAP_FUNCTIONAL: bool | None = None
+
+_SANDBOX_PROBE = """
+import socket, sys
+from pathlib import Path
+sentinel = sys.argv[1]
+git_config = Path(sys.argv[2])
+blob = Path("/proc/1/environ").read_bytes() + b"\\0" + Path("/proc/self/environ").read_bytes()
+if sentinel.encode() in blob:
+ raise SystemExit(2)
+if git_config.is_file():
+ raise SystemExit(3)
+for sock in sys.argv[3:]:
+ handle = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ handle.settimeout(0.2)
+ try:
+ handle.connect(sock)
+ except OSError:
+ pass
+ else:
+ raise SystemExit(4)
+ finally:
+ handle.close()
+try:
+ Path("/etc/mcproof-sandbox-ro-probe").write_text("x", encoding="utf-8")
+except OSError:
+ pass
+else:
+ raise SystemExit(5)
+raise SystemExit(0)
+"""
+
+
+def _address_space_cap_bytes() -> int:
+ """Virtual-memory cap for a confined process: this host's `MemTotal`, not more.
+
+ A fixed cap above the machine's RAM does not contain a memory hog.
+ """
+ try:
+ for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines():
+ if line.startswith("MemTotal:"):
+ kb = int(line.split()[1])
+ if kb > 0:
+ return kb * 1024
+ except (OSError, ValueError, IndexError):
+ pass
+ return 1024 * 1024 * 1024
+
+
+def _toolchain_elan_home() -> str:
+ root = Path(elan_bin_dir()).resolve().parent
+ return str(root) if (root / "bin").is_dir() else ""
+
+
+def _sandbox_env_pairs(caller_env: Mapping[str, str] | None) -> list[tuple[str, str]]:
+ """Allowlist passed to `env -i` and to `bwrap --setenv`. Nothing else crosses."""
+ elan = _toolchain_elan_home()
+ path_parts = ["/usr/bin", "/bin"]
+ if elan:
+ path_parts.append(str(Path(elan) / "bin"))
+ pairs = [
+ ("PATH", os.pathsep.join(path_parts)),
+ ("HOME", "/tmp/home"),
+ ("TMPDIR", "/tmp"),
+ ("LANG", "C.UTF-8"),
+ ("LC_ALL", "C.UTF-8"),
+ ]
+ if elan:
+ pairs.append(("ELAN_HOME", elan))
+ lean_path = (caller_env or {}).get("LEAN_PATH")
+ if lean_path:
+ pairs.append(("LEAN_PATH", lean_path))
+ return pairs
+
+
+def _confine_argv(
+ cmd: Sequence[str],
+ *,
+ cwd: Path,
+ caller_env: Mapping[str, str] | None,
+ readable_dirs: Sequence[Path],
+) -> list[str]:
+ """`prlimit` + `env -i` + `bwrap` over the toolchain, not the host root."""
+ prlimit_bin = shutil.which("prlimit")
+ env_bin = shutil.which("env")
+ bwrap_bin = shutil.which("bwrap")
+ if not prlimit_bin or not env_bin or not bwrap_bin:
+ raise CandidateSandboxUnavailable(
+ "Linux bubblewrap (`bwrap`), `env`, or `prlimit` is unavailable; "
+ "refusing to run candidate Lean unsandboxed."
+ )
+ cwd_path = Path(cwd).resolve()
+ cwd_s = str(cwd_path)
+ pairs = _sandbox_env_pairs(caller_env)
+ argv: list[str] = [
+ prlimit_bin,
+ f"--cpu={_SANDBOX_CPU_SEC}",
+ f"--as={_address_space_cap_bytes()}",
+ f"--nofile={_SANDBOX_NOFILE}",
+ f"--nproc={_SANDBOX_NPROC}",
+ "--",
+ env_bin,
+ "-i",
+ ]
+ argv.extend(f"{key}={value}" for key, value in pairs)
+ argv.extend(
+ (
+ bwrap_bin,
+ "--new-session",
+ "--unshare-all",
+ "--unshare-net",
+ "--die-with-parent",
+ "--dev",
+ "/dev",
+ "--proc",
+ "/proc",
+ )
+ )
+ for directory in _SANDBOX_SYS_RO:
+ if Path(directory).is_dir():
+ argv.extend(("--ro-bind", directory, directory))
+ for directory in _SANDBOX_TMPFS:
+ if Path(directory).is_dir():
+ argv.extend(("--tmpfs", directory))
+ # Lake's own sandbox mounts a tmpfs on `/run/user`. The directory has to
+ # exist; an empty tmpfs over `/run` would make that mkdir fail.
+ argv.extend(("--dir", "/tmp/home", "--dir", "/run/user"))
+ elan = _toolchain_elan_home()
+ if elan:
+ argv.extend(("--ro-bind", elan, elan))
+ deps = deps_dir()
+ if deps.is_dir():
+ deps_s = str(deps.resolve())
+ argv.extend(("--ro-bind", deps_s, deps_s))
+ for extra in readable_dirs:
+ extra_path = Path(extra).resolve()
+ extra_s = str(extra_path)
+ if not extra_path.exists():
+ continue
+ if extra_s == cwd_s or extra_path.is_relative_to(cwd_path):
+ continue
+ argv.extend(("--ro-bind", extra_s, extra_s))
+ argv.extend(("--bind", cwd_s, cwd_s, "--clearenv"))
+ for key, value in pairs:
+ argv.extend(("--setenv", key, value))
+ argv.extend(("--chdir", cwd_s, "--", *cmd))
+ return argv
+
+
+def _spawn_confined(
+ cmd: Sequence[str],
+ *,
+ cwd: Path,
+ caller_env: Mapping[str, str] | None,
+ timeout_sec: float,
+ readable_dirs: Sequence[Path] = (),
+) -> subprocess.CompletedProcess[str]:
+ argv = _confine_argv(cmd, cwd=cwd, caller_env=caller_env, readable_dirs=readable_dirs)
+ return subprocess.run(
+ argv,
+ capture_output=True,
+ text=True,
+ timeout=timeout_sec,
+ check=False,
+ )
+
+
+def linux_bwrap_functional(*, timeout_sec: float = 15.0) -> bool:
+ """Return True when the candidate sandbox actually confines a process.
+
+ The probe refuses a parent-env leak in `/proc/1/environ`, a readable
+ `.git/config`, a connected host socket, or a write on the read-only host.
+ A missing `bwrap` or `prlimit` is False. Callers must not fall back.
+ """
+ global _BWRAP_FUNCTIONAL
+ if _BWRAP_FUNCTIONAL is not None:
+ return _BWRAP_FUNCTIONAL
if not sys.platform.startswith("linux"):
+ _BWRAP_FUNCTIONAL = False
return False
- bwrap_bin = shutil.which("bwrap")
- if not bwrap_bin:
+ if not shutil.which("bwrap") or not shutil.which("prlimit") or not shutil.which("env"):
+ _BWRAP_FUNCTIONAL = False
return False
+ sentinel = f"mcproof-sentinel-{uuid.uuid4().hex}"
+ os.environ["MCPROOF_SANDBOX_SENTINEL"] = sentinel
try:
- basic = subprocess.run(
- [bwrap_bin, "--ro-bind", "/", "/", "true"],
- capture_output=True,
- timeout=timeout_sec,
- check=False,
- )
- if basic.returncode != 0:
- return False
- uid = os.getuid()
- lake_compat = subprocess.run(
- [
- bwrap_bin,
- "--ro-bind",
- "/",
- "/",
- "--bind",
- "/run",
- "/run",
- "--bind",
- "/tmp",
- "/tmp",
- "sh",
- "-c",
- f"mkdir -p /run/user/{uid} && test -w /run/user/{uid}",
- ],
- capture_output=True,
- timeout=timeout_sec,
- check=False,
- )
- except (OSError, subprocess.TimeoutExpired):
+ with tempfile.TemporaryDirectory(prefix="mcproof_bwrap_probe_") as tmp:
+ script = Path(tmp) / "probe.py"
+ script.write_text(_SANDBOX_PROBE, encoding="utf-8")
+ git_config = repo_root() / ".git" / "config"
+ probe = _spawn_confined(
+ ["python3", str(script), sentinel, str(git_config), *_SANDBOX_PROBE_SOCKS],
+ cwd=Path(tmp),
+ caller_env={},
+ timeout_sec=timeout_sec,
+ )
+ except (OSError, subprocess.TimeoutExpired, CandidateSandboxUnavailable):
+ _BWRAP_FUNCTIONAL = False
return False
- return lake_compat.returncode == 0
+ finally:
+ os.environ.pop("MCPROOF_SANDBOX_SENTINEL", None)
+ _BWRAP_FUNCTIONAL = probe.returncode == 0
+ return _BWRAP_FUNCTIONAL
+
+
+def run_confined_command(
+ cmd: Sequence[str],
+ *,
+ cwd: Path,
+ env: Mapping[str, str] | None = None,
+ timeout_sec: float = 300,
+ readable_dirs: Sequence[Path] = (),
+) -> subprocess.CompletedProcess[str]:
+ """Run `cmd` where the candidate cannot see the host.
+
+ `prlimit` caps cpu, address space, files, and processes. `env -i` and
+ `--new-session` start `bwrap` with only the toolchain allowlist, so
+ `/proc/1/environ` is not the parent environment. The mount is the toolchain,
+ system libraries, and `deps`, with `tmpfs` over `/run`, `/agent`, and
+ `/workspace`. Only `cwd` is writable. A missing or non-functional sandbox
+ raises `CandidateSandboxUnavailable` and never runs `cmd` on the host.
+ """
+ if not linux_bwrap_functional():
+ raise CandidateSandboxUnavailable(
+ "Linux bubblewrap (`bwrap`) is unavailable; refusing to run candidate Lean unsandboxed."
+ )
+ return _spawn_confined(
+ cmd,
+ cwd=cwd,
+ caller_env=env,
+ timeout_sec=timeout_sec,
+ readable_dirs=readable_dirs,
+ )
AXIOM_AUDIT_TEMPLATE = """import Lean
@@ -185,8 +412,144 @@ def _load_soko_lean4_auditor() -> Any:
return mod
+def _is_lean_letter_like(ch: str) -> bool:
+ """Lean `isLetterLike` ranges used to keep identifier tokens intact."""
+ o = ord(ch)
+ if 0x3B1 <= o <= 0x3C9 and o != 0x3BB:
+ return True
+ if 0x391 <= o <= 0x3A9 and o not in (0x3A0, 0x3A3):
+ return True
+ if 0x3CA <= o <= 0x3FB or 0x1F00 <= o <= 0x1FFE:
+ return True
+ if 0x2100 <= o <= 0x214F or 0x1D49C <= o <= 0x1D59F:
+ return True
+ if 0x00C0 <= o <= 0x00FF and o not in (0x00D7, 0x00F7):
+ return True
+ return 0x0100 <= o <= 0x017F
+
+
+def _is_lean_subscript_alnum(ch: str) -> bool:
+ o = ord(ch)
+ return (
+ 0x2080 <= o <= 0x2089
+ or 0x2090 <= o <= 0x209C
+ or 0x1D62 <= o <= 0x1D6A
+ or o == 0x2C7C
+ )
+
+
+def _is_lean_id_first(ch: str) -> bool:
+ return ch.isalpha() or ch == "_" or _is_lean_letter_like(ch)
+
+
+def _is_lean_id_rest(ch: str) -> bool:
+ return (
+ ch.isalnum()
+ or ch in "_'!?"
+ or _is_lean_letter_like(ch)
+ or _is_lean_subscript_alnum(ch)
+ )
+
+
+def _is_hex_digit(ch: str) -> bool:
+ return ch.isdigit() or "a" <= ch <= "f" or "A" <= ch <= "F"
+
+
+def _lean_ident_end(src: str, i: int) -> int:
+ """End index of the identifier that starts at `i`, including dotted segments and `«...»` parts."""
+ n = len(src)
+ while i < n:
+ if src[i] == "«":
+ j = src.find("»", i + 1)
+ i = n if j < 0 else j + 1
+ elif _is_lean_id_first(src[i]):
+ i += 1
+ while i < n and _is_lean_id_rest(src[i]):
+ i += 1
+ else:
+ break
+ if i < n and src[i] == "." and i + 1 < n and (src[i + 1] == "«" or _is_lean_id_first(src[i + 1])):
+ i += 1
+ continue
+ break
+ return i
+
+
+def _is_raw_str_start(src: str, i: int) -> bool:
+ """True when `src[i]` is `r` and the token is `r` plus zero or more `#` plus `"`."""
+ if i >= len(src) or src[i] != "r":
+ return False
+ j = i + 1
+ while j < len(src) and src[j] == "#":
+ j += 1
+ return j < len(src) and src[j] == '"'
+
+
+def _append_raw_string(src: str, i: int, out: list[str]) -> int:
+ """Blank a Lean raw string (`r"..."`, `r#"..."#`, any hash count). `\\` is not an escape."""
+ n = len(src)
+ j = i + 1
+ hashes = 0
+ while j < n and src[j] == "#":
+ hashes += 1
+ j += 1
+ if j >= n or src[j] != '"':
+ out.append(src[i])
+ return i + 1
+ j += 1
+ out.append('"')
+ while j < n:
+ if src[j] == '"':
+ k = j + 1
+ seen = 0
+ while seen < hashes and k < n and src[k] == "#":
+ seen += 1
+ k += 1
+ if seen == hashes:
+ j = k
+ break
+ if src[j] == "\n":
+ out.append("\n")
+ j += 1
+ out.append('"')
+ return j
+
+
+def _char_lit_end(src: str, i: int) -> int | None:
+ """End index of a Lean character literal at `i`, or None when `src[i:]` is not one.
+
+ Covers `'a'`, `'"'`, and escapes (`'\\n'`, `'\\''`, `'\\"'`, `'\\\\'`, `\\xNN`, `\\uNNNN`).
+ `''` is not a character literal.
+ """
+ n = len(src)
+ if i >= n or src[i] != "'" or i + 1 >= n or src[i + 1] == "'":
+ return None
+ j = i + 1
+ if src[j] == "\\":
+ if j + 1 >= n:
+ return None
+ nxt = src[j + 1]
+ if nxt in "\\\"'rnt":
+ j += 2
+ elif nxt == "x" and j + 3 < n and _is_hex_digit(src[j + 2]) and _is_hex_digit(src[j + 3]):
+ j += 4
+ elif nxt == "u" and j + 5 < n and all(_is_hex_digit(src[j + k]) for k in range(2, 6)):
+ j += 6
+ else:
+ return None
+ else:
+ j += 1
+ if j < n and src[j] == "'":
+ return j + 1
+ return None
+
+
def strip_lean_comments_and_strings(src: str) -> str:
- """Strip `--` line comments, nested `/- ... -/` block comments, and string literals while keeping line numbers."""
+ """Strip `--` line comments, nested `/- ... -/` block comments, and string literals while keeping line numbers.
+
+ Raw strings (`r"..."`, `r#"..."#`, any number of hashes) do not treat `\\` as an escape.
+ Character literals, including `'"'` and escaped forms, are kept so a following command stays visible.
+ """
out: list[str] = []
i = 0
n = len(src)
@@ -210,6 +573,20 @@ def strip_lean_comments_and_strings(src: str) -> str:
j = src.find("\n", i)
i = n if j < 0 else j
continue
+ if _is_raw_str_start(src, i):
+ i = _append_raw_string(src, i, out)
+ continue
+ if src[i] == "«" or _is_lean_id_first(src[i]):
+ j = _lean_ident_end(src, i)
+ out.append(src[i:j])
+ i = j
+ continue
+ if src[i] == "'":
+ end = _char_lit_end(src, i)
+ if end is not None:
+ out.append(src[i:end])
+ i = end
+ continue
if src[i] == '"':
i += 1
out.append('"')
@@ -660,6 +1037,14 @@ def verify_lean4_prompt_obligations(
if findings or not run_kernel_type_check or not obligations["theorem_specs"]:
return findings
+ for item in lint_lean4_source(
+ candidate_source, require_theorem=False, check_vacuous=False,
+ )["findings"]:
+ if item.get("rule") in COMPILE_BLOCKING_LINT_RULES:
+ findings.append(item)
+ if findings:
+ return findings
+
proj_dir = (lean_project_dir or (repo_root() / "lean")).resolve()
lean_bin = find_lean_tool("lean")
env = _lean_env()
@@ -715,27 +1100,27 @@ def verify_lean4_prompt_obligations(
run_env = dict(env)
run_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts)
- c_proc = subprocess.run(
- [lean_bin, "-j", "1", "-D", "Elab.async=false", str(cand_f), "-o", str(cand_o)],
- cwd=tdp,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
- if c_proc.returncode != 0:
+ readable = (lib_olean_dir,) if lib_olean_dir.is_dir() else ()
+ try:
+ c_proc = run_confined_command(
+ [lean_bin, "-j", "1", "-D", "Elab.async=false", str(cand_f), "-o", str(cand_o)],
+ cwd=tdp,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=readable,
+ )
+ if c_proc.returncode != 0:
+ return findings
+ d_proc = run_confined_command(
+ [lean_bin, "-j", "1", "-D", "Elab.async=false", str(drv_f)],
+ cwd=tdp,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=readable,
+ )
+ except CandidateSandboxUnavailable as exc:
+ findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)})
return findings
-
- d_proc = subprocess.run(
- [lean_bin, "-j", "1", "-D", "Elab.async=false", str(drv_f)],
- cwd=tdp,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
if d_proc.returncode != 0:
tail = " | ".join(ln.strip() for ln in ((d_proc.stdout or "") + "\n" + (d_proc.stderr or "")).splitlines()[-4:] if ln.strip())
findings.append({
@@ -765,11 +1150,19 @@ def verify_lean4_against_challenge(
timeout_sec: float = 60.0,
) -> list[dict[str, Any]]:
"""Verify via Lean `Meta.isDefEq` that `candidate_source` implements every def/inductive/theorem in `challenge_lean`."""
+ findings: list[dict[str, Any]] = [
+ item for item in lint_lean4_source(
+ candidate_source, require_theorem=False, check_vacuous=False,
+ )["findings"]
+ if item.get("rule") in COMPILE_BLOCKING_LINT_RULES
+ ]
+ if findings:
+ return findings
+
proj_dir = (lean_project_dir or (repo_root() / "lean")).resolve()
lean_bin = find_lean_tool("lean")
env = _lean_env()
lib_olean_dir = proj_dir / ".lake" / "build" / "lib" / "lean"
- findings: list[dict[str, Any]] = []
with tempfile.TemporaryDirectory(prefix="mcproof_chalcmp_") as td:
tdp = Path(td).resolve()
@@ -792,41 +1185,39 @@ def verify_lean4_against_challenge(
run_env = dict(env)
run_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts)
- s_proc = subprocess.run(
- [lean_bin, "-j", "1", "-D", "Elab.async=false", str(spec_f), "-o", str(spec_o)],
- cwd=tdp,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
- c_proc = subprocess.run(
- [lean_bin, "-j", "1", "-D", "Elab.async=false", str(cand_f), "-o", str(cand_o)],
- cwd=tdp,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
- if s_proc.returncode != 0 or c_proc.returncode != 0:
- findings.append({
- "line": 1,
- "rule": "CHALLENGE_COMPARE_BUILD_FAILED",
- "message": "Failed to compile challenge or candidate module for kernel statement comparison.",
- })
+ readable = (lib_olean_dir,) if lib_olean_dir.is_dir() else ()
+ try:
+ s_proc = run_confined_command(
+ [lean_bin, "-j", "1", "-D", "Elab.async=false", str(spec_f), "-o", str(spec_o)],
+ cwd=tdp,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=readable,
+ )
+ c_proc = run_confined_command(
+ [lean_bin, "-j", "1", "-D", "Elab.async=false", str(cand_f), "-o", str(cand_o)],
+ cwd=tdp,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=readable,
+ )
+ if s_proc.returncode != 0 or c_proc.returncode != 0:
+ findings.append({
+ "line": 1,
+ "rule": "CHALLENGE_COMPARE_BUILD_FAILED",
+ "message": "Failed to compile challenge or candidate module for kernel statement comparison.",
+ })
+ return findings
+ cmp_proc = run_confined_command(
+ [lean_bin, "-j", "1", "-D", "Elab.async=false", str(drv_f)],
+ cwd=tdp,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=readable,
+ )
+ except CandidateSandboxUnavailable as exc:
+ findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)})
return findings
-
- cmp_proc = subprocess.run(
- [lean_bin, "-j", "1", "-D", "Elab.async=false", str(drv_f)],
- cwd=tdp,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
if cmp_proc.returncode != 0:
tail = " | ".join(ln.strip() for ln in ((cmp_proc.stdout or "") + "\n" + (cmp_proc.stderr or "")).splitlines()[-4:] if ln.strip())
findings.append({
@@ -1083,23 +1474,71 @@ def verify_lean4_source(
require_theorem=require_theorem,
)
findings: list[dict[str, Any]] = list(lint["findings"])
+ # An execution lint means the source would run during compile or import.
+ # Returning here is what stops the host write. The sandbox is the other half.
+ if any(item.get("rule") in COMPILE_BLOCKING_LINT_RULES for item in findings):
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=(),
+ axioms_used=(),
+ nonstandard_axioms=(),
+ sorry_declarations=(),
+ paranoid_kernels_run=(),
+ sandboxed=False,
+ findings=tuple(findings),
+ )
lean_bin = find_lean_tool("lean")
lake_bin = find_lean_tool("lake")
leanchecker_bin = find_lean_tool("leanchecker")
env = _lean_env()
- # Ensure reference Lean library `.olean` files exist if project not yet built
+ # Ensure reference Lean library `.olean` files exist if project not yet built.
+ # The build is confined too: this function does not run Lean on the host.
lib_olean_dir = proj_dir / ".lake" / "build" / "lib" / "lean"
- if not lib_olean_dir.is_dir():
- subprocess.run(
- [lake_bin, "build", "Mcproof"],
- cwd=proj_dir,
- env=env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
+ try:
+ if not lib_olean_dir.is_dir():
+ run_confined_command(
+ [lake_bin, "build", "Mcproof"],
+ cwd=proj_dir,
+ env=env,
+ timeout_sec=timeout_sec,
+ )
+ except CandidateSandboxUnavailable as exc:
+ findings.append({
+ "line": 1,
+ "rule": "SANDBOX_UNAVAILABLE",
+ "message": str(exc),
+ })
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=(),
+ axioms_used=(),
+ nonstandard_axioms=(),
+ sorry_declarations=(),
+ paranoid_kernels_run=(),
+ sandboxed=False,
+ findings=tuple(findings),
+ )
+ except subprocess.TimeoutExpired as exc:
+ findings.append({
+ "line": 1,
+ "rule": "HOST_RESOURCE_EXHAUSTED",
+ "message": f"Lean elaboration timed out after {timeout_sec}s ({exc})",
+ })
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=(),
+ axioms_used=(),
+ nonstandard_axioms=(),
+ sorry_declarations=(),
+ paranoid_kernels_run=(),
+ sandboxed=False,
+ findings=tuple(findings),
+ host_resource_exhausted=True,
)
mod_name = "McproofCandidateCheck"
@@ -1128,14 +1567,12 @@ def verify_lean4_source(
max_memory_mib=max_memory_mib,
)
try:
- comp = subprocess.run(
+ comp = run_confined_command(
comp_cmd,
cwd=tmp_dir,
env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
+ timeout_sec=timeout_sec,
+ readable_dirs=(lib_olean_dir,) if lib_olean_dir.is_dir() else (),
)
except subprocess.TimeoutExpired as exc:
findings.append({
@@ -1151,10 +1588,23 @@ def verify_lean4_source(
nonstandard_axioms=(),
sorry_declarations=(),
paranoid_kernels_run=(),
- sandboxed=False,
+ sandboxed=True,
findings=tuple(findings),
host_resource_exhausted=True,
)
+ except CandidateSandboxUnavailable as exc:
+ findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)})
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=(),
+ axioms_used=(),
+ nonstandard_axioms=(),
+ sorry_declarations=(),
+ paranoid_kernels_run=(),
+ sandboxed=False,
+ findings=tuple(findings),
+ )
combined_out = (comp.stdout or "") + "\n" + (comp.stderr or "")
if comp.returncode != 0:
host_reason = classify_host_resource_failure(comp.returncode, combined_out)
@@ -1172,7 +1622,7 @@ def verify_lean4_source(
nonstandard_axioms=(),
sorry_declarations=(),
paranoid_kernels_run=(),
- sandboxed=False,
+ sandboxed=True,
findings=tuple(findings),
host_resource_exhausted=True,
)
@@ -1190,7 +1640,7 @@ def verify_lean4_source(
nonstandard_axioms=(),
sorry_declarations=(),
paranoid_kernels_run=(),
- sandboxed=False,
+ sandboxed=True,
findings=tuple(findings),
)
@@ -1208,15 +1658,27 @@ def verify_lean4_source(
AXIOM_AUDIT_TEMPLATE.format(module_name=mod_name, root_json=json.dumps(mod_name)),
encoding="utf-8",
)
- ax_run = subprocess.run(
- [lean_bin, str(audit_driver)],
- cwd=tmp_dir,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
+ try:
+ ax_run = run_confined_command(
+ [lean_bin, str(audit_driver)],
+ cwd=tmp_dir,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=(lib_olean_dir,) if lib_olean_dir.is_dir() else (),
+ )
+ except CandidateSandboxUnavailable as exc:
+ findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)})
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=(),
+ axioms_used=(),
+ nonstandard_axioms=(),
+ sorry_declarations=(),
+ paranoid_kernels_run=tuple(kernels_run),
+ sandboxed=False,
+ findings=tuple(findings),
+ )
if ax_run.returncode != 0:
tail = " | ".join(line.strip() for line in ((ax_run.stdout or "") + "\n" + (ax_run.stderr or "")).splitlines()[-4:] if line.strip())
findings.append({
@@ -1266,15 +1728,27 @@ def verify_lean4_source(
})
if run_paranoid_leanchecker and cand_olean.is_file():
- lc_run = subprocess.run(
- [leanchecker_bin, mod_name],
- cwd=tmp_dir,
- env=run_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
+ try:
+ lc_run = run_confined_command(
+ [leanchecker_bin, mod_name],
+ cwd=tmp_dir,
+ env=run_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=(lib_olean_dir,) if lib_olean_dir.is_dir() else (),
+ )
+ except CandidateSandboxUnavailable as exc:
+ findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)})
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=tuple(sorted(theorems_checked)),
+ axioms_used=tuple(sorted(all_axioms)),
+ nonstandard_axioms=tuple(sorted(nonstandard)),
+ sorry_declarations=tuple(sorted(sorry_decls)),
+ paranoid_kernels_run=tuple(kernels_run),
+ sandboxed=False,
+ findings=tuple(findings),
+ )
if lc_run.returncode != 0:
tail = " | ".join(line.strip() for line in ((lc_run.stdout or "") + "\n" + (lc_run.stderr or "")).splitlines()[-4:] if line.strip())
findings.append({
@@ -1299,11 +1773,437 @@ def verify_lean4_source(
nonstandard_axioms=tuple(sorted(nonstandard)),
sorry_declarations=tuple(sorted(sorry_decls)),
paranoid_kernels_run=tuple(kernels_run),
- sandboxed=False,
+ sandboxed=True,
findings=tuple(findings),
)
+class UntrustedProjectPath(Exception):
+ """A copied path is a symlink or a special file. The trusted copy refuses it."""
+
+ def __init__(self, message: str, *, rule: str = "UNTRUSTED_PROJECT_SYMLINK") -> None:
+ super().__init__(message)
+ self.rule = rule
+
+
+# `lstat(dir_fd=)` is the `stat` implementation. CPython lists `stat` in
+# `os.supports_dir_fd` and does not list `lstat` itself.
+_NOFOLLOW_DIR_OPS = ("open", "stat", "mkdir")
+_NOFOLLOW_OPEN_RULE = "NOFOLLOW_OPEN_UNAVAILABLE"
+
+
+def _nofollow_dir_ops_available() -> bool:
+ """True when a directory can be opened without following a symlink in any component."""
+ if not hasattr(os, "O_DIRECTORY") or not hasattr(os, "O_NOFOLLOW"):
+ return False
+ supported = os.supports_dir_fd
+ return all(getattr(os, name) in supported for name in _NOFOLLOW_DIR_OPS)
+
+
+def _nofollow_unavailable_finding() -> dict[str, Any]:
+ return {
+ "line": 1,
+ "rule": _NOFOLLOW_OPEN_RULE,
+ "message": (
+ "O_DIRECTORY, O_NOFOLLOW, or dir_fd is missing; "
+ "refusing to open the candidate project because a following copy is not safe."
+ ),
+ }
+
+
+def _refuse_nofollow_unavailable() -> None:
+ if _nofollow_dir_ops_available():
+ return
+ finding = _nofollow_unavailable_finding()
+ raise UntrustedProjectPath(str(finding["message"]), rule=_NOFOLLOW_OPEN_RULE)
+
+
+def finding_blocks_comparator(finding: Mapping[str, Any]) -> bool:
+ """An elaboration command means the comparator must not run.
+
+ `#eval`, `run_cmd`, and `run_meta` plant files during the build. The
+ comparator elaborates the project, so it must not start once one of them
+ has been seen. `elab_rules` stays out of this set: the confined build is
+ what contains it.
+ """
+ rule = str(finding.get("rule", ""))
+ message = str(finding.get("message", ""))
+ if rule in {"FORBIDDEN_EVAL_COMMAND", "FORBIDDEN_ELAB_COMMAND"}:
+ return True
+ tokens = ("run_meta", "run_cmd", "run_elab", "run_tac", "#eval", "#reduce", "#check", "#print", "#synth")
+ return rule in {"METAPROGRAM_ESCAPE", "FORBIDDEN_BUILD_SIDE_EFFECT"} and any(token in message for token in tokens)
+
+
+_LAKE_COMMAND_RE = re.compile(
+ r"(? tuple[int, int | None]:
+ """End of a terminated raw string, or where a short closer resumes code.
+
+ Zero hashes close at the next `"`. A positive hash count closes only at `"`
+ plus that many hashes. A `"` with fewer hashes is the error Lean recovers
+ from by elaborating the following command, which the comment stripper still
+ hides when the closer is short.
+ """
+ n = len(src)
+ j = i + 1
+ hashes = 0
+ while j < n and src[j] == "#":
+ hashes += 1
+ j += 1
+ if j >= n or src[j] != '"':
+ return i + 1, None
+ j += 1
+ if hashes == 0:
+ while j < n and src[j] != '"':
+ j += 1
+ return (j + 1, None) if j < n else (n, None)
+ while j < n:
+ if src[j] == '"':
+ k = j + 1
+ seen = 0
+ while seen < hashes and k < n and src[k] == "#":
+ seen += 1
+ k += 1
+ if seen == hashes:
+ return k, None
+ return n, k
+ j += 1
+ return n, None
+
+
+def _lean_commands_that_may_run(src: str) -> list[str]:
+ """Commands Lean can elaborate, including one hidden by a short raw-string closer.
+
+ A command inside a terminated string or comment is not included. The comment
+ stripper is unchanged, so a compile that must still run those payloads is
+ unchanged too.
+ """
+ found: list[str] = []
+ n = len(src)
+ i = 0
+ while i < n:
+ if src.startswith("/-", i):
+ depth = 1
+ i += 2
+ while i < n and depth > 0:
+ if src.startswith("/-", i):
+ depth += 1
+ i += 2
+ elif src.startswith("-/", i):
+ depth -= 1
+ i += 2
+ else:
+ i += 1
+ continue
+ if src.startswith("--", i):
+ newline = src.find("\n", i)
+ i = n if newline < 0 else newline
+ continue
+ if _is_raw_str_start(src, i):
+ end, resume = _raw_string_resume(src, i)
+ if resume is not None and resume > i:
+ i = resume
+ else:
+ i = end if end > i else i + 1
+ continue
+ match = _LAKE_COMMAND_RE.match(src, i)
+ if match:
+ cmd = match.group(0)
+ if cmd not in found:
+ found.append(cmd)
+ i += len(cmd)
+ continue
+ if src[i] == '"':
+ i += 1
+ while i < n and src[i] != '"':
+ if src[i] == "\\" and i + 1 < n:
+ i += 2
+ else:
+ i += 1
+ if i < n:
+ i += 1
+ continue
+ if src[i] == "'":
+ end = _char_lit_end(src, i)
+ if end is not None:
+ i = end
+ continue
+ if src[i] == "«" or _is_lean_id_first(src[i]):
+ i = _lean_ident_end(src, i)
+ continue
+ i += 1
+ return found
+
+
+def _command_findings(rel: str, text: str) -> list[dict[str, Any]]:
+ findings: list[dict[str, Any]] = []
+ for cmd in _lean_commands_that_may_run(text):
+ if cmd.startswith("#"):
+ findings.append({
+ "line": 1,
+ "rule": "FORBIDDEN_EVAL_COMMAND",
+ "message": f"{rel} contains a Lean command that runs during elaboration: {cmd}",
+ })
+ else:
+ findings.append({
+ "line": 1,
+ "rule": "METAPROGRAM_ESCAPE",
+ "message": f"forbidden Lean escape hatch matched {cmd!r}",
+ })
+ return findings
+
+
+def _lake_symlink_finding(proj: Path) -> dict[str, Any] | None:
+ """`.lake` as a symlink is a finding. `rmtree` on that path raises, and following it deletes the target."""
+ if not _nofollow_dir_ops_available():
+ return _nofollow_unavailable_finding()
+ try:
+ root_fd = os.open(proj, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ except OSError as exc:
+ return {
+ "line": 1,
+ "rule": "UNTRUSTED_PROJECT_SYMLINK",
+ "message": f"project root is not a real directory: {exc}",
+ }
+ try:
+ try:
+ st = os.lstat(".lake", dir_fd=root_fd)
+ except FileNotFoundError:
+ return None
+ if stat.S_ISLNK(st.st_mode):
+ return {
+ "line": 1,
+ "rule": "LAKE_CACHE_SYMLINK",
+ "message": ".lake is a symlink; refusing to follow or delete it",
+ }
+ return None
+ finally:
+ os.close(root_fd)
+
+
+def _read_project_tree(proj: Path) -> dict[str, bytes]:
+ """Regular files only. A symlink or special file in any component refuses the copy.
+
+ `.lake` and `.git` are not copied. Opening each component with `O_NOFOLLOW`
+ does not follow a parent the candidate swapped for a symlink.
+ """
+ _refuse_nofollow_unavailable()
+ root_fd = os.open(proj, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ files: dict[str, bytes] = {}
+ _read_tree_at(root_fd, "", files)
+ return files
+ finally:
+ os.close(root_fd)
+
+
+def _read_tree_at(dir_fd: int, rel: str, files: dict[str, bytes]) -> None:
+ for name in sorted(os.listdir(dir_fd)):
+ if name in {".lake", ".git"}:
+ continue
+ child = f"{rel}/{name}" if rel else name
+ st = os.lstat(name, dir_fd=dir_fd)
+ if stat.S_ISLNK(st.st_mode):
+ raise UntrustedProjectPath(f"{child} is a symlink")
+ if stat.S_ISDIR(st.st_mode):
+ child_fd = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=dir_fd)
+ try:
+ _read_tree_at(child_fd, child, files)
+ finally:
+ os.close(child_fd)
+ continue
+ if not stat.S_ISREG(st.st_mode):
+ raise UntrustedProjectPath(f"{child} is not a regular file", rule="UNTRUSTED_PROJECT_FILE")
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=dir_fd)
+ try:
+ chunks: list[bytes] = []
+ while True:
+ block = os.read(fd, 1024 * 1024)
+ if not block:
+ break
+ chunks.append(block)
+ files[child] = b"".join(chunks)
+ finally:
+ os.close(fd)
+
+
+def _trusted_inputs(files: dict[str, bytes]) -> dict[str, bytes]:
+ """Drop a lakefile Lean would prefer over `lakefile.toml`.
+
+ The toml is the trusted configuration. `lakefile.lean` beside it is the candidate's plant.
+ A `lake-manifest.json` that is already here is trusted. One the build creates later is not
+ in this map, so a fresh tree does not receive it.
+ """
+ if "lakefile.toml" not in files:
+ return dict(files)
+ kept: dict[str, bytes] = {}
+ for rel, data in files.items():
+ parent, _, name = rel.rpartition("/")
+ if parent == "" and name.startswith("lakefile.") and name != "lakefile.toml":
+ continue
+ kept[rel] = data
+ return kept
+
+
+def _materialize_trusted_tree(files: dict[str, bytes]) -> Path:
+ """A new directory of regular files. Nothing here is a path the candidate chose."""
+ _refuse_nofollow_unavailable()
+ root = Path(tempfile.mkdtemp(prefix="mcproof_trusted_"))
+ root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ for rel in sorted(files):
+ _write_regular_at(root_fd, rel, files[rel])
+ except Exception:
+ os.close(root_fd)
+ shutil.rmtree(root)
+ raise
+ os.close(root_fd)
+ return root
+
+
+def _write_regular_at(root_fd: int, rel: str, data: bytes) -> None:
+ parts = rel.split("/")
+ dir_fd = root_fd
+ opened: list[int] = []
+ try:
+ for part in parts[:-1]:
+ try:
+ os.mkdir(part, dir_fd=dir_fd)
+ except FileExistsError:
+ pass
+ st = os.lstat(part, dir_fd=dir_fd)
+ if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
+ raise UntrustedProjectPath(f"{rel} crosses a symlink")
+ next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=dir_fd)
+ opened.append(next_fd)
+ dir_fd = next_fd
+ fd = os.open(
+ parts[-1],
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
+ 0o644,
+ dir_fd=dir_fd,
+ )
+ try:
+ view = memoryview(data)
+ while view:
+ wrote = os.write(fd, view)
+ view = view[wrote:]
+ finally:
+ os.close(fd)
+ finally:
+ for fd in reversed(opened):
+ os.close(fd)
+
+
+def _real_dir(parent: Path, rel: str) -> bool:
+ """True when every component of `parent/rel` is a real directory."""
+ if not _nofollow_dir_ops_available():
+ return False
+ try:
+ dir_fd = os.open(parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ except OSError:
+ return False
+ try:
+ for part in rel.split("/"):
+ try:
+ st = os.lstat(part, dir_fd=dir_fd)
+ except FileNotFoundError:
+ return False
+ if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
+ return False
+ next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=dir_fd)
+ os.close(dir_fd)
+ dir_fd = next_fd
+ return True
+ finally:
+ os.close(dir_fd)
+
+
+def _audit_solution_axioms(
+ build_dir: Path,
+ *,
+ solution_mod: str,
+ permitted: set[str],
+ lean_bin: str,
+ env: dict[str, str],
+ timeout_sec: int,
+ findings: list[dict[str, Any]],
+) -> tuple[set[str], list[str], list[str], str | None]:
+ """Import `solution_mod` from the build directory. The last item is a sandbox refusal, if any."""
+ measured: set[str] = set()
+ sorry_decls: list[str] = []
+ nonstd: list[str] = []
+ with tempfile.TemporaryDirectory(prefix="mcproof_proj_ax_") as ax_tmp_str:
+ ax_tmp = Path(ax_tmp_str)
+ audit_driver = ax_tmp / "McproofProjectAxiomDriver.lean"
+ audit_driver.write_text(
+ MODULE_AXIOM_AUDIT_TEMPLATE.format(module_name=solution_mod),
+ encoding="utf-8",
+ )
+ ax_env = dict(env)
+ lean_path_parts = [str(ax_tmp)]
+ olean_rel = ".lake/build/lib/lean"
+ if _real_dir(build_dir, olean_rel):
+ lean_path_parts.append(str(build_dir / olean_rel))
+ ax_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts)
+ try:
+ ax_run = run_confined_command(
+ [lean_bin, str(audit_driver)],
+ cwd=ax_tmp,
+ env=ax_env,
+ timeout_sec=timeout_sec,
+ readable_dirs=(build_dir,),
+ )
+ except CandidateSandboxUnavailable as exc:
+ return measured, sorry_decls, nonstd, str(exc)
+ if ax_run.returncode != 0:
+ tail = " | ".join(
+ line.strip()
+ for line in ((ax_run.stdout or "") + "\n" + (ax_run.stderr or "")).splitlines()[-4:]
+ if line.strip()
+ )
+ findings.append({
+ "line": 1,
+ "rule": "AXIOM_WALK_FAILED",
+ "message": f"trusted collectAxioms driver failed on {solution_mod}: {tail}",
+ })
+ return measured, sorry_decls, nonstd, None
+ for line in (ax_run.stdout or "").splitlines():
+ if not line.startswith("MCPROOF_AUDIT\t"):
+ continue
+ parts = line.split("\t")
+ if len(parts) != 5:
+ continue
+ _, kind, _, decl_name, ax_csv = parts
+ axs = {a for a in ax_csv.split(",") if a}
+ measured.update(axs)
+ if kind in ("axiom", "opaque"):
+ findings.append({
+ "line": 1,
+ "rule": "KERNEL_EXTRA_AXIOM_OR_OPAQUE",
+ "message": f"solution module {solution_mod} contains {kind} declaration '{decl_name}'",
+ })
+ if "sorryAx" in axs:
+ sorry_decls.append(decl_name)
+ findings.append({
+ "line": 1,
+ "rule": "KERNEL_SORRY_AXIOM",
+ "message": f"solution declaration '{decl_name}' depends on 'sorryAx'",
+ })
+ extra_axs = axs - (permitted & STANDARD_AXIOMS) - {"sorryAx"}
+ if extra_axs:
+ nonstd.extend(sorted(extra_axs))
+ findings.append({
+ "line": 1,
+ "rule": "KERNEL_NONSTANDARD_AXIOM",
+ "message": f"solution declaration '{decl_name}' uses unpermitted axioms: {sorted(extra_axs)}",
+ })
+ return measured, sorry_decls, nonstd, None
+
+
def verify_lean4_project_comparator(
project_dir: Path | None = None,
*,
@@ -1311,16 +2211,80 @@ def verify_lean4_project_comparator(
allow_unsandboxed: bool = False,
timeout_sec: int = 300,
) -> LeanVerificationResult:
- """Run full 6-kernel `lake comparator --paranoid` + `collectAxioms` + source escape-hatch checks on a Lake project."""
+ """Run full 6-kernel `lake comparator --paranoid` + `collectAxioms` + source escape-hatch checks on a Lake project.
+
+ Trusted steps run in a directory built from an in-memory copy. The caller's tree is never
+ written. `allow_unsandboxed` does not run candidate Lean on the host.
+ """
proj = (project_dir or (repo_root() / "lean")).resolve()
- toolchain = _read_toolchain(proj)
- lean_bin = find_lean_tool("lean")
- lake_bin = find_lean_tool("lake")
- env = _lean_env()
findings: list[dict[str, Any]] = []
- cmp_path = proj / "comparator.json"
- if not cmp_path.is_file():
+ def _stopped(*, sandboxed: bool = False, caveats: tuple[str, ...] = ()) -> LeanVerificationResult:
+ return LeanVerificationResult(
+ passed=False,
+ toolchain=toolchain,
+ theorems_checked=theorem_names,
+ axioms_used=(),
+ nonstandard_axioms=(),
+ sorry_declarations=(),
+ paranoid_kernels_run=(),
+ sandboxed=sandboxed,
+ findings=tuple(findings),
+ caveats=caveats,
+ challenge_sorry_whitelisted_module=challenge_mod or None,
+ )
+
+ lake_hit = _lake_symlink_finding(proj)
+ if lake_hit is not None:
+ # The platform refusal must not stat or read through a candidate path.
+ if lake_hit.get("rule") == _NOFOLLOW_OPEN_RULE:
+ toolchain = "leanprover/lean4:v4.35.0"
+ else:
+ toolchain = _read_toolchain(proj) if (proj / "lean-toolchain").is_file() and not (proj / "lean-toolchain").is_symlink() else "leanprover/lean4:v4.35.0"
+ theorem_names = ()
+ challenge_mod = ""
+ findings.append(lake_hit)
+ return _stopped()
+
+ try:
+ project_files = _read_project_tree(proj)
+ except UntrustedProjectPath as exc:
+ toolchain = "leanprover/lean4:v4.35.0"
+ theorem_names = ()
+ challenge_mod = ""
+ findings.append({"line": 1, "rule": exc.rule, "message": str(exc)})
+ return _stopped()
+ except OSError as exc:
+ toolchain = "leanprover/lean4:v4.35.0"
+ theorem_names = ()
+ challenge_mod = ""
+ findings.append({
+ "line": 1,
+ "rule": "UNTRUSTED_PROJECT_SYMLINK",
+ "message": f"project root is not a real directory: {exc}",
+ })
+ return _stopped()
+
+ toolchain = project_files.get("lean-toolchain", b"").decode("utf-8", "replace").strip() or "leanprover/lean4:v4.35.0"
+ raw_cmp = project_files.get("comparator.json")
+ if raw_cmp is None:
+ theorem_names = ()
+ challenge_mod = ""
+ findings.append({"line": 1, "rule": "MISSING_COMPARATOR_JSON", "message": f"no comparator.json in {proj}"})
+ return _stopped()
+
+ try:
+ cmp_cfg = json.loads(raw_cmp.decode("utf-8"))
+ except json.JSONDecodeError as exc:
+ theorem_names = ()
+ challenge_mod = ""
+ findings.append({
+ "line": 1,
+ "rule": "COMPARATOR_JSON_MALFORMED",
+ "message": f"comparator.json is not valid JSON: {exc}",
+ })
+ return _stopped()
+ if not isinstance(cmp_cfg, dict):
return LeanVerificationResult(
passed=False,
toolchain=toolchain,
@@ -1330,10 +2294,12 @@ def verify_lean4_project_comparator(
sorry_declarations=(),
paranoid_kernels_run=(),
sandboxed=False,
- findings=({"line": 1, "rule": "MISSING_COMPARATOR_JSON", "message": f"no comparator.json in {proj}"},),
+ findings=({
+ "line": 1,
+ "rule": "COMPARATOR_JSON_MALFORMED",
+ "message": "comparator.json must be a JSON object",
+ },),
)
-
- cmp_cfg = json.loads(cmp_path.read_text(encoding="utf-8"))
challenge_mod = str(cmp_cfg.get("challenge_module", ""))
solution_mod = str(cmp_cfg.get("solution_module", "Mcproof.Proofs"))
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*", solution_mod):
@@ -1359,199 +2325,174 @@ def verify_lean4_project_comparator(
"message": f"comparator.json permits non-standard axioms: {sorted(extra_permitted)}",
})
- # Fail closed before compiling untrusted Lean code when Linux bubblewrap is unavailable unless explicitly opted in
- bwrap_available = linux_bwrap_functional()
- caveats: list[str] = []
- if not bwrap_available:
- if not allow_unsandboxed:
- findings.append({
- "line": 1,
- "rule": "SANDBOX_UNAVAILABLE",
- "message": (
- "Linux bubblewrap (`bwrap`) is unavailable on this host; "
- "pass allow_unsandboxed=True or `--allow-unsandboxed` to explicitly authorize unsandboxed execution"
- ),
- })
- return LeanVerificationResult(
- passed=False,
- toolchain=toolchain,
- theorems_checked=theorem_names,
- axioms_used=(),
- nonstandard_axioms=(),
- sorry_declarations=(),
- paranoid_kernels_run=(),
- sandboxed=False,
- findings=tuple(findings),
- caveats=(),
- challenge_sorry_whitelisted_module=challenge_mod or None,
- )
- caveats.append("UNSANDBOXED_EXECUTION")
-
- # Static source lint on every `.lean` file in the project outside `.lake` and `.git`
- for lean_file in sorted(proj.rglob("*.lean")):
- rel = lean_file.relative_to(proj)
- if any(part in (".lake", ".git") for part in rel.parts):
+ caveats: tuple[str, ...] = ()
+ for rel, data in sorted(project_files.items()):
+ if not rel.endswith(".lean"):
continue
- is_challenge = challenge_rel is not None and rel == challenge_rel
- lint = lint_lean4_source(
- lean_file.read_text(encoding="utf-8"),
- label=rel.as_posix(),
- strict_init_only=strict_init_only,
- allow_challenge_sorry=is_challenge,
- check_vacuous=True,
- require_theorem=False,
- )
- findings.extend(lint["findings"])
+ findings.extend(_command_findings(rel, data.decode("utf-8")))
+ if any(finding_blocks_comparator(item) for item in findings):
+ return _stopped()
- # Scrub challenge `.olean`/`.ir` before `lake build` so `Spec` always compiles fresh from disk
- scrub_challenge_artifacts(proj, challenge_mod)
+ challenge_key = challenge_rel.as_posix() if challenge_rel is not None else None
- # Run `lake build`
- build_res = subprocess.run(
- [lake_bin, "build"],
- cwd=proj,
- env=env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
- if build_res.returncode != 0:
- tail = " | ".join(line.strip() for line in ((build_res.stdout or "") + "\n" + (build_res.stderr or "")).splitlines()[-6:] if line.strip())
+ def _lint_project() -> None:
+ for rel, data in sorted(project_files.items()):
+ if not rel.endswith(".lean"):
+ continue
+ lint = lint_lean4_source(
+ data.decode("utf-8"),
+ label=rel,
+ strict_init_only=strict_init_only,
+ allow_challenge_sorry=rel == challenge_key,
+ check_vacuous=True,
+ require_theorem=False,
+ )
+ findings.extend(lint["findings"])
+
+ # Candidate Lean never runs on the host. The flag does not open that path.
+ # A missing auditor must not hide this refusal; when the auditor is present its
+ # findings are kept, including a planted axiom.
+ if not linux_bwrap_functional():
+ try:
+ _lint_project()
+ except FileNotFoundError:
+ pass
findings.append({
"line": 1,
- "rule": "LAKE_BUILD_FAILED",
- "message": f"`lake build` failed: {tail}",
+ "rule": "SANDBOX_UNAVAILABLE",
+ "message": (
+ "Linux bubblewrap (`bwrap`) is unavailable; refusing to run candidate Lean on the host"
+ + (" even though unsandboxed execution was requested." if allow_unsandboxed else ".")
+ ),
})
- return LeanVerificationResult(
- passed=False,
- toolchain=toolchain,
- theorems_checked=theorem_names,
- axioms_used=(),
- nonstandard_axioms=(),
- sorry_declarations=(),
- paranoid_kernels_run=(),
- sandboxed=bwrap_available,
- findings=tuple(findings),
- caveats=tuple(caveats),
- challenge_sorry_whitelisted_module=challenge_mod or None,
- )
+ return _stopped()
- # Measure actual transitive kernel axioms and sorry dependencies on solution_module via `collectAxioms`
- measured_axioms: set[str] = set()
- sorry_decls: list[str] = []
- nonstd: list[str] = []
- lib_olean_dir = proj / ".lake" / "build" / "lib" / "lean"
- with tempfile.TemporaryDirectory(prefix="mcproof_proj_ax_") as ax_tmp_str:
- ax_tmp = Path(ax_tmp_str)
- audit_driver = ax_tmp / "McproofProjectAxiomDriver.lean"
- audit_driver.write_text(
- MODULE_AXIOM_AUDIT_TEMPLATE.format(module_name=solution_mod),
- encoding="utf-8",
- )
- ax_env = dict(env)
- lean_path_parts = [str(ax_tmp)]
- if lib_olean_dir.is_dir():
- lean_path_parts.append(str(lib_olean_dir))
- ax_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts)
- ax_run = subprocess.run(
- [lean_bin, str(audit_driver)],
- cwd=ax_tmp,
- env=ax_env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
+ _lint_project()
+ if any(finding_blocks_comparator(item) for item in findings):
+ return _stopped()
+
+ lean_bin = find_lean_tool("lean")
+ lake_bin = find_lean_tool("lake")
+ env = _lean_env()
+ trusted_files = _trusted_inputs(project_files)
+
+ def refuse_sandbox(message: str) -> LeanVerificationResult:
+ findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": message})
+ return _stopped()
+
+ build_dir = _materialize_trusted_tree(trusted_files)
+ try:
+ scrub_challenge_artifacts(build_dir, challenge_mod)
+ try:
+ build_res = run_confined_command(
+ [lake_bin, "build"],
+ cwd=build_dir,
+ env=env,
+ timeout_sec=timeout_sec,
+ )
+ except CandidateSandboxUnavailable as exc:
+ return refuse_sandbox(str(exc))
+ if build_res.returncode != 0:
+ tail = " | ".join(
+ line.strip()
+ for line in ((build_res.stdout or "") + "\n" + (build_res.stderr or "")).splitlines()[-6:]
+ if line.strip()
+ )
+ findings.append({
+ "line": 1,
+ "rule": "LAKE_BUILD_FAILED",
+ "message": f"`lake build` failed: {tail}",
+ })
+ return _stopped(sandboxed=True)
+ measured_axioms, sorry_decls, nonstd, axiom_failed = _audit_solution_axioms(
+ build_dir,
+ solution_mod=solution_mod,
+ permitted=permitted,
+ lean_bin=lean_bin,
+ env=env,
+ timeout_sec=timeout_sec,
+ findings=findings,
)
- if ax_run.returncode != 0:
- tail = " | ".join(line.strip() for line in ((ax_run.stdout or "") + "\n" + (ax_run.stderr or "")).splitlines()[-4:] if line.strip())
+ if axiom_failed is not None:
+ return refuse_sandbox(axiom_failed)
+ finally:
+ shutil.rmtree(build_dir, ignore_errors=True)
+
+ # A second copy. The build directory now holds a manifest and anything the
+ # candidate planted; the comparator must not see either.
+ comp_dir = _materialize_trusted_tree(trusted_files)
+ try:
+ # `lake comparator` will not create a manifest inside its sandbox. Resolve one
+ # from this clean tree. The candidate build's manifest stays in the other directory.
+ try:
+ update_res = run_confined_command(
+ [lake_bin, "update"],
+ cwd=comp_dir,
+ env=env,
+ timeout_sec=timeout_sec,
+ )
+ except CandidateSandboxUnavailable as exc:
+ return refuse_sandbox(str(exc))
+ if update_res.returncode != 0:
+ tail = " | ".join(
+ line.strip()
+ for line in ((update_res.stdout or "") + "\n" + (update_res.stderr or "")).splitlines()[-6:]
+ if line.strip()
+ )
findings.append({
"line": 1,
- "rule": "AXIOM_WALK_FAILED",
- "message": f"trusted collectAxioms driver failed on {solution_mod}: {tail}",
+ "rule": "LAKE_BUILD_FAILED",
+ "message": f"`lake update` failed: {tail}",
+ })
+ return _stopped(sandboxed=True)
+ try:
+ cmp_res = run_confined_command(
+ [lake_bin, "comparator", "--paranoid"],
+ cwd=comp_dir,
+ env=env,
+ timeout_sec=timeout_sec,
+ )
+ except CandidateSandboxUnavailable as exc:
+ return refuse_sandbox(str(exc))
+ kernels_accepted, solution_ok, spoof_findings = parse_comparator_stdout(cmp_res.stdout or "", solution_mod)
+ findings.extend(spoof_findings)
+
+ cmp_out = (cmp_res.stdout or "") + "\n" + (cmp_res.stderr or "")
+ if cmp_res.returncode != 0 or not solution_ok:
+ if "sorryAx" in cmp_out and "sorryAx" not in sorry_decls:
+ sorry_decls.append("sorryAx")
+ for ax_m in re.finditer(r"Illegal axiom detected:\s*'([^']+)'", cmp_out):
+ ax_name = ax_m.group(1)
+ if ax_name == "sorryAx":
+ if ax_name not in sorry_decls:
+ sorry_decls.append(ax_name)
+ else:
+ nonstd.append(ax_name)
+ tail = " | ".join(line.strip() for line in cmp_out.strip().splitlines()[-6:] if line.strip())
+ findings.append({
+ "line": 1,
+ "rule": "COMPARATOR_PARANOID_REJECT",
+ "message": f"`lake comparator --paranoid` rejected project (exit {cmp_res.returncode}): {tail}",
})
- else:
- for line in (ax_run.stdout or "").splitlines():
- if not line.startswith("MCPROOF_AUDIT\t"):
- continue
- parts = line.split("\t")
- if len(parts) != 5:
- continue
- _, kind, _, decl_name, ax_csv = parts
- axs = {a for a in ax_csv.split(",") if a}
- measured_axioms.update(axs)
- if kind in ("axiom", "opaque"):
- findings.append({
- "line": 1,
- "rule": "KERNEL_EXTRA_AXIOM_OR_OPAQUE",
- "message": f"solution module {solution_mod} contains {kind} declaration '{decl_name}'",
- })
- if "sorryAx" in axs:
- sorry_decls.append(decl_name)
- findings.append({
- "line": 1,
- "rule": "KERNEL_SORRY_AXIOM",
- "message": f"solution declaration '{decl_name}' depends on 'sorryAx'",
- })
- extra_axs = axs - (permitted & STANDARD_AXIOMS) - {"sorryAx"}
- if extra_axs:
- nonstd.extend(sorted(extra_axs))
- findings.append({
- "line": 1,
- "rule": "KERNEL_NONSTANDARD_AXIOM",
- "message": f"solution declaration '{decl_name}' uses unpermitted axioms: {sorted(extra_axs)}",
- })
-
- cmp_cmd = [lake_bin, "comparator", "--paranoid"]
- if not bwrap_available:
- cmp_cmd.append("--inadvisably-no-sandbox")
-
- cmp_res = subprocess.run(
- cmp_cmd,
- cwd=proj,
- env=env,
- capture_output=True,
- text=True,
- timeout=timeout_sec,
- check=False,
- )
- kernels_accepted, solution_ok, spoof_findings = parse_comparator_stdout(cmp_res.stdout or "", solution_mod)
- findings.extend(spoof_findings)
-
- cmp_out = (cmp_res.stdout or "") + "\n" + (cmp_res.stderr or "")
- if cmp_res.returncode != 0 or not solution_ok:
- if "sorryAx" in cmp_out and "sorryAx" not in sorry_decls:
- sorry_decls.append("sorryAx")
- for ax_m in re.finditer(r"Illegal axiom detected:\s*'([^']+)'", cmp_out):
- ax_name = ax_m.group(1)
- if ax_name == "sorryAx":
- if ax_name not in sorry_decls:
- sorry_decls.append(ax_name)
- else:
- nonstd.append(ax_name)
- tail = " | ".join(line.strip() for line in cmp_out.strip().splitlines()[-6:] if line.strip())
- findings.append({
- "line": 1,
- "rule": "COMPARATOR_PARANOID_REJECT",
- "message": f"`lake comparator --paranoid` rejected project (exit {cmp_res.returncode}): {tail}",
- })
- passed = (
- len(findings) == 0
- and cmp_res.returncode == 0
- and solution_ok
- and len(kernels_accepted) == 6
- )
- return LeanVerificationResult(
- passed=passed,
- toolchain=toolchain,
- theorems_checked=theorem_names,
- axioms_used=tuple(sorted(measured_axioms - {"sorryAx"})),
- nonstandard_axioms=tuple(sorted(set(nonstd))),
- sorry_declarations=tuple(sorted(set(sorry_decls))),
- paranoid_kernels_run=tuple(kernels_accepted),
- sandboxed=bwrap_available,
- findings=tuple(findings),
- caveats=tuple(caveats),
- challenge_sorry_whitelisted_module=challenge_mod or None,
- )
+ passed = (
+ len(findings) == 0
+ and cmp_res.returncode == 0
+ and solution_ok
+ and len(kernels_accepted) == 6
+ )
+ return LeanVerificationResult(
+ passed=passed,
+ toolchain=toolchain,
+ theorems_checked=theorem_names,
+ axioms_used=tuple(sorted(measured_axioms - {"sorryAx"})),
+ nonstandard_axioms=tuple(sorted(set(nonstd))),
+ sorry_declarations=tuple(sorted(set(sorry_decls))),
+ paranoid_kernels_run=tuple(kernels_accepted),
+ sandboxed=True,
+ findings=tuple(findings),
+ caveats=caveats,
+ challenge_sorry_whitelisted_module=challenge_mod or None,
+ )
+ finally:
+ shutil.rmtree(comp_dir, ignore_errors=True)
diff --git a/src/mcproof/repair_loop.py b/src/mcproof/repair_loop.py
index d2c52e9..4b51282 100644
--- a/src/mcproof/repair_loop.py
+++ b/src/mcproof/repair_loop.py
@@ -33,9 +33,21 @@
import urllib.request
from .lean_harness import (
+ BAR_FORBIDDEN_RULES,
THEOREM_DECL_RE,
+ CandidateSandboxUnavailable,
+ UntrustedProjectPath,
+ _lake_symlink_finding,
+ _lean_commands_that_may_run,
+ _lean_env,
+ _materialize_trusted_tree,
+ _read_project_tree,
+ _trusted_inputs,
+ linux_bwrap_functional,
+ run_confined_command,
strip_lean_comments_and_strings,
verify_lean4_against_challenge,
+ verify_lean4_project_comparator,
verify_lean4_prompt_obligations,
verify_pinned_lean_defs,
)
@@ -52,7 +64,7 @@
run_verdicts_oracle,
sanitize_verdict_id,
)
-from .paths import dep_repo, repo_root
+from .paths import dep_repo, find_lean_tool, repo_root
MAX_RETRIEVAL_TOKENS_HARD_CAP = 1500
QWEN35_STOP_TOKENS: tuple[str, ...] = ("<|im_end|>", "<|endoftext|>")
@@ -819,77 +831,531 @@ def _extract_first_json_block(text: str) -> str | None:
return blocks[0].strip() if blocks else None
-def _run_public_family_c_harness(harness: Mapping[str, Any], completion_text: str) -> list[dict[str, Any]]:
- """Post-hoc Family C ground-truth scorer matching `datasets/scripts/grade_item.py`."""
- otype = harness.get("oracle_type")
- meta = harness.get("spec_meta") or {}
+_FAMILY_C_STATUS_VERIFIED_RE = re.compile(r"(?im)^status\s*:\s*verified\b")
+_FAMILY_C_STATUS_NOT_VERIFIED_RE = re.compile(r"(?im)^status\s*:.*not verified")
+_FAMILY_C_SORRY_OR_ADMIT_RE = re.compile(r"\b(sorry|admit)\b")
+# Lean atomic names include `«quoted»` forms and non-ASCII letters such as `α` and `café`.
+_LEAN_NAME_ATOM = r"(?:«[^»]*»|_*(?:[^\W\d_])[\w!?']*)"
+_LEAN_NAME = rf"{_LEAN_NAME_ATOM}(?:\.{_LEAN_NAME_ATOM})*"
+_FAMILY_C_DECL_NAME_RE = re.compile(
+ rf"\b(?:theorem|lemma)\b[ \t]+(?P
{_LEAN_NAME})"
+)
+_FAMILY_C_OTHER_DECL_RE = re.compile(
+ rf"(?{_LEAN_NAME}))?(?=[ \t]*:)"
+ rf"|example\b(?:[ \t]+(?P{_LEAN_NAME}))?(?=[ \t]*:)"
+ rf"|abbrev\b[ \t]+(?P{_LEAN_NAME})"
+ rf")"
+)
+
+
+def _normalize_family_c_statement(text: str) -> str:
+ """Collapse whitespace so statement hashes are layout-insensitive."""
+ return re.sub(r"\s+", " ", text).strip()
+
+
+def _family_c_candidate_statements(candidate_lean: str) -> dict[str, str]:
+ """Map each fully-qualified theorem name to the sha256 of its normalized statement."""
+ cleaned = strip_lean_comments_and_strings(candidate_lean)
+ stmts: dict[str, str] = {}
+ for match in THEOREM_DECL_RE.finditer(cleaned):
+ full = str(match.group("name"))
+ stmt = _normalize_family_c_statement(f"{full} {match.group('header')}")
+ stmts[full] = hashlib.sha256(stmt.encode("utf-8")).hexdigest()
+ return stmts
+
+
+def _family_c_all_decl_names(candidate_lean: str) -> set[str]:
+ """Declaration names the line-start ASCII theorem regex does not keep.
+
+ Includes a mid-line `theorem`, a `«quoted»` or non-ASCII name, and
+ `instance`, `example`, and `abbrev`. An unnamed `example` or `instance`
+ is recorded under that keyword.
+ """
+ cleaned = strip_lean_comments_and_strings(candidate_lean)
+ names = {str(match.group("name")) for match in _FAMILY_C_DECL_NAME_RE.finditer(cleaned)}
+ for match in _FAMILY_C_OTHER_DECL_RE.finditer(cleaned):
+ if match.group(0).startswith("instance"):
+ names.add(str(match.group("inst") or "instance"))
+ elif match.group(0).startswith("example"):
+ names.add(str(match.group("ex") or "example"))
+ elif match.group("abbrev"):
+ names.add(str(match.group("abbrev")))
+ return names
+
+
+def _family_c_forbidden_eval_findings(candidate_lean: str) -> list[dict[str, Any]]:
+ """Reject every command in the `FORBIDDEN_EVAL_COMMAND` lint, including mid-line.
+
+ The scan uses that lint's own pattern on comment-stripped and string-stripped
+ source. A hit returns before `lake build`, because those commands run candidate
+ code during elaboration.
+ """
+ cleaned = strip_lean_comments_and_strings(candidate_lean)
+ rx = dict(BAR_FORBIDDEN_RULES)["FORBIDDEN_EVAL_COMMAND"]
+ found: list[str] = []
+ for match in rx.finditer(cleaned):
+ cmd = match.group(0)
+ if cmd not in found:
+ found.append(cmd)
+ if not found:
+ return []
+ return [
+ {
+ "rule": "FORBIDDEN_EVAL_COMMAND",
+ "message": (
+ "candidate contains a Lean command that runs during elaboration: "
+ + ", ".join(found)
+ + "."
+ ),
+ }
+ ]
+
+
+# `initialize` / `builtin_initialize` and the `@[init]` / `@[builtin_init]` attributes run IO
+# during `lake build`. `run_cmd`, `run_elab`, `run_tac`, and `elab` do too, before the
+# comparator's own lint. Identifier characters include `'`, `.`, and `«»`, which are not
+# `\w`, so the boundary is explicit: `elab'`, `x.elab`, and `«elab»` stay legal names.
+_FAMILY_C_NAME_EDGE = r"\w.'»«"
+_FAMILY_C_INITIALIZER_RE = re.compile(
+ rf"(? list[str]:
+ found: list[str] = []
+ for match in rx.finditer(cleaned):
+ cmd = match.group(0)
+ if cmd not in found:
+ found.append(cmd)
+ return found
+
+
+def _family_c_initializer_findings(candidate_lean: str) -> list[dict[str, Any]]:
+ """Reject initializers before `lake build`. They execute IO while the project builds."""
+ cleaned = strip_lean_comments_and_strings(candidate_lean)
+ found = _family_c_unique_matches(_FAMILY_C_INITIALIZER_RE, cleaned)
+ if not found:
+ return []
+ return [
+ {
+ "rule": "FORBIDDEN_INITIALIZER",
+ "message": (
+ "candidate contains a Lean initializer that runs during lake build: "
+ + ", ".join(found)
+ + "."
+ ),
+ }
+ ]
+
+
+def _family_c_elab_command_findings(candidate_lean: str) -> list[dict[str, Any]]:
+ """Reject elaboration commands before the first `lake build`, not only in the comparator."""
+ cleaned = strip_lean_comments_and_strings(candidate_lean)
+ found = _family_c_unique_matches(_FAMILY_C_ELAB_COMMAND_RE, cleaned)
+ if not found:
+ return []
+ return [
+ {
+ "rule": "FORBIDDEN_ELAB_COMMAND",
+ "message": (
+ "candidate contains a Lean elaboration command that runs during lake build: "
+ + ", ".join(found)
+ + "."
+ ),
+ }
+ ]
+
+
+def _family_c_build_side_effect_findings(candidate_lean: str) -> list[dict[str, Any]]:
+ """Record `attribute [init]`, `run_meta`, and `elab_rules` without skipping the build.
+
+ The sandbox is what stops the write. These findings stay on the result either way.
+ """
+ cleaned = strip_lean_comments_and_strings(candidate_lean)
+ found = _family_c_unique_matches(_FAMILY_C_BUILD_SIDE_EFFECT_RE, cleaned)
+ if not found:
+ return []
+ return [
+ {
+ "rule": "FORBIDDEN_BUILD_SIDE_EFFECT",
+ "message": (
+ "candidate contains a command that runs during compilation or import: "
+ + ", ".join(found)
+ + "."
+ ),
+ }
+ ]
+
+
+def _family_c_statement_headers(
+ meta: Mapping[str, Any], theorem_names: Sequence[str]
+) -> dict[str, str] | None:
+ """Return the pinned header of every challenge theorem, or None if any pin is missing.
+
+ A header is the text after the fully-qualified theorem name, the same span
+ `THEOREM_DECL_RE` captures. Callers hash that text. Nothing here invents `op x = x`.
+ """
+ raw = meta.get("statements")
+ if not isinstance(raw, Mapping):
+ return None
+ headers: dict[str, str] = {}
+ for name in theorem_names:
+ full = str(name)
+ header = raw.get(full)
+ if not isinstance(header, str) or not header.strip():
+ return None
+ headers[full] = header.strip()
+ return headers
+
+
+def _family_c_expected_statements(headers: Mapping[str, str]) -> dict[str, str]:
+ """Map each fully-qualified name to the sha256 of its pinned, whitespace-normalized statement."""
+ expected: dict[str, str] = {}
+ for full, header in headers.items():
+ stmt = _normalize_family_c_statement(f"{full} {header}")
+ expected[str(full)] = hashlib.sha256(stmt.encode("utf-8")).hexdigest()
+ return expected
+
+
+def _family_c_root_source(pkg: str, meta: Mapping[str, Any]) -> str:
+ """Library module for the generated project. Uses caller-supplied defs, never an identity `op`."""
+ defs = meta.get("definitions")
+ if isinstance(defs, str) and defs.strip():
+ return defs.strip() + "\n"
+ return f"namespace {pkg}\nend {pkg}\n"
+
+
+def _family_c_spec_source(pkg: str, headers: Mapping[str, str]) -> str:
+ """Challenge module: each pinned header, proved with `sorry` so the solution file is what `lake` checks."""
+ lines = [f"import {pkg}", f"namespace {pkg}.Spec"]
+ for full, header in headers.items():
+ short = str(full).split(".")[-1]
+ lines.append(f"theorem {short} {header} := by sorry")
+ lines.append(f"end {pkg}.Spec")
+ return "\n".join(lines) + "\n"
+
+
+def _family_c_lakefile(pkg: str) -> str:
+ """Build the library, the challenge, and the candidate proofs. `["{pkg}"]` alone skips the proofs."""
+ return (
+ f'name = "{pkg.lower()}"\nversion = "0.1.0"\n'
+ f'defaultTargets = ["{pkg}", "{pkg}.Spec", "{pkg}.Proofs"]\n\n'
+ f'[[lean_lib]]\nname = "{pkg}"\n\n[[lean_lib]]\nname = "{pkg}.Spec"\n\n'
+ f'[[lean_lib]]\nname = "{pkg}.Proofs"\n\n[[lean_exe]]\nname = "{pkg.lower()}"\nroot = "Main"\n'
+ )
+
+
+def _family_c_code_under_proof(pkg: str, meta: Mapping[str, Any]) -> list[str]:
+ raw = meta.get("code_under_proof")
+ if isinstance(raw, list) and raw and all(isinstance(item, str) and item.strip() for item in raw):
+ return [str(item) for item in raw]
+ return [pkg]
+
+
+def _family_c_toolchain_pin() -> str:
+ return (repo_root() / "lean" / "lean-toolchain").read_text(encoding="utf-8").strip() + "\n"
+
+
+def _check_family_c_statement_match(
+ meta: Mapping[str, Any],
+ theorem_names: Sequence[str],
+ candidate_lean: str,
+) -> list[dict[str, Any]]:
+ """Statement-match guard: names plus hashes of the pinned target statements."""
findings: list[dict[str, Any]] = []
+ headers = _family_c_statement_headers(meta, theorem_names)
+ if headers is None:
+ findings.append(
+ {
+ "rule": "FAMILY_C_TARGET_STATEMENT_ABSENT",
+ "message": (
+ "spec_meta.statements must pin the header of every theorem_names entry. "
+ "The turn does not invent an identity statement."
+ ),
+ }
+ )
+ return findings
+ cand = _family_c_candidate_statements(candidate_lean)
+ exp = _family_c_expected_statements(headers)
+ hidden = _family_c_all_decl_names(candidate_lean) - set(cand)
+ if hidden or set(cand) != set(exp):
+ findings.append(
+ {
+ "rule": "FAMILY_C_THEOREM_NAME_MISMATCH",
+ "message": (
+ "candidate theorem names do not equal challenge meta: "
+ f"missing={sorted(set(exp) - set(cand))} "
+ f"extra={sorted((set(cand) - set(exp)) | hidden)}."
+ ),
+ }
+ )
+ return findings
+ for name in sorted(exp):
+ if cand[name] != exp[name]:
+ findings.append(
+ {
+ "rule": "FAMILY_C_STATEMENT_MISMATCH",
+ "message": (
+ f"candidate statement hash for '{name}' does not equal challenge meta; "
+ "statements must match exactly."
+ ),
+ }
+ )
+ return findings
- if otype == "bar_check":
- bar_tpl = dep_repo("mission") / "bar" / "template"
- bar_chk = dep_repo("mission") / "bar" / "check.py"
- pkg = str(meta["pkg"])
- thms = list(meta["theorem_names"])
- readme_body = re.sub(r"(?im)^Claim-Tier:[^\n]*\n+", "", completion_text, count=1)
- says_verified = bool(
- re.search(r"(?im)^status\s*:\s*verified\b", readme_body)
- and not re.search(r"(?im)^status\s*:.*not verified", readme_body)
+
+def _family_c_lake_failure_message(stdout: str, stderr: str) -> str:
+ """Keep the compiler `file:line:column` lines, then the short lake tail."""
+ lines = [line.strip() for line in f"{stdout}\n{stderr}".splitlines() if line.strip()]
+ located = [line for line in lines if re.search(r"\.lean:\d+:\d+", line)]
+ tail = lines[-6:]
+ kept: list[str] = []
+ for line in located + tail:
+ if line not in kept:
+ kept.append(line)
+ return " | ".join(kept[-8:])
+
+
+def _family_c_sandbox_unavailable_finding() -> dict[str, Any]:
+ return {
+ "rule": "SANDBOX_UNAVAILABLE",
+ "message": (
+ "Linux bubblewrap (`bwrap`) is unavailable; "
+ "refusing to compile or import candidate Lean unsandboxed."
+ ),
+ }
+
+
+def _family_c_direct_lake_build(root: Path) -> list[dict[str, Any]]:
+ """Run `lake build` on candidate text inside the bubblewrap sandbox.
+
+ A missing `soko` tree must not hide a Lean error. A missing `lean`/`lake` still fails closed.
+ A missing sandbox refuses the build. There is no unsandboxed fallback.
+ """
+ lake_hit = _lake_symlink_finding(root)
+ if lake_hit is not None:
+ return [lake_hit]
+ if not linux_bwrap_functional():
+ return [_family_c_sandbox_unavailable_finding()]
+ try:
+ lake_bin = find_lean_tool("lake")
+ env = _lean_env()
+ except (OSError, RuntimeError) as exc:
+ return [
+ {
+ "rule": "FAMILY_C_LEAN_TOOLCHAIN_UNAVAILABLE",
+ "message": f"Lean toolchain unavailable; turn fails closed: {exc}",
+ }
+ ]
+ try:
+ build_res = run_confined_command(
+ [lake_bin, "build"],
+ cwd=root,
+ env=env,
+ timeout_sec=300,
+ )
+ except CandidateSandboxUnavailable:
+ return [_family_c_sandbox_unavailable_finding()]
+ if build_res.returncode != 0:
+ return [
+ {
+ "rule": "LAKE_BUILD_FAILED",
+ "message": f"`lake build` failed: {_family_c_lake_failure_message(build_res.stdout or '', build_res.stderr or '')}",
+ }
+ ]
+ return []
+
+
+def _lean_exception_is_missing_toolchain(exc: BaseException) -> bool:
+ message = str(exc)
+ return "Lean tool" in message or "elan bin" in message
+
+
+def _run_family_c_real_lean_turn(harness: Mapping[str, Any], completion_text: str) -> list[dict[str, Any]]:
+ """Real-Lean Family C turn for `oracle_type: bar_check` only.
+
+ `bar_status` comes from harness meta. The challenge statements come from
+ `spec_meta.statements`. The solution file is the candidate's fenced lean.
+ `verdict_audit` items never enter this function. `lake build` still runs when
+ the mission template or the soko auditor checkout is absent. It does not run
+ when `lean` and `lake` themselves are absent.
+ """
+ meta = harness.get("spec_meta") or {}
+ pkg = str(meta.get("pkg", "")).strip()
+ thms = [str(t) for t in (meta.get("theorem_names") or [])]
+ # Bar status comes from harness meta exclusively; candidate prose can never promote it.
+ bar_status = str(meta.get("bar_status", "")).strip()
+ if not pkg or not thms:
+ return [
+ {
+ "rule": "FAMILY_C_MALFORMED_HARNESS",
+ "message": "harness spec_meta must define pkg and theorem_names.",
+ }
+ ]
+ findings: list[dict[str, Any]] = []
+ readme_body = re.sub(r"(?im)^Claim-Tier:[^\n]*\n+", "", completion_text, count=1)
+ if (
+ _FAMILY_C_STATUS_VERIFIED_RE.search(readme_body)
+ and not _FAMILY_C_STATUS_NOT_VERIFIED_RE.search(readme_body)
+ and bar_status.lower() != "verified"
+ ):
+ findings.append(
+ {
+ "rule": "FAMILY_C_STATUS_SELF_ATTESTATION",
+ "message": (
+ f"candidate declares 'Status: verified' but harness meta bar_status is {bar_status!r}; "
+ "bar status comes from harness meta exclusively."
+ ),
+ }
)
- bar_status = "verified" if says_verified else str(meta["bar_status"])
- with tempfile.TemporaryDirectory(prefix="mcproof_rep_bar_") as td:
- root = Path(td)
- shutil.copytree(bar_tpl, root, dirs_exist_ok=True)
+ lean_blocks = extract_fenced_blocks(completion_text, ("lean", "lean4"))
+ candidate_lean = "\n\n".join(block.strip() for block in lean_blocks if block.strip())
+ if not candidate_lean:
+ findings.append(
+ {
+ "rule": "FAMILY_C_MISSING_CANDIDATE_LEAN",
+ "message": "no ```lean code blocks found; the checked project is built from the candidate's lean blocks.",
+ }
+ )
+ return findings
+ if _FAMILY_C_SORRY_OR_ADMIT_RE.search(strip_lean_comments_and_strings(candidate_lean)):
+ findings.append(
+ {
+ "rule": "FAMILY_C_SOLUTION_USES_SORRY_OR_ADMIT",
+ "message": "solution module uses 'sorry' or 'admit'; the turn fails.",
+ }
+ )
+ findings.extend(_family_c_forbidden_eval_findings(candidate_lean))
+ findings.extend(_family_c_initializer_findings(candidate_lean))
+ findings.extend(_family_c_elab_command_findings(candidate_lean))
+ for cmd in _lean_commands_that_may_run(candidate_lean):
+ if any(cmd in str(item.get("message", "")) for item in findings):
+ continue
+ if cmd.startswith("#"):
+ findings.append({
+ "rule": "FORBIDDEN_EVAL_COMMAND",
+ "message": "candidate contains a Lean command that runs during elaboration: " + cmd + ".",
+ })
+ else:
+ findings.append({
+ "rule": "FORBIDDEN_ELAB_COMMAND",
+ "message": "candidate contains a Lean elaboration command that runs during lake build: " + cmd + ".",
+ })
+ findings.extend(_check_family_c_statement_match(meta, thms, candidate_lean))
+ if findings:
+ return findings
+ headers = _family_c_statement_headers(meta, thms)
+ if headers is None:
+ return [
+ {
+ "rule": "FAMILY_C_TARGET_STATEMENT_ABSENT",
+ "message": (
+ "spec_meta.statements must pin the header of every theorem_names entry. "
+ "The turn does not invent an identity statement."
+ ),
+ }
+ ]
+ mission_bar: tuple[Path, Path] | None = None
+ try:
+ mission = dep_repo("mission")
+ except FileNotFoundError as exc:
+ findings.append(
+ {
+ "rule": "FAMILY_C_MISSION_BAR_UNAVAILABLE",
+ "message": (
+ "mission bar template is unavailable, so the structural bar replay was not run. "
+ f"{exc}"
+ ),
+ }
+ )
+ else:
+ bar_tpl = mission / "bar" / "template"
+ bar_chk = mission / "bar" / "check.py"
+ if bar_tpl.is_dir() and bar_chk.is_file():
+ mission_bar = (bar_tpl, bar_chk)
+ else:
+ findings.append(
+ {
+ "rule": "FAMILY_C_MISSION_BAR_UNAVAILABLE",
+ "message": f"mission checkout at {mission} has no bar/template or bar/check.py.",
+ }
+ )
+ code_toml = ", ".join(json.dumps(name) for name in _family_c_code_under_proof(pkg, meta))
+ test_cmd = str(meta.get("test_cmd") or "python3 tests/run_tests.py")
+ with tempfile.TemporaryDirectory(prefix="mcproof_rep_bar_") as td:
+ root = Path(td)
+ if mission_bar is not None:
+ shutil.copytree(mission_bar[0], root, dirs_exist_ok=True)
(root / "Clamp.lean").unlink(missing_ok=True)
shutil.rmtree(root / "Clamp", ignore_errors=True)
- (root / f"{pkg}.lean").write_text(
- f"namespace {pkg}\ndef op (x : Nat) : Nat := x\nend {pkg}\n",
- encoding="utf-8",
- )
- (root / pkg).mkdir(exist_ok=True)
- spec_lines = [f"import {pkg}", f"namespace {pkg}.Spec"]
- proof_lines = [f"import {pkg}", f"namespace {pkg}.Spec"]
- for tfull in thms:
- tshort = str(tfull).split(".")[-1]
- spec_lines.append(f"theorem {tshort} (x : Nat) : {pkg}.op x = x := by sorry")
- proof_lines.append(f"theorem {tshort} (x : Nat) : {pkg}.op x = x := rfl")
- spec_lines.append(f"end {pkg}.Spec\n")
- proof_lines.append(f"end {pkg}.Spec\n")
- (root / pkg / "Spec.lean").write_text("\n".join(spec_lines), encoding="utf-8")
- (root / pkg / "Proofs.lean").write_text("\n".join(proof_lines), encoding="utf-8")
- (root / "Main.lean").write_text(
- f'import {pkg}\ndef main : IO Unit := IO.println s!"{{{pkg}.op 1}}"\n',
- encoding="utf-8",
- )
- (root / "lakefile.toml").write_text(
- f'name = "{pkg.lower()}"\nversion = "0.1.0"\ndefaultTargets = ["{pkg}"]\n\n'
- f'[[lean_lib]]\nname = "{pkg}"\n\n[[lean_lib]]\nname = "{pkg}.Spec"\n\n'
- f'[[lean_lib]]\nname = "{pkg}.Proofs"\n\n[[lean_exe]]\nname = "{pkg.lower()}"\nroot = "Main"\n',
- encoding="utf-8",
- )
- (root / "comparator.json").write_text(
- json.dumps(
- {
- "challenge_module": f"{pkg}.Spec",
- "solution_module": f"{pkg}.Proofs",
- "theorem_names": thms,
- "permitted_axioms": ["propext", "Quot.sound", "Classical.choice"],
- },
- indent=2,
- )
- + "\n",
- encoding="utf-8",
+ # Keep lake-manifest.json. bar/check.py item 3 fails closed when it is
+ # absent, including under --no-lean, so deleting it rejects a correct proof.
+ else:
+ (root / "lean-toolchain").write_text(_family_c_toolchain_pin(), encoding="utf-8")
+ (root / f"{pkg}.lean").write_text(_family_c_root_source(pkg, meta), encoding="utf-8")
+ (root / pkg).mkdir(exist_ok=True)
+ (root / pkg / "Spec.lean").write_text(_family_c_spec_source(pkg, headers), encoding="utf-8")
+ # Solution module is the candidate's lean blocks verbatim. Theorems must use
+ # the fully-qualified challenge name (for example `theorem CrtPair.Spec.crt_mod_left ...`).
+ proofs_path = root / pkg / "Proofs.lean"
+ proofs_text = f"import {pkg}\n\n{candidate_lean}\n"
+ proofs_path.write_text(proofs_text, encoding="utf-8")
+ (root / "Main.lean").write_text(
+ f'import {pkg}\ndef main : IO Unit := IO.println "ok"\n',
+ encoding="utf-8",
+ )
+ (root / "lakefile.toml").write_text(_family_c_lakefile(pkg), encoding="utf-8")
+ comparator_path = root / "comparator.json"
+ comparator_text = (
+ json.dumps(
+ {
+ "challenge_module": f"{pkg}.Spec",
+ "solution_module": f"{pkg}.Proofs",
+ "theorem_names": thms,
+ "permitted_axioms": ["propext", "Quot.sound", "Classical.choice"],
+ },
+ indent=2,
)
+ + "\n"
+ )
+ comparator_path.write_text(comparator_text, encoding="utf-8")
+ if mission_bar is not None:
(root / "bar.toml").write_text(
f'[project]\nname = "{pkg.lower()}"\nstatus = "{bar_status}"\npage = "README.md"\n'
f'spec_authors = ["example-author"]\nentry_points = ["Main.lean"]\n\n'
- f'[spec]\nfiles = ["SPEC.md", "{pkg}/Spec.lean"]\ncode = ["{pkg}.op"]\n\n'
- f'[tests]\nresults = "tests/TEST-RESULTS.md"\ncommand = "{meta["test_cmd"]}"\nfiles = ["tests/run_tests.py"]\n',
+ f'[spec]\nfiles = ["SPEC.md", "{pkg}/Spec.lean"]\ncode = [{code_toml}]\n\n'
+ f'[tests]\nresults = "tests/TEST-RESULTS.md"\ncommand = "{test_cmd}"\nfiles = ["tests/run_tests.py"]\n',
encoding="utf-8",
)
(root / "README.md").write_text(readme_body, encoding="utf-8")
out_json = root / "bar_out.json"
proc = subprocess.run(
- [sys.executable, "-O", "-B", "-W", "error", str(bar_chk), str(root), "--no-lean", "--offline", "--json", str(out_json)],
+ [
+ sys.executable,
+ "-O",
+ "-B",
+ "-W",
+ "error",
+ str(mission_bar[1]),
+ str(root),
+ "--no-lean",
+ "--offline",
+ "--json",
+ str(out_json),
+ ],
capture_output=True,
text=True,
check=False,
@@ -902,7 +1368,79 @@ def _run_public_family_c_harness(harness: Mapping[str, Any], completion_text: st
for req_i in (2, 4, 5, 6):
if by_item.get(req_i) != "PASS":
findings.append({"rule": "BAR_CHECK_ITEM_FAIL", "message": f"bar item {req_i} did not pass"})
- return findings
+ # `lake build` is the formal signal. Its message keeps `.lean:line:column` lines.
+ # The comparator's own tail keeps only the last 6 lines, which can drop that error.
+ # Kernel checks run only after this build succeeds, and they run on a fresh
+ # copy of the files taken before the build. The candidate tree is not written again.
+ lake_hit = _lake_symlink_finding(root)
+ if lake_hit is not None:
+ findings.append(lake_hit)
+ return findings
+ try:
+ trusted_inputs = _trusted_inputs(_read_project_tree(root))
+ except UntrustedProjectPath as exc:
+ findings.append({"rule": exc.rule, "message": str(exc)})
+ return findings
+ findings.extend(_family_c_build_side_effect_findings(candidate_lean))
+ findings.extend(_family_c_direct_lake_build(root))
+ if any(
+ f.get("rule")
+ in {
+ "LAKE_BUILD_FAILED",
+ "FAMILY_C_LEAN_TOOLCHAIN_UNAVAILABLE",
+ "SANDBOX_UNAVAILABLE",
+ "LAKE_CACHE_SYMLINK",
+ "UNTRUSTED_PROJECT_SYMLINK",
+ "UNTRUSTED_PROJECT_FILE",
+ "NOFOLLOW_OPEN_UNAVAILABLE",
+ }
+ for f in findings
+ ):
+ return findings
+ fresh = _materialize_trusted_tree(trusted_inputs)
+ try:
+ try:
+ lean_res = verify_lean4_project_comparator(fresh, allow_unsandboxed=False)
+ except FileNotFoundError as exc:
+ if _lean_exception_is_missing_toolchain(exc):
+ findings.append(
+ {
+ "rule": "FAMILY_C_LEAN_TOOLCHAIN_UNAVAILABLE",
+ "message": f"Lean toolchain unavailable; turn fails closed: {exc}",
+ }
+ )
+ return findings
+ findings.append(
+ {
+ "rule": "FAMILY_C_LEAN_AUDIT_DEPS_UNAVAILABLE",
+ "message": f"lake build passed, but the comparator auditor checkout is missing: {exc}",
+ }
+ )
+ return findings
+ except (OSError, RuntimeError) as exc:
+ findings.append(
+ {
+ "rule": "FAMILY_C_LEAN_TOOLCHAIN_UNAVAILABLE",
+ "message": f"Lean toolchain unavailable; turn fails closed: {exc}",
+ }
+ )
+ return findings
+ for finding in lean_res.findings:
+ findings.append(dict(finding))
+ finally:
+ shutil.rmtree(fresh, ignore_errors=True)
+ return findings
+
+
+def _run_public_family_c_harness(harness: Mapping[str, Any], completion_text: str) -> list[dict[str, Any]]:
+ """Post-hoc Family C ground-truth scorer matching `datasets/scripts/grade_item.py`."""
+ otype = harness.get("oracle_type")
+
+ if otype == "bar_check":
+ return _run_family_c_real_lean_turn(harness, completion_text)
+
+ meta = harness.get("spec_meta") or {}
+ findings: list[dict[str, Any]] = []
if otype == "verdict_audit":
jb = _extract_first_json_block(completion_text)
@@ -1101,6 +1639,8 @@ def run_repair_item(
datasets_root: Path | None = None,
spec_path: Path | None = None,
include_plane1_retrieval: bool = True,
+ allow_early_stop: bool = True,
+ forbid_subtier_early_stop: bool = False,
) -> dict[str, Any]:
"""Execute bounded `k`-turn label-free inference repair + post-hoc benchmark scoring on one item.
@@ -1135,6 +1675,9 @@ def run_repair_item(
turn_records: list[dict[str, Any]] = []
eval_pass_by_turn: dict[int, bool] = {}
+ best_oracle_turn_by_k: dict[int, int | None] = {}
+ best_oracle_rank = 0
+ best_oracle_turn: int | None = None
total_prompt_tokens = 0
total_completion_tokens = 0
total_retrieved_tokens = 0
@@ -1219,10 +1762,24 @@ def run_repair_item(
total_retrieved_tokens += ret_toks
total_elapsed_ms += gen_ms + inf_ms
+ # Stopping rule depends ONLY on label-free `inf_passed` & fail-closed allowlist (Issue #12)!
+ inf_status = str(inf_res.get("epistemic_status", "")).strip().upper()
+ subtier_blocked = forbid_subtier_early_stop and inf_status not in ("VERIFIED", "PROVEN")
+ early_stop_blocked = inf_passed and (not allow_early_stop or subtier_blocked)
+
+ # Label-free candidate retention: never silently drop an oracle-passing turn when early stop is blocked.
+ turn_rank = 2 if (inf_passed and inf_status in ("VERIFIED", "PROVEN")) else (1 if inf_passed else 0)
+ if turn_rank > best_oracle_rank:
+ best_oracle_rank = turn_rank
+ best_oracle_turn = turn_idx
+ best_oracle_turn_by_k[turn_idx] = best_oracle_turn
+
turn_records.append(
{
"turn": turn_idx,
"inference_passed": inf_passed,
+ "inference_epistemic_status": inf_status,
+ "early_stop_blocked": early_stop_blocked,
"eval_passed": eval_passed,
"passed": eval_passed,
"stagnation_prompt_mode": stagnation_next,
@@ -1242,20 +1799,20 @@ def run_repair_item(
}
)
- # Stopping rule depends ONLY on label-free `inf_passed`!
- if inf_passed:
+ if inf_passed and allow_early_stop and not subtier_blocked:
inference_certified_at_turn = turn_idx
deployed_eval_passed_when_certified = eval_passed
break
- primary_rule = sanitized[0]["rule"] if sanitized else "ORACLE_REJECTED"
- refuted_routes.append(
- {
- "turn": turn_idx,
- "state_hash": state_hash[:12],
- "primary_rule": primary_rule,
- }
- )
+ if not inf_passed:
+ primary_rule = sanitized[0]["rule"] if sanitized else "ORACLE_REJECTED"
+ refuted_routes.append(
+ {
+ "turn": turn_idx,
+ "state_hash": state_hash[:12],
+ "primary_rule": primary_rule,
+ }
+ )
prior_completion = comp_text
prior_inf_findings = inf_findings
prior_sanitized = sanitized
@@ -1263,14 +1820,19 @@ def run_repair_item(
# Deployed output at budget k (1..max_turns):
# - If inference oracle certified at turn t <= k, the deployed output at budget k is turn t's output!
- # - Otherwise the loop ran through turn k, so the deployed output at budget k is turn k's output.
+ # - Else if an earlier turn passed the inference oracle (e.g. early stop blocked), deploy the earliest
+ # highest-tier oracle-passing turn up through k (strictly label-free; never drops a passing turn).
+ # - Otherwise the loop ran through turn k with no oracle pass, so deploy turn k's output.
pass_by_k: dict[str, bool] = {}
first_eval_pass_turn: int | None = None
for k in range(1, max_turns + 1):
+ capped_k = min(k, len(turn_records))
if inference_certified_at_turn is not None and inference_certified_at_turn <= k:
deployed_ok = bool(deployed_eval_passed_when_certified)
+ elif best_oracle_turn_by_k.get(capped_k) is not None:
+ deployed_ok = bool(eval_pass_by_turn.get(int(best_oracle_turn_by_k[capped_k]), False))
else:
- deployed_ok = bool(eval_pass_by_turn.get(min(k, len(turn_records)), False))
+ deployed_ok = bool(eval_pass_by_turn.get(capped_k, False))
pass_by_k[f"pass_at_{k}"] = deployed_ok
if deployed_ok and first_eval_pass_turn is None:
first_eval_pass_turn = k
@@ -1281,9 +1843,12 @@ def run_repair_item(
"family": fam,
"max_turns": max_turns,
"label_free_inference_stopping": True,
+ "allow_early_stop": allow_early_stop,
+ "forbid_subtier_early_stop": forbid_subtier_early_stop,
"passed": final_deployed_passed,
"inference_certified": inference_certified_at_turn is not None,
"inference_certified_at_turn": inference_certified_at_turn,
+ "best_oracle_pass_turn": best_oracle_turn,
"solved_at_turn": first_eval_pass_turn,
"turns_used": len(turn_records),
"oracle_calls": len(turn_records),
@@ -1299,6 +1864,31 @@ def run_repair_item(
}
+def _checkpoint_record_valid(
+ rec: Mapping[str, Any],
+ *,
+ max_turns: int,
+ allow_early_stop: bool,
+ forbid_subtier_early_stop: bool,
+) -> bool:
+ """Return True iff a cached checkpoint record satisfies the active stopping policy and turn budget."""
+ cached_turns = int(rec.get("turns_used", 0))
+ cached_max_turns = int(rec.get("max_turns", max_turns))
+ if cached_turns > max_turns or cached_max_turns != max_turns:
+ return False
+ if not allow_early_stop and (
+ cached_turns < max_turns
+ or bool(rec.get("inference_certified", False))
+ or rec.get("allow_early_stop") is True
+ ):
+ return False
+ if forbid_subtier_early_stop and rec.get("forbid_subtier_early_stop") is not True and (
+ cached_turns < max_turns or bool(rec.get("inference_certified", False))
+ ):
+ return False
+ return True
+
+
def run_repair_split(
items: Sequence[Mapping[str, Any]],
generator_fn: Callable[[str, int], dict[str, Any] | str],
@@ -1312,8 +1902,26 @@ def run_repair_split(
spec_path: Path | None = None,
include_plane1_retrieval: bool = True,
checkpoint_jsonl: Path | None = None,
+ early_stop_disabled_families: frozenset[str] = frozenset(),
+ forbid_subtier_early_stop: bool = False,
+ oracle_version: str = "mcproof-inference-oracle/v0.2",
+ max_early_stop_false_pass_rate: Fraction = Fraction(1, 20),
+ min_early_stop_oracle_passes: int = 1,
+ prior_gap_summary: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
"""Run bounded label-free closed-loop repair across a dataset split with crash-safe checkpointing."""
+ disabled_set = {str(f).strip().upper() for f in early_stop_disabled_families}
+ if prior_gap_summary is not None:
+ prior_elig = evaluate_early_stop_eligibility(
+ prior_gap_summary,
+ max_false_pass_rate=max_early_stop_false_pass_rate,
+ min_oracle_passes=min_early_stop_oracle_passes,
+ )
+ for fam_key, gate in prior_elig.items():
+ if not gate["allow_early_stop"]:
+ disabled_set.add(str(fam_key).strip().upper())
+ disabled_norm = frozenset(disabled_set)
+
completed_by_id: dict[str, dict[str, Any]] = {}
if checkpoint_jsonl is not None and checkpoint_jsonl.is_file():
for ln in checkpoint_jsonl.read_text(encoding="utf-8").splitlines():
@@ -1324,7 +1932,14 @@ def run_repair_split(
results: list[dict[str, Any]] = []
for item in items:
iid = str(item["id"])
- if iid in completed_by_id:
+ fam_norm = str(item["family"]).strip().upper()
+ item_allow_early_stop = fam_norm not in disabled_norm
+ if iid in completed_by_id and _checkpoint_record_valid(
+ completed_by_id[iid],
+ max_turns=max_turns,
+ allow_early_stop=item_allow_early_stop,
+ forbid_subtier_early_stop=forbid_subtier_early_stop,
+ ):
results.append(completed_by_id[iid])
continue
res = run_repair_item(
@@ -1338,6 +1953,8 @@ def run_repair_split(
datasets_root=datasets_root,
spec_path=spec_path,
include_plane1_retrieval=include_plane1_retrieval,
+ allow_early_stop=item_allow_early_stop,
+ forbid_subtier_early_stop=forbid_subtier_early_stop,
)
results.append(res)
if checkpoint_jsonl is not None:
@@ -1369,15 +1986,25 @@ def run_repair_split(
for k in range(1, max_turns + 1)
}
+ oracle_grader_gap = summarize_oracle_grader_gap(results, oracle_version=oracle_version)
+ early_stop_eligibility = evaluate_early_stop_eligibility(
+ oracle_grader_gap,
+ max_false_pass_rate=max_early_stop_false_pass_rate,
+ min_oracle_passes=min_early_stop_oracle_passes,
+ )
return {
"schema": "mcproof-repair-loop-receipt/v0.2",
"label_free_inference_stopping": True,
+ "early_stop_disabled_families": sorted(disabled_norm),
+ "forbid_subtier_early_stop": forbid_subtier_early_stop,
"max_turns": max_turns,
"retrieval_max_tokens": retrieval_max_tokens,
"include_plane1_retrieval": include_plane1_retrieval,
"total_items": n_total,
"pass_curve": pass_curve,
"by_family": by_family,
+ "oracle_grader_gap": oracle_grader_gap,
+ "early_stop_eligibility": early_stop_eligibility,
"budget_totals": {
"replies_used": sum(int(r["turns_used"]) for r in results),
"oracle_calls": sum(int(r["oracle_calls"]) for r in results),
@@ -1394,3 +2021,136 @@ def run_repair_split(
},
"items": results,
}
+
+
+def _item_oracle_pass_outcome(row: Mapping[str, Any]) -> tuple[bool, bool]:
+ """Return `(had_oracle_pass, oracle_false_pass)` from turn records (falling back to `inference_certified`)."""
+ turns = row.get("turns")
+ if isinstance(turns, list) and len(turns) > 0:
+ first_o = next((t for t in turns if isinstance(t, Mapping) and bool(t.get("inference_passed", False))), None)
+ had_oracle_pass = (first_o is not None) or bool(row.get("inference_certified", False))
+ if not had_oracle_pass:
+ return False, False
+ if first_o is not None:
+ first_eval_ok = bool(first_o.get("eval_passed", first_o.get("passed", False)))
+ return True, (not first_eval_ok) or (not bool(row.get("passed", False)))
+ return True, not bool(row.get("passed", False))
+ had_oracle_pass = bool(row.get("inference_certified", False))
+ return had_oracle_pass, had_oracle_pass and not bool(row.get("passed", False))
+
+
+def summarize_oracle_grader_gap(
+ results: Sequence[Mapping[str, Any]],
+ *,
+ oracle_version: str = "mcproof-inference-oracle/v0.2",
+) -> dict[str, Any]:
+ """Post-hoc grader-side accounting of oracle-pass vs grader-reject gaps (Issue #12).
+
+ Computed strictly after the repair run so no ground-truth label reaches the loop.
+ Counts oracle passes from per-turn `inference_passed` when turn records exist (so
+ early-stop-disabled and subtier-blocked families still report their real gap) and
+ falls back to `inference_certified` for compact receipts without `turns`.
+ Uses exact integers and rational strings (zero floats on decision paths).
+ """
+ by_family: dict[str, dict[str, Any]] = {}
+ tot_oracle = 0
+ tot_false = 0
+ tot_grader_pass = 0
+ tot_grader_without_oracle = 0
+ tot_turn1_false = 0
+ for fam in ("A", "B", "C", "D"):
+ rows = [r for r in results if str(r.get("family", "")).strip().upper() == fam]
+ if not rows:
+ continue
+ o_pass = 0
+ g_rej_among_o = 0
+ g_pass = 0
+ g_without_o = 0
+ t1_false = 0
+ for r in rows:
+ had_o, false_o = _item_oracle_pass_outcome(r)
+ passed_ok = bool(r.get("passed", False))
+ if had_o:
+ o_pass += 1
+ if false_o:
+ g_rej_among_o += 1
+ elif passed_ok:
+ g_without_o += 1
+ if passed_ok:
+ g_pass += 1
+ if bool(r.get("inference_certified", False)) and not passed_ok and r.get("turns_used") == 1:
+ t1_false += 1
+ rate = Fraction(g_rej_among_o, o_pass) if o_pass > 0 else None
+ by_family[fam] = {
+ "items": len(rows),
+ "oracle_passes": o_pass,
+ "grader_rejects_among_oracle_passes": g_rej_among_o,
+ "grader_passes": g_pass,
+ "grader_without_oracle_passes": g_without_o,
+ "premature_turn1_stops": t1_false,
+ "false_pass_rate_frac": None if rate is None else f"{rate.numerator}/{rate.denominator}",
+ }
+ tot_oracle += o_pass
+ tot_false += g_rej_among_o
+ tot_grader_pass += g_pass
+ tot_grader_without_oracle += g_without_o
+ tot_turn1_false += t1_false
+
+ tot_rate = Fraction(tot_false, tot_oracle) if tot_oracle > 0 else None
+ return {
+ "oracle_version": oracle_version,
+ "by_family": by_family,
+ "totals": {
+ "items": len(results),
+ "oracle_passes": tot_oracle,
+ "grader_rejects_among_oracle_passes": tot_false,
+ "grader_passes": tot_grader_pass,
+ "grader_without_oracle_passes": tot_grader_without_oracle,
+ "premature_turn1_stops": tot_turn1_false,
+ "false_pass_rate_frac": None if tot_rate is None else f"{tot_rate.numerator}/{tot_rate.denominator}",
+ },
+ }
+
+
+def evaluate_early_stop_eligibility(
+ gap_summary: Mapping[str, Any],
+ *,
+ max_false_pass_rate: Fraction = Fraction(1, 20),
+ min_oracle_passes: int = 1,
+) -> dict[str, dict[str, Any]]:
+ """Fail-closed per-family early-stopping eligibility gate (Issue #12 Proposal #2/#3)."""
+ if not isinstance(gap_summary, Mapping):
+ raise ValueError("gap_summary must be a mapping")
+ if not isinstance(max_false_pass_rate, Fraction) or max_false_pass_rate < 0 or max_false_pass_rate > 1:
+ raise ValueError("max_false_pass_rate must be a Fraction in [0, 1]")
+ if type(min_oracle_passes) is not int or min_oracle_passes < 1:
+ raise ValueError("min_oracle_passes must be an int >= 1")
+ by_fam = gap_summary.get("by_family")
+ if not isinstance(by_fam, Mapping):
+ raise ValueError("gap_summary.by_family must be a mapping")
+ out: dict[str, dict[str, Any]] = {}
+ for fam, stats in by_fam.items():
+ if not isinstance(stats, Mapping):
+ raise ValueError(f"by_family[{fam!r}] must be a mapping")
+ o_pass = stats.get("oracle_passes")
+ g_rej = stats.get("grader_rejects_among_oracle_passes")
+ if type(o_pass) is not int or type(g_rej) is not int:
+ raise ValueError(f"by_family[{fam!r}] counts must be exact int (bool/float/str forbidden)")
+ if o_pass < 0 or g_rej < 0 or g_rej > o_pass:
+ raise ValueError(f"by_family[{fam!r}] must satisfy 0 <= grader_rejects <= oracle_passes")
+ if o_pass < min_oracle_passes:
+ out[fam] = {
+ "allow_early_stop": False,
+ "allow_calibration_filter": False,
+ "reason": "UNMEASURED_OR_UNDERPOWERED_ORACLE_GAP",
+ }
+ continue
+ rate = Fraction(g_rej, o_pass)
+ ok = rate <= max_false_pass_rate
+ out[fam] = {
+ "allow_early_stop": ok,
+ "allow_calibration_filter": ok,
+ "false_pass_rate_frac": f"{rate.numerator}/{rate.denominator}",
+ "reason": "ELIGIBLE" if ok else "ORACLE_GAP_EXCEEDS_THRESHOLD",
+ }
+ return out
diff --git a/tests/test_audit_rule_coverage.py b/tests/test_audit_rule_coverage.py
new file mode 100644
index 0000000..e758ddb
--- /dev/null
+++ b/tests/test_audit_rule_coverage.py
@@ -0,0 +1,88 @@
+"""Each certificate rule below must have a test that turns red when the rule is removed.
+
+Deleting the check for one of these four rules used to leave every test green.
+Each case adds one corruption to a minimal VERIFIED certificate with good pins
+and digest. The corruption fires that rule and no other, and the matching good
+certificate passes, so a test cannot go green by rejecting for a different reason.
+"""
+
+from __future__ import annotations
+
+from mcproof.domain_protocol import audit_transition_certificate
+
+from helpers import expect_eq, expect_false, expect_true
+
+HEX64 = "a" * 64
+OTHER_HEX64 = "b" * 64
+
+
+def _minimal_verified(**extra: object) -> dict:
+ cert: dict = {
+ "epistemic_status": "VERIFIED",
+ "witness_or_proof_sha256": HEX64,
+ "tcb_pins": {"tcb_manifest_verified": True, "checker_sha256": HEX64},
+ }
+ cert.update(extra)
+ return cert
+
+
+def _expect_only_rule(cert: dict, rule: str) -> None:
+ result = audit_transition_certificate(cert)
+ expect_false(result["passed"], f"{rule}: corrupted certificate was accepted: {result}")
+ expect_eq(result["epistemic_status"], "REJECTED")
+ expect_eq([f["rule"] for f in result["findings"]], [rule], "the corruption must fire this rule alone")
+
+
+def _expect_accepted(cert: dict) -> None:
+ result = audit_transition_certificate(cert)
+ expect_true(result["passed"], f"good certificate was rejected: {result}")
+ expect_eq(result["epistemic_status"], "VERIFIED")
+
+
+def _control(*, passed: bool) -> dict:
+ return _minimal_verified(
+ must_fail_controls=["c1"],
+ control_records=[{"name": "c1", "oracle_invoked": True, "unexpectedly_passed": passed}],
+ )
+
+
+def test_a6_control_that_unexpectedly_passed_is_rejected() -> None:
+ _expect_accepted(_control(passed=False))
+ _expect_only_rule(_control(passed=True), "CERT_A6_CONTROL_PASSED")
+
+
+def _floor(*, floor: int, bound: int, moves: int) -> dict:
+ return _minimal_verified(
+ proven_floor=floor,
+ max_bound=bound,
+ witness="U" * moves,
+ exact_optimum_reached=True,
+ )
+
+
+def test_floor_above_the_search_bound_is_rejected() -> None:
+ _expect_accepted(_floor(floor=10, bound=10, moves=10))
+ _expect_only_rule(_floor(floor=12, bound=10, moves=12), "CERT_FLOOR_EXCEEDS_MAX_BOUND")
+
+
+def test_instance_digest_that_differs_from_the_canonical_one_is_rejected() -> None:
+ _expect_accepted(_minimal_verified(instance_sha256=HEX64, canonical_instance_sha256=HEX64))
+ _expect_only_rule(
+ _minimal_verified(instance_sha256=HEX64, canonical_instance_sha256=OTHER_HEX64),
+ "CERT_INSTANCE_DIGEST_MISMATCH",
+ )
+
+
+def test_witness_cost_that_differs_from_the_claimed_floor_is_rejected() -> None:
+ _expect_accepted(_floor(floor=12, bound=12, moves=12))
+ _expect_only_rule(_floor(floor=12, bound=12, moves=11), "CERT_WITNESS_FLOOR_MISMATCH")
+
+
+def test_rejected_witness_cannot_carry_verified() -> None:
+ _expect_accepted(_minimal_verified(valid_winning_witness=True))
+ _expect_only_rule(_minimal_verified(valid_winning_witness=False), "CERT_A7_ILLEGAL_TIER_SWAP")
+ _expect_only_rule(_minimal_verified(valid_winning_route=False), "CERT_A7_ILLEGAL_TIER_SWAP")
+
+
+def test_empty_must_fail_controls_list_is_rejected() -> None:
+ _expect_only_rule(_minimal_verified(must_fail_controls=[]), "CERT_A6_MISSING_OR_DUPLICATE_CONTROLS")
diff --git a/tests/test_audit_type_confusion.py b/tests/test_audit_type_confusion.py
new file mode 100644
index 0000000..876ab8a
--- /dev/null
+++ b/tests/test_audit_type_confusion.py
@@ -0,0 +1,172 @@
+"""The auditor must check the type of a red-flag field before it compares the value.
+
+A flag written as the string "false" or as 0, a negative or fractional count, or a
+witness key left out used to come back VERIFIED. Each case pairs a control (the red
+flag in its usual form, which was already rejected) with a variant (which was not).
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import sys
+from typing import Any
+
+import pytest
+
+from mcproof.cli import main as cli_main
+from mcproof.domain_protocol import audit_transition_certificate
+
+from helpers import expect_eq, expect_false, expect_in, expect_true
+
+HEX64 = "a" * 64
+TYPE_RULE = "CERT_FIELD_TYPE_INVALID"
+
+
+def _verified(**extra: Any) -> dict:
+ cert: dict = {
+ "epistemic_status": "VERIFIED",
+ "witness_or_proof_sha256": HEX64,
+ "tcb_pins": {"tcb_manifest_verified": True, "checker_sha256": HEX64},
+ }
+ cert.update(extra)
+ return cert
+
+
+def _rules(cert: Any) -> list[str]:
+ return [f["rule"] for f in audit_transition_certificate(cert)["findings"]]
+
+
+def _expect_rejected(cert: dict, rule: str) -> None:
+ result = audit_transition_certificate(cert)
+ expect_false(result["passed"], f"accepted: {cert} -> {result}")
+ expect_eq(result["epistemic_status"], "REJECTED")
+ expect_in(rule, _rules(cert))
+
+
+def test_unmodified_verified_certificate_still_passes() -> None:
+ result = audit_transition_certificate(_verified())
+ expect_true(result["passed"], str(result))
+ expect_eq(result["epistemic_status"], "VERIFIED")
+
+
+def test_correctly_typed_flags_and_counts_still_pass() -> None:
+ cert = _verified(
+ includes_hidden_state=True,
+ caller_bounds_verified=True,
+ differential_match=True,
+ oracles_checked=["a", "b"],
+ step_consistency_violations=0,
+ open_transitions=0,
+ proven_floor=12,
+ max_bound=12,
+ witness="U" * 12,
+ exact_optimum_reached=True,
+ )
+ result = audit_transition_certificate(cert)
+ expect_true(result["passed"], str(result))
+
+
+CASES = [
+ (
+ "tcb_pins.tcb_manifest_verified",
+ {"tcb_pins": {"tcb_manifest_verified": False, "checker_sha256": HEX64}},
+ "CERT_TCB_MANIFEST_UNLOCKED",
+ [
+ {"tcb_pins": {"tcb_manifest_verified": "false", "checker_sha256": HEX64}},
+ {"tcb_pins": {"tcb_manifest_verified": "", "checker_sha256": HEX64}},
+ {"tcb_pins": {"tcb_manifest_verified": 1, "checker_sha256": HEX64}},
+ {"tcb_pins": {"tcb_manifest_verified": None, "checker_sha256": HEX64}},
+ ],
+ ),
+ ("includes_hidden_state", {"includes_hidden_state": False}, "CERT_PARTIAL_STATE_PROJECTION", [{"includes_hidden_state": 0}, {"includes_hidden_state": "false"}]),
+ ("caller_bounds_verified", {"caller_bounds_verified": False}, "CERT_UNVERIFIED_CALLER_INFLATION", [{"caller_bounds_verified": 0}, {"caller_bounds_verified": "no"}]),
+ (
+ "differential_match",
+ {"differential_match": True, "oracles_checked": ["only"]},
+ "CERT_SINGLE_ORACLE_DIFFERENTIAL",
+ [{"differential_match": 1, "oracles_checked": ["only"]}, {"differential_match": "true", "oracles_checked": ["only"]}],
+ ),
+ (
+ "step_consistency_violations",
+ {"step_consistency_violations": 1},
+ "CERT_STEP_INCONSISTENCY",
+ [{"step_consistency_violations": -3}, {"step_consistency_violations": "1"}, {"step_consistency_violations": True}, {"step_consistency_violations": 0.9}],
+ ),
+ ("open_transitions", {"open_transitions": 2, "proof_mode": "inductive_potential"}, "CERT_TRUNCATED_INDUCTIVE_POTENTIAL", [{"open_transitions": -1}, {"open_transitions": "2"}]),
+ ("exact_optimum_reached", {"exact_optimum_reached": False, "witness": "UUU", "proven_floor": 3}, "CERT_UNWITNESSED_VERIFIED_OPTIMUM", [{"exact_optimum_reached": 0, "witness": "UUU", "proven_floor": 3}]),
+ (
+ "proven_floor",
+ {"proven_floor": 12, "witness": "U" * 11, "exact_optimum_reached": True},
+ "CERT_WITNESS_FLOOR_MISMATCH",
+ [
+ {"proven_floor": "12", "witness": "U" * 12, "exact_optimum_reached": True},
+ {"proven_floor": -12, "witness": "U" * 12, "exact_optimum_reached": True},
+ {"proven_floor": True, "witness": "U", "exact_optimum_reached": True},
+ ],
+ ),
+]
+
+
+@pytest.mark.parametrize("field,control,control_rule,variants", CASES, ids=[c[0] for c in CASES])
+def test_red_flag_variant_is_rejected_like_its_control(field: str, control: dict, control_rule: str, variants: list) -> None:
+ _expect_rejected(_verified(**control), control_rule)
+ for variant in variants:
+ cert = _verified(**variant)
+ _expect_rejected(cert, TYPE_RULE)
+ named = [f["message"] for f in audit_transition_certificate(cert)["findings"] if f["rule"] == TYPE_RULE]
+ expect_true(any(field.split(".")[-1] in m for m in named), f"finding does not name {field}: {named}")
+
+
+def test_state_hash_mode_spelling_does_not_hide_a_partial_projection() -> None:
+ for spelled in ("ascii_only", "ASCII_ONLY", " Ascii_Only "):
+ _expect_rejected(_verified(state_hash_mode=spelled), "CERT_PARTIAL_STATE_PROJECTION")
+ _expect_rejected(_verified(state_hash_mode=7), TYPE_RULE)
+
+
+def test_missing_proven_floor_does_not_skip_the_unwitnessed_optimum_check() -> None:
+ control = _verified(witness=None, exact_optimum_reached=False, proven_floor=12)
+ _expect_rejected(control, "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+ for variant in (
+ _verified(witness=None, exact_optimum_reached=False),
+ _verified(exact_optimum_reached=False),
+ _verified(witness=None),
+ _verified(winning_witness=""),
+ ):
+ _expect_rejected(variant, "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+
+
+def test_control_records_must_be_objects_with_boolean_flags() -> None:
+ base = {"must_fail_controls": ["c1"]}
+ _expect_rejected(_verified(**base, control_records=["c1"]), TYPE_RULE)
+ _expect_rejected(_verified(**base, control_records=[{"name": "c1", "oracle_invoked": "false"}]), TYPE_RULE)
+ _expect_rejected(_verified(**base, control_records=[{"name": "c1", "oracle_invoked": True, "unexpectedly_passed": 1}]), TYPE_RULE)
+ _expect_rejected(_verified(must_fail_controls=[1, 2]), TYPE_RULE)
+ _expect_rejected(_verified(must_fail_controls="c1"), TYPE_RULE)
+
+
+def test_certificate_that_is_not_an_object_is_rejected() -> None:
+ for bad in ([], [{"epistemic_status": "VERIFIED"}], "VERIFIED", 7, None):
+ result = audit_transition_certificate(bad) # type: ignore[arg-type]
+ expect_false(result["passed"], str(result))
+ expect_eq(result["epistemic_status"], "REJECTED")
+ expect_eq([f["rule"] for f in result["findings"]], ["CERT_NOT_AN_OBJECT"])
+
+
+def _run_cli(cert_json: str, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> tuple[int, dict]:
+ monkeypatch.setattr(sys, "stdin", io.StringIO(cert_json))
+ code = cli_main(["--json", "audit-cert", "-"])
+ return code, json.loads(capsys.readouterr().out)
+
+
+def test_cli_rejects_string_false_and_non_object(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
+ string_false = _verified(tcb_pins={"tcb_manifest_verified": "false", "checker_sha256": HEX64})
+ code, receipt = _run_cli(json.dumps(string_false), monkeypatch, capsys)
+ expect_eq(code, 1)
+ expect_eq(receipt["epistemic_status"], "REJECTED")
+ code, receipt = _run_cli("[]", monkeypatch, capsys)
+ expect_eq(code, 1)
+ expect_eq(receipt["epistemic_status"], "REJECTED")
+ code, receipt = _run_cli(json.dumps(_verified()), monkeypatch, capsys)
+ expect_eq(code, 0)
+ expect_eq(receipt["epistemic_status"], "VERIFIED")
diff --git a/tests/test_candidate_confinement.py b/tests/test_candidate_confinement.py
new file mode 100644
index 0000000..5031d65
--- /dev/null
+++ b/tests/test_candidate_confinement.py
@@ -0,0 +1,945 @@
+"""Host writes, env leaks, and trusted-input swaps must fail closed.
+
+Each test is aimed at one fix. Reverting that fix fails its test:
+a passthrough `run_confined_command` writes the host marker, dropping `env -i`
+leaks the sentinel, `--ro-bind / /` makes `.git/config` and the sockets visible,
+a line-anchored `attribute` regex misses the split form, skipping the restore
+lets the kernel see the rewritten Proofs file, and an uncaught `json.loads`
+raises on malformed `comparator.json`.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+from pathlib import Path
+import shutil
+import socket
+import threading
+import uuid
+
+import pytest
+
+from helpers import expect_false, expect_in, expect_true, has_dep, has_lean_toolchain
+from mcproof.cli import main as cli_main
+from mcproof.lean_harness import (
+ _NOFOLLOW_OPEN_RULE,
+ _SANDBOX_CPU_SEC,
+ UntrustedProjectPath,
+ _address_space_cap_bytes,
+ _nofollow_dir_ops_available,
+ _spawn_confined,
+ linux_bwrap_functional,
+ lint_lean4_source,
+ verify_lean4_project_comparator,
+ verify_lean4_source,
+)
+from mcproof.oracles import grade_family_completion, run_prose_and_mixed_zone_oracle
+from mcproof.repair_loop import _family_c_build_side_effect_findings, _run_family_c_real_lean_turn
+from test_domain_and_repair_loop import _family_c_refl_harness, _family_c_with_theorems
+
+
+def _skip_without_confinement() -> None:
+ if not has_lean_toolchain():
+ pytest.skip("Lean is absent, so this confinement path was not exercised")
+ if not linux_bwrap_functional():
+ pytest.skip("bwrap confinement probe failed, so this path was not exercised")
+
+
+def _skip_without_soko() -> None:
+ if not has_dep("soko"):
+ pytest.skip("soko is absent, so the Lean auditor path was not exercised")
+
+
+def _hidden_eval(marker: Path) -> str:
+ """`#eval` hidden by a short raw-string closer. The lint does not see it, so the compile runs."""
+ return (
+ "theorem host_marker_witness (n : Nat) : n = n := rfl\n"
+ 'def s := r##"foo"#\n'
+ f'#eval IO.FS.writeFile "{marker}" "p"\n'
+ )
+
+
+def _expect_host_marker_absent(run) -> None:
+ marker = Path("/tmp") / f"mcproof-host-marker-{uuid.uuid4().hex}"
+ marker.unlink(missing_ok=True)
+ try:
+ run(marker)
+ expect_false(marker.is_file(), f"candidate wrote {marker}; the compile was not confined")
+ finally:
+ marker.unlink(missing_ok=True)
+
+
+def test_verify_lean4_source_cannot_write_a_host_marker() -> None:
+ """Family A's compiler. A passthrough sandbox writes the marker and this fails."""
+ _skip_without_confinement()
+ _skip_without_soko()
+
+ def run(marker: Path) -> None:
+ verify_lean4_source(_hidden_eval(marker))
+
+ _expect_host_marker_absent(run)
+
+
+def test_family_a_grader_cannot_write_a_host_marker() -> None:
+ _skip_without_confinement()
+ _skip_without_soko()
+
+ def run(marker: Path) -> None:
+ grade_family_completion("A", "```lean\n" + _hidden_eval(marker) + "```\n")
+
+ _expect_host_marker_absent(run)
+
+
+def test_family_c_grader_cannot_write_a_host_marker() -> None:
+ """`grade_family_completion` for Family C runs before the sandboxed harness."""
+ _skip_without_confinement()
+ _skip_without_soko()
+
+ def run(marker: Path) -> None:
+ grade_family_completion("C", "```lean\n" + _hidden_eval(marker) + "```\n")
+
+ _expect_host_marker_absent(run)
+
+
+def test_family_d_embedded_lean_cannot_write_a_host_marker() -> None:
+ _skip_without_confinement()
+ _skip_without_soko()
+
+ def run(marker: Path) -> None:
+ text = "```lean\n" + _hidden_eval(marker) + "```\n"
+ run_prose_and_mixed_zone_oracle(
+ text,
+ require_formal_sections=False,
+ require_data_eido_skip=False,
+ verify_embedded_lean=True,
+ verify_verdict_shas=False,
+ )
+ grade_family_completion("D", text)
+
+ _expect_host_marker_absent(run)
+
+
+def test_cli_lean_cannot_write_a_host_marker(monkeypatch: pytest.MonkeyPatch) -> None:
+ _skip_without_confinement()
+ _skip_without_soko()
+
+ def run(marker: Path) -> None:
+ monkeypatch.setattr("sys.stdin", io.StringIO(_hidden_eval(marker)))
+ cli_main(["lean", "-"])
+
+ _expect_host_marker_absent(run)
+
+
+def test_run_lean4_verification_cannot_write_a_host_marker() -> None:
+ _skip_without_confinement()
+ if not has_dep("soko"):
+ pytest.skip("soko is absent, so run_lean4_verification was not exercised")
+ from verification.graders.common import run_lean4_verification
+
+ def run(marker: Path) -> None:
+ run_lean4_verification(_hidden_eval(marker))
+
+ _expect_host_marker_absent(run)
+
+
+def test_execution_lint_stops_verify_lean4_source_before_compile(monkeypatch: pytest.MonkeyPatch) -> None:
+ """`attribute [init]` is a lint finding. Removing the early return calls Lean and this fails."""
+ _skip_without_soko()
+
+ def boom(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("Lean ran after an execution lint")
+
+ monkeypatch.setattr("mcproof.lean_harness.run_confined_command", boom)
+ monkeypatch.setattr("mcproof.lean_harness.subprocess.run", boom)
+ res = verify_lean4_source(
+ 'def pwnInit : IO Unit := pure ()\nattribute [init] pwnInit\n',
+ require_theorem=False,
+ )
+ expect_in("FORBIDDEN_INIT_ATTRIBUTE", {f["rule"] for f in res.findings})
+
+
+def test_execution_lint_stops_run_lean4_verification_before_compile(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """soko accepts `attribute [init]`. Removing this lint stop compiles it and this fails."""
+ if not has_dep("soko"):
+ pytest.skip("soko is absent, so run_lean4_verification was not exercised")
+ from verification.graders.common import run_lean4_verification
+
+ def boom(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("Lean ran after an execution lint")
+
+ monkeypatch.setattr("mcproof.lean_harness.run_confined_command", boom)
+ monkeypatch.setattr("verification.graders.common.run_confined_command", boom)
+ rep = run_lean4_verification('def pwnInit : IO Unit := pure ()\nattribute [init] pwnInit\n')
+ expect_false(rep["ok"], str(rep))
+ expect_true(any(str(err).startswith("lint:FORBIDDEN_INIT_ATTRIBUTE") for err in rep["errors"]), rep)
+
+
+def _skip_without_bwrap() -> None:
+ if not shutil.which("bwrap"):
+ pytest.skip("bwrap is absent, so this confinement check was not exercised")
+
+
+def test_confined_process_does_not_leak_parent_environ(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """Dropping `env -i` puts this sentinel in `/proc/1/environ` and this fails."""
+ _skip_without_bwrap()
+ monkeypatch.setenv("MCPROOF_SANDBOX_SENTINEL", "leakme-parent-env")
+ monkeypatch.setenv("GIT_CONFIG_VALUE_0", "supersecret-git")
+ proc = _spawn_confined(
+ [
+ "python3",
+ "-c",
+ "from pathlib import Path; print('ENV_BEGIN'); print(Path('/proc/1/environ').read_bytes().decode('utf-8','replace'))",
+ ],
+ cwd=tmp_path,
+ caller_env={},
+ timeout_sec=30,
+ )
+ text = proc.stdout or ""
+ expect_true(proc.returncode == 0 and "ENV_BEGIN" in text, (proc.returncode, proc.stderr))
+ expect_false("leakme-parent-env" in text, text)
+ expect_false("GIT_CONFIG_VALUE_0" in text, text)
+ expect_false("supersecret-git" in text, text)
+
+
+def test_confined_process_cannot_read_git_config(tmp_path: Path) -> None:
+ """`--ro-bind / /` makes the checkout config readable and this fails."""
+ _skip_without_bwrap()
+ proc = _spawn_confined(
+ [
+ "python3",
+ "-c",
+ "from pathlib import Path; p=Path('/agent/repos/mcproof/.git/config'); print('YES' if p.is_file() else 'NO')",
+ ],
+ cwd=tmp_path,
+ caller_env={},
+ timeout_sec=30,
+ )
+ expect_true(proc.returncode == 0, proc.stderr)
+ expect_true((proc.stdout or "").strip() == "NO", (proc.stdout, proc.stderr))
+
+
+def test_confined_process_cannot_connect_host_sockets(tmp_path: Path) -> None:
+ """A visible `/run` lets the sandbox connect to the host sockets and this fails."""
+ _skip_without_bwrap()
+ script = (
+ "import socket\n"
+ "socks=('/run/cursor/api.sock','/run/host-services/ssh-auth.sock')\n"
+ "ok=[]\n"
+ "for sock in socks:\n"
+ " h=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n"
+ " h.settimeout(0.3)\n"
+ " try:\n"
+ " h.connect(sock)\n"
+ " ok.append(sock)\n"
+ " except OSError:\n"
+ " pass\n"
+ " finally:\n"
+ " h.close()\n"
+ "print('CONNECT_OK' if ok else 'NO')\n"
+ )
+ proc = _spawn_confined(["python3", "-c", script], cwd=tmp_path, caller_env={}, timeout_sec=30)
+ expect_true(proc.returncode == 0, proc.stderr)
+ expect_true((proc.stdout or "").strip() == "NO", (proc.stdout, proc.stderr))
+
+
+def test_confined_process_has_resource_limits(tmp_path: Path) -> None:
+ """Removing `prlimit` leaves the address space unlimited and this fails."""
+ _skip_without_bwrap()
+ script = (
+ "import resource\n"
+ f"print(resource.getrlimit(resource.RLIMIT_AS)[0])\n"
+ f"print(resource.getrlimit(resource.RLIMIT_CPU)[0])\n"
+ )
+ proc = _spawn_confined(["python3", "-c", script], cwd=tmp_path, caller_env={}, timeout_sec=30)
+ lines = [ln.strip() for ln in (proc.stdout or "").splitlines() if ln.strip()]
+ expect_true(len(lines) == 2, proc.stdout + (proc.stderr or ""))
+ memtotal = 0
+ for line in Path("/proc/meminfo").read_text(encoding="utf-8").splitlines():
+ if line.startswith("MemTotal:"):
+ memtotal = int(line.split()[1]) * 1024
+ soft = int(lines[0])
+ # A fixed 32 GiB cap is above this host. Unlimited is -1, and -1 <= MemTotal.
+ expect_true(memtotal > 0 and soft > 0 and soft <= memtotal, (soft, memtotal))
+ expect_true(soft == _address_space_cap_bytes(), (soft, _address_space_cap_bytes()))
+ expect_true(int(lines[1]) == _SANDBOX_CPU_SEC, lines)
+
+
+def test_split_attribute_init_is_a_lint_finding() -> None:
+ """A column-zero regex misses both of these. Restoring it makes this fail."""
+ samples = (
+ "theorem t (n : Nat) : n = n := rfl attribute [init] pwnInit\n",
+ "theorem t (n : Nat) : n = n := rfl\nattribute\n[init] pwnInit\n",
+ )
+ for src in samples:
+ if has_dep("soko"):
+ rules = {f["rule"] for f in lint_lean4_source(src, require_theorem=False)["findings"]}
+ expect_in("FORBIDDEN_INIT_ATTRIBUTE", rules, src)
+ side = {f["rule"] for f in _family_c_build_side_effect_findings(src)}
+ expect_in("FORBIDDEN_BUILD_SIDE_EFFECT", side, src)
+
+
+def test_family_c_split_attribute_init_is_rejected() -> None:
+ """The full turn used to accept these with no rules. A line-anchored regex does that again."""
+ _skip_without_confinement()
+ samples = (
+ "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl attribute [init] pwnInit\n"
+ "def pwnInit : IO Unit := pure ()\n",
+ "attribute\n[init] pwnInit\ndef pwnInit : IO Unit := pure ()\n",
+ )
+ for snippet in samples:
+ findings = _run_family_c_real_lean_turn(
+ _family_c_refl_harness(),
+ _family_c_with_theorems(snippet),
+ )
+ rules = {f["rule"] for f in findings}
+ expect_true(
+ "FORBIDDEN_BUILD_SIDE_EFFECT" in rules or "FORBIDDEN_INIT_ATTRIBUTE" in rules,
+ findings,
+ )
+
+
+def test_family_c_restores_proofs_and_comparator_after_the_build() -> None:
+ """The build rewrites both files. Skipping the restore drops the axiom finding or raises."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ snippet = (
+ "axiom planted_bad : False\n"
+ "run_meta do\n"
+ " IO.FS.writeFile \"CrtPair/Proofs.lean\" "
+ "\"import CrtPair\\n\\ntheorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\\n"
+ "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\\n\"\n"
+ " IO.FS.writeFile \"comparator.json\" \"not-json\"\n"
+ )
+ findings = _run_family_c_real_lean_turn(
+ _family_c_refl_harness(),
+ _family_c_with_theorems(snippet, prelude="import Lean\n"),
+ )
+ rules = {f["rule"] for f in findings}
+ expect_in("EXTRA_AXIOM_DECL", rules, str(findings))
+ expect_false("COMPARATOR_JSON_MALFORMED" in rules, findings)
+
+
+def test_malformed_comparator_json_is_a_finding(tmp_path: Path) -> None:
+ """An uncaught `json.loads` raises `JSONDecodeError` and this errors instead of failing closed."""
+ (tmp_path / "comparator.json").write_text("{", encoding="utf-8")
+ res = verify_lean4_project_comparator(tmp_path)
+ expect_false(res.passed)
+ rules = {f["rule"] for f in res.findings}
+ if _nofollow_dir_ops_available():
+ expect_in("COMPARATOR_JSON_MALFORMED", rules)
+ else:
+ expect_in(_NOFOLLOW_OPEN_RULE, rules)
+
+
+_ORIGINAL_PROOFS = "import Probe\ntheorem Probe.Proofs.goal : True := trivial\n"
+
+
+def _write_toml_project(root: Path, proofs: str) -> None:
+ (root / "Probe").mkdir(parents=True)
+ (root / "lean-toolchain").write_text("leanprover/lean4:v4.35.0\n", encoding="utf-8")
+ (root / "lakefile.toml").write_text(
+ 'name = "probe"\nversion = "0.1.0"\n'
+ 'defaultTargets = ["Probe", "Probe.Proofs"]\n\n'
+ '[[lean_lib]]\nname = "Probe"\n\n[[lean_lib]]\nname = "Probe.Proofs"\n',
+ encoding="utf-8",
+ )
+ (root / "Probe.lean").write_text("theorem probeRoot : True := trivial\n", encoding="utf-8")
+ (root / "Probe" / "Proofs.lean").write_text(proofs, encoding="utf-8")
+ (root / "comparator.json").write_text(
+ '{"challenge_module":"Probe","solution_module":"Probe.Proofs",'
+ '"theorem_names":["Probe.Proofs.goal"],'
+ '"permitted_axioms":["propext","Quot.sound","Classical.choice"]}\n',
+ encoding="utf-8",
+ )
+
+
+def test_planted_lakefile_is_not_elaborated(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """Lake prefers lakefile.lean. Copying it into the trusted tree elaborates the plant."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ import mcproof.lean_harness as harness
+
+ root = tmp_path / "proj"
+ _write_toml_project(root, _ORIGINAL_PROOFS)
+ marker = root / "plant-marker.txt"
+ (root / "lakefile.lean").write_text(
+ "import Lean\n"
+ "elab \"pwnPlant\" : command => do\n"
+ " let _ ← IO.FS.writeFile \"plant-marker.txt\" \"ELABORATED\"\n"
+ "pwnPlant\n",
+ encoding="utf-8",
+ )
+ real = harness.run_confined_command
+ elaborated: list[str] = []
+
+ def _wrap(argv, *args, **kwargs):
+ res = real(argv, *args, **kwargs)
+ if any(str(part) == "build" for part in argv):
+ cwd = Path(kwargs.get("cwd") or ".")
+ if (cwd / "lakefile.lean").exists() or (cwd / "plant-marker.txt").is_file():
+ elaborated.append(str(cwd))
+ return res
+
+ monkeypatch.setattr(harness, "run_confined_command", _wrap)
+ verify_lean4_project_comparator(root, allow_unsandboxed=False)
+ expect_false(marker.is_file(), "the planted lakefile was elaborated on the caller tree")
+ expect_true(elaborated == [], elaborated)
+ expect_true(
+ (root / "Probe" / "Proofs.lean").read_text(encoding="utf-8") == _ORIGINAL_PROOFS,
+ (root / "Probe" / "Proofs.lean").read_text(encoding="utf-8"),
+ )
+
+
+def test_comparator_cannot_see_the_host(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """A host `lake comparator` re-elaborates a cold lakefile and this report shows the host."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ monkeypatch.setenv("MCPROOF_SANDBOX_SENTINEL", "leakme-parent-env")
+ root = tmp_path / "proj"
+ (root / "Probe").mkdir(parents=True)
+ (root / "lean-toolchain").write_text("leanprover/lean4:v4.35.0\n", encoding="utf-8")
+ (root / "lakefile.toml").write_text(
+ 'name = "probe"\nversion = "0.1.0"\n'
+ 'defaultTargets = ["Probe", "Probe.Proofs"]\n\n'
+ '[[lean_lib]]\nname = "Probe"\n\n[[lean_lib]]\nname = "Probe.Proofs"\n',
+ encoding="utf-8",
+ )
+ (root / "Probe.lean").write_text(
+ "import Lean\n"
+ "elab \"pwnProbe\" : command => do\n"
+ " let _ ← IO.Process.output { cmd := \"python3\", args := #[\"probe.py\"] }\n"
+ "pwnProbe\n"
+ "theorem probeRoot : True := trivial\n",
+ encoding="utf-8",
+ )
+ (root / "Probe" / "Proofs.lean").write_text(_ORIGINAL_PROOFS, encoding="utf-8")
+ (root / "comparator.json").write_text(
+ '{"challenge_module":"Probe","solution_module":"Probe.Proofs",'
+ '"theorem_names":["Probe.Proofs.goal"],'
+ '"permitted_axioms":["propext","Quot.sound","Classical.choice"]}\n',
+ encoding="utf-8",
+ )
+ hits: list[bytes] = []
+ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ server.settimeout(0.2)
+ port = server.getsockname()[1]
+ stop = threading.Event()
+
+ def serve() -> None:
+ while not stop.is_set():
+ try:
+ conn, _addr = server.accept()
+ except TimeoutError:
+ continue
+ except OSError:
+ return
+ try:
+ hits.append(conn.recv(64))
+ finally:
+ conn.close()
+
+ thread = threading.Thread(target=serve, daemon=True)
+ thread.start()
+ (root / "probe.py").write_text(
+ "import os, socket\n"
+ "from pathlib import Path\n"
+ "phase = Path('probe-phase.txt')\n"
+ "tag = 'comparator' if phase.is_file() else 'build'\n"
+ "try:\n"
+ " if not phase.is_file():\n"
+ " phase.write_text('done\\n')\n"
+ "except OSError:\n"
+ " pass\n"
+ "git = Path('/agent/repos/mcproof/.git/config')\n"
+ "sock = '0'\n"
+ "try:\n"
+ " h = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n"
+ " h.settimeout(0.3)\n"
+ " h.connect('/run/host-services/ssh-auth.sock')\n"
+ " sock = '1'\n"
+ " h.close()\n"
+ "except OSError:\n"
+ " pass\n"
+ "tcp = '0'\n"
+ "try:\n"
+ f" c = socket.create_connection(('127.0.0.1', {port}), 0.3)\n"
+ " c.sendall(b'NET_OK')\n"
+ " c.close()\n"
+ " tcp = '1'\n"
+ "except OSError:\n"
+ " pass\n"
+ "env = os.environ.get('MCPROOF_SANDBOX_SENTINEL', '')\n"
+ "proc = Path('/proc/1/environ').read_bytes().decode('utf-8', 'replace') if Path('/proc/1/environ').is_file() else ''\n"
+ "sent = '1' if ('leakme-parent-env' in env or 'leakme-parent-env' in proc) else '0'\n"
+ "lake = Path('.lake')\n"
+ "lake.mkdir(exist_ok=True)\n"
+ "(lake / 'probe-report.txt').write_text(f'{tag} GIT={1 if git.is_file() else 0} SOCK={sock} TCP={tcp} SENTINEL={sent}\\n')\n"
+ "proofs = Path('Probe/Proofs.lean')\n"
+ "if tag == 'build':\n"
+ " proofs.write_text(proofs.read_text() + '-- rewritten-by-probe\\n')\n"
+ "else:\n"
+ " try:\n"
+ " proofs.write_text('ELABORATED\\n')\n"
+ " except OSError:\n"
+ " pass\n",
+ encoding="utf-8",
+ )
+ import mcproof.lean_harness as harness
+
+ real = harness.run_confined_command
+ reports: list[str] = []
+
+ def _wrap(argv, *args, **kwargs):
+ res = real(argv, *args, **kwargs)
+ if any(str(part) == "comparator" for part in argv):
+ report_path = Path(kwargs.get("cwd") or ".") / ".lake" / "probe-report.txt"
+ reports.append(report_path.read_text(encoding="utf-8") if report_path.is_file() else "")
+ return res
+
+ monkeypatch.setattr(harness, "run_confined_command", _wrap)
+ try:
+ verify_lean4_project_comparator(root, allow_unsandboxed=False)
+ report = reports[-1] if reports else ""
+ expect_true(bool(reports), "the comparator command did not run")
+ expect_true("GIT=0" in report and "SOCK=0" in report and "TCP=0" in report, report)
+ expect_true("SENTINEL=0" in report and "leakme-parent-env" not in report, report)
+ expect_true(hits == [], hits)
+ expect_true(
+ (root / "Probe" / "Proofs.lean").read_text(encoding="utf-8") == _ORIGINAL_PROOFS,
+ (root / "Probe" / "Proofs.lean").read_text(encoding="utf-8"),
+ )
+ finally:
+ stop.set()
+ server.close()
+ thread.join(timeout=2)
+
+
+def test_eval_or_run_meta_never_runs_the_comparator(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """Removing the early return reaches `lake comparator` and this fails."""
+ _skip_without_soko()
+ if not has_lean_toolchain():
+ pytest.skip("Lean is absent, so the comparator stop was not exercised")
+
+ import mcproof.lean_harness as harness
+
+ real_run = harness.subprocess.run
+ real_confined = harness.run_confined_command
+
+ def reject_run(argv, *args, **kwargs):
+ if any(str(part) == "comparator" for part in argv):
+ raise AssertionError(f"comparator ran: {argv}")
+ return real_run(argv, *args, **kwargs)
+
+ def reject_confined(argv, *args, **kwargs):
+ if any(str(part) == "comparator" for part in argv):
+ raise AssertionError(f"comparator ran: {argv}")
+ return real_confined(argv, *args, **kwargs)
+
+ monkeypatch.setattr(harness, "run_confined_command", reject_confined)
+ monkeypatch.setattr(harness.subprocess, "run", reject_run)
+ samples = (
+ _ORIGINAL_PROOFS + "#eval IO.println \"hi\"\n",
+ "import Lean\n" + _ORIGINAL_PROOFS + "run_meta do pure ()\n",
+ )
+ for proofs in samples:
+ root = tmp_path / uuid.uuid4().hex
+ _write_toml_project(root, proofs)
+ res = verify_lean4_project_comparator(root, allow_unsandboxed=False)
+ rules = {f["rule"] for f in res.findings}
+ expect_true(
+ "FORBIDDEN_EVAL_COMMAND" in rules or any("run_meta" in str(f.get("message", "")) for f in res.findings),
+ res.findings,
+ )
+
+
+def test_confined_compile_error_reports_sandboxed() -> None:
+ """The compile ran inside the sandbox. Reporting sandboxed=False makes this fail."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ res = verify_lean4_source(
+ 'theorem t (n : Nat) : n = n := rfl\ndef s := r##"foo"#\n',
+ )
+ expect_in("LEAN_COMPILE_ERROR", {f["rule"] for f in res.findings})
+ expect_true(res.sandboxed is True, res)
+
+
+class _Failed:
+ returncode = 1
+ stdout = ""
+ stderr = "failed"
+
+
+def _fingerprint(root: Path) -> tuple:
+ rows = []
+ for path in sorted(root.rglob("*")):
+ rel = path.relative_to(root).as_posix()
+ if path.is_symlink():
+ rows.append((rel, "symlink", str(path.readlink())))
+ elif path.is_dir():
+ rows.append((rel, "dir", ""))
+ else:
+ rows.append((rel, "file", path.read_bytes()))
+ return tuple(rows)
+
+
+def _make_victim(path: Path) -> None:
+ path.mkdir()
+ (path / "file.txt").write_text("SENTINEL_FILE\n", encoding="utf-8")
+ (path / "dir.d").mkdir()
+ (path / "dir.d" / "secret").write_text("KEEP\n", encoding="utf-8")
+ (path / "CANARY").write_text("CANARY\n", encoding="utf-8")
+
+
+def _plant_restore_targets(root: Path) -> None:
+ """Files a restore would copy. `dir.d` is a file here and a directory in the victim."""
+ for name in ("Probe", "CrtPair", "notes"):
+ directory = root / name
+ directory.mkdir(exist_ok=True)
+ (directory / "file.txt").write_text(f"project-{name}-file\n", encoding="utf-8")
+ (directory / "dir.d").write_text(f"project-{name}-dir\n", encoding="utf-8")
+
+
+def _swap_parents(root: Path, victims: dict[str, Path]) -> None:
+ for name, victim in victims.items():
+ dest = root / name
+ if dest.is_symlink():
+ continue
+ if dest.is_dir():
+ shutil.rmtree(dest)
+ elif dest.exists():
+ dest.unlink()
+ dest.symlink_to(victim, target_is_directory=True)
+
+
+def _assert_victims_unchanged(victims: dict[str, Path], before: dict[str, tuple]) -> None:
+ for name, victim in victims.items():
+ expect_true(_fingerprint(victim) == before[name], name)
+ expect_true((victim / "file.txt").read_text(encoding="utf-8") == "SENTINEL_FILE\n", name)
+ expect_true((victim / "dir.d" / "secret").read_text(encoding="utf-8") == "KEEP\n", name)
+ expect_true((victim / "CANARY").read_text(encoding="utf-8") == "CANARY\n", name)
+ expect_true(victim.is_dir() and not victim.is_symlink(), name)
+
+
+def test_verify_parent_symlink_restore_does_not_touch_the_host(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A build that swaps Probe, CrtPair, or notes must not make the restore write the host."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ import mcproof.lean_harness as harness
+
+ root = tmp_path / "proj"
+ _write_toml_project(root, _ORIGINAL_PROOFS)
+ _plant_restore_targets(root)
+ victims = {name: tmp_path / f"victim-{name}" for name in ("Probe", "CrtPair", "notes")}
+ for victim in victims.values():
+ _make_victim(victim)
+ before = {name: _fingerprint(path) for name, path in victims.items()}
+ called = {"build": False}
+
+ def _fake(argv, *args, **kwargs):
+ if any(str(part) == "build" for part in argv):
+ called["build"] = True
+ _swap_parents(root, victims)
+ return _Failed()
+ raise AssertionError(f"unexpected command: {argv}")
+
+ monkeypatch.setattr(harness, "run_confined_command", _fake)
+ verify_lean4_project_comparator(root, allow_unsandboxed=False)
+ expect_true(called["build"], "the build never ran, so the symlink swap was not tested")
+ _assert_victims_unchanged(victims, before)
+
+
+def test_family_c_parent_symlink_restore_does_not_touch_the_host(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Family C's failure path must not write the host through a swapped parent directory."""
+ _skip_without_confinement()
+ import mcproof.lean_harness as harness
+ import mcproof.repair_loop as repair
+
+ victims = {name: tmp_path / f"victim-{name}" for name in ("Probe", "CrtPair", "notes")}
+ for victim in victims.values():
+ _make_victim(victim)
+ before = {name: _fingerprint(path) for name, path in victims.items()}
+ called = {"build": False}
+
+ def _read(proj: Path):
+ _plant_restore_targets(Path(proj))
+ return harness._read_project_tree(proj)
+
+ def _fake(argv, *args, **kwargs):
+ if any(str(part) == "build" for part in argv):
+ called["build"] = True
+ _swap_parents(Path(kwargs["cwd"]), victims)
+ return _Failed()
+ raise AssertionError(f"unexpected command: {argv}")
+
+ monkeypatch.setattr(repair, "_read_project_tree", _read)
+ monkeypatch.setattr(repair, "run_confined_command", _fake)
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(""))
+ expect_true(called["build"], f"the build never ran: {findings}")
+ expect_in("LAKE_BUILD_FAILED", {f["rule"] for f in findings})
+ _assert_victims_unchanged(victims, before)
+
+
+def test_lake_symlink_is_a_finding(tmp_path: Path) -> None:
+ """`.lake` as a symlink is a finding. Following it, or rmtree on it, touches the target."""
+ root = tmp_path / "proj"
+ _write_toml_project(root, _ORIGINAL_PROOFS)
+ precious = tmp_path / "precious"
+ precious.mkdir()
+ (precious / "KEEP").write_text("KEEP\n", encoding="utf-8")
+ lake = root / ".lake"
+ lake.symlink_to(precious, target_is_directory=True)
+ res = verify_lean4_project_comparator(root, allow_unsandboxed=True)
+ rules = {f["rule"] for f in res.findings}
+ if _nofollow_dir_ops_available():
+ expect_in("LAKE_CACHE_SYMLINK", rules)
+ else:
+ expect_in(_NOFOLLOW_OPEN_RULE, rules)
+ expect_true((precious / "KEEP").read_text(encoding="utf-8") == "KEEP\n")
+ expect_true(lake.is_symlink())
+
+
+def test_family_c_lake_symlink_is_a_finding(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """The Family C build must not raise, follow, or delete through a `.lake` symlink."""
+ import mcproof.repair_loop as repair
+
+ precious = tmp_path / "precious"
+ precious.mkdir()
+ (precious / "KEEP").write_text("KEEP\n", encoding="utf-8")
+
+ def _wrap(root: Path):
+ lake = Path(root) / ".lake"
+ if lake.is_symlink():
+ lake.unlink()
+ elif lake.is_dir():
+ shutil.rmtree(lake)
+ elif lake.exists():
+ lake.unlink()
+ lake.symlink_to(precious, target_is_directory=True)
+ return repair_build(root)
+
+ repair_build = repair._family_c_direct_lake_build
+ monkeypatch.setattr(repair, "_family_c_direct_lake_build", _wrap)
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(""))
+ rules = {f["rule"] for f in findings}
+ if _nofollow_dir_ops_available():
+ expect_in("LAKE_CACHE_SYMLINK", rules)
+ else:
+ expect_in(_NOFOLLOW_OPEN_RULE, rules)
+ expect_true((precious / "KEEP").read_text(encoding="utf-8") == "KEEP\n", findings)
+ expect_true((Path(precious)).is_dir(), findings)
+
+
+def test_build_created_manifest_does_not_reach_the_comparator(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A manifest written by the build must not be the one `lake comparator` reads."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ import mcproof.lean_harness as harness
+
+ root = tmp_path / "proj"
+ _write_toml_project(root, _ORIGINAL_PROOFS)
+ real = harness.run_confined_command
+ build_cwds: list[Path] = []
+ seen: list[str] = []
+
+ def _wrap(argv, *args, **kwargs):
+ res = real(argv, *args, **kwargs)
+ cwd = Path(kwargs.get("cwd") or ".").resolve()
+ if any(str(part) == "build" for part in argv):
+ (cwd / "lake-manifest.json").write_text('{"evil-path-dep": true}\n', encoding="utf-8")
+ build_cwds.append(cwd)
+ if any(str(part) == "comparator" for part in argv):
+ manifest = cwd / "lake-manifest.json"
+ seen.append(manifest.read_text(encoding="utf-8") if manifest.is_file() else "")
+ expect_false(cwd in build_cwds, f"comparator reused the build directory {cwd}")
+ return res
+
+ monkeypatch.setattr(harness, "run_confined_command", _wrap)
+ verify_lean4_project_comparator(root, allow_unsandboxed=False)
+ expect_true(bool(seen), "the comparator did not run")
+ expect_true(all("evil-path-dep" not in text for text in seen), seen)
+
+
+def test_family_c_build_created_manifest_does_not_reach_the_comparator(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Family C's comparator copy is the pre-build tree, not the tree the build rewrote."""
+ _skip_without_confinement()
+ _skip_without_soko()
+ import mcproof.lean_harness as harness
+ import mcproof.repair_loop as repair
+
+ real = harness.run_confined_command
+ build_cwds: list[Path] = []
+ seen: list[str] = []
+
+ def _wrap(argv, *args, **kwargs):
+ res = real(argv, *args, **kwargs)
+ cwd = Path(kwargs.get("cwd") or ".").resolve()
+ if any(str(part) == "build" for part in argv):
+ (cwd / "lake-manifest.json").write_text('{"evil-path-dep": true}\n', encoding="utf-8")
+ build_cwds.append(cwd)
+ if any(str(part) == "comparator" for part in argv):
+ manifest = cwd / "lake-manifest.json"
+ seen.append(manifest.read_text(encoding="utf-8") if manifest.is_file() else "")
+ expect_false(cwd in build_cwds, f"comparator reused the build directory {cwd}")
+ return res
+
+ real_verify = repair.verify_lean4_project_comparator
+ entered: list[str] = []
+
+ def _verify(project_dir, *args, **kwargs):
+ manifest = Path(project_dir) / "lake-manifest.json"
+ entered.append(manifest.read_text(encoding="utf-8") if manifest.is_file() else "")
+ return real_verify(project_dir, *args, **kwargs)
+
+ monkeypatch.setattr(harness, "run_confined_command", _wrap)
+ monkeypatch.setattr(repair, "run_confined_command", _wrap)
+ monkeypatch.setattr(repair, "verify_lean4_project_comparator", _verify)
+ _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(""))
+ expect_true(bool(seen), "the comparator did not run")
+ expect_true(all("evil-path-dep" not in text for text in seen), seen)
+ expect_true(bool(entered), "verify was not given a trusted tree")
+ expect_true(all("evil-path-dep" not in text for text in entered), entered)
+
+
+def test_allow_unsandboxed_does_not_run_lake_on_the_host(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A failed bwrap probe refuses the build. The flag must not run lake on the host."""
+ _skip_without_soko()
+ import mcproof.lean_harness as harness
+
+ monkeypatch.setattr(harness, "linux_bwrap_functional", lambda **_kwargs: False)
+ real_run = harness.subprocess.run
+
+ def _host(argv, *args, **kwargs):
+ if any(part in {"lake", "lean"} or str(part).endswith(("/lake", "/lean")) for part in argv):
+ raise AssertionError(f"candidate command ran on the host: {argv}")
+ return real_run(argv, *args, **kwargs)
+
+ def _confined(argv, *args, **kwargs):
+ raise AssertionError(f"candidate command ran without a working sandbox: {argv}")
+
+ monkeypatch.setattr(harness.subprocess, "run", _host)
+ monkeypatch.setattr(harness, "run_confined_command", _confined)
+ root = tmp_path / "proj"
+ _write_toml_project(root, _ORIGINAL_PROOFS)
+ res = verify_lean4_project_comparator(root, allow_unsandboxed=True)
+ expect_false(res.passed)
+ expect_in("SANDBOX_UNAVAILABLE", {f["rule"] for f in res.findings})
+
+
+def test_run_cmd_and_hidden_eval_never_reach_lake(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """`run_cmd` and a `#eval` after a short raw-string closer never reach lake."""
+ import mcproof.lean_harness as harness
+ import mcproof.repair_loop as repair
+
+ real_run = harness.subprocess.run
+
+ def _boom(argv, *args, **kwargs):
+ parts = [str(part) for part in argv]
+ if any(part == "lake" or part.endswith("/lake") or part == "lean" or part.endswith("/lean") for part in parts):
+ raise AssertionError(f"lake ran: {argv}")
+ if any(part in {"build", "comparator", "update"} for part in parts):
+ raise AssertionError(f"lake ran: {argv}")
+ return real_run(argv, *args, **kwargs)
+
+ monkeypatch.setattr(harness, "run_confined_command", _boom)
+ monkeypatch.setattr(harness.subprocess, "run", _boom)
+ monkeypatch.setattr(repair, "run_confined_command", _boom)
+ hidden = 'def s := r##"foo"#\n#eval IO.FS.writeFile "/tmp/mcproof-should-not-run" "p"\n'
+ run_cmd = "run_cmd do pure ()\n"
+ for proofs in (_ORIGINAL_PROOFS + hidden, _ORIGINAL_PROOFS + run_cmd):
+ root = tmp_path / uuid.uuid4().hex
+ _write_toml_project(root, proofs)
+ res = verify_lean4_project_comparator(root, allow_unsandboxed=True)
+ rules = {f["rule"] for f in res.findings}
+ if _nofollow_dir_ops_available():
+ expect_true(
+ "FORBIDDEN_EVAL_COMMAND" in rules or "METAPROGRAM_ESCAPE" in rules,
+ res.findings,
+ )
+ else:
+ expect_in(_NOFOLLOW_OPEN_RULE, rules)
+ expect_false(res.passed)
+ for snippet in (hidden, run_cmd):
+ findings = _run_family_c_real_lean_turn(
+ _family_c_refl_harness(),
+ _family_c_with_theorems(snippet),
+ )
+ rules = {f["rule"] for f in findings}
+ expect_true(
+ "FORBIDDEN_EVAL_COMMAND" in rules or "FORBIDDEN_ELAB_COMMAND" in rules,
+ findings,
+ )
+
+
+def test_missing_nofollow_open_refuses_without_copying(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """Missing `O_DIRECTORY`, `O_NOFOLLOW`, or dir_fd support refuses. It does not follow a copy."""
+ import os
+
+ import mcproof.lean_harness as harness
+ import mcproof.repair_loop as repair
+
+ def _swapped() -> tuple[Path, Path, tuple]:
+ root = tmp_path / uuid.uuid4().hex
+ _write_toml_project(root, _ORIGINAL_PROOFS)
+ victim = tmp_path / f"{root.name}-victim"
+ _make_victim(victim)
+ before = _fingerprint(victim)
+ probe = root / "Probe"
+ shutil.rmtree(probe)
+ probe.symlink_to(victim, target_is_directory=True)
+ return root, victim, before
+
+ def _expect_refusal() -> None:
+ root, victim, before = _swapped()
+ res = verify_lean4_project_comparator(root, allow_unsandboxed=True)
+ expect_false(res.passed)
+ expect_in(_NOFOLLOW_OPEN_RULE, {f["rule"] for f in res.findings})
+ raised = False
+ try:
+ harness._read_project_tree(root)
+ except UntrustedProjectPath as exc:
+ raised = exc.rule == _NOFOLLOW_OPEN_RULE
+ expect_true(raised, "the tree read followed a path or used another rule")
+ try:
+ harness._materialize_trusted_tree({"Probe/file.txt": b"SENTINEL_FILE\n"})
+ except UntrustedProjectPath as exc:
+ raised = exc.rule == _NOFOLLOW_OPEN_RULE
+ else:
+ raised = False
+ expect_true(raised, "materialize copied without a non-following open")
+ expect_false(harness._real_dir(root, "Probe"))
+ findings = repair._family_c_direct_lake_build(root)
+ expect_in(_NOFOLLOW_OPEN_RULE, {f["rule"] for f in findings})
+ expect_true(_fingerprint(victim) == before)
+ expect_true((victim / "file.txt").read_text(encoding="utf-8") == "SENTINEL_FILE\n")
+ expect_true((victim / "dir.d" / "secret").read_text(encoding="utf-8") == "KEEP\n")
+
+ if _nofollow_dir_ops_available():
+ with monkeypatch.context() as hidden:
+ hidden.delattr(os, "O_DIRECTORY", raising=False)
+ hidden.delattr(os, "O_NOFOLLOW", raising=False)
+ expect_false(_nofollow_dir_ops_available())
+ _expect_refusal()
+ expect_true(_nofollow_dir_ops_available())
+ with monkeypatch.context() as hidden:
+ hidden.setattr(os, "supports_dir_fd", frozenset())
+ expect_false(_nofollow_dir_ops_available())
+ _expect_refusal()
+ expect_true(_nofollow_dir_ops_available())
+ else:
+ _expect_refusal()
diff --git a/tests/test_domain_and_repair_loop.py b/tests/test_domain_and_repair_loop.py
index 190e167..b1b26a5 100644
--- a/tests/test_domain_and_repair_loop.py
+++ b/tests/test_domain_and_repair_loop.py
@@ -2,11 +2,17 @@
from __future__ import annotations
+import importlib.util
import io
import json
from pathlib import Path
+import re
+import subprocess
import sys
from typing import Any, Mapping, Sequence
+import uuid
+
+import pytest
from mcproof.cli import main as cli_main
from mcproof.domain_protocol import (
@@ -23,9 +29,17 @@
verify_minimal_goal_stopping,
verify_rational_lp_certificate,
)
+from mcproof.lean_harness import (
+ _NOFOLLOW_OPEN_RULE,
+ _nofollow_dir_ops_available,
+ linux_bwrap_functional,
+ strip_lean_comments_and_strings,
+)
from mcproof.paths import repo_root
from mcproof.repair_loop import (
MAX_RETRIEVAL_TOKENS_HARD_CAP,
+ _family_c_direct_lake_build,
+ _run_family_c_real_lean_turn,
compute_candidate_state_hash,
compute_failure_signature,
default_inference_oracle,
@@ -36,7 +50,7 @@
sanitize_oracle_diagnostics,
)
-from helpers import expect_eq, expect_false, expect_in, expect_true, requires_dep, requires_mde
+from helpers import expect_eq, expect_false, expect_in, expect_true, has_dep, has_lean_toolchain, requires_dep, requires_mde
def test_targeted_plane1_retrieval_stays_under_1500_tokens_across_validation_split() -> None:
@@ -457,3 +471,552 @@ def test_audit_transition_certificate_catches_f01_to_f08_and_a6_a7(tmp_path: Pat
lp_farkas_ok = verify_rational_lp_certificate({"mode": "infeasible", "A": [[-1, -1]], "b": [1], "y": [1]})
expect_true(lp_farkas_ok["passed"])
+
+
+# Coprime two-modulus residue claims. These are the target statements the guard hashes.
+# They are not `op x = x`.
+_CRT_LEFT = (
+ "(m1 m2 x y : Nat) (hcop : Nat.gcd m1 m2 = 1) "
+ "(h1 : Dvd.dvd m1 (x - y)) (h2 : Dvd.dvd m2 (x - y)) : Dvd.dvd (m1 * m2) (x - y)"
+)
+_CRT_RIGHT = (
+ "(m1 m2 x : Nat) (hcop : Nat.gcd m1 m2 = 1) (hx : Dvd.dvd (m1 * m2) x) : Dvd.dvd m1 x"
+)
+
+
+def _family_c_spoof_harness() -> dict[str, Any]:
+ return {
+ "oracle_type": "bar_check",
+ "spec_meta": {
+ "pkg": "CrtPair",
+ "bar_status": "in-progress",
+ "test_cmd": "python3 tests/run_tests.py",
+ "theorem_names": ["CrtPair.Spec.crt_mod_left", "CrtPair.Spec.crt_mod_right"],
+ "statements": {
+ "CrtPair.Spec.crt_mod_left": _CRT_LEFT,
+ "CrtPair.Spec.crt_mod_right": _CRT_RIGHT,
+ },
+ },
+ }
+
+
+def test_family_c_real_lean_turn_rejects_says_verified_spoof() -> None:
+ comp = "Claim-Tier: PROVEN\n\nStatus: verified. All checks passed.\n"
+ findings = _run_family_c_real_lean_turn(_family_c_spoof_harness(), comp)
+ expect_true(bool(findings), "spoofed verified claim must fail the turn")
+ expect_in("FAMILY_C_STATUS_SELF_ATTESTATION", {f["rule"] for f in findings})
+
+
+def test_family_c_identity_plus_rfl_scaffold_no_longer_passes() -> None:
+ comp = (
+ "Claim-Tier: PROVEN\n\nStatus: verified.\n\n"
+ "```lean\ntheorem crt_mod_left (x : Nat) : CrtPair.op x = x := rfl\n```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_spoof_harness(), comp)
+ expect_true(bool(findings), "identity scaffold with rfl must fail the turn")
+ expect_in("FAMILY_C_THEOREM_NAME_MISMATCH", {f["rule"] for f in findings})
+
+
+def test_family_c_lean_error_text_reaches_next_turn_prompt() -> None:
+ """Formats a hand-written diagnostic. This test does not run `lake`."""
+ findings = [
+ {
+ "line": 1,
+ "rule": "LAKE_BUILD_FAILED",
+ "message": "`lake build` failed: error: CrtPair/Proofs.lean:2:59: Unknown constant `Nat.noSuchLemma` | error: build failed",
+ }
+ ]
+ text = format_diagnostics(findings, family="C")
+ expect_in("LAKE_BUILD_FAILED", text)
+ expect_in("Proofs.lean:2:59", text)
+
+
+def test_family_c_fully_qualified_identity_rfl_fails_statement_hash() -> None:
+ """Fully-qualified `rfl` of `op x = x` must fail the pinned-statement hash.
+
+ The names match the challenge, so a disabled hash compare
+ (`if False and cand[name] != exp[name]`) lets this candidate through the guard
+ and this test fails.
+ """
+ comp = (
+ "Status: in progress.\n\n"
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (x : Nat) : CrtPair.op x = x := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (x : Nat) : CrtPair.op x = x := rfl\n"
+ "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_spoof_harness(), comp)
+ rules = {f["rule"] for f in findings}
+ expect_in("FAMILY_C_STATEMENT_MISMATCH", rules)
+ expect_false("LAKE_BUILD_FAILED" in rules, "a statement mismatch must return before lake")
+ expect_false("FAMILY_C_THEOREM_NAME_MISMATCH" in rules, rules)
+
+
+def test_family_c_missing_statement_pin_does_not_fall_back_to_identity() -> None:
+ harness = _family_c_spoof_harness()
+ del harness["spec_meta"]["statements"]
+ comp = (
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (x : Nat) : CrtPair.op x = x := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (x : Nat) : CrtPair.op x = x := rfl\n"
+ "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(harness, comp)
+ expect_in("FAMILY_C_TARGET_STATEMENT_ABSENT", {f["rule"] for f in findings})
+
+
+def test_family_c_known_bad_proof_reaches_lake_build() -> None:
+ """Run `lake build` on a statement-exact candidate whose proof does not elaborate.
+
+ Skips only when `lean` and `lake` are absent. The skip reason says the lake path was not exercised.
+ """
+ if not has_lean_toolchain():
+ pytest.skip(
+ "Lean 4.35.0 (`lean` and `lake`) is absent, so the Family C lake path was not exercised"
+ )
+ if not linux_bwrap_functional():
+ pytest.skip(
+ "functional Linux bwrap is absent, so the confined Family C lake build was not exercised"
+ )
+ comp = (
+ "Status: in progress.\n\n"
+ "```lean\n"
+ f"theorem CrtPair.Spec.crt_mod_left {_CRT_LEFT} := by\n exact Nat.noSuchLemma x\n"
+ f"theorem CrtPair.Spec.crt_mod_right {_CRT_RIGHT} := by\n exact Nat.noSuchLemma x\n"
+ "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_spoof_harness(), comp)
+ rules = {f["rule"] for f in findings}
+ expect_in("LAKE_BUILD_FAILED", rules)
+ blob = "\n".join(str(f.get("message", "")) for f in findings)
+ expect_in("noSuchLemma", blob)
+ expect_true(bool(re.search(r"\.lean:\d+:\d+", blob)), blob)
+
+
+_REFL_HEADER = "(n : Nat) : n = n"
+
+
+def _family_c_refl_harness() -> dict[str, Any]:
+ return {
+ "oracle_type": "bar_check",
+ "spec_meta": {
+ "pkg": "CrtPair",
+ "bar_status": "in-progress",
+ "test_cmd": "python3 tests/run_tests.py",
+ "theorem_names": ["CrtPair.Spec.crt_mod_left", "CrtPair.Spec.crt_mod_right"],
+ "statements": {
+ "CrtPair.Spec.crt_mod_left": _REFL_HEADER,
+ "CrtPair.Spec.crt_mod_right": _REFL_HEADER,
+ },
+ },
+ }
+
+
+def _family_c_refl_completion() -> str:
+ readme = (repo_root() / "datasets" / "targets" / "family_c" / "PUB-C-V01.md").read_text(encoding="utf-8")
+ return (
+ readme
+ + "\n```lean\n"
+ + "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ + "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ + "```\n"
+ )
+
+
+def test_family_c_correct_proof_passes_when_manifest_is_kept() -> None:
+ """A correct `rfl` proof yields no findings when the template manifest is kept.
+
+ `bar/check.py` item 3 fails closed without `lake-manifest.json`, including under
+ `--no-lean`. Deleting that file makes this test fail with `BAR_CHECK_FAILED`.
+ The test skips only when `lean` or the pinned `mission` checkout is absent.
+ """
+ if not has_lean_toolchain():
+ pytest.skip(
+ "Lean 4.35.0 (`lean` and `lake`) is absent, so the Family C correct-proof path was not exercised"
+ )
+ if not has_dep("mission"):
+ pytest.skip(
+ "pinned dependency 'mission' is absent, so the Family C bar path was not exercised"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_refl_completion())
+ expect_eq(findings, [], "a correct proof must not be rejected when lake-manifest.json is kept")
+
+
+def test_family_c_midline_theorem_counts_as_an_extra_name() -> None:
+ """A theorem that does not start a line is still part of the name set."""
+ comp = (
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ "def pad := 0 theorem Extra : True := trivial\n"
+ "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), comp)
+ rules = {f["rule"] for f in findings}
+ expect_in("FAMILY_C_THEOREM_NAME_MISMATCH", rules)
+ expect_true(any("Extra" in str(f.get("message", "")) for f in findings), findings)
+ expect_false("LAKE_BUILD_FAILED" in rules, findings)
+ expect_false("BAR_CHECK_FAILED" in rules, findings)
+
+
+def _family_c_block_lake(monkeypatch: pytest.MonkeyPatch) -> dict[str, bool]:
+ """Record a lake or comparator call and return no findings from either."""
+ called = {"lake": False}
+
+ def _no_lake(*_args: object, **_kwargs: object) -> list[dict[str, Any]]:
+ called["lake"] = True
+ return []
+
+ def _no_cmp(*_args: object, **_kwargs: object) -> Any:
+ called["lake"] = True
+ return type("Cmp", (), {"findings": ()})()
+
+ monkeypatch.setattr("mcproof.repair_loop._family_c_direct_lake_build", _no_lake)
+ monkeypatch.setattr("mcproof.repair_loop.verify_lean4_project_comparator", _no_cmp)
+ return called
+
+
+def test_family_c_midline_eval_commands_rejected_before_lake(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every command in the eval lint is rejected before `lake`, including mid-line.
+
+ The turn reads `FORBIDDEN_EVAL_COMMAND` itself. Putting the start-of-line
+ anchor back on that pattern lets these completions reach lake and this test fails.
+ A `#eval` or `#reduce` that sits in a comment or a string does not.
+ """
+ called = _family_c_block_lake(monkeypatch)
+ for command in ("#eval", "#reduce", "#check", "#print", "#synth"):
+ called["lake"] = False
+ comp = (
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ f"def pad := 0 {command} (1 : Nat)\n"
+ "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), comp)
+ rules = {f["rule"] for f in findings}
+ expect_false(called["lake"], f"lake ran for {command}: {findings}")
+ expect_in("FORBIDDEN_EVAL_COMMAND", rules, command)
+ expect_true(any(command in str(f.get("message", "")) for f in findings), findings)
+ expect_false("LAKE_BUILD_FAILED" in rules, findings)
+ decoy = (
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ "-- #eval IO.println \"x\"\n"
+ "def note := \"#reduce\"\n"
+ "```\n"
+ )
+ called["lake"] = False
+ decoy_findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), decoy)
+ decoy_rules = {f["rule"] for f in decoy_findings}
+ expect_false("FORBIDDEN_EVAL_COMMAND" in decoy_rules, decoy_findings)
+ if not _nofollow_dir_ops_available():
+ expect_in(_NOFOLLOW_OPEN_RULE, decoy_rules)
+ expect_false(called["lake"], decoy_findings)
+
+
+def test_family_c_raw_string_and_char_literal_do_not_hide_eval(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A real `#eval` after a raw string or a character literal is rejected before lake.
+
+ `r"\\"`, `r#"\\"#, `r###"\\"###`, `'"'`, and `'\\"'` used to desync the stripper,
+ so the command vanished from the pre-lake check and from the comparator lint.
+ Reverting the lexer makes `stripped` lose `#eval` and lets lake run.
+ """
+ called = _family_c_block_lake(monkeypatch)
+ snippets = (
+ 'def s := r"\\"\n#eval (1 : Nat)\n',
+ 'def s := r#"\\"#\n#eval (1 : Nat)\n',
+ 'def s := r###"\\"###\n#eval (1 : Nat)\n',
+ "def c := '\"'\n#eval (1 : Nat)\n",
+ "def c := '\\\"'\n#eval (1 : Nat)\n",
+ )
+ for snippet in snippets:
+ called["lake"] = False
+ stripped = strip_lean_comments_and_strings(snippet)
+ expect_in("#eval", stripped, snippet)
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(snippet))
+ rules = {f["rule"] for f in findings}
+ expect_false(called["lake"], f"lake ran for {snippet!r}: {findings}")
+ expect_in("FORBIDDEN_EVAL_COMMAND", rules, snippet)
+ expect_true(any("#eval" in str(f.get("message", "")) for f in findings), findings)
+ expect_false("LAKE_BUILD_FAILED" in rules, findings)
+
+
+def test_family_c_initializers_rejected_before_lake(monkeypatch: pytest.MonkeyPatch) -> None:
+ """`initialize`, `@[init]`, `builtin_initialize`, and `@[builtin_init]` never reach lake."""
+ called = _family_c_block_lake(monkeypatch)
+ cases = (
+ ("initialize do pure ()\n", "initialize"),
+ ("@[init] def pwnInit : IO Unit := pure ()\n", "@[init"),
+ ("builtin_initialize do pure ()\n", "builtin_initialize"),
+ ("@[builtin_init] def pwnBuilt : IO Unit := pure ()\n", "@[builtin_init"),
+ ("@[inline, init] def pwnInline : IO Unit := pure ()\n", "init"),
+ )
+ for snippet, needle in cases:
+ called["lake"] = False
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(snippet))
+ rules = {f["rule"] for f in findings}
+ expect_false(called["lake"], f"lake ran for {needle}: {findings}")
+ expect_in("FORBIDDEN_INITIALIZER", rules, needle)
+ expect_true(any(needle in str(f.get("message", "")) for f in findings), findings)
+ expect_false("LAKE_BUILD_FAILED" in rules, findings)
+
+
+def test_family_c_elab_commands_rejected_before_lake(monkeypatch: pytest.MonkeyPatch) -> None:
+ """`run_cmd`, `run_elab`, `run_tac`, and `elab` are rejected before the first lake build."""
+ called = _family_c_block_lake(monkeypatch)
+ cases = (
+ ("run_cmd pure ()\n", "run_cmd"),
+ ("run_elab pure ()\n", "run_elab"),
+ ("run_tac pure ()\n", "run_tac"),
+ ('elab "pwn" : command => pure ()\n', "elab"),
+ ("def pad := 0\nrun_cmd pure ()\n", "run_cmd"),
+ )
+ for snippet, needle in cases:
+ called["lake"] = False
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(snippet))
+ rules = {f["rule"] for f in findings}
+ expect_false(called["lake"], f"lake ran for {needle}: {findings}")
+ expect_in("FORBIDDEN_ELAB_COMMAND", rules, needle)
+ expect_true(any(needle in str(f.get("message", "")) for f in findings), findings)
+ expect_false("LAKE_BUILD_FAILED" in rules, findings)
+
+
+def test_family_c_banned_commands_inside_text_are_not_findings(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Comments, docstrings, strings, and README prose are not elaboration commands."""
+ called = _family_c_block_lake(monkeypatch)
+ comp = (
+ "The README mentions #eval, initialize, @[init], builtin_initialize, "
+ "run_cmd, run_elab, run_tac, and elab.\n\n"
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ "-- #eval initialize @[init] builtin_initialize run_cmd run_elab run_tac elab\n"
+ "/-- #eval initialize @[init] builtin_initialize run_cmd run_elab run_tac elab -/\n"
+ 'def note := "#eval initialize @[init] builtin_initialize run_cmd run_elab run_tac elab"\n'
+ 'def raw := r"#eval initialize @[init] run_cmd run_elab run_tac elab"\n'
+ "def ch := '\"'\n"
+ "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), comp)
+ rules = {f["rule"] for f in findings}
+ expect_false("FORBIDDEN_EVAL_COMMAND" in rules, findings)
+ expect_false("FORBIDDEN_INITIALIZER" in rules, findings)
+ expect_false("FORBIDDEN_ELAB_COMMAND" in rules, findings)
+ if not _nofollow_dir_ops_available():
+ expect_in(_NOFOLLOW_OPEN_RULE, rules)
+ expect_false(called["lake"], findings)
+
+
+def _family_c_with_theorems(snippet: str, *, prelude: str = "") -> str:
+ return (
+ "```lean\n"
+ + prelude
+ + "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ + "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ + snippet
+ + "```\n"
+ )
+
+
+def _skip_without_family_c_sandbox() -> None:
+ if not has_lean_toolchain():
+ pytest.skip(
+ "Lean 4.35.0 (`lean` and `lake`) is absent, so the Family C sandbox path was not exercised"
+ )
+ if not linux_bwrap_functional():
+ pytest.skip(
+ "Linux bwrap is missing or non-functional, so the Family C sandbox path was not exercised"
+ )
+
+
+def _expect_family_c_marker_absent(snippet: str, *, prelude: str = "") -> None:
+ """The host marker must stay absent. A passthrough sandbox writes it and this fails."""
+ marker = Path("/tmp") / f"mcproof-sandbox-marker-{uuid.uuid4().hex}"
+ marker.unlink(missing_ok=True)
+ body = snippet.replace("MARKER", str(marker))
+ try:
+ _run_family_c_real_lean_turn(
+ _family_c_refl_harness(),
+ _family_c_with_theorems(body, prelude=prelude),
+ )
+ expect_false(
+ marker.is_file(),
+ f"candidate wrote {marker}; the sandbox did not confine the build",
+ )
+ finally:
+ marker.unlink(missing_ok=True)
+
+
+def test_family_c_attribute_init_cannot_write_a_host_marker() -> None:
+ """`attribute [init]` runs when the axiom driver imports the built module.
+
+ The pre-lake regex only matches `@[`, so it does not keep this marker absent.
+ Disabling the sandbox lets the import write the host file and this test fails.
+ """
+ _skip_without_family_c_sandbox()
+ _expect_family_c_marker_absent(
+ 'def pwnInit : IO Unit := IO.FS.writeFile "MARKER" "p"\nattribute [init] pwnInit\n'
+ )
+
+
+def test_family_c_short_raw_string_cannot_write_a_host_marker() -> None:
+ """A raw string closed with fewer hashes hides `#eval` from the stripper.
+
+ The turn rejects that command before lake, so the marker stays absent.
+ Reaching the build makes the spy in the confinement test fail.
+ """
+ _skip_without_family_c_sandbox()
+ _expect_family_c_marker_absent(
+ 'def s := r##"foo"#\n#eval IO.FS.writeFile "MARKER" "p"\n'
+ )
+
+
+def test_family_c_lambda_and_sigma_raw_string_cannot_write_a_host_marker() -> None:
+ """`λ` and `Σ` hide a raw string from the stripper. Lean still runs the `#eval`."""
+ _skip_without_family_c_sandbox()
+ for snippet in (
+ 'def s := λr"\\"\n#eval IO.FS.writeFile "MARKER" "p"\n',
+ 'def s := Σr"\\"\n#eval IO.FS.writeFile "MARKER" "p"\n',
+ ):
+ _expect_family_c_marker_absent(snippet)
+
+
+def test_family_c_unclosed_char_literal_cannot_write_a_host_marker() -> None:
+ """An unclosed `'\"` hides the next `#eval`. Lean reports the error and still runs it."""
+ _skip_without_family_c_sandbox()
+ _expect_family_c_marker_absent(
+ 'def c := \'"\n#eval IO.FS.writeFile "MARKER" "p"\n'
+ )
+
+
+def test_family_c_interpolation_cannot_write_a_host_marker() -> None:
+ """`s!\"{\"}\"` hides the next `#eval`. Lean still runs it during the lake build."""
+ _skip_without_family_c_sandbox()
+ _expect_family_c_marker_absent(
+ 'def s := s!"{"}"\n#eval IO.FS.writeFile "MARKER" "p"\n'
+ )
+
+
+def test_family_c_run_meta_cannot_write_a_host_marker() -> None:
+ """`run_meta` runs in the first lake build, before the comparator flags it."""
+ _skip_without_family_c_sandbox()
+ _expect_family_c_marker_absent(
+ 'run_meta do IO.FS.writeFile "MARKER" "p"\n',
+ prelude="import Lean\n",
+ )
+
+
+def test_family_c_elab_rules_cannot_write_a_host_marker() -> None:
+ """`elab_rules` runs in the first lake build, before the comparator flags it."""
+ _skip_without_family_c_sandbox()
+ _expect_family_c_marker_absent(
+ 'syntax "pwn" : command\n'
+ "elab_rules : command\n"
+ ' | `(command| pwn) => do IO.FS.writeFile "MARKER" "p"\n'
+ "pwn\n",
+ prelude="import Lean\n",
+ )
+
+
+def test_family_c_refuses_candidate_build_when_sandbox_is_unavailable(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """A candidate build is refused when `bwrap` is unavailable. This needs neither Lean nor bwrap."""
+ monkeypatch.setattr("mcproof.repair_loop.linux_bwrap_functional", lambda **_kwargs: False)
+ monkeypatch.setattr("mcproof.lean_harness.linux_bwrap_functional", lambda **_kwargs: False)
+
+ def _refuse(cmd: object, *_args: object, **_kwargs: object) -> None:
+ raise AssertionError(f"candidate command ran without a sandbox: {cmd}")
+
+ monkeypatch.setattr(subprocess, "run", _refuse)
+ findings = _family_c_direct_lake_build(tmp_path)
+ rules = {f["rule"] for f in findings}
+ if _nofollow_dir_ops_available():
+ expect_eq(rules, {"SANDBOX_UNAVAILABLE"}, str(findings))
+ expect_true(any("unsandboxed" in str(f.get("message", "")) for f in findings), findings)
+ else:
+ expect_eq(rules, {_NOFOLLOW_OPEN_RULE}, str(findings))
+
+
+def test_family_c_compilable_elab_names_are_not_commands(monkeypatch: pytest.MonkeyPatch) -> None:
+ """`elab'`, `x.elab`, and `«elab»` compile. The bare-word ban must not reject them."""
+ called = _family_c_block_lake(monkeypatch)
+ for snippet in ("def elab' := 1\n", "def x.elab := 1\n", "def «elab» := 1\n", "def elab.foo := 1\n"):
+ called["lake"] = False
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), _family_c_with_theorems(snippet))
+ rules = {f["rule"] for f in findings}
+ expect_false("FORBIDDEN_ELAB_COMMAND" in rules, f"{snippet!r}: {findings}")
+ if _nofollow_dir_ops_available():
+ expect_true(called["lake"], f"{snippet!r} never reached the build: {findings}")
+ else:
+ expect_in(_NOFOLLOW_OPEN_RULE, rules)
+ expect_false(called["lake"], findings)
+
+
+def test_family_c_non_ascii_and_other_decls_count_as_extra_names(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """`«Extra»`, `α`, `café`, `instance`, `example`, and `abbrev` are extra names."""
+ called = _family_c_block_lake(monkeypatch)
+ cases = (
+ ("theorem «Extra» : True := trivial\n", "«Extra»"),
+ ("def pad := 0 theorem «Extra» : True := trivial\n", "«Extra»"),
+ ("theorem α : True := trivial\n", "α"),
+ ("def pad := 0 theorem α : True := trivial\n", "α"),
+ ("theorem café : True := trivial\n", "café"),
+ ("instance extraInst : Inhabited Unit := ⟨()⟩\n", "extraInst"),
+ ("def pad := 0 instance extraInst : Inhabited Unit := ⟨()⟩\n", "extraInst"),
+ ("example : True := trivial\n", "example"),
+ ("abbrev FooN := Nat\n", "FooN"),
+ )
+ for snippet, needle in cases:
+ called["lake"] = False
+ comp = (
+ "```lean\n"
+ "theorem CrtPair.Spec.crt_mod_left (n : Nat) : n = n := rfl\n"
+ "theorem CrtPair.Spec.crt_mod_right (n : Nat) : n = n := rfl\n"
+ + snippet
+ + "```\n"
+ )
+ findings = _run_family_c_real_lean_turn(_family_c_refl_harness(), comp)
+ rules = {f["rule"] for f in findings}
+ expect_false(called["lake"], f"lake ran for {needle}: {findings}")
+ expect_in("FAMILY_C_THEOREM_NAME_MISMATCH", rules, needle)
+ expect_true(any(needle in str(f.get("message", "")) for f in findings), findings)
+ expect_false("LAKE_BUILD_FAILED" in rules, findings)
+
+
+def test_grade_item_pins_statements_and_refuses_identity_scaffold() -> None:
+ script = repo_root() / "datasets" / "scripts" / "grade_item.py"
+ spec = importlib.util.spec_from_file_location("grade_item_under_test", script)
+ expect_true(spec is not None and spec.loader is not None, "grade_item.py failed to load")
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod) # type: ignore[union-attr]
+ harness = _family_c_spoof_harness()
+ bare = json.loads(json.dumps(harness))
+ del bare["spec_meta"]["statements"]
+ ok, errs = mod._run_family_c_structural_replay(bare, "Status: in progress.\n")
+ expect_false(ok, errs)
+ expect_true(any("target_statements_absent" in err for err in errs), errs)
+ readme = (repo_root() / "datasets" / "targets" / "family_c" / "PUB-C-V01.md").read_text(encoding="utf-8")
+ ok_pinned, pinned_errs = mod._run_family_c_structural_replay(harness, readme)
+ mission_check = mod.DEPS_ROOT / "mission" / "bar" / "check.py"
+ if not mission_check.is_file():
+ expect_false(ok_pinned, pinned_errs)
+ expect_true(any("missing_mission_dep" in err for err in pinned_errs), pinned_errs)
+ return
+ expect_true(ok_pinned, pinned_errs)
+ spec_src = mod._family_c_spec_source("CrtPair", harness["spec_meta"]["statements"])
+ expect_in("Dvd.dvd (m1 * m2) (x - y)", spec_src)
+ expect_false("op x = x" in spec_src, spec_src)
+ lake = mod._family_c_lakefile("CrtPair")
+ expect_in('"CrtPair.Spec"', lake)
+ expect_in('"CrtPair.Proofs"', lake)
+ expect_false(lake.split("defaultTargets = ", 1)[1].startswith('["CrtPair"]\n'), lake)
diff --git a/tests/test_lean_harness.py b/tests/test_lean_harness.py
index 64d0787..9213bba 100644
--- a/tests/test_lean_harness.py
+++ b/tests/test_lean_harness.py
@@ -129,7 +129,7 @@ def test_reference_lean_project_passes_six_kernel_comparator() -> None:
if not linux_bwrap_functional():
pytest.skip(
"Linux bwrap is missing or non-functional on this host "
- "(minimal `bwrap --ro-bind / / true` or lake `/run/user` session probe failed)"
+ "(the confinement probe rejected the sandbox)"
)
res = verify_lean4_project_comparator(repo_root() / "lean", allow_unsandboxed=False)
expect_true(res.passed, f"reference lean project failed: {res.findings}")
diff --git a/tests/test_pr16_hardening_and_issue12.py b/tests/test_pr16_hardening_and_issue12.py
new file mode 100644
index 0000000..f72fbe4
--- /dev/null
+++ b/tests/test_pr16_hardening_and_issue12.py
@@ -0,0 +1,1083 @@
+"""Comprehensive regression and guard-coverage suite for PR #16 hardening and Issue #12.
+
+Every guard introduced in `domain_protocol.py` and `repair_loop.py` is paired with an
+accepted positive control and a failing negative variant asserting exact rule names,
+covering 100% of named rules in `domain_protocol.py` and every Issue #12 stopping,
+gap-accounting, eligibility, and checkpoint-invalidation path.
+"""
+
+from __future__ import annotations
+
+from fractions import Fraction
+import io
+import json
+from pathlib import Path
+import sys
+from typing import Any, Mapping
+
+import pytest
+
+from mcproof.cli import main as cli_main
+from mcproof.domain_protocol import (
+ audit_portfolio_bounds,
+ audit_transition_certificate,
+ run_restricted_sandbox_cell,
+ verify_dual_product_parity,
+ verify_minimal_goal_stopping,
+ verify_rational_lp_certificate,
+)
+from mcproof.repair_loop import (
+ evaluate_early_stop_eligibility,
+ run_repair_item,
+ run_repair_split,
+ summarize_oracle_grader_gap,
+)
+
+from helpers import expect_eq, expect_false, expect_in, expect_true
+
+HEX64 = "a" * 64
+HEX64_B = "b" * 64
+HEX64_C = "c" * 64
+ZEROS64 = "0" * 64
+TYPE_RULE = "CERT_FIELD_TYPE_INVALID"
+
+
+def _verified(**extra: Any) -> dict[str, Any]:
+ cert: dict[str, Any] = {
+ "epistemic_status": "VERIFIED",
+ "witness_or_proof_sha256": HEX64,
+ "tcb_pins": {"tcb_manifest_verified": True, "checker_sha256": HEX64},
+ }
+ cert.update(extra)
+ return cert
+
+
+def _rules(rep: Mapping[str, Any]) -> list[str]:
+ return [str(f["rule"]) for f in rep.get("findings", ())]
+
+
+def _expect_only_rule(cert: Mapping[str, Any], rule: str, **kwargs: Any) -> None:
+ rep = audit_transition_certificate(cert, **kwargs)
+ expect_false(rep["passed"], f"expected {rule} rejection, got {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_eq(_rules(rep), [rule], f"expected solely {rule}, got {rep}")
+
+
+def _expect_rejected_with(cert: Mapping[str, Any], rule: str, **kwargs: Any) -> None:
+ rep = audit_transition_certificate(cert, **kwargs)
+ expect_false(rep["passed"], f"expected {rule} rejection, got {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_in(rule, _rules(rep))
+
+
+def _expect_accepted(cert: Mapping[str, Any], expected_status: str = "VERIFIED", **kwargs: Any) -> None:
+ rep = audit_transition_certificate(cert, **kwargs)
+ expect_true(rep["passed"], f"valid cert rejected: {rep}")
+ expect_eq(rep["epistemic_status"], expected_status)
+
+
+# ---------------------------------------------------------------------------
+# 1. Sandbox injected_globals validation (domain_protocol.py:422-435)
+# ---------------------------------------------------------------------------
+
+
+def test_sandbox_injected_globals_rejects_trailing_newline_and_bad_keys() -> None:
+ ok_res = run_restricted_sandbox_cell("print(x_1 + 1)", injected_globals={"x_1": 41})
+ expect_true(ok_res["ok"], f"valid injected_globals failed: {ok_res}")
+ expect_eq(ok_res["stdout"].strip(), "42")
+
+ for bad_key in ("x\n", "1bad", "a;import os", "", "a" * 65, 7):
+ res = run_restricted_sandbox_cell("print(1)", injected_globals={bad_key: 1}) # type: ignore[dict-item]
+ expect_false(res["ok"], f"bad key {bad_key!r} should be rejected")
+ expect_true(res["ast_rejected"])
+ expect_eq(res["returncode"], 2)
+ expect_true(any("invalid_injected_global_key" in v for v in res["violations"]))
+
+
+# ---------------------------------------------------------------------------
+# 2. Portfolio bounds hardening (domain_protocol.py:600-675)
+# ---------------------------------------------------------------------------
+
+
+def test_portfolio_bounds_empty_types_transitivity_and_whitespace_status() -> None:
+ # Empty / non-sequence inputs fail closed with CERT_PORTFOLIO_EMPTY
+ for bad_items in ([], "", b"abc", None):
+ rep = audit_portfolio_bounds(bad_items) # type: ignore[arg-type]
+ expect_false(rep["passed"])
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_eq(_rules(rep), ["CERT_PORTFOLIO_EMPTY"])
+
+ # Valid registered item passes cleanly
+ ok_rep = audit_portfolio_bounds(
+ [{"id": "P1", "proven_floor": 5, "shortest_known": 6, "live_record": 7, "epistemic_status": "VERIFIED"}],
+ registered_verified_ids=frozenset({"P1"}),
+ )
+ expect_true(ok_rep["passed"], str(ok_rep))
+ expect_eq(ok_rep["items"][0]["epistemic_status"], "VERIFIED")
+
+ # Unregistered non-VERIFIED item is triaged without error
+ unreg_ok = audit_portfolio_bounds(
+ [{"id": "P2", "proven_floor": 5, "shortest_known": 6, "epistemic_status": "LOWER_BOUND"}],
+ registered_verified_ids=frozenset(),
+ )
+ expect_true(unreg_ok["passed"], str(unreg_ok))
+ expect_eq(unreg_ok["items"][0]["epistemic_status"], "UNVERIFIED_CALLER_BOUNDS")
+
+ # Non-mapping item rejected with CERT_FIELD_TYPE_INVALID
+ bad_row = audit_portfolio_bounds(["not_an_object"]) # type: ignore[list-item]
+ expect_false(bad_row["passed"])
+ expect_eq(_rules(bad_row), [TYPE_RULE])
+
+ # Non-count bounds and non-str epistemic_status rejected with CERT_FIELD_TYPE_INVALID
+ for bad_field in (
+ {"id": "B1", "proven_floor": True},
+ {"id": "B2", "shortest_known": -1},
+ {"id": "B3", "live_record": "5"},
+ {"id": "B4", "epistemic_status": 123},
+ ):
+ rep = audit_portfolio_bounds([bad_field])
+ expect_false(rep["passed"], f"accepted bad field {bad_field}")
+ expect_eq(_rules(rep), [TYPE_RULE])
+ expect_eq(rep["items"][0]["epistemic_status"], "REJECTED_INVALID_BOUND_TYPE")
+
+ # All three inversion pairs: p_floor > s_known, s_known > l_rec, p_floor > l_rec (s_known omitted)
+ for inv_row in (
+ {"id": "I1", "proven_floor": 10, "shortest_known": 9},
+ {"id": "I2", "shortest_known": 10, "live_record": 9},
+ {"id": "I3", "proven_floor": 10, "live_record": 9},
+ ):
+ rep = audit_portfolio_bounds([inv_row], registered_verified_ids=frozenset({inv_row["id"]}))
+ expect_false(rep["passed"], f"accepted inverted bounds {inv_row}")
+ expect_eq(_rules(rep), ["CERT_F07_INCONSISTENT_PORTFOLIO_BOUNDS"])
+
+ # Whitespace-padded VERIFIED / PROVEN on unregistered ID fails closed!
+ for padded in (" VERIFIED", "VERIFIED ", "\tPROVEN\n", " proven "):
+ rep = audit_portfolio_bounds(
+ [{"id": "UNREG", "proven_floor": 5, "shortest_known": 5, "epistemic_status": padded}],
+ registered_verified_ids=frozenset(),
+ )
+ expect_false(rep["passed"], f"whitespace status {padded!r} bypassed F-07")
+ expect_eq(_rules(rep), ["CERT_F07_UNVERIFIED_CALLER_BOUNDS"])
+
+
+# ---------------------------------------------------------------------------
+# 3. Blank Unicode, dual witness keys, nested empty containers, A6, F01, F03, F08
+# ---------------------------------------------------------------------------
+
+
+def test_blank_unicode_rejected_across_witness_engines_controls_and_known_citation() -> None:
+ # Positive control: NFD accented text has a visible base letter + combining mark (Mn) and must pass
+ _expect_accepted(_verified(witness="e\u0301", proven_floor=2))
+ _expect_accepted(_verified(differential_match=True, oracles_checked=["engine_a", "e\u0301"]))
+
+ blank_tokens = (
+ "\u2800", # Braille Pattern Blank
+ "\u3164", # Hangul Filler
+ "\uffa0", # Halfwidth Hangul Filler
+ "\u00ad", # Soft Hyphen (Cf)
+ "\u200b", # Zero-Width Space (Cf)
+ "\u00a0", # No-Break Space (Zs)
+ "\u2028", # Line Separator (Zl)
+ "\u034f", # Combining Grapheme Joiner (Mn)
+ "\ufe00", # Variation Selector-1 (Mn)
+ "\ufe0f", # Variation Selector-16 (Mn)
+ "\U000e0100", # Variation Selector Supplement-17 (Mn)
+ "\u180b", # Mongolian Free Variation Selector One (Mn)
+ "\u0301", # Standalone Combining Acute Accent (Mn)
+ )
+ for tok in blank_tokens:
+ # Witness string & list element
+ _expect_only_rule(_verified(witness=tok, proven_floor=1), "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+ _expect_rejected_with(_verified(witness=[tok], proven_floor=1), "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+ _expect_rejected_with(_verified(witness=[tok], proven_floor=1), TYPE_RULE)
+
+ # Differential engine lists
+ _expect_rejected_with(
+ _verified(differential_match=True, oracles_checked=["engine_a", tok]),
+ TYPE_RULE,
+ )
+ _expect_rejected_with(
+ _verified(differential_match=True, oracles_checked=["engine_a", tok]),
+ "CERT_SINGLE_ORACLE_DIFFERENTIAL",
+ )
+
+ # Control names in must_fail_controls & control_records
+ _expect_rejected_with(
+ _verified(
+ must_fail_controls=[tok],
+ control_records=[{"name": tok, "oracle_invoked": True, "unexpectedly_passed": False}],
+ ),
+ "CERT_A6_MISSING_OR_DUPLICATE_CONTROLS",
+ )
+ _expect_rejected_with(
+ _verified(
+ must_fail_controls=["c1"],
+ control_records=[{"name": tok, "oracle_invoked": True, "unexpectedly_passed": False}],
+ ),
+ TYPE_RULE,
+ )
+
+ # KNOWN citation fields
+ _expect_only_rule(
+ {
+ "epistemic_status": "KNOWN",
+ "citation": {"source": tok, "reference": "ref-1", "artifact_sha256": HEX64},
+ },
+ "CERT_KNOWN_CITATION_MISSING",
+ )
+
+
+def test_dual_witness_keys_and_nested_empty_containers_fail_closed() -> None:
+ # Both present & valid & matching proven_floor -> accepted
+ _expect_accepted(_verified(witness="U", winning_witness="U", proven_floor=1))
+ _expect_accepted(_verified(witness=[{"move": "U", "step": 1}], proven_floor=1))
+
+ # Dual witness keys: one valid + one empty / null / blank -> rejected!
+ for bad_dual in (
+ _verified(witness="U", winning_witness="", proven_floor=1),
+ _verified(witness="", winning_witness="U", proven_floor=1),
+ _verified(witness="U", winning_witness=None, proven_floor=1),
+ _verified(witness="U", winning_witness="\u2800", proven_floor=1),
+ ):
+ _expect_only_rule(bad_dual, "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+
+ # Dual witness keys: length disagreement against proven_floor -> CERT_WITNESS_FLOOR_MISMATCH
+ _expect_only_rule(_verified(witness="U", winning_witness="UU", proven_floor=1), "CERT_WITNESS_FLOOR_MISMATCH")
+
+ # Empty and nested-empty container list witnesses fail closed!
+ for bad_list_witness in (
+ [],
+ [[]],
+ [{}],
+ [[], {}],
+ [[[]]],
+ [{"a": ""}],
+ [{"a": []}],
+ [{"\u2800": 1}],
+ [{"a": None}],
+ [{"a": True}],
+ [None],
+ [True],
+ [1.5], # intentional negative control: float step forbidden
+ ):
+ cert = _verified(witness=bad_list_witness, proven_floor=1)
+ _expect_rejected_with(cert, "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+ if len(bad_list_witness) > 0:
+ _expect_rejected_with(cert, TYPE_RULE)
+
+ # Non-string, non-list witness, non-JSON element, and over-deep nested witness (>16) fail closed
+ _expect_rejected_with(_verified(witness=123, proven_floor=1), TYPE_RULE)
+ _expect_rejected_with(_verified(witness=[object()], proven_floor=1), TYPE_RULE)
+ deep_w: Any = "U"
+ for _ in range(18):
+ deep_w = [deep_w]
+ _expect_rejected_with(_verified(witness=deep_w, proven_floor=1), TYPE_RULE)
+
+
+def test_a6_must_fail_controls_omitted_control_records_and_tautological_omissions(
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
+) -> None:
+ # Good control coverage passes
+ good = _verified(
+ must_fail_controls=["c1", "c2"],
+ control_records=[
+ {"name": "c1", "oracle_invoked": True, "unexpectedly_passed": False},
+ {"name": "c2", "oracle_invoked": True, "unexpectedly_passed": False},
+ ],
+ )
+ _expect_accepted(good)
+
+ # Partial control_records misses c2
+ _expect_only_rule(
+ _verified(
+ must_fail_controls=["c1", "c2"],
+ control_records=[{"name": "c1", "oracle_invoked": True, "unexpectedly_passed": False}],
+ ),
+ "CERT_A6_CONTROL_COVERAGE_INCOMPLETE",
+ )
+
+ # Omitted control_records entirely when must_fail_controls is declared -> fails closed EVEN without require_must_fail_controls!
+ omitted_crecs = _verified(must_fail_controls=["c1"])
+ _expect_only_rule(omitted_crecs, "CERT_A6_CONTROL_COVERAGE_INCOMPLETE")
+
+ # Same payload via `mcproof audit-cert` CLI (`cli.py:363`) fails closed with exit code 1!
+ monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(omitted_crecs)))
+ rc = cli_main(["--json", "audit-cert", "-"])
+ out = json.loads(capsys.readouterr().out)
+ expect_eq(rc, 1)
+ expect_eq(out["epistemic_status"], "REJECTED")
+ expect_in("CERT_A6_CONTROL_COVERAGE_INCOMPLETE", [f["rule"] for f in out["findings"]])
+
+ # Control record omitting oracle_invoked or unexpectedly_passed -> CERT_A6_TAUTOLOGICAL_CONTROL
+ _expect_only_rule(
+ _verified(must_fail_controls=["c1"], control_records=[{"name": "c1", "unexpectedly_passed": False}]),
+ "CERT_A6_TAUTOLOGICAL_CONTROL",
+ )
+ _expect_only_rule(
+ _verified(must_fail_controls=["c1"], control_records=[{"name": "c1", "oracle_invoked": True}]),
+ "CERT_A6_TAUTOLOGICAL_CONTROL",
+ )
+
+
+def test_f01_all_present_oracle_lists_f03_all_present_tcb_pins_and_f08_instance_digests() -> None:
+ # F-01: every present oracle list must have >= 2 distinct visible engines
+ _expect_accepted(
+ _verified(differential_match=True, oracles_checked=["a", "b"], engines_verified=["x", "y"])
+ )
+ _expect_only_rule(
+ _verified(differential_match=True, oracles_checked=["a", "b"], engines_verified=["x", "x"]),
+ "CERT_SINGLE_ORACLE_DIFFERENTIAL",
+ )
+ _expect_only_rule(
+ _verified(differential_match=True),
+ "CERT_SINGLE_ORACLE_DIFFERENTIAL",
+ )
+ _expect_rejected_with(
+ _verified(differential_match=True, checkers_executed="not_a_list"),
+ TYPE_RULE,
+ )
+
+ # F-03: every present checker digest key in tcb_pins must be valid non-zero 64-hex (no trailing newline!)
+ _expect_accepted(
+ _verified(
+ tcb_pins={
+ "tcb_manifest_verified": True,
+ "checker_sha256": HEX64,
+ "checker_auditor_py_sha256": HEX64_B,
+ }
+ )
+ )
+ for bad_digest in (ZEROS64, HEX64 + "\n", "A" * 64, "short"):
+ _expect_only_rule(
+ _verified(
+ tcb_pins={
+ "tcb_manifest_verified": True,
+ "checker_sha256": HEX64,
+ "checker_auditor_py_sha256": bad_digest,
+ }
+ ),
+ "CERT_TCB_MANIFEST_UNLOCKED",
+ )
+
+ # F-08: witness_or_proof_sha256 rejects all-zeros and trailing newline
+ for bad_wsha in (ZEROS64, HEX64 + "\n"):
+ _expect_only_rule(_verified(witness_or_proof_sha256=bad_wsha), "CERT_INVALID_WITNESS_SHA256")
+
+ # Instance digest format checks reject all-zeros, uppercase, short, and trailing newline
+ _expect_accepted(_verified(instance_sha256=HEX64_B, canonical_instance_sha256=HEX64_B))
+ for bad_idig in (ZEROS64, HEX64 + "\n", "B" * 64, "abc", ""):
+ _expect_only_rule(_verified(instance_sha256=bad_idig), "CERT_INSTANCE_DIGEST_MALFORMED")
+ _expect_only_rule(_verified(canonical_instance_sha256=bad_idig), "CERT_INSTANCE_DIGEST_MALFORMED")
+
+ # certified_lower_bound type guard + F-05 incomplete graph
+ _expect_accepted(_verified(certified_lower_bound=5, complete_space=True))
+ _expect_only_rule(_verified(certified_lower_bound=5, complete_space=False), "CERT_TRUNCATED_INDUCTIVE_POTENTIAL")
+ _expect_rejected_with(_verified(certified_lower_bound=-1, complete_space=True), TYPE_RULE)
+ _expect_rejected_with(_verified(certified_lower_bound=True, complete_space=True), TYPE_RULE)
+
+
+# ---------------------------------------------------------------------------
+# 4. Complete coverage of remaining domain_protocol.py rules (100% of 47 rules)
+# ---------------------------------------------------------------------------
+
+
+def test_verify_dual_product_parity_covers_all_f05_and_f06_rules() -> None:
+ def _base(**overrides: Any) -> dict[str, Any]:
+ kw: dict[str, Any] = {
+ "spec_init": 0,
+ "impl_init": 0,
+ "spec_actions": lambda s: [1] if s < 2 else [],
+ "impl_actions": lambda u: [1] if u < 2 else [],
+ "spec_step": lambda s, a: s + a,
+ "impl_step": lambda u, a: u + a,
+ "spec_invariant": lambda s: 0 <= s <= 2,
+ "impl_invariant": lambda u: 0 <= u <= 2,
+ "spec_is_goal": lambda s: s == 2,
+ "impl_is_goal": lambda u: u == 2,
+ "spec_obs": lambda s: s,
+ "impl_obs": lambda u: u,
+ "max_product_states": 100,
+ }
+ kw.update(overrides)
+ return verify_dual_product_parity(**kw)
+
+ ok = _base()
+ expect_true(ok["passed"])
+ expect_eq(ok["epistemic_status"], "PROVEN")
+
+ obs_bad = _base(impl_obs=lambda u: u + 10)
+ expect_false(obs_bad["passed"])
+ expect_eq(_rules(obs_bad), ["F06_OBSERVATION_DIVERGENCE"])
+
+ goal_bad = _base(impl_is_goal=lambda u: u == 1)
+ expect_false(goal_bad["passed"])
+ expect_eq(_rules(goal_bad), ["F06_GOAL_PARITY_MISMATCH"])
+
+ act_bad = _base(impl_actions=lambda u: [1, 2] if u == 0 else [])
+ expect_false(act_bad["passed"])
+ expect_eq(_rules(act_bad), ["F06_ACTION_SET_MISMATCH"])
+
+ trunc = _base(max_product_states=1)
+ expect_false(trunc["passed"])
+ expect_eq(trunc["epistemic_status"], "REJECTED_INCOMPLETE_PRODUCT_SPACE")
+ expect_eq(_rules(trunc), ["F05_INCOMPLETE_PRODUCT_GRAPH"])
+
+
+def test_verify_minimal_goal_stopping_covers_invalid_step_and_goal_not_reached() -> None:
+ bad_step = verify_minimal_goal_stopping(
+ init_state=0,
+ actions=[1, 99],
+ step_fn=lambda s, a: None if a == 99 else s + a,
+ is_goal_fn=lambda s: s == 2,
+ )
+ expect_false(bad_step["passed"])
+ expect_eq(_rules(bad_step), ["CERT_INVALID_TRANSITION_STEP"])
+
+ not_reached = verify_minimal_goal_stopping(
+ init_state=0,
+ actions=[1],
+ step_fn=lambda s, a: s + a,
+ is_goal_fn=lambda s: s == 2,
+ )
+ expect_false(not_reached["passed"])
+ expect_eq(_rules(not_reached), ["CERT_GOAL_NOT_REACHED"])
+
+
+def test_verify_rational_lp_certificate_covers_every_rule_and_guard() -> None:
+ # Valid bounds certificate
+ ok_bounds = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": [[1, 1]], "b": [5], "c": [1, 1], "y": [1], "claimed_lower_bound": 5}
+ )
+ expect_true(ok_bounds["passed"])
+
+ # Valid Farkas infeasibility certificate: A=[[-1]], b=[1], y=[1] => y^T A = [-1] <= 0, y^T b = 1 > 0
+ ok_farkas = verify_rational_lp_certificate({"mode": "infeasible", "A": [[-1]], "b": [1], "y": [1]})
+ expect_true(ok_farkas["passed"])
+
+ # LP_CERT_NOT_AN_OBJECT
+ for non_obj in ([], None, "bounds", 42):
+ rep = verify_rational_lp_certificate(non_obj) # type: ignore[arg-type]
+ expect_false(rep["passed"])
+ expect_eq(_rules(rep), ["LP_CERT_NOT_AN_OBJECT"])
+
+ # LP_CERT_MALFORMED (non-str mode, non-list A/b/y/c, non-list row in A, missing key, float/bool)
+ for malformed in (
+ {"mode": 7, "A": [[1]], "b": [1], "y": [1], "c": [1], "claimed_lower_bound": 1},
+ {"mode": "bounds", "A": "not_list", "b": [1], "y": [1], "c": [1], "claimed_lower_bound": 1},
+ {"mode": "bounds", "A": ["1"], "b": [1], "y": [1], "c": [1], "claimed_lower_bound": 1},
+ {"mode": "bounds", "A": [[1]], "b": [1], "y": [1], "c": "1", "claimed_lower_bound": 1},
+ {"mode": "bounds", "A": [[1]], "b": [1], "y": [1]},
+ ):
+ rep = verify_rational_lp_certificate(malformed)
+ expect_false(rep["passed"], f"accepted malformed LP cert {malformed}")
+ expect_eq(_rules(rep), ["LP_CERT_MALFORMED"])
+
+ # LP_CERT_EMPTY_SYSTEM
+ for empty_a in ([], [[]]):
+ rep = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": empty_a, "b": [], "c": [], "y": [], "claimed_lower_bound": 0}
+ )
+ expect_false(rep["passed"])
+ expect_eq(_rules(rep), ["LP_CERT_EMPTY_SYSTEM"])
+
+ # LP_CERT_DIMENSION_MISMATCH (b/y/jagged A/c)
+ for bad_dim in (
+ {"mode": "bounds", "A": [[1, 1]], "b": [1, 2], "c": [1, 1], "y": [1], "claimed_lower_bound": 1},
+ {"mode": "bounds", "A": [[1, 1], [1]], "b": [1, 1], "c": [1, 1], "y": [1, 1], "claimed_lower_bound": 1},
+ {"mode": "bounds", "A": [[1, 1]], "b": [1], "c": [1], "y": [1], "claimed_lower_bound": 1},
+ ):
+ rep = verify_rational_lp_certificate(bad_dim)
+ expect_false(rep["passed"])
+ expect_in("LP_CERT_DIMENSION_MISMATCH", _rules(rep))
+
+ # LP_DUAL_NEGATIVE_MULTIPLIER
+ neg_y = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": [[1]], "b": [-1], "c": [1], "y": [-1], "claimed_lower_bound": 0}
+ )
+ expect_false(neg_y["passed"])
+ expect_in("LP_DUAL_NEGATIVE_MULTIPLIER", _rules(neg_y))
+
+ # LP_DUAL_INFEASIBLE_COLUMN (y^T A = 2 > c = 1)
+ infeas_col = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": [[2]], "b": [1], "c": [1], "y": [1], "claimed_lower_bound": 1}
+ )
+ expect_false(infeas_col["passed"])
+ expect_eq(_rules(infeas_col), ["LP_DUAL_INFEASIBLE_COLUMN"])
+
+ # LP_DUAL_OBJECTIVE_BELOW_CLAIM (y^T b = 1 < claim = 2)
+ below = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": [[1]], "b": [1], "c": [1], "y": [1], "claimed_lower_bound": 2}
+ )
+ expect_false(below["passed"])
+ expect_eq(_rules(below), ["LP_DUAL_OBJECTIVE_BELOW_CLAIM"])
+
+ # LP_FARKAS_POSITIVE_COLUMN (y^T A = [1] > 0)
+ farkas_pos = verify_rational_lp_certificate({"mode": "infeasible", "A": [[1]], "b": [1], "y": [1]})
+ expect_false(farkas_pos["passed"])
+ expect_eq(_rules(farkas_pos), ["LP_FARKAS_POSITIVE_COLUMN"])
+
+ # LP_FARKAS_NONPOSITIVE_WITNESS (y^T b = 0 <= 0)
+ farkas_zero = verify_rational_lp_certificate({"mode": "infeasible", "A": [[-1]], "b": [0], "y": [1]})
+ expect_false(farkas_zero["passed"])
+ expect_eq(_rules(farkas_zero), ["LP_FARKAS_NONPOSITIVE_WITNESS"])
+
+ # LP_CERT_UNSUPPORTED_MODE
+ bad_mode = verify_rational_lp_certificate({"mode": "primal_magic", "A": [[1]], "b": [1], "y": [1]})
+ expect_false(bad_mode["passed"])
+ expect_eq(_rules(bad_mode), ["LP_CERT_UNSUPPORTED_MODE"])
+
+
+# ---------------------------------------------------------------------------
+# 5. Repair loop Issue #12: subtier stopping, retention, gap, eligibility, checkpoints
+# ---------------------------------------------------------------------------
+
+
+def test_repair_loop_default_preserves_backward_compat_and_forbid_subtier_retains_best_turn() -> None:
+ item = {"id": "WIT-B-01", "family": "B", "prompt": "Write exact checker"}
+ lint_oracle = lambda _pv, _c: {"passed": True, "epistemic_status": "LINT_PASS", "findings": []}
+ turn1_only_grader = lambda _it, c: {"passed": c == "cand_1", "findings": []}
+ gen = lambda _p, t: f"cand_{t}"
+
+ # Default forbid_subtier_early_stop=False preserves backward-compatible turn-1 stop
+ default_res = run_repair_item(
+ item,
+ gen,
+ max_turns=4,
+ inference_oracle_fn=lint_oracle,
+ eval_grader_fn=turn1_only_grader,
+ include_plane1_retrieval=False,
+ )
+ expect_eq(default_res["turns_used"], 1)
+ expect_true(default_res["passed"])
+ expect_true(default_res["inference_certified"])
+ expect_false(default_res["forbid_subtier_early_stop"])
+
+ # Opt-in forbid_subtier_early_stop=True blocks subtier stop AND retains best oracle-passing turn (turn 1)
+ strict_res = run_repair_item(
+ item,
+ gen,
+ max_turns=4,
+ inference_oracle_fn=lint_oracle,
+ eval_grader_fn=turn1_only_grader,
+ include_plane1_retrieval=False,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(strict_res["turns_used"], 4)
+ expect_false(strict_res["inference_certified"])
+ expect_eq(strict_res["best_oracle_pass_turn"], 1)
+ expect_true(strict_res["pass_at_1"])
+ expect_true(strict_res["pass_at_2"])
+ expect_true(strict_res["pass_at_3"])
+ expect_true(strict_res["pass_at_4"])
+ expect_true(strict_res["passed"])
+ expect_eq(strict_res["refuted_routes"], [])
+
+ # When a later turn upgrades from LINT_PASS to VERIFIED, strict mode stops and deploys the upgraded turn
+ upgrade_oracle = lambda _pv, c: {
+ "passed": True,
+ "epistemic_status": "VERIFIED" if c == "cand_3" else "LINT_PASS",
+ "findings": [],
+ }
+ turn3_grader = lambda _it, c: {"passed": c == "cand_3", "findings": []}
+ up_res = run_repair_item(
+ item,
+ gen,
+ max_turns=4,
+ inference_oracle_fn=upgrade_oracle,
+ eval_grader_fn=turn3_grader,
+ include_plane1_retrieval=False,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(up_res["turns_used"], 3)
+ expect_true(up_res["inference_certified"])
+ expect_eq(up_res["inference_certified_at_turn"], 3)
+ expect_false(up_res["pass_at_1"])
+ expect_false(up_res["pass_at_2"])
+ expect_true(up_res["pass_at_3"])
+ expect_true(up_res["passed"])
+
+ # Even with allow_early_stop=False, a later VERIFIED turn outranks an earlier LINT_PASS turn
+ no_stop_up = run_repair_item(
+ item,
+ gen,
+ max_turns=4,
+ inference_oracle_fn=upgrade_oracle,
+ eval_grader_fn=turn3_grader,
+ include_plane1_retrieval=False,
+ allow_early_stop=False,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(no_stop_up["turns_used"], 4)
+ expect_false(no_stop_up["inference_certified"])
+ expect_eq(no_stop_up["best_oracle_pass_turn"], 3)
+ expect_false(no_stop_up["pass_at_1"])
+ expect_false(no_stop_up["pass_at_2"])
+ expect_true(no_stop_up["pass_at_3"])
+ expect_true(no_stop_up["passed"])
+
+ # PROVEN also stops early under forbid_subtier_early_stop=True; missing/unknown status does NOT
+ proven_res = run_repair_item(
+ item,
+ gen,
+ max_turns=3,
+ inference_oracle_fn=lambda _pv, _c: {"passed": True, "epistemic_status": "PROVEN", "findings": []},
+ eval_grader_fn=turn1_only_grader,
+ include_plane1_retrieval=False,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(proven_res["turns_used"], 1)
+ expect_true(proven_res["inference_certified"])
+
+ missing_status_res = run_repair_item(
+ item,
+ gen,
+ max_turns=3,
+ inference_oracle_fn=lambda _pv, _c: {"passed": True, "findings": []},
+ eval_grader_fn=turn1_only_grader,
+ include_plane1_retrieval=False,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(missing_status_res["turns_used"], 3)
+ expect_false(missing_status_res["inference_certified"])
+ expect_true(missing_status_res["passed"])
+
+
+def test_repair_split_gap_counting_eligibility_wiring_and_checkpoint_invalidation(tmp_path: Path) -> None:
+ items = [
+ {"id": "A-1", "family": "A", "prompt": "Prove A"},
+ {"id": "B-1", "family": "B", "prompt": "Check B1"},
+ {"id": "B-2", "family": "B", "prompt": "Check B2"},
+ ]
+ calls: list[str] = []
+
+ def _gen(prompt: str, turn_idx: int) -> str:
+ calls.append(f"{turn_idx}:{prompt[:12]}")
+ return f"attempt_{turn_idx}"
+
+ def _inf(pub: Mapping[str, Any], _comp: str) -> dict[str, Any]:
+ if pub["family"] == "A":
+ return {"passed": True, "epistemic_status": "VERIFIED", "findings": []}
+ return {"passed": True, "epistemic_status": "LINT_PASS", "findings": []}
+
+ def _eval(it: Mapping[str, Any], _comp: str) -> dict[str, Any]:
+ # Family A passes grader; Family B fails grader (100% false oracle pass rate!)
+ return {"passed": it["family"] == "A", "findings": []}
+
+ ckpt = tmp_path / "issue12_ckpt.jsonl"
+
+ # Run 1: default early stop enabled -> all 3 items stop at turn 1
+ run1 = run_repair_split(
+ items,
+ _gen,
+ max_turns=3,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt,
+ )
+ expect_eq(len(calls), 3)
+ expect_eq(run1["oracle_grader_gap"]["by_family"]["A"]["false_pass_rate_frac"], "0/1")
+ expect_eq(run1["oracle_grader_gap"]["by_family"]["B"]["false_pass_rate_frac"], "1/1")
+ expect_eq(run1["oracle_grader_gap"]["by_family"]["B"]["premature_turn1_stops"], 2)
+ expect_true(run1["early_stop_eligibility"]["A"]["allow_early_stop"])
+ expect_eq(run1["early_stop_eligibility"]["A"]["reason"], "ELIGIBLE")
+ expect_false(run1["early_stop_eligibility"]["B"]["allow_early_stop"])
+ expect_eq(run1["early_stop_eligibility"]["B"]["reason"], "ORACLE_GAP_EXCEEDS_THRESHOLD")
+
+ # Run 2: resume SAME checkpoint with lowercase `early_stop_disabled_families={"b"}`
+ # -> MUST invalidate cached 1-turn Family B records and re-run B for all 3 turns while skipping A!
+ calls.clear()
+ run2 = run_repair_split(
+ items,
+ _gen,
+ max_turns=3,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt,
+ early_stop_disabled_families=frozenset({"b"}),
+ )
+ expect_eq(run2["early_stop_disabled_families"], ["B"])
+ expect_eq(len(calls), 6, "expected 2 Family B items x 3 turns re-run (Family A stays cached)")
+ b_rows = [r for r in run2["items"] if r["family"] == "B"]
+ expect_eq([r["turns_used"] for r in b_rows], [3, 3])
+ # Crucially, Family B STILL measures oracle_passes=2 & ORACLE_GAP_EXCEEDS_THRESHOLD (not 0/UNMEASURED!)
+ expect_eq(run2["oracle_grader_gap"]["by_family"]["B"]["oracle_passes"], 2)
+ expect_eq(run2["oracle_grader_gap"]["by_family"]["B"]["grader_rejects_among_oracle_passes"], 2)
+ expect_eq(run2["oracle_grader_gap"]["by_family"]["B"]["false_pass_rate_frac"], "1/1")
+ expect_false(run2["early_stop_eligibility"]["B"]["allow_early_stop"])
+ expect_eq(run2["early_stop_eligibility"]["B"]["reason"], "ORACLE_GAP_EXCEEDS_THRESHOLD")
+
+ # Run 3: resume again with same policy -> updated 3-turn records are now cached (0 calls!)
+ calls.clear()
+ run3 = run_repair_split(
+ items,
+ _gen,
+ max_turns=3,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt,
+ early_stop_disabled_families=frozenset({"B"}),
+ )
+ expect_eq(len(calls), 0, "refreshed 3-turn Family B checkpoint must be reused")
+ expect_eq(run3["oracle_grader_gap"]["by_family"]["B"]["oracle_passes"], 2)
+
+ # Run 4: prior_gap_summary automatically disables ineligible Family B on a fresh split
+ calls.clear()
+ run4 = run_repair_split(
+ items,
+ _gen,
+ max_turns=3,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ prior_gap_summary=run1["oracle_grader_gap"],
+ )
+ expect_eq(run4["early_stop_disabled_families"], ["B"])
+ expect_eq(len(calls), 1 + 3 + 3, "Family A stops at 1; Family B auto-disabled and runs 3 turns each")
+
+ # Run 5: forbid_subtier_early_stop=True invalidates earlier 1-turn LINT_PASS checkpoint
+ ckpt2 = tmp_path / "subtier_ckpt.jsonl"
+ run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=3,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt2,
+ forbid_subtier_early_stop=False,
+ )
+ calls.clear()
+ run5 = run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=3,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt2,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(len(calls), 3, "forbid_subtier_early_stop=True must invalidate subtier 1-turn checkpoint")
+ expect_eq(run5["items"][0]["turns_used"], 3)
+
+ # Run 6: increasing max_turns invalidates an uncertified cached record
+ ckpt3 = tmp_path / "budget_grow_ckpt.jsonl"
+ always_fail_oracle = lambda _pv, _c: {"passed": False, "epistemic_status": "REJECTED", "findings": []}
+ run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=2,
+ inference_oracle_fn=always_fail_oracle,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt3,
+ )
+ calls.clear()
+ run6 = run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=4,
+ inference_oracle_fn=always_fail_oracle,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt3,
+ )
+ expect_eq(len(calls), 4, "increasing max_turns must invalidate uncertified cached item")
+ expect_eq(run6["items"][0]["turns_used"], 4)
+
+ # Run 7: shrinking max_turns (4 -> 2) invalidates cached 4-turn record
+ ckpt4 = tmp_path / "budget_shrink_ckpt.jsonl"
+ run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=4,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt4,
+ early_stop_disabled_families=frozenset({"B"}),
+ )
+ calls.clear()
+ run7 = run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=2,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt4,
+ early_stop_disabled_families=frozenset({"B"}),
+ )
+ expect_eq(len(calls), 2, "shrinking max_turns (4 -> 2) must invalidate 4-turn cached record")
+ expect_eq(run7["max_turns"], 2)
+ expect_eq(run7["items"][0]["max_turns"], 2)
+ expect_eq(run7["items"][0]["turns_used"], 2)
+
+ # Run 8: max_turns == 1 policy flips (allow_early_stop True -> False, forbid_subtier False -> True) invalidate
+ ckpt5 = tmp_path / "max1_flip_ckpt.jsonl"
+ run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=1,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt5,
+ )
+ calls.clear()
+ run8_disabled = run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=1,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt5,
+ early_stop_disabled_families=frozenset({"B"}),
+ )
+ expect_eq(len(calls), 1, "max_turns=1 early_stop_disabled policy flip must invalidate cached certified record")
+ expect_false(run8_disabled["items"][0]["inference_certified"])
+ expect_false(run8_disabled["items"][0]["allow_early_stop"])
+
+ ckpt6 = tmp_path / "max1_subtier_ckpt.jsonl"
+ run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=1,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt6,
+ forbid_subtier_early_stop=False,
+ )
+ calls.clear()
+ run8_subtier = run_repair_split(
+ [items[1]],
+ _gen,
+ max_turns=1,
+ inference_oracle_fn=_inf,
+ eval_grader_fn=_eval,
+ include_plane1_retrieval=False,
+ checkpoint_jsonl=ckpt6,
+ forbid_subtier_early_stop=True,
+ )
+ expect_eq(len(calls), 1, "max_turns=1 forbid_subtier_early_stop flip must invalidate cached certified record")
+ expect_false(run8_subtier["items"][0]["inference_certified"])
+ expect_true(run8_subtier["items"][0]["forbid_subtier_early_stop"])
+
+
+def test_summarize_oracle_grader_gap_legacy_compact_and_eligibility_validation() -> None:
+ # Compact legacy receipts (no `turns` key): 23 oracle passes, 15 rejects, 10 turn-1 stops
+ compact_rows: list[dict[str, Any]] = []
+ for i in range(10):
+ compact_rows.append({"family": "B", "inference_certified": True, "passed": False, "turns_used": 1})
+ for i in range(5):
+ compact_rows.append({"family": "B", "inference_certified": True, "passed": False, "turns_used": 2})
+ for i in range(8):
+ compact_rows.append({"family": "B", "inference_certified": True, "passed": True, "turns_used": 1})
+ compact_rows.append({"family": "B", "inference_certified": False, "passed": True, "turns_used": 4})
+
+ gap = summarize_oracle_grader_gap(compact_rows)
+ fam_b = gap["by_family"]["B"]
+ expect_eq(fam_b["oracle_passes"], 23)
+ expect_eq(fam_b["grader_rejects_among_oracle_passes"], 15)
+ expect_eq(fam_b["premature_turn1_stops"], 10)
+ expect_eq(fam_b["grader_without_oracle_passes"], 1)
+ expect_eq(fam_b["false_pass_rate_frac"], "15/23")
+
+ # Exact eligibility threshold boundaries & underpowered guard
+ elig = evaluate_early_stop_eligibility(
+ {
+ "by_family": {
+ "A": {"oracle_passes": 20, "grader_rejects_among_oracle_passes": 1}, # exact 1/20 == threshold -> ELIGIBLE
+ "B": {"oracle_passes": 23, "grader_rejects_among_oracle_passes": 15}, # > 1/20 -> ineligible
+ "C": {"oracle_passes": 0, "grader_rejects_among_oracle_passes": 0}, # < min_oracle_passes -> underpowered
+ }
+ },
+ max_false_pass_rate=Fraction(1, 20),
+ min_oracle_passes=1,
+ )
+ expect_true(elig["A"]["allow_early_stop"])
+ expect_eq(elig["A"]["reason"], "ELIGIBLE")
+ expect_false(elig["B"]["allow_early_stop"])
+ expect_eq(elig["B"]["reason"], "ORACLE_GAP_EXCEEDS_THRESHOLD")
+ expect_false(elig["C"]["allow_early_stop"])
+ expect_eq(elig["C"]["reason"], "UNMEASURED_OR_UNDERPOWERED_ORACLE_GAP")
+
+ # Fail-closed ValueError guards on malformed inputs & non-int/bool/float counts
+ bad_calls = [
+ lambda: evaluate_early_stop_eligibility("not_a_mapping"), # type: ignore[arg-type]
+ lambda: evaluate_early_stop_eligibility({"by_family": {}}, max_false_pass_rate=Fraction(-1, 10)),
+ lambda: evaluate_early_stop_eligibility({"by_family": {}}, max_false_pass_rate=Fraction(11, 10)),
+ lambda: evaluate_early_stop_eligibility({"by_family": {}}, max_false_pass_rate=0.05), # type: ignore[arg-type]
+ lambda: evaluate_early_stop_eligibility({"by_family": {}}, min_oracle_passes=0),
+ lambda: evaluate_early_stop_eligibility({"by_family": {}}, min_oracle_passes=True),
+ lambda: evaluate_early_stop_eligibility({"by_family": "not_a_mapping"}),
+ lambda: evaluate_early_stop_eligibility({"by_family": {"A": "not_a_mapping"}}),
+ lambda: evaluate_early_stop_eligibility({"by_family": {"A": {"oracle_passes": True, "grader_rejects_among_oracle_passes": 0}}}),
+ lambda: evaluate_early_stop_eligibility({"by_family": {"A": {"oracle_passes": 5, "grader_rejects_among_oracle_passes": 6}}}),
+ lambda: evaluate_early_stop_eligibility({"by_family": {"A": {"oracle_passes": -1, "grader_rejects_among_oracle_passes": 0}}}),
+ ]
+ for fn in bad_calls:
+ with pytest.raises(ValueError):
+ fn()
+
+
+# ---------------------------------------------------------------------------
+# 13. Review 6012069978: 20 offline (-O-safe, tiktoken-free) separating tests
+# covering every listed accept/reject boundary in src/mcproof/domain_protocol.py
+# ---------------------------------------------------------------------------
+
+
+def test_review_6012069978_01_sandbox_mixed_int_str_injected_globals() -> None:
+ rep = run_restricted_sandbox_cell("x = 1", injected_globals={1: 1, "a": 2}) # type: ignore[dict-item]
+ expect_false(rep["ok"], f"mixed int/str injected_globals must be rejected cleanly: {rep}")
+ expect_true(rep["ast_rejected"])
+ expect_eq(rep["violations"], ["invalid_injected_global_key:1"])
+
+
+def test_review_6012069978_02_portfolio_shortest_known_eq_live_record_accepted() -> None:
+ rep = audit_portfolio_bounds(
+ [{"id": "p1", "shortest_known": 5, "live_record": 5}],
+ registered_verified_ids=frozenset({"p1"}),
+ )
+ expect_true(rep["passed"], f"shortest_known == live_record must be accepted: {rep}")
+ expect_eq(rep["epistemic_status"], "VERIFIED")
+ expect_eq(rep["items"][0]["epistemic_status"], "VERIFIED")
+ expect_eq(rep["findings"], [])
+
+
+def test_review_6012069978_03_portfolio_floor_eq_live_record_accepted() -> None:
+ rep = audit_portfolio_bounds(
+ [{"id": "p1", "proven_floor": 5, "live_record": 5}],
+ registered_verified_ids=frozenset({"p1"}),
+ )
+ expect_true(rep["passed"], f"proven_floor == live_record must be accepted: {rep}")
+ expect_eq(rep["epistemic_status"], "VERIFIED")
+ expect_eq(rep["items"][0]["epistemic_status"], "VERIFIED")
+ expect_eq(rep["findings"], [])
+
+
+def test_review_6012069978_04_lower_bound_int_witness_sha256_rejected() -> None:
+ _expect_only_rule(
+ {
+ "epistemic_status": "LOWER_BOUND",
+ "tcb_pins": {"tcb_manifest_verified": True, "checker_sha256": HEX64},
+ "witness_or_proof_sha256": 5,
+ },
+ TYPE_RULE,
+ )
+
+
+def test_review_6012069978_05_verified_none_instance_sha256_rejected() -> None:
+ _expect_only_rule(_verified(instance_sha256=None), TYPE_RULE)
+
+
+def test_review_6012069978_06_verified_int_canonical_instance_sha256_without_instance_rejected() -> None:
+ _expect_only_rule(_verified(canonical_instance_sha256=5), TYPE_RULE)
+
+
+def test_review_6012069978_07_differential_match_oracles_checked_int_tail_rejected() -> None:
+ _expect_only_rule(
+ _verified(differential_match=True, oracles_checked=["a", "b", 5]),
+ TYPE_RULE,
+ )
+
+
+def test_review_6012069978_08_control_records_padded_name_matches_must_fail_controls() -> None:
+ _expect_accepted(
+ _verified(
+ must_fail_controls=["c1"],
+ control_records=[{"name": " c1 ", "oracle_invoked": True, "unexpectedly_passed": False}],
+ )
+ )
+
+
+def test_review_6012069978_09_control_records_nonlist_int_cleanly_rejected() -> None:
+ rep = audit_transition_certificate(_verified(must_fail_controls=["c1"], control_records=1))
+ expect_false(rep["passed"], f"non-list control_records must be rejected cleanly: {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_in(TYPE_RULE, _rules(rep))
+ expect_in("CERT_A6_CONTROL_COVERAGE_INCOMPLETE", _rules(rep))
+
+
+def test_review_6012069978_10_must_fail_controls_padded_name_matches_control_record() -> None:
+ _expect_accepted(
+ _verified(
+ must_fail_controls=[" c1 "],
+ control_records=[{"name": "c1", "oracle_invoked": True, "unexpectedly_passed": False}],
+ )
+ )
+
+
+def test_review_6012069978_11_differential_match_padded_duplicate_oracles_rejected() -> None:
+ _expect_only_rule(
+ _verified(differential_match=True, oracles_checked=["x", " x"]),
+ "CERT_SINGLE_ORACLE_DIFFERENTIAL",
+ )
+
+
+def test_review_6012069978_12_tcb_pins_empty_pin_keys_rejected() -> None:
+ _expect_only_rule(
+ _verified(tcb_pins={"tcb_manifest_verified": True}),
+ "CERT_TCB_MANIFEST_UNLOCKED",
+ )
+
+
+def test_review_6012069978_13_proven_empty_witness_with_floor_rejected() -> None:
+ _expect_only_rule(
+ _verified(epistemic_status="PROVEN", witness="", proven_floor=1),
+ "CERT_UNWITNESSED_VERIFIED_OPTIMUM",
+ )
+
+
+def test_review_6012069978_14_explicit_witness_cost_mismatch_when_len_matches_floor_rejected() -> None:
+ _expect_only_rule(
+ _verified(witness="UU", proven_floor=2, witness_cost=5),
+ "CERT_WITNESS_FLOOR_MISMATCH",
+ )
+
+
+def test_review_6012069978_15_lp_string_b_rejected() -> None:
+ rep = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": [[1]], "b": "1", "y": [1], "c": [1], "claimed_lower_bound": 1}
+ )
+ expect_false(rep["passed"], f"string b must be rejected: {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_eq(_rules(rep), ["LP_CERT_MALFORMED"])
+
+
+def test_review_6012069978_16_lp_string_y_rejected() -> None:
+ rep = verify_rational_lp_certificate(
+ {"mode": "bounds", "A": [[1]], "b": [1], "y": "1", "c": [1], "claimed_lower_bound": 1}
+ )
+ expect_false(rep["passed"], f"string y must be rejected: {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_eq(_rules(rep), ["LP_CERT_MALFORMED"])
+
+
+def test_review_6012069978_17_witness_hangul_choseong_filler_u115f_rejected() -> None:
+ _expect_only_rule(_verified(witness="\u115f", proven_floor=1), "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+
+
+def test_review_6012069978_18_witness_hangul_jungseong_filler_u1160_rejected() -> None:
+ _expect_only_rule(_verified(witness="\u1160", proven_floor=1), "CERT_UNWITNESSED_VERIFIED_OPTIMUM")
+
+
+def test_review_6012069978_19_witness_nested_list_with_blank_element_rejected() -> None:
+ rep = audit_transition_certificate(_verified(witness=[["U", ""]], proven_floor=1))
+ expect_false(rep["passed"], f"nested blank element in witness list must be rejected: {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_in(TYPE_RULE, _rules(rep))
+ expect_in("CERT_UNWITNESSED_VERIFIED_OPTIMUM", _rules(rep))
+
+
+def test_review_6012069978_20_witness_mapping_non_str_key_cleanly_rejected() -> None:
+ rep = audit_transition_certificate(_verified(witness=[{1: 2}], proven_floor=1))
+ expect_false(rep["passed"], f"non-string dict key in witness must be rejected cleanly: {rep}")
+ expect_eq(rep["epistemic_status"], "REJECTED")
+ expect_in(TYPE_RULE, _rules(rep))
+ expect_in("CERT_UNWITNESSED_VERIFIED_OPTIMUM", _rules(rep))
diff --git a/tests/test_regex_fullmatch.py b/tests/test_regex_fullmatch.py
index 063eb10..449464a 100644
--- a/tests/test_regex_fullmatch.py
+++ b/tests/test_regex_fullmatch.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import importlib.machinery
+import importlib.util
import json
from pathlib import Path
@@ -59,3 +61,15 @@ def test_upstream_commit_trailing_newline_rejected(tmp_path: Path) -> None:
(deps / "DEPS_MANIFEST.json").write_text(json.dumps({"repos": repos}), encoding="utf-8")
with pytest.raises(StaleLineageError):
build_lineage_manifest(root, d_dir=deps)
+
+
+def test_bootstrap_deps_rejects_commit_pin_with_trailing_newline(tmp_path: Path) -> None:
+ script = repo_root() / "bin" / "bootstrap-deps"
+ loader = importlib.machinery.SourceFileLoader("bootstrap_deps_under_test", str(script))
+ spec = importlib.util.spec_from_loader(loader.name, loader)
+ if spec is None:
+ raise AssertionError("bootstrap-deps failed to load")
+ mod = importlib.util.module_from_spec(spec)
+ loader.exec_module(mod)
+ with pytest.raises(ValueError):
+ mod._clone_at_exact_sha("https://example.invalid/repo.git", "a" * 40 + "\n", tmp_path / "dest")
diff --git a/verification/VERIFICATION_RECEIPT.json b/verification/VERIFICATION_RECEIPT.json
index 74c95fa..5e5aa78 100644
--- a/verification/VERIFICATION_RECEIPT.json
+++ b/verification/VERIFICATION_RECEIPT.json
@@ -591,7 +591,7 @@
"base_gguf_q8_0_sha256": "10cc391b403021dd11c614679d2fd92f611c3681d29e29651b717316965d61e1",
"compiler_manifest_sha256": "fcec69eace974d2cb8629935864ced711a8859b07e7a396e530cf373f2606fac",
"corpus_tree_sha256": "93624aae09eea99c3d35ebfa2e9acde1f9ac9c675167461652486850f206b642",
- "datasets_sha256sums_manifest_sha256": "312953bc99bb42e6cbef1d1a3c240975f2baf3c60506df6c9eef06a678d45d56",
+ "datasets_sha256sums_manifest_sha256": "3e81ab327058baca6739841ea6c664d1b8a5e019526e7074560d57dd402781af",
"lean_toolchain": "leanprover/lean4:v4.35.0",
"llama_server_version": "0.5.0 (build 11146, commit 7fe450e19)",
"p2b_artifact_commit": "6c40a4c3dea2380101dd1392ec6a344b1ff96dee",
@@ -603,7 +603,7 @@
"public_holdout_commitment_sha256": "e7c9b9da52be68c4731e35961c31ec33decf440e4ccb00b2c9072e029054f032",
"safetensors_checkpoint_fingerprint": "1ed4483f1d3ffbc3ffc7a26984be212e7cce455ac1e0651d1bcba1313ea2bd64",
"spec_lineage_json_sha256": "344f5506e702dc8dc0ee7374d30af788e3d4c2c370fcdbc877435e133da26a76",
- "tracked_evidence_merkle_sha256": "9477fe31b344bb3362988e99969434b5f57a81d9b5c71f09899de5aabc49cd5b",
+ "tracked_evidence_merkle_sha256": "841bb8a4234166c172ac43b5cfb7eb1c7b1c02599cb40e9b4add55fcd605184f",
"vault_sha256sums_manifest_sha256": "b14cf1efeedf7a7c8c15ed57e587c3d18087f557e6ff1807068c4e9c9ef6f6ee",
"zone_manifest_id": "sha256:4e00656cb47fce97f687ae638afba22c569b9680b3780eeb2e5ea71a62c55eca"
},
@@ -1088,9 +1088,9 @@
"total": 15
},
"pytest_strict": {
- "executed_total": 34,
- "passed": 34,
- "skipped": 0
+ "executed_total": 53,
+ "passed": 53,
+ "skipped": 1
}
},
"stack": {
diff --git a/verification/graders/common.py b/verification/graders/common.py
index 137990c..9bc06e5 100644
--- a/verification/graders/common.py
+++ b/verification/graders/common.py
@@ -15,6 +15,13 @@
import tempfile
from typing import Any, Mapping, Sequence
+from mcproof.lean_harness import (
+ COMPILE_BLOCKING_LINT_RULES,
+ CandidateSandboxUnavailable,
+ lint_lean4_source,
+ run_confined_command,
+)
+
getcontext().prec = 100
REPO_ROOT = Path(__file__).resolve().parents[2]
@@ -274,6 +281,21 @@ def run_lean4_verification(
"leanchecker_ran": False,
}
+ # The soko auditor does not treat `attribute [init]` as a reason to stop.
+ # This lint does. The compile below is confined either way.
+ lint = lint_lean4_source(lean_source, require_theorem=False, check_vacuous=False)
+ for item in lint["findings"]:
+ if item.get("rule") in COMPILE_BLOCKING_LINT_RULES:
+ errors.append(f"lint:{item.get('rule')}:{item.get('message')}")
+ if errors:
+ return {
+ "ok": False,
+ "errors": errors,
+ "auditor": audit_rep,
+ "axioms": {},
+ "leanchecker_ran": False,
+ }
+
tc_bin = find_lean_toolchain_bin()
lean_exe = str(tc_bin / "lean")
checker_exe = str(tc_bin / "leanchecker")
@@ -300,14 +322,22 @@ def run_lean4_verification(
olean_path = Path(td) / "CandidateMod.olean"
mod_path.write_text(combined_source, encoding="utf-8")
- comp = subprocess.run(
- [lean_exe, "-o", str(olean_path), str(mod_path)],
- cwd=td,
- capture_output=True,
- text=True,
- env=env,
- timeout=timeout_sec,
- )
+ try:
+ comp = run_confined_command(
+ [lean_exe, "-o", str(olean_path), str(mod_path)],
+ cwd=Path(td),
+ env=env,
+ timeout_sec=timeout_sec,
+ )
+ except CandidateSandboxUnavailable as exc:
+ errors.append(f"sandbox_unavailable:{exc}")
+ return {
+ "ok": False,
+ "errors": errors,
+ "auditor": audit_rep,
+ "axioms": axioms_by_thm,
+ "leanchecker_ran": False,
+ }
if comp.returncode != 0:
msg = (comp.stdout + "\n" + comp.stderr).strip()
errors.append(f"lean_compile_failed:{msg[:400]}")
@@ -343,14 +373,22 @@ def run_lean4_verification(
if not errors and run_leanchecker and Path(checker_exe).is_file():
env_chk = dict(env)
env_chk["LEAN_PATH"] = f"{td}{os.pathsep}{libdir}"
- chk_run = subprocess.run(
- [checker_exe, "CandidateMod"],
- cwd=td,
- capture_output=True,
- text=True,
- env=env_chk,
- timeout=timeout_sec,
- )
+ try:
+ chk_run = run_confined_command(
+ [checker_exe, "CandidateMod"],
+ cwd=Path(td),
+ env=env_chk,
+ timeout_sec=timeout_sec,
+ )
+ except CandidateSandboxUnavailable as exc:
+ errors.append(f"sandbox_unavailable:{exc}")
+ return {
+ "ok": False,
+ "errors": errors,
+ "auditor": audit_rep,
+ "axioms": axioms_by_thm,
+ "leanchecker_ran": False,
+ }
if chk_run.returncode != 0:
msg = (chk_run.stdout + "\n" + chk_run.stderr).strip()
errors.append(f"leanchecker_failed:{msg[:300]}")
diff --git a/verification/oracles_verification_receipt.json b/verification/oracles_verification_receipt.json
index 76ef1bd..84730ae 100644
--- a/verification/oracles_verification_receipt.json
+++ b/verification/oracles_verification_receipt.json
@@ -15,8 +15,8 @@
"float_true_division_cheat": {
"actual_pass": false,
"expected_pass": false,
- "kill_fraction": "5/5",
- "kill_rate_bps": 10000,
+ "kill_fraction": null,
+ "kill_rate_bps": null,
"matched_expectation": true,
"rules": [
"FLOAT_DIVISION_IN_EXACT_CHECKER",
@@ -177,7 +177,7 @@
"native_decide_cheat": {
"caught": true,
"nonstandard_axioms": [
- "t_native._native.native_decide.ax_1_1"
+ "t_native._native.native_decide.ax_1"
],
"rules": [
"UNVERIFIED_NATIVE_DECIDE",
@@ -265,6 +265,7 @@
],
"challenge_sorry_whitelisted_module": "Mcproof.Spec",
"findings": [],
+ "host_resource_exhausted": false,
"nonstandard_axioms": [],
"paranoid_kernels_run": [
"lean-paranoid",
@@ -285,7 +286,28 @@
"Mcproof.Spec.ratLeCross_sound",
"Mcproof.Spec.ratLeCross_refl_pos",
"Mcproof.Spec.cleanSegments_safe",
- "Mcproof.Spec.cleanSegments_singleton"
+ "Mcproof.Spec.cleanSegments_singleton",
+ "Mcproof.Spec.quotientHeuristic_step_consistent",
+ "Mcproof.Spec.quotientHeuristic_admissible",
+ "Mcproof.Spec.prefundedHeuristic_admissible_and_goal",
+ "Mcproof.Spec.prefundedHeuristic_step_consistent",
+ "Mcproof.Spec.prefundedVal_bounded_drop_witness",
+ "Mcproof.Spec.operatorCounting_dual_scaled_sound",
+ "Mcproof.Spec.operatorCounting_dual_div_admissible",
+ "Mcproof.Spec.dualFloorNat_sound_and_witness",
+ "Mcproof.Spec.cyclicSwitchTax_triangle",
+ "Mcproof.Spec.cyclicSwitchDist_metric_and_witness",
+ "Mcproof.Spec.conservation_harvest_potential_repair",
+ "Mcproof.Spec.vertexSplit_unit_flow_horizon_bound",
+ "Mcproof.Spec.zeroSelfLoop_deficit_composition",
+ "Mcproof.Spec.ceilDiv_step_consistent_and_admissible",
+ "Mcproof.Spec.rmsnorm_tangent_orthogonal",
+ "Mcproof.Spec.rmsnorm_orthogonal_stack_norm_inflation",
+ "Mcproof.Spec.multilayer_quadratic_shrinkage_reduction",
+ "Mcproof.Spec.swiglu_gate_metric_and_counterexample",
+ "Mcproof.Spec.swiglu_radial_null_orthogonality",
+ "Mcproof.Spec.scalar_projection_retention_illusion",
+ "Mcproof.Spec.rmsnorm_rational_shrinkage_sandwich"
],
"toolchain": "leanprover/lean4:v4.35.0"
},
@@ -317,7 +339,7 @@
"bytes": 106763,
"control_bytes": [],
"lineage_details": {
- "corpus_tree_sha256": "5bdb7f30363b956e82947f668f98c48f99876e87fb5ed4f785b873e4f4f98305",
+ "corpus_tree_sha256": "93624aae09eea99c3d35ebfa2e9acde1f9ac9c675167461652486850f206b642",
"deps_checkouts_verified": true,
"deps_manifest_verified": true,
"findings": [],
@@ -333,15 +355,16 @@
"sha256": "49beff2a0185cfa4032170b614a543c0d67541494e858803d21cfb837111b230"
},
"prose_gate": {
- "check_dupes_out": "check-prose --dupes: clean (11 file(s))",
+ "check_dupes_out": "check-prose --dupes: clean (12 file(s))",
"check_dupes_rc": 0,
- "check_prose_out": "check-prose: clean (11 file(s), 2422 lines)",
+ "check_prose_out": "check-prose: clean (12 file(s), 2546 lines)",
"check_prose_rc": 0,
"files": [
"README.md",
"compile/README.md",
"datasets/README.md",
"docs/CONTINUITY.md",
+ "docs/CROSS_POLLINATION.md",
"lean/README.md",
"lean/SPEC.md",
"lean/tests/TEST-RESULTS.md",
@@ -353,24 +376,24 @@
},
"pytest_strict": {
"counts": {
- "executed_total": 34,
+ "executed_total": 53,
"failed": 0,
- "passed": 34,
- "skipped": 0
+ "passed": 53,
+ "skipped": 1
},
"returncode": 0,
"summary_tail": [
- "../../../Work/mcproof-lab/repo/tests/test_lean_harness.py ........... [ 73%]",
- "../../../Work/mcproof-lab/repo/tests/test_lineage_prose_and_cli.py ..... [ 88%]",
- ".... [100%]",
+ "tests/test_lean_harness.py ....s........ [ 70%]",
+ "tests/test_lineage_prose_and_cli.py ......... [ 87%]",
+ "tests/test_neon_audit_regressions.py ....... [100%]",
"",
- "======================== 34 passed in 137.54s (0:02:17) ========================"
+ "================== 53 passed, 1 skipped in 148.14s (0:02:28) ==================="
]
},
"readme_top_lines": [
"# mcproof",
"`mcproof` is the verification harness, Plane 1 rulebook, dataset suite, weight compiler, and serving benchmark for the Siliconcordat Formal Verification MDE. It checks Lean 4.35.0 proofs across six kernels, grades exact-math checkers against planted bugs, compiles `weft` adapters, and audits live `warp-modeld` mounts. Proof authors, verifiers, and researchers use it to test formal reasoning without weakening deterministic gates.",
- "Blueprint and gates live in [siliconcordat/mde issue 4](https://github.com/siliconcordat/mde/issues/4) under the [Master Plan](https://github.com/siliconcordat/.github/blob/main/MASTER-PLAN.md). Companion serving changes live in [siliconcordat/exo](https://github.com/siliconcordat/exo/tree/feat/mde4-phase4-phase6-stack) and [siliconcordat/warp PR 5](https://github.com/siliconcordat/warp/pull/5)."
+ "Blueprint and gates live in [siliconcordat/mde issue 4](https://github.com/siliconcordat/mde/issues/4) under the [Master Plan](https://github.com/siliconcordat/.github/blob/main/MASTER-PLAN.md). Companion serving changes live in [siliconcordat/exo](https://github.com/siliconcordat/exo/tree/feat/mde4-phase4-phase6-stack) and [siliconcordat/warp](https://github.com/siliconcordat/warp/tree/feat/mde4-phase4-live-gate)."
],
"siliconcordat_clean": {
"exo": "",