from pathlib import Path
import datetime as dt,hashlib,json,platform,subprocess,tempfile,urllib.request
REVISION='3a55a795767f3043112673ea561cdaf6dc7e2d0f'
IMAGE='python@sha256:2986c55feb36e6cae00fa1fefb454283e4b33f35e75ff8bdd123b134130be301'
EXPECTED={'tools/generate_moons.py': '0c070352991b48283a9ab9aa40425b50df9406a5d36dd1788f5c8d34290f86f9', 'tools/moon_model.py': 'db77e50ed990ca92ec047b32b4bfdd755b2583da02dd6743c22e53af6d123445', 'tools/validate_moons.py': 'ec1c04c0921ec8ecc15bd3fba38e1e797f2392bd3cdb13d30f72cef611401826', 'tools/collect_moon_evidence.py': '01516b7f9b2a8d709893f7462a9b3c9fc886c4c9256f3f9cc9c978b2304b5bcf', 'tools/ephemeris-data/generation-manifest.json': '00848b3b835128c28b40dd7b5a05990bb0d22bdecb2796cb360cf71dbf0bb649', 'tools/ephemeris-data/moons/horizons_satellite_elements.csv': 'cb411a5566e75dc7c42ff48387d294653282f52e5e484d4ba9a43ff1a0716e4f', 'tools/ephemeris-data/moons/horizons_satellite_vectors.csv': 'ef5c679c7916196121b08712f7fe58b6a9d4fda0a5db40a7bcdaef5e6bfdb918', 'tools/ephemeris-data/moons/jpl_satellite_physical.csv': '03c688bca6064568665a396ec9c189dcdb2d169fe782e90b3660a72c99a00a99', 'apps/web/js/moons.js': '0fe13220d6214d62a6b472f5cc8e2ccb2f8fbfaeb7eb1d5e611b40c272a90f51', 'apps/web/js/moonelements.js': 'e1dfc8d737bf92c96cc132756c7e13e0c6bb9a6c49b86654996bb472112be05f'}
COLLECTOR=b'#!/usr/bin/env python3\n"""Read-only JSON evidence for one native pinned-image moon comparison.\n\nRun in the manifest\'s exact Linux x86_64 CPython image. The trusted launcher\nmust inspect/pin that image and supply SOL_MOON_GENERATOR_IMAGE_DIGEST; this\nenvironment assertion alone is not container attestation. No network or writes\nare performed by comparison mode. Pending qualification is never promoted.\n--snapshot creates only a bounded input copy under build/ for a read-only\ncontainer mount, excluding .git and credentials.\nExit 0: comparison passed (possibly still pending); 1: comparison failed;\n2: runtime/image/source admission refused. See docs/CANONICAL_GENERATION.md.\n"""\nfrom __future__ import annotations\n\nimport contextlib\nimport argparse\nimport datetime as dt\nimport hashlib\nimport io\nimport json\nimport os\nfrom pathlib import Path\nimport re\nimport sys\n\nimport generate_moons as generator\nimport validate_moons as validator\n\nROOT = Path(__file__).resolve().parents[1]\nOUTPUTS = (\'apps/web/js/moons.js\', \'apps/web/js/moonelements.js\')\nINPUTS = (\'tools/generate_moons.py\', \'tools/moon_model.py\', \'tools/validate_moons.py\',\n          \'tools/collect_moon_evidence.py\', \'tools/ephemeris-data/generation-manifest.json\',\n          \'tools/ephemeris-data/moons/horizons_satellite_elements.csv\',\n          \'tools/ephemeris-data/moons/horizons_satellite_vectors.csv\',\n          \'tools/ephemeris-data/moons/jpl_satellite_physical.csv\', *OUTPUTS)\n\n\ndef input_bytes() -> dict[str, bytes]:\n    result = {}\n    for name in INPUTS:\n        path = ROOT / name\n        if path.is_symlink() or not path.is_file() or path.stat().st_size > 32 * 1024 * 1024:\n            raise ValueError(\'moon evidence input unavailable, redirected or oversized\')\n        with path.open(\'rb\') as stream:\n            raw = stream.read(32 * 1024 * 1024 + 1)\n        if len(raw) > 32 * 1024 * 1024:\n            raise ValueError(\'moon evidence input exceeds its byte budget\')\n        result[name] = raw\n    return result\n\n\ndef fingerprints() -> dict[str, str]:\n    return {name: hashlib.sha256(raw).hexdigest() for name, raw in input_bytes().items()}\n\n\ndef snapshot(destination: Path) -> dict:\n    generator.verify_source_identity(generator.load_generation_manifest())\n    target = destination.resolve(); build_root = ROOT / \'build\'\n    if build_root.resolve() != ROOT.resolve() / \'build\' or destination.is_symlink() \\\n            or not target.is_relative_to(build_root.resolve()) or target.exists():\n        raise ValueError(\'snapshot must use a new directory under build/\')\n    sources = input_bytes()\n    target.mkdir(parents=True)\n    for name, raw in sources.items():\n        path = target / name; path.parent.mkdir(parents=True, exist_ok=True)\n        with path.open(\'xb\') as stream:\n            stream.write(raw)\n    before = {name: hashlib.sha256(raw).hexdigest() for name, raw in sources.items()}\n    if fingerprints() != before:\n        raise ValueError(\'sources changed while preparing the snapshot; preserve incomplete output\')\n    return {\'schema_version\': \'canonical-moon-inputs.v1\', \'snapshot_created\': True,\n            \'qualification_granted\': False, \'source_sha256\': before}\n\n\ndef collect() -> dict:\n    manifest = generator.load_generation_manifest()\n    generator.verify_source_identity(manifest)\n    canonical = manifest[\'canonical\']; runtime = generator.runtime_identity()\n    digest = os.environ.get(\'SOL_MOON_GENERATOR_IMAGE_DIGEST\')\n    if not re.fullmatch(r\'sha256:[a-f0-9]{64}\', str(canonical.get(\'image_digest\', \'\'))) or digest != canonical[\'image_digest\']:\n        raise ValueError(\'trusted launcher must assert the exact pinned image digest\')\n    if runtime[\'system\'] != \'Linux\' or runtime[\'machine\'] not in (\'x86_64\', \'amd64\') \\\n            or runtime[\'implementation\'] != \'CPython\' or runtime[\'python_version\'] != canonical[\'python_version\']:\n        raise ValueError(\'native pinned Linux x86_64 CPython runtime required\')\n    if canonical[\'status\'] not in (\'pending\', \'qualified\'):\n        raise ValueError(\'unsupported canonical qualification state\')\n    if canonical[\'status\'] == \'qualified\' and generator.canonical_errors(manifest, runtime, digest):\n        raise ValueError(\'recorded qualification conditions are incomplete\')\n    revision = os.environ.get(\'GITHUB_SHA\')\n    if revision is not None and re.fullmatch(r\'[a-f0-9]{40}\', revision) is None:\n        raise ValueError(\'source revision must be a complete Git SHA\')\n    if set(manifest[\'outputs\']) != set(OUTPUTS):\n        raise ValueError(\'both authoritative outputs must be pinned\')\n    before = fingerprints()\n    built = generator.build()\n    if len(built) != len(OUTPUTS) or not all(isinstance(text, str) for text in built):\n        raise ValueError(\'generator must return exactly two UTF-8 module strings\')\n    generated = {name: hashlib.sha256(text.encode(\'utf-8\')).hexdigest() for name, text in zip(OUTPUTS, built)}\n    log = io.StringIO()\n    with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):\n        numerical_exit = validator.main([\'--require-canonical\'] if canonical[\'status\'] == \'qualified\' else [])\n    after = fingerprints()\n    committed = {name: after[name] for name in OUTPUTS}\n    passed = before == after and generated == manifest[\'outputs\'] == committed and numerical_exit == 0\n    return {\'schema_version\': \'canonical-moon-evidence.v1\',\n            \'status\': \'comparison_passed\' if passed else \'comparison_failed\',\n            \'comparison_passed\': passed, \'qualification_status\': canonical[\'status\'],\n            \'qualification_granted\': False, \'source_revision\': revision,\n            \'completed_at_utc\': dt.datetime.now(dt.timezone.utc).isoformat(),\n            \'runtime\': runtime, \'launcher_asserted_image_digest\': digest,\n            \'scope\': \'One full source/output/numerical comparison; two fresh native image runs and independent review are still required for qualification.\',\n            \'source_sha256_before\': before, \'source_sha256_after\': after,\n            \'generated_sha256\': generated, \'committed_sha256\': committed,\n            \'numerical_validator_exit\': numerical_exit, \'validator_log\': log.getvalue()}\n\n\ndef main(argv: list[str] | None = None) -> int:\n    parser = argparse.ArgumentParser(description=__doc__)\n    parser.add_argument(\'--snapshot\', type=Path, help=\'copy only fixed public inputs into a new build directory; does not qualify them\')\n    args = parser.parse_args(argv)\n    try:\n        report = snapshot(args.snapshot) if args.snapshot is not None else collect()\n    except (ValueError, KeyError, TypeError, OSError) as exc:\n        print(json.dumps({\'schema_version\': \'canonical-moon-evidence.v1\', \'status\': \'refused\',\n                          \'comparison_passed\': False, \'qualification_granted\': False,\n                          \'error\': str(exc)}, allow_nan=False))\n        return 2\n    print(json.dumps(report, indent=2, allow_nan=False))\n    return 0 if report.get(\'snapshot_created\') or report[\'comparison_passed\'] else 1\n\n\nif __name__ == \'__main__\':\n    raise SystemExit(main())\n'
root=Path(tempfile.mkdtemp(prefix='sol-moon-native-20261103-',dir='/tmp'))
source=root/'inputs';source.mkdir()
print('SOL_WORK_ROOT='+str(root),flush=True)
if platform.system()!='Linux' or platform.machine()!='x86_64':raise RuntimeError('Native Linux x86_64 VM required')
for name,digest in EXPECTED.items():
    if name=='tools/collect_moon_evidence.py':raw=COLLECTOR
    else:
        url='https://raw.githubusercontent.com/Protonmatter/sol/'+REVISION+'/'+name
        with urllib.request.urlopen(url,timeout=30) as response:raw=response.read(33554433)
        if len(raw)>33554432:raise RuntimeError('Oversized public input')
        if name=='tools/validate_moons.py':
            raw=raw.replace(b'def main() -> int:',b'def main(argv: list[str] | None = None) -> int:').replace(b'args = parser.parse_args()',b'args = parser.parse_args(argv)')
    if hashlib.sha256(raw).hexdigest()!=digest:raise RuntimeError('Input identity differs: '+name)
    target=source/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(raw)
print('SOL_INPUTS_VERIFIED='+str(len(EXPECTED)),flush=True)
with (root/'image-pull.log').open('w') as stream:
    subprocess.run(['docker','pull','--platform','linux/amd64',IMAGE],stdout=stream,stderr=subprocess.STDOUT,check=True,timeout=300)
image=json.loads(subprocess.run(['docker','image','inspect',IMAGE],capture_output=True,text=True,check=True,timeout=30).stdout)[0]
if image['Architecture']!='amd64' or image['Os']!='linux' or not any(value.endswith('@'+IMAGE.split('@')[1]) for value in image['RepoDigests']):raise RuntimeError('Image architecture/digest differs')
metadata=dict(schema_version='sol-cloud-moon-native.v1',host_system=platform.system(),host_machine=platform.machine(),
             source_revision_base=REVISION,current_source_sha256=EXPECTED,collector_sha256=hashlib.sha256(COLLECTOR).hexdigest(),
             image_ref=IMAGE,image_id=image['Id'],image_architecture=image['Architecture'],image_os=image['Os'],repo_digests=image['RepoDigests'],
             started_at_utc=dt.datetime.now(dt.timezone.utc).isoformat(),runs=[])
(root/'native-metadata.json').write_text(json.dumps(metadata,indent=2)+'\n')
for index in (1,2):
    result=subprocess.run(['docker','run','--pull=never','--rm','--platform','linux/amd64','--network','none','--read-only',
        '--cpus=2','--memory=1g','--pids-limit=128','--cap-drop=ALL','--security-opt=no-new-privileges',
        '--mount','type=bind,src='+str(source)+',dst=/work,readonly','--workdir','/work',
        '--env','PYTHONDONTWRITEBYTECODE=1','--env','SOL_MOON_GENERATOR_IMAGE_DIGEST='+IMAGE.split('@')[1],
        IMAGE,'python','-B','tools/collect_moon_evidence.py'],capture_output=True,text=True,timeout=300)
    (root/('comparison-'+str(index)+'.json')).write_text(result.stdout)
    (root/('comparison-'+str(index)+'.stderr')).write_text(result.stderr)
    report=json.loads(result.stdout)
    metadata['runs'].append(dict(index=index,exit_code=result.returncode,report_sha256=hashlib.sha256(result.stdout.encode()).hexdigest(),
                                comparison_passed=report.get('comparison_passed'),generated_sha256=report.get('generated_sha256'),runtime=report.get('runtime')))
    (root/'native-metadata.json').write_text(json.dumps(metadata,indent=2)+'\n')
    print('SOL_RUN_RESULT='+json.dumps(metadata['runs'][-1]),flush=True)
metadata['completed_at_utc']=dt.datetime.now(dt.timezone.utc).isoformat()
(root/'native-metadata.json').write_text(json.dumps(metadata,indent=2)+'\n')
print('SOL_NATIVE_COMPLETE='+str(root),flush=True)
