"""Verification evidence for result/close rows. Standard library; no lane writes. Receipts attest recorded executions, not authorship or the adequacy of a theorem statement. See ../docs/verification.md for the schema and trust boundary. """ import datetime as dt import hashlib import json import math import os from pathlib import Path import re import shlex import signal import subprocess import sys import tempfile LEVELS = ('L0', 'L1', 'L2', 'L3') RULE_FROM = '2026-11-03T18:06:17+00:00' STANDARD_AXIOMS = {'propext', 'Classical.choice', 'Quot.sound'} EVIDENCE_FIELDS = { 'verification', 'finite_component', 'verification_scope', 'finite_evidence', 'producer_author', 'checker_author', 'certificate', 'checker', 'checker_max_seconds', 'expected_output_sha256', 'run_receipt', 'run_receipt_sha256', 'lean_project', 'build_receipt', 'build_receipt_sha256', 'axioms_receipt', 'main_theorems', } FORBIDDEN = re.compile(r'(? 40 and re.search(r'trust|compil|kernel|evaluat|reduc', line, re.I) and not re.search(r'\b(?:no|not|never|without|unused)\b', line, re.I) for line in lines): raise ValueError('native_decide requires an explanatory trust-boundary line in AXIOMS.md') found = {} # Include audit output printed during the build, so a separately trimmed # axioms receipt cannot conceal an inherited premise visible in that build. for match in re.finditer(r"'([^']+)' depends on axioms:\s*\[([^\]]*)\]", axioms + '\n' + build): name, values = match.groups() values = {x.strip() for x in values.split(',') if x.strip()} if name in found and values != found[name]: raise ValueError('conflicting axiom receipts for ' + name) found[name] = values for name in re.findall(r"'([^']+)' does not depend on any axioms", axioms + '\n' + build): if name in found and found[name]: raise ValueError('conflicting axiom receipts for ' + name) found[name] = set() mains = evidence.get('main_theorems') recorded = set(re.findall(r"'([^']+)' (?:depends on axioms:|does not depend on any axioms)", axioms)) if not isinstance(mains, list) or not mains or not all(isinstance(n, str) and n in found and n in recorded for n in mains): raise ValueError('axioms_receipt must contain #print axioms output for each main_theorems entry') audit_requests = set(re.findall(r'^\s*#print\s+axioms\s+([\w.]+)', '\n'.join(t for _, t in texts[:-3]), re.M)) if not set(mains) <= audit_requests: raise ValueError('main_theorems must have #print axioms requests in the hashed sources') nonstandard = set().union(*found.values()) - STANDARD_AXIOMS # Even unused explicit axioms must be disclosed, using their qualified name # from the table (or their literal name when outside a namespace). for _, text in texts[:-3]: for name in re.findall(r'^\s*(?:private\s+|protected\s+)?axiom\s+([\w.]+)', text, re.M): matches = {n for n in declared if n == name or n.endswith('.' + name)} if not matches and name not in STANDARD_AXIOMS: raise ValueError('unlisted source axiom: ' + name) nonstandard.update(matches) if nonstandard - declared.keys(): raise ValueError('unlisted non-standard axiom(s): ' + ', '.join(sorted(nonstandard - declared.keys()))) if level == 'L3' and (nonstandard or declared): raise ValueError('L3 requires an empty non-standard axiom list') def validate_row(row, base, required=False, rerun=True): """Return evidence failures. Legacy untagged rows remain valid by default.""" try: if not isinstance(row, dict): raise ValueError('verification row must be an object') tagged = any(k in row for k in ('verification', 'finite_component')) if required or tagged: if row.get('verification') not in LEVELS: raise ValueError('verification must be L0|L1|L2|L3') if row.get('finite_component') not in LEVELS + ('none',): raise ValueError('finite_component must be L0|L1|L2|L3|none') for component, level in (('verification', row.get('verification')), ('finite_component', row.get('finite_component'))): if level not in ('L1', 'L2', 'L3'): continue evidence = row if component == 'finite_component' and 'finite_evidence' in row: evidence = row['finite_evidence'] if not isinstance(evidence, dict): raise ValueError('finite_evidence must be an object') scope = evidence.get('verification_scope') if not isinstance(scope, str) or not scope.strip() or '\n' in scope: raise ValueError('verification_scope must name the exact certified/proved statement in one line') if level == 'L1': _l1(evidence, base, rerun) else: _lean(evidence, base, level) return [] except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc: return ['verification: ' + str(exc)] def new_close(row): if row.get('event') != 'close' and row.get('status') != 'closed': return False # A sweep read mark copies the closed row with a new `revised`; it is not a close. 11-10: math's # four 10-31/11-01 closes failed lint as new because their 11-03 read marks came after the # cutoff. The close itself was judged on its own row, under its own date. if row.get('event') == 'read': return False # A close written while the lane was not opted in remains historical when # the owner enables the rule later. External appenders have the cutoff. if row.get('verification_required_at_close') is False: return False if row.get('verification_policy_version') == 1: return True try: when = dt.datetime.fromisoformat((row.get('revised') or row.get('created', '')).replace('Z', '+00:00')) return when >= dt.datetime.fromisoformat(RULE_FROM) except (ValueError, TypeError, AttributeError): # Missing or malformed timestamps cannot grandfather an external close. return True def apply_metadata(row, args, base, required=False): """Apply CLI metadata before append; never accept arbitrary row overrides.""" explicit = args.verification is not None or args.finite_component is not None or args.verification_evidence is not None if explicit: for field in EVIDENCE_FIELDS: row.pop(field, None) # A new attempt must not silently inherit receipts. if args.verification_evidence: path = args.verification_evidence.expanduser().resolve() evidence = object_json(path) unknown = evidence.keys() - EVIDENCE_FIELDS if unknown: raise ValueError('unknown verification evidence fields: ' + ', '.join(sorted(unknown))) row.update(evidence) if args.verification is not None: row['verification'] = args.verification if args.finite_component is not None: row['finite_component'] = args.finite_component elif args.action == 'result' or (args.action == 'close' and args.result_path and str(Path(args.result_path).expanduser().resolve()) != row.get('result_path')): for field in EVIDENCE_FIELDS: row.pop(field, None) errors = validate_row(row, base, required=required) if errors: raise ValueError('; '.join(errors)) row['verification_policy_version'] = 1 if args.action == 'close': row['verification_required_at_close'] = bool(required) def verification_line(row): level, finite = row.get('verification', 'L0'), row.get('finite_component', 'none') if level not in LEVELS or finite not in LEVELS + ('none',): raise ValueError('invalid verification level') descriptions = {'L0': 'prose or AI review; no strict certificate claim', 'L1': 'exact finite certificate; differently authored checker', 'L2': 'Lean proof of the stated step; cited inherited axioms allowed', 'L3': 'Lean proof of the full scoped statement; standard axioms only'} scope = row.get('verification_scope', '') if '\n' in scope or '\r' in scope: raise ValueError('verification_scope must be one line') return 'Verification level: {} ({}{}); finite component: {}.'.format( level, descriptions[level], '; scope: ' + scope if scope else '', finite) def publication_errors(file): """Check level claims against FILE.verification.json without running code. Any bare level token is treated as a claim, except explicitly labelled finite components. Conservative by design; quote discussions in separate documents. """ path = Path(file) body = path.read_text() tokens = list(re.finditer(r'\b(?:L0|L1(?!-(?:same-agent|independence-unestablished|partial)\b)|L2|L3)\b', body, re.I)) if not any(m.group().upper() != 'L0' for m in tokens): return [] try: sidecar = object_json(str(path) + '.verification.json') if sidecar.get('sha256') != sha256(path): raise ValueError('publication verification sidecar body hash mismatch') row = sidecar.get('row') errors = validate_row(row, path.parent, required=True, rerun=False) if errors: return errors finite_spans = [m.span(1) for m in re.finditer( r'\bfinite(?:[ -]+(?:component|parts?|portion))?\s*(?:level)?\s*[:=]?\s*\**(L[0-3])\b', body, re.I)] for token in tokens: component = 'finite_component' if token.span() in finite_spans else 'verification' supported = row[component] if supported == 'none' or int(token.group()[1]) > int(supported[1]): raise ValueError('public ' + component + ' claim ' + token.group() + ' exceeds supported ' + supported) return [] except (OSError, ValueError, TypeError, KeyError) as exc: return ['verification: ' + str(exc)]