"""Compile and execute the fixed original-library probe (no network imports).""" from __future__ import annotations import argparse import hashlib import json import os from pathlib import Path import shutil import subprocess import sys import time import uuid ROOT = Path(__file__).resolve().parents[2] SOURCE = Path(__file__).resolve().parent LOCAL = ROOT / "local_state/battle_runtime" def compile_probe(build_directory: Path | None = None) -> dict: sdk = LOCAL / "air_sdk" build = build_directory if build_directory is not None else LOCAL / "build" build.mkdir(parents=True, exist_ok=True) captured_source = build / "source" captured_source.mkdir(exist_ok=True) source_bytes = (SOURCE / "OriginalProbe.as").read_bytes() (captured_source / "OriginalProbe.as").write_bytes(source_bytes) bridge = SOURCE / "SnapshotBridge.as" bridge_bytes = bridge.read_bytes() if bridge.is_file() else None if bridge_bytes is not None: (captured_source / "SnapshotBridge.as").write_bytes(bridge_bytes) config = build / "compiler-config.xml" config.write_text("", encoding="utf-8") command = [shutil.which("java") or "java", "-Duser.language=en", "-Duser.country=US", "-jar", str(sdk / "lib/mxmlc-cli.jar"), "-load-config=" + str(config), "-compiler.external-library-path=" + str(sdk / "frameworks/libs/air/airglobal.swc"), "-compiler.library-path=" + str(sdk / "frameworks/libs/core.swc"), "-swf-version=50", "-debug=true", "-default-frame-rate=50", "-default-size=640,960", "-output=" + str(build / "OriginalProbe.swf"), str(captured_source / "OriginalProbe.as")] if bridge_bytes is not None: command.insert(-1, "-source-path=" + str(captured_source)) command.insert(-1, "-includes=SnapshotBridge") result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) evidence = {"command": command, "exit_code": result.returncode, "stdout": result.stdout, "stderr": result.stderr, "source_sha256": hashlib.sha256(source_bytes).hexdigest()} (build / "compile.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8") if result.returncode != 0: raise RuntimeError("AIR harness compile failed: " + result.stdout + result.stderr) shutil.copyfile(SOURCE / "probe-app.xml", build / "probe-app.xml") descriptor = build / "probe-app.xml" descriptor.write_text(descriptor.read_text(encoding="utf-8").replace( "local.ranchassistant.originalprobe", "local.ranchassistant.originalprobe.j" + uuid.uuid4().hex), encoding="utf-8") evidence["swf_sha256"] = hashlib.sha256((build / "OriginalProbe.swf").read_bytes()).hexdigest() if bridge_bytes is not None: evidence["snapshot_bridge_sha256"] = hashlib.sha256(bridge_bytes).hexdigest() return evidence def execute_probe(*, timeout: float = 690.0, cancel_event=None, scene: bool = False, source_request: dict | None = None) -> dict: # Re-derive all original libraries rather than accepting imported manifest claims. from tools.battle_runtime.prepare import prepare from tools.battle_runtime.trusted import SDK_FILES, LIBRARY_FILES, verify_files dependency_errors = verify_files(LOCAL / "air_sdk", SDK_FILES) if dependency_errors: raise RuntimeError("Untrusted/missing AIR dependencies: " + json.dumps(dependency_errors)) identity = prepare() validation = None if source_request is not None: from tools.battle_runtime.inputs import validate validation = validate(source_request) if validation["reasons"]: raise ValueError("Original request refused: " + json.dumps(validation["reasons"])) attempt = LOCAL / "experiments" / uuid.uuid4().hex attempt.mkdir(parents=True) compiler = compile_probe(attempt / "build") library_errors = verify_files(LOCAL / "original", LIBRARY_FILES) if library_errors: raise RuntimeError("Original library identity mismatch: " + json.dumps(library_errors)) request = attempt / "request.json" nonce = uuid.uuid4().hex native_request = validation["native_request"] if validation is not None else {"stage_id":"0101","difficulty":1,"scene":scene} native_request = dict(native_request,nonce=nonce,watchdog_ms=int(timeout*1000)) request.write_text(json.dumps(native_request,ensure_ascii=False,allow_nan=False), encoding="utf-8") sdk = LOCAL / "air_sdk" command = [str(sdk / "bin/adl64.exe"), "-runtime", str(sdk / "runtimes/air/win64"), "-nodebug", "-profile", "extendedDesktop", str(attempt / "build/probe-app.xml"), "--", str(LOCAL / "original"), str(request), str(attempt / "result.json")] started = time.monotonic() with (attempt / "stdout.log").open("wb") as stdout, (attempt / "stderr.log").open("wb") as stderr: process = subprocess.Popen(command, cwd=attempt, stdout=stdout, stderr=stderr, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) interrupted = None try: while process.poll() is None: if cancel_event is not None and cancel_event.is_set(): interrupted = "cancelled"; break if time.monotonic() - started >= timeout: interrupted = "timeout"; break time.sleep(.05) finally: if process.poll() is None: process.kill() process.wait(timeout=5) result_file = attempt / "result.json" result = json.loads(result_file.read_text(encoding="utf-8")) if result_file.exists() and not interrupted else { "status": interrupted or "process_failed", "battle_executed": None, "settlement_eligible": False} if result_file.exists() and not interrupted and result.get("nonce") != nonce: raise ValueError("Native AIR result nonce mismatch") audit = audit_resources(result) evidence = {"command": command, "compiler": compiler, "process_exit_code": process.returncode, "duration_seconds": time.monotonic() - started, "result": result, "resource_identity": {"apk_sha256": identity["apk_sha256"], "main_swf_sha256": identity["main_swf_sha256"]}, "resource_audit": audit, "input_sha256":hashlib.sha256(json.dumps(source_request,ensure_ascii=True,allow_nan=False,sort_keys=True,separators=(",", ":")).encode("ascii")).hexdigest() if source_request is not None else None, "directory": str(attempt)} (attempt / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8") return evidence def audit_resources(result: dict) -> dict: """Compare every read image with the pinned APK; retain genuine absences.""" import zipfile reads = [event["data"] for event in result.get("events", []) if event.get("kind") == "original_asset_read"] members = {read["member"] for read in reads} candidates = list(ROOT.glob("*_1.9.68.apk")) if len(candidates) != 1: raise ValueError("Ambiguous original APK during resource audit") missing, mismatched = [], [] with zipfile.ZipFile(candidates[0]) as archive: names = set(archive.namelist()) for member in sorted(members): if not member.startswith("codes/") or len(member) != 38 or any(c not in "0123456789abcdef" for c in member[6:]): raise ValueError("Invalid resource identity in original trace") if "assets/" + member not in names: missing.append(member) if any(read.get("crc32") is not None for read in reads if read["member"] == member): mismatched.append(member) else: info = archive.getinfo("assets/" + member) if any(read.get("crc32") != info.CRC or read.get("bytes") != info.file_size for read in reads if read["member"] == member): mismatched.append(member) return {"used_asset_count":len(members), "original_missing_members":missing, "mismatched_members":mismatched, "all_present_assets_match_apk":not mismatched} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--compile-only", action="store_true") parser.add_argument("--scene", action="store_true") args = parser.parse_args() if args.compile_only: print(json.dumps(compile_probe(), indent=2)) else: print(json.dumps(execute_probe(scene=args.scene), indent=2)) if __name__ == "__main__": sys.path.insert(0, str(ROOT)) main()