"""Execute pinned original AIR combat offline, with original result/check callbacks. Canonical stage/task inputs and complete snapshots use the original compiled BattleCenter/BattleGround/skills. This development adapter never authorizes game API actions or claims server compatibility. See the implementation evidence. """ from __future__ import annotations from collections.abc import Mapping from dataclasses import asdict, dataclass, fields import hashlib import json import math import os from pathlib import Path import sys import time from typing import Any import uuid ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / "local_state/battle_runtime" ORIGINAL_APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d" ORIGINAL_MAIN_SHA256 = "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf" CONTEXTS = frozenset(("ordinary_stage", "task_battle", "task_pass_stage")) # Release checkpoint: final callback-binding/Engine integration QA is pending. # Offline execution remains available. Do not enable before that bounded QA. NATIVE_ADMISSION_ENABLED = False ORIGINAL_FIXTURE_ROSTER = {"kind": "original_fixture", "species": 1001010, "players": 3, "level": 1, "mode": 2, "growth_area": .5, "master_level": 1} @dataclass(frozen=True) class BattleRequest: context: str original_data: Mapping[str, Any] roster: Mapping[str, Any] stage_id: str | None = None difficulty: int = 1 task_id: str | None = None step_index: int | None = None purpose: str = "settlement" team: str | None = None battle_position: Mapping[str, Any] | None = None def original_fixture_request() -> BattleRequest: """Explicit synthetic fixture, never an account roster or settlement request.""" return BattleRequest("ordinary_stage", {"source": "original_apk", "resource_identity": { "apk_sha256": ORIGINAL_APK_SHA256, "main_swf_sha256": ORIGINAL_MAIN_SHA256}}, dict(ORIGINAL_FIXTURE_ROSTER), stage_id="0101", purpose="offline_validation") def _canonical(value: Any) -> bytes: return json.dumps(value, ensure_ascii=True, allow_nan=False, sort_keys=True, separators=(",", ":")).encode("ascii") def _validate_callback_binding(scene, native, evidence, validation): """Validate original callback provenance/data; never synthesize statistics.""" data=scene["battle_data"] events=native.get("events",[]) completed=[event for event in events if event.get("kind")=="original_battle_completed"] built=[event for event in events if event.get("kind")=="snapshot_bridge_built"] if len(completed)!=1 or completed[0].get("data")!=scene or not built or built[-1].get("data",{}).get("installed") is not True: raise ValueError("Missing or mismatched original snapshot/completion callback evidence") if not any(event.get("kind")=="BattleCenter_started" for event in events): raise ValueError("Missing original BattleCenter execution evidence") ids=data.get("battleMonIds") expected=validation["expected_battle_mon_ids"] if not isinstance(ids,list) or any(type(mid) is not int for mid in ids) or sorted(ids)!=sorted(expected): raise ValueError("Original callback roster does not match the selected input team") records=scene["anomaly_records"] if set(records)!={"mons","damages","master","text"} or not isinstance(records["mons"],list) or not isinstance(records["damages"],list) or not isinstance(records["text"],str): raise ValueError("Original anomaly records are incomplete") checked=[record.get("mid") for record in records["mons"] if isinstance(record,dict)] # Original makeRecord may serialize mid as a decimal String, while # BattleData.battleMonIds is numeric. Compare identity without rewriting # either original output representation. if any(type(mid) not in (str,int) or not str(mid).isdecimal() for mid in checked): raise ValueError("Invalid original player integrity record identity") if len(checked)!=len(records["mons"]) or sorted(map(int,checked))!=sorted(expected): raise ValueError("Original player integrity checks do not match the selected roster") if data["cheatNum"]==0: if data.get("cheatRecords")!="": raise ValueError("Original zero-count callback serialization mismatch") elif not isinstance(data.get("cheatRecords"),str) or json.loads(data["cheatRecords"])!=records: raise ValueError("Original serialized anomaly records were altered") for field in ("leftTime","killNum","totalDamage","bossDamage","deadNum","aliveNum","apLeft"): if type(data.get(field)) is not int: raise ValueError("Missing original callback statistic: "+field) if not 0 <= data["leftTime"] <= validation["battle_seconds"]*1000 or not isinstance(data.get("killMonster"),dict): raise ValueError("Invalid original battle clock or kill dictionary") if scene.get("game_api_requests")!=0 or scene.get("requested_fps")!=50 or not isinstance(scene.get("wall_ms"),(int,float)) or scene["wall_ms"]<=0 or scene.get("observed_frames",0)<=0: raise ValueError("Missing original offline clock/frame evidence") if not native.get("nonce") or not native.get("application_id") or not native.get("storage_directory"): raise ValueError("Missing isolated native application identity") return True def _coerce(request) -> tuple[BattleRequest | None, list[dict]]: if isinstance(request, BattleRequest): try: request = asdict(request) except (TypeError, ValueError, RecursionError) as error: return None, [{"code": "invalid_request", "detail": str(error)}] if not isinstance(request, Mapping): return None, [{"code": "invalid_request", "detail": "Expected BattleRequest or a mapping"}] allowed = {field.name for field in fields(BattleRequest)} unknown = set(request) - allowed if unknown: return None, [{"code": "unknown_request_fields", "detail": ", ".join(sorted(map(str, unknown)))}] try: encoded = _canonical(dict(request)) if len(encoded) > 4 * 1024 * 1024: raise ValueError("Request exceeds 4 MiB") snapshot = json.loads(encoded) # detached from mutable caller state result = BattleRequest(**snapshot) except (TypeError, ValueError, OverflowError, RecursionError) as error: return None, [{"code": "invalid_request", "detail": str(error)}] return result, [] class BattleRuntime: """Fixed original runtime, with a separate offline-validation capability. inspect() is read-only and returns a dictionary. supported means this exact OFFLINE job can execute. Online callers must additionally require faithful AND settlement_eligible. Complete original snapshot requests can be admitted; only a verified completed callback can yield an eligible result. Server acceptance remains explicitly unverified. Diagnostic fixtures never qualify. Imported commands, paths, manifests, engine results and verified claims never select an executable or enable support. """ def __init__(self, runtime_config: Mapping | None = None): self._config_reasons = [] if runtime_config is not None: if not isinstance(runtime_config, Mapping) or set(runtime_config) - {"backend"}: self._config_reasons.append({"code": "untrusted_runtime_config", "detail": "Only backend=original_air is accepted; commands and verification claims are forbidden"}) elif runtime_config.get("backend", "original_air") != "original_air": self._config_reasons.append({"code": "unknown_backend", "detail": "Expected original_air"}) def inspect(self, request: BattleRequest | Mapping) -> dict: req, reasons = _coerce(request) reasons.extend(self._config_reasons) result = {"supported": False, "offline_supported": False, "settlement_eligible": False, "faithful": False, "approximate":False,"original_core": True, "backend": "original_air", "execution_mode":"original","server_acceptance_verified":False, "reasons": reasons, "resource_identity": {"apk_sha256": ORIGINAL_APK_SHA256, "main_swf_sha256": ORIGINAL_MAIN_SHA256, "baseline": "original APK 1.9.68", "live_resource_match_verified": False}, "coverage": {"validated_offline_fixtures": ["ordinary_stage:0101:1:three_level1_slimes"], "validated_skills": [3], "validated_online_contexts": [], "validated_callback_route":"BattlePanel.battleCompleteHandler to local observer", "original_checks_preserved": True}, "limitations": ["Original APK lacks 1001010_q_2s.png; original local error callbacks execute", "Math.random is native and unseeded; no synchronized trace comparison", "Current live-resource matching and server acceptance remain unvalidated"]} if req is None: return result result["request_sha256"] = hashlib.sha256(_canonical(asdict(req))).hexdigest() if isinstance(req.roster,Mapping) and ("snapshot" in req.roster or "master" in req.roster): return self._inspect_snapshot(req,result) if not isinstance(req.context, str) or req.context not in CONTEXTS: reasons.append({"code": "unknown_context", "detail": str(req.context)}) elif req.context != "ordinary_stage": reasons.append({"code": "task_route_not_validated", "detail": req.context}) if req.purpose not in ("settlement", "offline_validation"): reasons.append({"code": "unknown_purpose", "detail": str(req.purpose)}) if req.purpose != "offline_validation": reasons.append({"code": "settlement_not_validated", "detail": "This development build cannot authorize an online battle start or settlement"}) if req.stage_id != "0101" or type(req.difficulty) is not int or req.difficulty != 1: reasons.append({"code": "scene_not_validated", "detail": "Only original stage 0101, difficulty 1 has a native fixture proof"}) if req.task_id is not None or req.step_index is not None: reasons.append({"code": "task_input_not_validated", "detail": "No task context may reuse the ordinary-stage fixture"}) if not isinstance(req.original_data, Mapping): reasons.append({"code": "original_data_required", "detail": "Expected original APK source and resource identity"}) else: data = req.original_data if set(data) - {"source", "resource_identity"}: reasons.append({"code": "external_battle_data_unvalidated", "detail": "Only pinned original APK tables are executed; imported tables/commands/verification claims are refused"}) identity = data.get("resource_identity") if data.get("source") != "original_apk" or not isinstance(identity, Mapping): reasons.append({"code": "original_data_identity_missing", "detail": "Expected source=original_apk and resource_identity"}) elif dict(identity) != {"apk_sha256": ORIGINAL_APK_SHA256, "main_swf_sha256": ORIGINAL_MAIN_SHA256}: reasons.append({"code": "resource_identity_mismatch", "detail": "Expected the pinned original APK and main SWF"}) if not isinstance(req.roster, Mapping) or dict(req.roster) != ORIGINAL_FIXTURE_ROSTER: reasons.append({"code": "roster_not_validated", "detail": "Only the explicit original_fixture roster is supported offline; real snapshots and reference stats are unvalidated"}) if os.name != "nt": reasons.append({"code": "runtime_platform_unavailable", "detail": "The pinned native runner uses Windows x64 AIR"}) from tools.battle_runtime.trusted import LIBRARY_FILES, SDK_FILES, verify_files sdk_reasons = verify_files(LOCAL / "air_sdk", SDK_FILES) library_reasons = verify_files(LOCAL / "original", LIBRARY_FILES) reasons.extend(sdk_reasons) reasons.extend(library_reasons) result["resource_identity"]["sdk_pins_match"] = not sdk_reasons result["resource_identity"]["prepared_library_pins_match"] = not library_reasons candidates = list(ROOT.glob("*_1.9.68.apk")) if not candidates: reasons.append({"code": "original_apk_missing", "detail": "The worker re-verifies the original local APK before executing"}) elif len(candidates) != 1: reasons.append({"code":"original_apk_ambiguous","detail":"Expected exactly one original *_1.9.68.apk"}) result["supported"] = result["offline_supported"] = not reasons return result def _inspect_snapshot(self,req,result): from tools.battle_runtime.inputs import validate from tools.battle_runtime.trusted import LIBRARY_FILES,SDK_FILES,verify_files reasons = result["reasons"] if req.purpose not in ("settlement","offline_validation"): reasons.append({"code":"unknown_purpose","detail":str(req.purpose)}) if os.name != "nt": reasons.append({"code":"runtime_platform_unavailable","detail":"Windows x64 AIR is required"}) if not (ROOT / "tools/battle_runtime/SnapshotBridge.as").is_file(): reasons.append({"code":"snapshot_bridge_unavailable","detail":"Bundled original snapshot bridge source is missing"}) try: validation = validate(asdict(req)) except (OSError,ValueError,KeyError,TypeError,AttributeError) as error: validation = {"reasons":[{"code":"invalid_original_request","detail":str(error)}]} reasons.extend(validation["reasons"]) sdk_reasons = verify_files(LOCAL/"air_sdk",SDK_FILES) library_reasons = verify_files(LOCAL/"original",LIBRARY_FILES) reasons.extend(sdk_reasons);reasons.extend(library_reasons) result["resource_identity"].update(sdk_pins_match=not sdk_reasons,prepared_library_pins_match=not library_reasons) result["coverage"] = {**result["coverage"],**validation.get("coverage",{}),"input_mode":"original_snapshot"} result["coverage"]["validated_offline_contexts"] = sorted(CONTEXTS) result["coverage"]["fidelity_basis"] = "unchanged original compiled core, original event loop and result/check callbacks" result["limitations"] = ["Server acceptance and current live-resource compatibility have not been tested", "Native Math.random is unseeded; results use the actual original event loop", "Original empty optional image declarations retain their recorded local IO-error callbacks"] result["native_position"] = validation.get("position") seconds = validation.get("battle_seconds",300) result["battle_seconds"] = seconds result["watchdog_seconds"] = seconds*2+90 result["supported"] = result["offline_supported"] = not reasons result["faithful"] = not reasons result["settlement_eligible"] = NATIVE_ADMISSION_ENABLED and not reasons and req.purpose=="settlement" result["native_admission_validation_pending"] = not NATIVE_ADMISSION_ENABLED result["admission_requires_completed_original_checks"] = True return result def run(self, request: BattleRequest | Mapping, *, cancel_event=None, timeout: float | None = None) -> dict: if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (float, int)) or not math.isfinite(timeout) or timeout <= 0): raise ValueError("timeout must be a finite positive number") started = time.monotonic() if cancel_event is not None and cancel_event.is_set(): return {"status": "cancelled", "battle_executed": False, "settlement_eligible": False, "faithful": False} # Freeze caller input once, before inspection and process serialization. # Mutating a shared policy/snapshot cannot redirect an inspected job. frozen, _ = _coerce(request) from tools.battle_runtime.inputs import InspectionInterrupted, inspection_budget try: with inspection_budget(cancel_event,started+timeout if timeout is not None else None): capability = self.inspect(frozen if frozen is not None else request) except InspectionInterrupted as error: return {"status":error.status,"battle_executed":False,"battle_completed":False, "settlement_eligible":False,"faithful":False} if not capability["supported"]: return {"status": "unsupported", "battle_executed": False, "settlement_eligible": False, "faithful": False, "capability": capability, "reasons": capability["reasons"]} deadline = timeout if timeout is not None else capability.get("watchdog_seconds",690.0) remaining = deadline-(time.monotonic()-started) if (cancel_event is not None and cancel_event.is_set()) or remaining <= 0: return {"status":"cancelled" if cancel_event is not None and cancel_event.is_set() else "timeout", "battle_executed":False,"battle_completed":False,"faithful":False,"settlement_eligible":False} source_request = asdict(frozen) if capability["coverage"].get("input_mode")=="original_snapshot" else None return self._execute(scene=True, timeout=remaining, cancel_event=cancel_event, request_sha256=capability["request_sha256"],source_request=source_request, expected_position=capability.get("native_position"),admitted=capability["settlement_eligible"]) def probe_original_components(self, *, cancel_event=None, timeout: float = 60.0) -> dict: """Explicit diagnostic operation; cannot produce settlement data.""" if self._config_reasons: return {"status": "unsupported", "reasons": list(self._config_reasons), "settlement_eligible": False} from tools.battle_runtime.trusted import SDK_FILES, verify_files reasons = verify_files(LOCAL / "air_sdk", SDK_FILES) if reasons: return {"status": "unsupported", "reasons": reasons, "settlement_eligible": False} return self._execute(scene=False, timeout=timeout, cancel_event=cancel_event, request_sha256=None) def _execute(self, *, scene, timeout, cancel_event, request_sha256,source_request=None,expected_position=None,admitted=False): from tools.battle_runtime.isolation import run_isolated validation=None if source_request is not None: from tools.battle_runtime.inputs import validate validation=validate(source_request) if validation["reasons"]: return {"status":"unsupported","supported":False,"faithful":False,"settlement_eligible":False, "battle_executed":False,"battle_completed":False,"server_acceptance_verified":False, "reasons":validation["reasons"]} attempt = LOCAL / "jobs" / uuid.uuid4().hex attempt.mkdir(parents=True) nonce = uuid.uuid4().hex output = attempt / "worker-result.json" argv = [sys.executable, "-I", "-B", str(ROOT / "tools/battle_runtime/worker.py"), "--output", str(output), "--nonce", nonce, "--action", "scene" if scene else "components","--timeout",str(timeout)] if source_request is not None: input_path = attempt / "worker-input.local.json" input_path.write_bytes(_canonical(source_request)) argv.extend(("--input",str(input_path))) process = run_isolated(argv, cwd=attempt, timeout=timeout, cancel_event=cancel_event) result = {"status": process.status, "settlement_eligible": False, "faithful": False, "approximate":False,"original_core":True,"execution_mode":"original", "server_acceptance_verified":False,"supported":False,"terminal":False, "battle_executed": None, "battle_completed": False, "request_sha256": request_sha256, "diagnostics_directory": str(attempt), "process_exit_code": process.returncode} if process.status != "completed": result["error"] = process.stderr[-4000:] or process.stdout[-4000:] return result try: if output.stat().st_size > 2 * 1024 * 1024: raise ValueError("Oversized original runner evidence") payload = json.loads(output.read_text(encoding="utf-8")) if payload["nonce"] != nonce or payload["schema"] != 1: raise ValueError("Original runner evidence binding mismatch") evidence = payload["evidence"] native = evidence["result"] if source_request is not None and evidence.get("input_sha256") != request_sha256: raise ValueError("Native execution belongs to a different input snapshot") if evidence["resource_identity"].get("apk_sha256") != ORIGINAL_APK_SHA256 or evidence["resource_identity"]["main_swf_sha256"] != ORIGINAL_MAIN_SHA256: raise ValueError("Original runner resource identity mismatch") if native.get("settlement_eligible") is not False or native.get("faithful", False) is not False: raise ValueError("Runner claimed unvalidated settlement eligibility or fidelity") if evidence.get("resource_audit", {}).get("all_present_assets_match_apk") is not True: raise ValueError("Original assets do not match the pinned APK") completed = native.get("status") == ("scene_completed" if scene else "probe_completed") if completed and evidence["process_exit_code"] == 0: result["status"] = "completed" else: result["status"] = "error" result["error"] = native.get("error") or {"code":"native_process_failed", "detail":"Original runtime did not complete the requested operation"} result["battle_executed"] = native.get("battle_executed") is True result["evidence"] = evidence if completed and scene: if not result["battle_executed"] or not isinstance(native.get("scene_result"), dict): raise ValueError("Scene completion lacks an executed original battle result") scene_result = native["scene_result"] outcome = scene_result.get("outcome") data = scene_result.get("battle_data") if outcome not in ("win", "loss") or not isinstance(data, dict) or type(data.get("win")) is not bool: raise ValueError("Invalid native outcome/data") cheat_num = data.get("cheatNum") if type(cheat_num) not in (int,float) or not math.isfinite(cheat_num) or cheat_num < 0 or int(cheat_num) != cheat_num: raise ValueError("Missing or invalid original anomaly count") if data["win"] != (outcome == "win") or not isinstance(scene_result.get("anomaly_records"), dict): raise ValueError("Native result is inconsistent or lacks original anomaly records") wanted_position = expected_position if expected_position is not None else {"battleType":"stage", "stageLevel":"1", "stageId":"0101", "taskTypeId":None, "taskStep":0} if data.get("battlePosition") != wanted_position: raise ValueError("Native result belongs to a different battle route") if validation is not None: _validate_callback_binding(scene_result,native,evidence,validation) result["outcome"] = outcome result["offline_result"] = scene_result result["battle_data"] = data result["battle_completed"] = True result["checks_passed"] = data.get("cheatNum")==0 result["server_validated"] = False result["faithful"] = validation is not None result["supported"] = True result["terminal"] = True result["execution_status"] = "completed" result["terminal_reason"] = scene_result.get("terminal_reason") result["wall_time_ms"] = scene_result.get("wall_ms") result["requires_realtime_wait"] = False result["resource_identity"] = evidence["resource_identity"] result["settlement_eligible"] = admitted and validation is not None and result["checks_passed"] if data.get("cheatNum",0)>0: result["status"]="anomaly" except (OSError, KeyError, TypeError, ValueError) as error: result.update(status="error", battle_executed=None, battle_completed=False,settlement_eligible=False,faithful=False,error=str(error)) result.pop("outcome", None); result.pop("offline_result", None);result.pop("battle_data",None) return result