sidrefresh's picture
Add files using upload-large-folder tool
5463b45 verified
Raw History Blame Contribute Delete
4.51 kB
"""Preserve available game outputs; never assign a gameplay score."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
from datetime import datetime, timezone
def copy(source, output, attempts=3):
"""Copy, retrying briefly: a bind mount can fail a copy that then succeeds.
Seen locally as EDEADLK on the host bind mount while filing the notes. The
collector runs on a loop, so a transient loss would usually heal itself — but
not for the last collection of a try, which is that try's evidence.
"""
for attempt in range(attempts):
try:
shutil.copy2(source, output)
return
except OSError:
if attempt == attempts - 1:
raise
time.sleep(0.2)
def current_try():
"""Which try's park is on screen; the supervisor publishes it per try."""
try:
return int(json.loads(Path("/logs/artifacts/tries/current.json").read_text())["try"])
except (FileNotFoundError, KeyError, ValueError, OSError):
return int(os.environ.get("T37_TRY", "1"))
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--screenshot", action="store_true")
args = parser.parse_args()
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
home = Path.home()
# The park is thrown away between tries, so each try's saves are kept apart
# and every try can be proven against the engine afterwards.
attempt = current_try()
roots = {
f"save/try-{attempt}": home / ".config/OpenRCT2/save",
f"screenshots/try-{attempt}": home / ".config/OpenRCT2/screenshot",
# The notepad's file is cumulative and outlives the park reset, so the
# copy filed under a try is that try's view of the agent's own notes:
# the try-N copy stops changing the moment try N+1 begins.
f"notes/try-{attempt}": Path(os.environ.get("T37_NOTES_DIR", "/notes")),
"desktop": home / "Desktop",
"downloads": home / "Downloads",
}
targets = [Path("/logs/artifacts"), Path("/logs/verifier/artifacts")]
errors = []
records = []
for target in targets:
target.mkdir(parents=True, exist_ok=True)
audit = targets[0] / "audit"
if audit.exists():
shutil.copytree(audit, targets[1] / "audit", dirs_exist_ok=True)
for label, root in roots.items():
if not root.is_dir():
continue
for source in sorted(root.rglob("*")):
if not source.is_file() or source.is_symlink():
continue
if source.suffix.lower() not in {".park", ".sv6", ".sv4", ".png", ".jpg",
".jpeg", ".bak", ".txt", ".md"}:
continue
relative = Path(label) / source.relative_to(root)
try:
for target in targets:
output = target / relative
output.parent.mkdir(parents=True, exist_ok=True)
copy(source, output)
saved = targets[0] / relative
records.append({
"path": str(relative), "bytes": saved.stat().st_size,
"sha256": hashlib.sha256(saved.read_bytes()).hexdigest(),
})
except OSError as error:
errors.append(f"{relative}: {error}")
if args.screenshot and os.environ.get("DISPLAY"):
relative = Path("checkpoints") / f"{stamp}.png"
image = targets[0] / relative
image.parent.mkdir(parents=True, exist_ok=True)
result = subprocess.run(["scrot", "-o", str(image)], capture_output=True)
if result.returncode == 0:
(targets[1] / relative).parent.mkdir(parents=True, exist_ok=True)
copy(image, targets[1] / relative)
records.append({
"path": str(relative), "bytes": image.stat().st_size,
"sha256": hashlib.sha256(image.read_bytes()).hexdigest(),
})
else:
errors.append(result.stderr.decode(errors="replace"))
record = {"timestamp_utc": stamp, "artifacts": records, "errors": errors}
for target in targets:
checkpoint = target / "checkpoints" / f"{stamp}.json"
checkpoint.parent.mkdir(parents=True, exist_ok=True)
checkpoint.write_text(json.dumps(record, indent=2) + "\n")
print(json.dumps(record))
if __name__ == "__main__":
main()