#!/usr/bin/env python3 """Verify archived bytes; run research tests in a disposable copy.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import shutil import subprocess import sys import tempfile ROOT = Path(__file__).resolve().parent def check_entries(base: Path, entries: list[dict], size_key: str) -> int: seen = set() for entry in entries: name = entry['path'] path = base / name if name in seen or path.is_symlink() or not path.resolve().is_relative_to(base.resolve()): raise ValueError(f'Unsafe or duplicate manifest path: {name}') seen.add(name) data = path.read_bytes() if len(data) != entry[size_key] or hashlib.sha256(data).hexdigest() != entry['sha256']: raise ValueError(f'Integrity check failed: {name}') return len(seen) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--quick', action='store_true', help='Check archived hashes without executing research tests.') args = parser.parse_args() if sys.version_info < (3, 10): raise RuntimeError('Python 3.10 or newer is required.') manifest = json.loads((ROOT / 'release-manifest.json').read_text(encoding='utf-8')) if manifest['schema_version'] != 1: raise ValueError('Unsupported release manifest version.') count = check_entries(ROOT, manifest['files'], 'size_bytes') research = ROOT / 'research' original = json.loads((research / 'MANIFEST.json').read_text(encoding='utf-8')) check_entries(research, original['files'], 'bytes') lock = json.loads((research / 'PROTOCOL_LOCK.json').read_text(encoding='utf-8')) for name, expected in lock['source_sha256'].items(): if hashlib.sha256((research / name).read_bytes()).hexdigest() != expected: raise ValueError(f'Original source lock failed: {name}') cases = [json.loads(line) for line in (ROOT / 'data/cases.jsonl').read_text(encoding='utf-8').splitlines()] generations = [json.loads(line) for line in (ROOT / 'data/generations.jsonl').read_text(encoding='utf-8').splitlines()] if len(cases) != 24 or len(generations) != 192: raise ValueError('Unexpected dataset row counts.') print(f'PASS: {count} release files, original manifest/source lock, 24 case rows, 192 generation rows.') if not args.quick: with tempfile.TemporaryDirectory(prefix='nhais_dq_checks_') as folder: target = Path(folder) / 'research' shutil.copytree(research, target) subprocess.run([sys.executable, str(target / 'tests.py')], check=True, cwd=target) print('PASS: original independent checks completed in a temporary copy.') return 0 if __name__ == '__main__': try: raise SystemExit(main()) except (OSError, ValueError, KeyError, RuntimeError, subprocess.CalledProcessError) as exc: print(f'Verification failed: {exc}', file=sys.stderr) raise SystemExit(1)