"""Offline checks for the prepared Avenyra Hugging Face repository.""" from __future__ import annotations import hashlib import json import re from pathlib import Path import sympy as sp ROOT = Path(__file__).resolve().parents[1] def require(condition, message): if not condition: raise ValueError(message) def records(path): return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line.strip()] def read_state(serialized, dimension): state = json.loads(serialized) require(len(state['x']) == dimension, 'Endpoint dimension mismatch') require(len(state['A']) == dimension, 'Matrix dimension mismatch') require(all(len(row) == dimension for row in state['A']), 'Matrix row mismatch') x = sp.Matrix([sp.Rational(v) for v in state['x']]) if dimension else sp.zeros(0, 1) A = sp.Matrix([[sp.Rational(v) for v in row] for row in state['A']]) if dimension else sp.zeros(0) require(A.T == -A, 'State operator is not skew') return x, A def main(): manifest = json.loads((ROOT / 'manifest.json').read_text(encoding='utf-8')) files = manifest['files'] for relative, expected in files.items(): path = (ROOT / relative).resolve() require(path.is_relative_to(ROOT), f'Unsafe manifest path: {relative}') require(path.is_file(), f'Missing file: {relative}') digest = hashlib.sha256(path.read_bytes()).hexdigest() require(digest == expected['sha256'], f'Checksum mismatch: {relative}') require(path.stat().st_size == expected['size_bytes'], f'Size mismatch: {relative}') checksum_text = ''.join(f"{entry['sha256']} {relative}\n" for relative, entry in files.items()) require((ROOT / 'SHA256SUMS.txt').read_text(encoding='utf-8') == checksum_text, 'Checksum manifests disagree') claims = records(ROOT / 'data/claims.jsonl') source_path = ROOT / 'manuscript/Avenyra_Area_Feedback_v1.0.0.tex' source = source_path.read_text(encoding='utf-8') labels = set(re.findall(r'\\label\{([^}]+)\}', source)) matches = list(re.finditer( r'\\begin\{(theorem|proposition|lemma|corollary|conjecture)\}' r'(?:\[([^\]]*)\])?\s*(.*?)\\end\{\1\}', source, re.S)) require(len(claims) == len(matches) == manifest['claim_records'], 'Claim count mismatch') require(len({row['claim_id'] for row in claims}) == len(claims), 'Duplicate claim IDs') required_claim_fields = {'claim_id','title','environment','component','status','statement_latex','proof_latex', 'references_in_statement_or_proof','source_file','proof_audit_file', 'priority_status','verification_limit'} for row, match in zip(claims, matches): require(set(row) == required_claim_fields, 'Claim schema mismatch') require(row['statement_latex'] == match.group(3).strip(), 'Claim statement differs from source') require(row['claim_id'] in labels, 'Missing source label') require(row['environment'] == match.group(1), 'Environment mismatch') require(row['title'] == (match.group(2) or row['claim_id']), 'Claim title mismatch') proof_match = re.match(r'\s*(?:\\subsection\{[^}]*\}\s*)?\\begin\{proof\}\s*(.*?)\\end\{proof\}', source[match.end():], re.S) actual_proof = proof_match.group(1).strip() if proof_match else '' require(row['proof_latex'] == actual_proof, 'Claim proof differs from source') expected_status = 'conjecture' if match.group(1) == 'conjecture' else 'manuscript_proved' require(row['status'] == expected_status, 'Proof status mismatch') require(bool(actual_proof) or expected_status == 'conjecture', 'Statement lacks its claimed proof') require(set(row['references_in_statement_or_proof']) <= labels, 'Unresolved extracted reference') for field in ['source_file', 'proof_audit_file']: require((ROOT / row[field]).is_file(), 'Claim evidence file missing') examples = records(ROOT / 'data/worked_examples.jsonl') require(len(examples) == manifest['example_records'] == 8, 'Example count mismatch') require(len({row['example_id'] for row in examples}) == len(examples), 'Duplicate example IDs') required_example_fields = {'example_id','dimension','initial_state_json','controls_json','all_controls_legal', 'first_illegal_step','final_legal_prefix_state_json','final_rank','final_rho_squared', 'note','source_file'} for row in examples: require(set(row) == required_example_fields, 'Example schema mismatch') d = row['dimension'] x, A = read_state(row['initial_state_json'], d) blocked = 0 for i, displacement in enumerate(json.loads(row['controls_json']), 1): require(len(displacement) == d, 'Control dimension mismatch') a = sp.Matrix([sp.Rational(v) for v in displacement]) if d else sp.zeros(0,1) if A * a != sp.zeros(d,1): blocked = i break updated_A = A + x*a.T - a*x.T x = x + a A = updated_A expected_x, expected_A = read_state(row['final_legal_prefix_state_json'], d) require(x == expected_x and A == expected_A, f"Final state differs: {row['example_id']}") require(blocked == row['first_illegal_step'], 'Gate-failure index mismatch') require((blocked == 0) == row['all_controls_legal'], 'Gate-status mismatch') require(int(A.rank()) == row['final_rank'], 'Rank mismatch') null_vectors = A.nullspace() if d == 0: squared_radius = sp.Integer(0) else: if null_vectors: N = sp.Matrix.hstack(*null_vectors) w = N * (N.T*N).inv() * N.T*x else: w = sp.zeros(d,1) u = x-w squared_radius = sp.factor((u.T*u)[0]) require(squared_radius == sp.Rational(row['final_rho_squared']), 'Projection-radius mismatch') card = (ROOT / 'README.md').read_text(encoding='utf-8') require(card.startswith('---\n'), 'Dataset card lacks YAML metadata') metadata = card.split('---',2)[1] require('config_name: claims' in metadata and 'config_name: worked_examples' in metadata, 'Dataset configs missing') try: import yaml except ImportError: yaml_status = 'not installed; basic metadata checks only' else: parsed = yaml.safe_load(metadata) require(parsed['language'] == ['en'], 'Unexpected language metadata') require(len(parsed['configs']) == 2, 'Unexpected dataset config count') require(sum(bool(c.get('default',False)) for c in parsed['configs']) == 1, 'Default config mismatch') for config in parsed['configs']: for data_file in config['data_files']: require((ROOT/data_file['path']).is_file(), 'Missing configured dataset file') yaml.safe_load((ROOT/'CITATION.cff').read_text(encoding='utf-8')) yaml_status = 'parsed successfully' for path in ROOT.rglob('*.md'): for target in re.findall(r'\]\(([^)]+)\)', path.read_text(encoding='utf-8')): if re.match(r'^[a-zA-Z][a-zA-Z0-9+.-]*:', target) or target.startswith('#'): continue target_path = (path.parent/target.split('#',1)[0]).resolve() require(target_path.is_relative_to(ROOT) and target_path.exists(), f'Broken local link: {path.name}: {target}') print(json.dumps({'status':'PASS','checksummed_files':len(files),'claims':len(claims), 'worked_examples':len(examples),'yaml_metadata':yaml_status, 'scope':'Package integrity, exact extraction, local references, and finite exact examples; not universal proof or priority certification.'}, indent=2)) if __name__ == '__main__': main()