"""Capture engine evidence outside the evaluated application UI.""" import json import os from pathlib import Path import signal import subprocess import sys from datetime import datetime, timezone root = Path(os.environ["T39_AUDIT_DIR"]) root.mkdir(parents=True, exist_ok=True) # The supervisor is told out of band when the engine has settled the objective, # when a fresh attempt has unsettled it again, and while the park is reporting. outcome = os.environ.get("T39_RUN_OUTCOME") heartbeat = os.environ.get("T39_RUN_HEARTBEAT") settled = ("objective_complete", "objective_failed") with (root / "game.jsonl").open("a", buffering=1) as audit, (root / "engine.log").open("a", buffering=1) as log: def write(record): record["observed_at"] = datetime.now(timezone.utc).isoformat() audit.write(json.dumps(record) + "\n") # The controller's five-second report is real-time, not tick-driven, so it # keeps arriving while the park is paused before the clock starts. if heartbeat and record.get("kind") == "onetile_state": Path(heartbeat).write_text(record["observed_at"]) # A run is three attempts, so a settled outcome is the outcome of the # attempt being played: the controller configuring a fresh park clears it # again, and the supervisor reads this file to decide whether the run -- # rather than the attempt -- is over. if outcome and record.get("kind") == "onetile_initialized": Path(outcome).unlink(missing_ok=True) elif outcome and record.get("kind") in settled: Path(outcome).write_text(record["kind"]) write({"kind": "engine_start", "schema": 1}) child = subprocess.Popen(["stdbuf", "-oL", "-eL", "openrct2", *sys.argv[1:]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) for sig in (signal.SIGINT, signal.SIGTERM): signal.signal(sig, lambda signum, frame: child.send_signal(signum)) for line in child.stdout: log.write(line) if "T39JSON " in line: try: record, _ = json.JSONDecoder().raw_decode(line.split("T39JSON ", 1)[1]) write(record) except (ValueError, TypeError) as error: write({"kind": "observer_error", "message": str(error)}) code = child.wait() write({"kind": "engine_stop", "returncode": code}) sys.exit(code)