diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..c747b39 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -41,6 +41,7 @@ jobs: with: {python-version: '3.12'} - run: python -m pip install -e . - run: harbor run --game-suite minihack-balrog --standard --list + - run: harbor run --game-suite pacman --standard --list - run: python game_first_exam/tests/test_game_harbor.py fresh-clone-smoke: runs-on: ubuntu-latest @@ -77,8 +78,43 @@ jobs: name: fresh-clone-room-evidence path: jobs/ retention-days: 7 + pacman-smoke: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + with: {persist-credentials: false} + - uses: actions/setup-python@v5 + with: {python-version: '3.12'} + - uses: docker/setup-docker-action@v5 + with: + version: v29.5.2 + set-host: true + daemon-config: '{"features":{"containerd-snapshotter":true}}' + - run: python -m pip install -e . + - name: Assemble the pinned Pac-Man files image + run: python scripts/files_image.py build pacman-files + - name: Run the 600-point reference + run: | + harbor run --game-suite pacman --standard -c configs/harbor/oracle.json \ + --jobs-dir "$PWD/jobs" --job-name pacman-clear -y + python ci_checks/check-pacman-result.py jobs/pacman-clear 1 + - name: Run the ghost-collision control + run: | + python game_first_exam/tests/benchmarks/pacman/ghost_collision/run_harbor.py + python ci_checks/check-pacman-result.py jobs/pacman-failure-control 0 + - uses: actions/upload-artifact@v4 + if: always() + with: + name: pacman-smoke-evidence + path: | + jobs/*/result.json + jobs/*/*/artifacts/data/final.json + jobs/*/*/verifier/reward.json + jobs/*/*/trial.log + retention-days: 7 invariants: - needs: [static, adapters, harbor, fresh-clone-smoke] + needs: [static, adapters, harbor, fresh-clone-smoke, pacman-smoke] if: ${{ always() }} runs-on: ubuntu-latest steps: @@ -87,4 +123,5 @@ jobs: ADAPTERS: ${{ needs.adapters.result }} HARBOR: ${{ needs.harbor.result }} SMOKE: ${{ needs.fresh-clone-smoke.result }} - run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success + PACMAN_SMOKE: ${{ needs.pacman-smoke.result }} + run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success && test "$PACMAN_SMOKE" = success diff --git a/README.md b/README.md index 5e00e1f..01fc7c5 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi ## 已接入的游戏 -当前共有 **5 个 benchmark、42 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 44 个任务目录**。同一原生任务的不同模式单独计数。 +当前共有 **6 个 benchmark、43 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 45 个任务目录**。同一原生任务的不同模式单独计数。 | Benchmark | standard | 其他模式 | 主要内容 | 说明 | |---|---:|---|---|---| @@ -33,6 +33,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi | TextWorld | 9 | — | 文字探索、寻宝、烹饪 | 冻结 `.z8` 游戏,通过原生引擎执行 | | Baba Is AI | 2 | — | 移动文字、改变规则、解谜 | 基础关卡与复合关卡的最小 smoke 验证 | | MiniHack | 10 | 1 privileged | Room、River、导航、战斗、Quest、Boxoban | 原生 MiniHack/NLE 环境;Room 另有 privileged 版本 | +| Pac-Man | 1 | — | 浏览器吃豆与躲避幽灵 | GameWorld 固定 600 分目标;通关 1.0、死亡对照 0.0,含录像 | 套件由 [configs/game_suites/](configs/game_suites/) 定义,可以重叠,数量不能直接相加: @@ -45,8 +46,9 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi | `textworld` | 9 | TextWorld 当前实例 | | `babaisai` | 2 | Baba Is AI smoke | | `minihack` | 3 | Room/River standard + Room privileged | +| `pacman` | 1 | GameWorld Pac-Man 600 分;本地适配验证中 | | `minihack-balrog` | 8 | 参考 BALROG 选取的原生 MiniHack 任务 | -| `all` | 44 | 所有套件去重后的任务;汇总时应选择一种模式 | +| `all` | 45 | 所有套件去重后的任务;汇总时应选择一种模式 | `minihack-balrog` 包含 MazeWalk 9×9、MazeWalk 15×15、Corridor R3、CorridorBattle Dark、Quest Easy、Quest Medium、Boxoban Medium、Boxoban Hard。**使用相同原生环境名称不意味着与 BALROG 的 LLM 输入、prompt、agent、seed 和预算完全相同**,成绩不能直接当作 BALROG 排行榜成绩。 @@ -153,7 +155,7 @@ harbor run --game-suite minihack --standard --family room \ | 模式 | 执行方式 | 当前覆盖 | |---|---|---| -| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 5 个游戏、42 个配置 | +| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 6 个游戏、43 个配置 | | `privileged` | agent 可本地探索和规划;最终动作序列由独立 verifier 重新执行 | MiniHack Room | | `realtime` | 首次有效动作计划启动固定 tick;程序与模型思考期间游戏继续推进 | Crafter survival i01 | diff --git a/ci_checks/check-pacman-result.py b/ci_checks/check-pacman-result.py new file mode 100644 index 0000000..672a648 --- /dev/null +++ b/ci_checks/check-pacman-result.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Validate a Pac-Man Harbor reference or failure job from trusted artifacts.""" + +import json +import sys +from pathlib import Path + + +def check(job: Path, expected_success: int): + trials = sorted(job.glob("*/result.json")) + if len(trials) != 1: + raise ValueError(f"Expected one Pac-Man trial in {job}, got {len(trials)}") + + result = json.loads(trials[0].read_text()) + if result.get("exception_info") is not None: + raise ValueError(f"Harbor raised an exception: {result['exception_info']}") + if result.get("agent_info", {}).get("name") != "oracle": + raise ValueError("Reference run must use the oracle agent") + if result["task_name"].rsplit("/", 1)[-1] != "pacman-600-i01-standard": + raise ValueError("Wrong Pac-Man task") + + trial = trials[0].parent + reward = json.loads((trial / "verifier/reward.json").read_text()) + final = json.loads((trial / "artifacts/data/final.json").read_text()) + for key in ("infra_error", "sim_error", "environment_error"): + if reward.get(key) != 0: + raise ValueError(f"{key}: {reward.get(key)}") + if (reward.get("result_valid") != 1 or reward.get("success") != expected_success + or reward.get("primary_score") != expected_success or reward.get("steps", 0) <= 0): + raise ValueError(f"Unexpected verifier outcome: {reward}") + + metrics = final["metrics"] + if final.get("initial_state_sha256") != "628cb4ead38e34e34a34f78fa4481f2a0ccf8e9139acfae69d79dc997e90e36b": + raise ValueError("Pac-Man opening changed") + if final.get("steps") != reward["steps"] or final.get("success") != bool(expected_success): + raise ValueError("Native result disagrees with verifier") + if expected_success: + if metrics["score"] < 600 or metrics["deaths"] != 0: + raise ValueError(f"Reference did not clear 600 points: {metrics}") + elif metrics["score"] >= 600 or metrics["deaths"] < 1: + raise ValueError(f"Control did not end in game over below 600: {metrics}") + print(f"{job}: valid Pac-Man {'clear' if expected_success else 'failure'}, " + f"score={metrics['score']}, steps={reward['steps']}") + + +if __name__ == "__main__": + check(Path(sys.argv[1]), int(sys.argv[2])) diff --git a/configs/game_benchmarks.toml b/configs/game_benchmarks.toml index 8f77b59..fb2e5d7 100644 --- a/configs/game_benchmarks.toml +++ b/configs/game_benchmarks.toml @@ -14,3 +14,6 @@ schema = "game_first_exam/benchmarks/babaisai/instance_schema.py" [benchmarks.minihack] schema = "game_first_exam/benchmarks/minihack/instance_schema.py" + +[benchmarks.pacman] +schema = "game_first_exam/benchmarks/pacman/instance_schema.py" diff --git a/configs/game_suites/pacman.toml b/configs/game_suites/pacman.toml new file mode 100644 index 0000000..e41a517 --- /dev/null +++ b/configs/game_suites/pacman.toml @@ -0,0 +1,10 @@ +schema_version = "game-suite/2.1" +version = "1.0.0" +tier = "smoke" +name = "games-pacman-minimal-v1.0.0" +files_images = ["connection-files", "game-files", "pacman-files"] + +[[tasks]] +name = "pacman-600-i01-standard" +benchmark = "pacman" +family = "score-600" diff --git a/docs/demos/pacman/600-point-clear.mp4 b/docs/demos/pacman/600-point-clear.mp4 new file mode 100644 index 0000000..2357660 Binary files /dev/null and b/docs/demos/pacman/600-point-clear.mp4 differ diff --git a/docs/demos/pacman/explained-clear.mp4 b/docs/demos/pacman/explained-clear.mp4 new file mode 100644 index 0000000..f8955a7 Binary files /dev/null and b/docs/demos/pacman/explained-clear.mp4 differ diff --git a/docs/demos/pacman/explained-failure.mp4 b/docs/demos/pacman/explained-failure.mp4 new file mode 100644 index 0000000..3caf900 Binary files /dev/null and b/docs/demos/pacman/explained-failure.mp4 differ diff --git a/docs/demos/pacman/ghost-collision.mp4 b/docs/demos/pacman/ghost-collision.mp4 new file mode 100644 index 0000000..5ea5391 Binary files /dev/null and b/docs/demos/pacman/ghost-collision.mp4 differ diff --git a/game_first_exam/benchmarks/pacman/README.md b/game_first_exam/benchmarks/pacman/README.md new file mode 100644 index 0000000..36cd38b --- /dev/null +++ b/game_first_exam/benchmarks/pacman/README.md @@ -0,0 +1,7 @@ +# Pac-Man: 600 points + +GameWorld's pinned `23_pacman` browser snapshot. An agent controls Pac-Man with four arrow keys and RGB screenshots. The native score must reach 600 before the native game-over screen. Ghost movement and collisions stay native; a game over terminates with reward zero. The adapter freezes browser time between 500 ms input intervals. The score is read from the native GameWorld API, not OCR or agent output. + +This is an integration task based on the first GameWorld score threshold, not a claim of reproducing the GameWorld leaderboard. The source is https://github.com/gameworld-project/GameWorld-Games/tree/e5ddb16df85b91a1d17bb0577621cc7c5e65d738/benchmark/23_pacman ; see `RIGHTS.md` in that directory. + +The 24-action reference route reached 600 points on the unmodified pinned browser game at seed 42. A stationary control ended in native game over at 120 points. Both browser runs were recorded. The `pacman-files` OCI digest was calculated locally but has not yet been published to GHCR. The Harbor oracle scored 1.0 in 24 actions with 600 points and zero deaths; the 78-action ghost-collision control scored 0.0 with 120 points and one game over. Both verifier records were valid and reported zero environment errors (2026-11-24). diff --git a/game_first_exam/benchmarks/pacman/adapter.py b/game_first_exam/benchmarks/pacman/adapter.py new file mode 100644 index 0000000..96ea2f2 --- /dev/null +++ b/game_first_exam/benchmarks/pacman/adapter.py @@ -0,0 +1,111 @@ +"""Play the pinned GameWorld Pac-Man snapshot with paused browser time.""" + +from base64 import b64decode +from contextlib import ExitStack +from datetime import datetime, timedelta, timezone +from io import BytesIO +from pathlib import Path +from urllib.parse import unquote, urlsplit + +import numpy as np +from PIL import Image +from playwright.sync_api import sync_playwright + +from contracts import Capabilities, Transition +from encoding import png, state_hash + +KEYS = {"wait": None, "up": "ArrowUp", "down": "ArrowDown", "left": "ArrowLeft", "right": "ArrowRight"} +ORIGIN = "http://pacman.test" +TARGET_SCORE = 600 + + +class Adapter: + def __init__(self, instance, assets=None): + self.resources = ExitStack() + try: + self.start((Path(assets) / "game").resolve()) + except BaseException: + self.close() + raise + + def start(self, root): + driver = self.resources.enter_context(sync_playwright()) + browser = driver.chromium.launch(args=["--mute-audio"]) + self.resources.callback(browser.close) + self.page = browser.new_page(viewport={"width": 854, "height": 480}) + + def serve(route): + url = urlsplit(route.request.url) + path = (root / unquote(url.path).lstrip("/")).resolve() + if url.netloc == "pacman.test" and path.is_relative_to(root) and path.is_file(): + route.fulfill(path=path) + else: + route.abort() + + self.page.route("**/*", serve) + self.cdp = self.page.context.new_cdp_session(self.page) + opening = datetime(2025, 1, 1, tzinfo=timezone.utc) + self.page.clock.install(time=opening) + self.page.clock.pause_at(opening + timedelta(seconds=1)) + self.page.goto(ORIGIN + "/index.html", wait_until="domcontentloaded") + for _ in range(1000): + self.page.clock.run_for(50) + self.state = self.page.evaluate("() => window.gameAPI?.getState()") + if self.state and self.state["status"] == "playing": + break + else: + raise RuntimeError(f"Pac-Man did not start: {self.state}") + if self.state["game_state"]["score"] is None: + raise RuntimeError("Native score unavailable at start") + self.capture() + + def spec(self): + return {"adapter_version": "1.0.0", "capabilities": Capabilities(True, "enum").to_dict(), + "action_schema": {"type": "string", "enum": list(KEYS)}, + "goal": "Earn at least 600 points before native game over."} + + def success(self): + return self.state["game_state"]["score"] >= TARGET_SCORE + + def done(self): + return self.success() or self.state["terminal"]["isTerminal"] + + def step(self, action): + if self.done() or action not in KEYS: + raise ValueError("Expected a legal action during a live game") + key = KEYS[action] + if key: + self.page.keyboard.down(key) + try: + # Keep native timers and collisions moving for half a second. + for _ in range(10): + self.page.clock.run_for(50) + self.state = self.page.evaluate("gameAPI.getState()") + if self.done(): + break + finally: + if key: + self.page.keyboard.up(key) + self.capture() + return Transition(float(self.success()), self.done()) + + def metrics(self): + return {"score": self.state["game_state"]["score"], + "deaths": self.state["metrics"]["deaths"], "success": int(self.success())} + + def fingerprint(self): + return state_hash({"score": self.state["game_state"]["score"]}) + + def capture(self): + data = self.cdp.send("Page.captureScreenshot", {"format": "png"})["data"] + with Image.open(BytesIO(b64decode(data))) as image: + self.rgb = np.array(image.convert("RGB")) + + def observe(self): + return {"image_png_base64": png(self.rgb)} + + def frame(self): + return self.rgb + + def close(self): + self.resources.close() diff --git a/game_first_exam/benchmarks/pacman/instance_schema.py b/game_first_exam/benchmarks/pacman/instance_schema.py new file mode 100644 index 0000000..41d9af9 --- /dev/null +++ b/game_first_exam/benchmarks/pacman/instance_schema.py @@ -0,0 +1,13 @@ +SCHEMA_VERSION = "1.0.0" +BENCHMARK = "pacman" +FIELDS = {"engine_commit"} +METRICS = {"success"} +PROFILES = {"native-rgb-v1"} +REDUCERS = {("family_macro", "1.0.0")} + + +def validate(value): + if value["seed"] != 42 or value["engine_commit"] != "e5ddb16df85b91a1d17bb0577621cc7c5e65d738": + raise ValueError("unknown GameWorld-Games version") + if (value["env_id"], value["family"], value["max_steps"]) != ("pacman", "score-600", 500): + raise ValueError("unknown Pac-Man task configuration") diff --git a/game_first_exam/benchmarks/pacman/metric_rules.py b/game_first_exam/benchmarks/pacman/metric_rules.py new file mode 100644 index 0000000..c2c2945 --- /dev/null +++ b/game_first_exam/benchmarks/pacman/metric_rules.py @@ -0,0 +1,14 @@ +def validate_metrics(final, instance): + metrics = final["metrics"] + score, deaths, success = (metrics[k] for k in ("score", "deaths", "success")) + if type(score) is not int or score < 0: + raise ValueError("Invalid native score") + if type(deaths) is not int or deaths < 0: + raise ValueError("Invalid native death count") + if type(success) is not int or success not in (0, 1) or success != int(score >= 600): + raise ValueError("Score and goal disagree") + won = bool(success) + if final["terminated"] != bool(won or deaths): + raise ValueError("Terminal flag disagrees with native result") + if final["success"] != won or final["return"] != float(won): + raise ValueError("Reward disagrees with native result") diff --git a/game_first_exam/benchmarks/pacman/requirements.txt b/game_first_exam/benchmarks/pacman/requirements.txt new file mode 100644 index 0000000..70da3b9 --- /dev/null +++ b/game_first_exam/benchmarks/pacman/requirements.txt @@ -0,0 +1,5 @@ +playwright==1.55.0 +numpy==1.26.4 +pillow==10.4.0 +imageio-ffmpeg==0.6.0 +imageio==2.37.0 diff --git a/game_first_exam/images/pacman-files/FILES.json b/game_first_exam/images/pacman-files/FILES.json new file mode 100644 index 0000000..4edcb0d --- /dev/null +++ b/game_first_exam/images/pacman-files/FILES.json @@ -0,0 +1,10 @@ +{ + "source": "game_first_exam/benchmarks/pacman", + "files": { + "adapter.py": "0a33907c604133a5a5af6cc03c7db35b572f0b331cdd3fa6b865064969466ae7", + "instance_schema.py": "a86fb55845148f97828faacb8194633ee4a9f1ec7f7c5f6549355c9afc7898c7", + "metric_rules.py": "fda0b03387377d98e4e2a4ef04a862668a0fe6ef2eedb90b6ca445cb05fff788", + "requirements.txt": "f7b63cd5e9d2d806613a620bb7340f27ce6735ba76c9d5a08f77d48e527d4733" + }, + "image": "ghcr.io/mll-lab-nu/efe:pacman-files-0.1.0@sha256:6bec51b36730d5c42218d0cb7eccea95243a642665e780e50f4b33948a2984eb" +} diff --git a/game_first_exam/images/pacman-files/VERSION b/game_first_exam/images/pacman-files/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/game_first_exam/images/pacman-files/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/game_first_exam/tasks/pacman/README.md b/game_first_exam/tasks/pacman/README.md new file mode 100644 index 0000000..f307d6d --- /dev/null +++ b/game_first_exam/tasks/pacman/README.md @@ -0,0 +1,12 @@ +# Pac-Man: 600 points + +Score 600 in GameWorld's Pac-Man using native RGB screenshots and keyboard moves. A game over or action limit scores zero. Five original GameWorld task presets cover score thresholds; this integration freezes the first threshold. + +Run from the repository root (the pinned files image is assembled locally): `harbor run --game-suite pacman --standard -a oracle -y`. + +| Replay | Native result | +| --- | --- | +| [600-point clear](../../../docs/demos/pacman/600-point-clear.mp4) | 600 points, success | +| [Ghost collision](../../../docs/demos/pacman/ghost-collision.mp4) | 120 points, game over | + +For a first viewing, the [annotated clear](../../../docs/demos/pacman/explained-clear.mp4) and [annotated failure](../../../docs/demos/pacman/explained-failure.mp4) identify the player, pellets, ghosts and the 600-point task goal. The raw replays above preserve the game display without added text. Reaching 600 completes this frozen task; it does not clear the entire maze. diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/DIGEST b/game_first_exam/tasks/pacman/pacman-600-i01-standard/DIGEST new file mode 100644 index 0000000..8c58fe2 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/DIGEST @@ -0,0 +1 @@ +sha256:453d682ae5f83fccf95bb85e9a4118f1f9a52b7004e62ad04f7b722f4db68471 diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/README.md b/game_first_exam/tasks/pacman/pacman-600-i01-standard/README.md new file mode 100644 index 0000000..0ab2ba1 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/README.md @@ -0,0 +1,35 @@ +# pacman-600-i01-standard + +| | | +|---|---| +| Benchmark | Pac-Man | +| Mode | standard (`game-standard/2.2`) | +| Twin | — (none: Pac-Man has no privileged mode, PROTOCOL §2) | +| Simulator / robot | `pacman` / `game-agent` | +| Family / instance | `score-600` / seed 42 | +| Oracle | `full` | +| Agent time budget | 600 s; tokens: protocol default (docs/protocol/running.md "Official runs") | +| Base image | `docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db` | + +## Task +Collect pellets and avoid ghosts until the native game score reaches 600. + +## Difficulty +Continuously moving ghosts require route planning and timely turns in the maze. + +## Reference solution +The 24-action route in `solution/` scored 1.0 in the Harbor oracle run. The ghost-collision control scored 0.0. + +## Verification +The isolated verifier validates the native score and awards one point at 600, zero on game over or budget exhaustion. + +## Resources +Caps per container (PROTOCOL §6). + +| Container | CPUs | Memory | Processes | GPU memory | Disk | +|---|---|---|---|---|---| +| `main` (the agent's) | 1 | 1 GiB | 256 | no GPU | 2 GiB | +| `sim` | 1 | 1 GiB | 128 | no GPU | — | +| verifier (as `main`) | 1 | 1 GiB | no cap | no GPU | 2 GiB | + +- GPU: not needed. diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/Dockerfile b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/Dockerfile new file mode 100644 index 0000000..10dcc84 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/Dockerfile @@ -0,0 +1,9 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN apt-get update && apt-get install -y --no-install-recommends bash curl git nodejs npm ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN npm install -g @openai/codex@0.167.1 && npm cache clean --force +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /game_client.py /app/game_client.py +COPY --from=ghcr.io/mll-lab-nu/efe:connection-files-0.1.0@sha256:6d1002dea6ca507b4148d3196e233838e645b33bcfa9a27ae4a43027ae519999 /service_connection.py /app/service_connection.py +ENV PYTHONUNBUFFERED=1 PYTHONPATH=/app +RUN mkdir -p /app/output +WORKDIR /app diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/docker-compose.yaml b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/docker-compose.yaml new file mode 100644 index 0000000..7fa17b4 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/docker-compose.yaml @@ -0,0 +1,43 @@ +services: + main: + pids_limit: 256 # rcb-monitor + volumes: # rcb-monitor + - rcb_limits:/run/rcb-limits:ro # rcb-monitor + depends_on: [sim] + sim: + cpus: 1 # rcb-monitor + mem_limit: 1024m # rcb-monitor + pids_limit: 128 # rcb-monitor + volumes: # rcb-monitor + - rcb_observe:/run/rcb-observe:ro # rcb-monitor + build: + context: sim + dockerfile: Dockerfile + working_dir: /srv + command: python3 /srv/server.py + environment: + RCB_WALL_CLOCK_S: "600" + # >>> rcb_monitor (resource monitor, PROTOCOL §6; generated by images/monitor/rcb_monitor/inject.py) + rcb_monitor: + image: ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a + pid: host + cgroup: host + network_mode: none + cap_add: [SYS_PTRACE] + cpus: 0.5 + mem_limit: 256m + pids_limit: 64 + restart: on-failure + working_dir: /var/rcb-monitor + volumes: + - ./rcb_monitor/limits.json:/opt/rcb_monitor/limits.json:ro + - rcb_limits:/run/rcb-limits + - rcb_observe:/run/rcb-observe + environment: + RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} + RCB_LIMITS_TOLERANCE: ${RCB_LIMITS_TOLERANCE:-0.05} + command: ["python3", "/opt/rcb_monitor/monitor.py", "run"] + # <<< rcb_monitor +volumes: # rcb-monitor + rcb_limits: # rcb-monitor + rcb_observe: # rcb-monitor diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/rcb_monitor/limits.json b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/rcb_monitor/limits.json new file mode 100644 index 0000000..ecb96e5 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/rcb_monitor/limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "pacman-600-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/sim/Dockerfile b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/sim/Dockerfile new file mode 100644 index 0000000..f8a9869 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/sim/Dockerfile @@ -0,0 +1,18 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +ENV PYTHONUNBUFFERED=1 +COPY --from=ghcr.io/mll-lab-nu/efe:pacman-files-0.1.0@sha256:6bec51b36730d5c42218d0cb7eccea95243a642665e780e50f4b33948a2984eb /requirements.txt /srv/requirements.txt +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* +RUN pip install --no-cache-dir -r /srv/requirements.txt +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /server.py /srv/server.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /reducers.py /srv/reducers.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /config_schema.py /srv/config_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /contracts.py /srv/contracts.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /encoding.py /srv/encoding.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /recording.py /srv/recording.py +COPY --from=ghcr.io/mll-lab-nu/efe:pacman-files-0.1.0@sha256:6bec51b36730d5c42218d0cb7eccea95243a642665e780e50f4b33948a2984eb /adapter.py /srv/adapter.py +RUN python -m playwright install --with-deps --only-shell chromium +RUN git init /tmp/upstream && cd /tmp/upstream && git remote add origin https://github.com/gameworld-project/GameWorld-Games.git && git sparse-checkout init --cone && git sparse-checkout set benchmark/23_pacman && git fetch --depth=1 --filter=blob:none origin e5ddb16df85b91a1d17bb0577621cc7c5e65d738 && git checkout --detach FETCH_HEAD && mv benchmark/23_pacman /srv/game && rm -rf /tmp/upstream +COPY --from=ghcr.io/mll-lab-nu/efe:pacman-files-0.1.0@sha256:6bec51b36730d5c42218d0cb7eccea95243a642665e780e50f4b33948a2984eb /instance_schema.py /srv/instance_schema.py +COPY instance.json /srv/instance.json +WORKDIR /srv +CMD ["python3", "/srv/server.py"] diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/sim/instance.json b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/sim/instance.json new file mode 100644 index 0000000..1e7d51a --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/environment/sim/instance.json @@ -0,0 +1,25 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": true, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": false + }, + "benchmark": "pacman", + "env_id": "pacman", + "family": "score-600", + "seed": 42, + "max_steps": 500, + "engine_commit": "e5ddb16df85b91a1d17bb0577621cc7c5e65d738", + "observation_profile": "native-rgb-v1", + "metric_spec": { + "primary": "success", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "act_one_clear" + }, + "initial_state_sha256": "628cb4ead38e34e34a34f78fa4481f2a0ccf8e9139acfae69d79dc997e90e36b" +} diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/instruction.md b/game_first_exam/tasks/pacman/pacman-600-i01-standard/instruction.md new file mode 100644 index 0000000..b9fce3e --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/instruction.md @@ -0,0 +1,27 @@ +# Pac-Man + +Earn at least 600 points by clearing pellets while avoiding ghosts. You receive an RGB screenshot after each action. Your score comes from the original game. Reaching 600 ends the run successfully; native game over or exhausting 500 actions scores zero. Each action advances the game by up to 500 ms; `wait` releases the movement keys while the game continues. + +Use the live service through `/app/game_client.py`: + +```python +from game_client import GameClient +game = GameClient() +print(game.spec()) +obs = game.observe() +print(obs["observation"]) +# obs = game.step("right", expected_step=obs["step"]) +``` + +Actions: `up`, `down`, `left`, `right`, `wait`. The public response contains `step`, `done`, `steps_remaining`, and `time_left_s`; screenshots are returned as `image_png_base64`. Supply the current `expected_step` for each step. The client creates a request ID if omitted. On a lost response, retry with the same ID and payload, or observe before taking another step. Your output files do not determine the score. + +## External material +The network is open. You may install packages (pip, apt), and you may search for, download and use public tools and pretrained controllers. Do not look up a ready-made solution to this exact task. Say in your notes what you used. + +## Resources +Your container: **1 CPUs**, **1 GiB of memory**, **256 processes and threads** and **2 GiB** of disk (new files under `/app`, `/tmp` and `/root`). Your container has no GPU. The simulator runs in its own container and does not count against these. CPU only slows you down; a process that goes over any other cap can be killed. Usage and caps: `/run/rcb-limits/usage.json`. + +## Time limit +You have 600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task. + +This is wall-clock time from the start of your session; the time you wait for the simulator service counts. When it is up you are stopped without warning and the episode is graded as it stands at that moment. The service's `time_left_s` counts the same limit from your first request to the service, so it never runs out before your time does: your real time left is `time_left_s` minus the time you spent before that request. Plan by it. Your session started when you received this task. `/run/rcb-limits/usage.json`, rewritten every few seconds, gives the time left on this limit (`time_left_s`) and its end (`deadline_utc`), counted from a little before your session started, so it never gives you more time than you have: read it (or run `date`) before you decide that time is short, never guess. Waiting counts too: a tool call that sends input to a process that keeps running (an interactive interpreter, a simulator loop, a server) can wait for the whole wait or yield time you give it even when the answer is printed at once, so give such calls a short wait and poll again if the output is not complete, or run one-shot scripts that exit when they are done. Installing packages is not cheating (`## External material` above). diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/route.json b/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/route.json new file mode 100644 index 0000000..aafa188 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/route.json @@ -0,0 +1,26 @@ +[ + "right", + "right", + "down", + "down", + "right", + "right", + "up", + "up", + "left", + "right", + "left", + "right", + "left", + "right", + "left", + "left", + "left", + "left", + "left", + "left", + "down", + "down", + "right", + "right" +] diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/solve.py b/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/solve.py new file mode 100644 index 0000000..ed89b48 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/solve.py @@ -0,0 +1,13 @@ +import json +from pathlib import Path + +from game_client import GameClient + + +game = GameClient() +state = game.observe() +route = json.loads(Path(__file__).with_name("route.json").read_text()) +for action in route: + if state["done"]: + break + state = game.step(action, expected_step=state["step"]) diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/solve.sh b/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/solve.sh new file mode 100755 index 0000000..a856bf7 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +exec python3 /solution/solve.py diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/task.toml b/game_first_exam/tasks/pacman/pacman-600-i01-standard/task.toml new file mode 100644 index 0000000..1f138ea --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/task.toml @@ -0,0 +1,58 @@ +schema_version = "1.3" +artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, { source = "/data/final.json", service = "sim" }, + { source = "/data/episode.jsonl", service = "sim" }, + { source = "/data/recording.json", service = "sim" }, + { source = "/data/replay.mp4", service = "sim" }, + { source = "/data/replay.last.png", service = "sim" }, + "/app/output/", +] + +[task] +name = "embodied-first-exam/pacman-600-i01-standard" +description = "Score 600 points in GameWorld Pac-Man." +keywords = ["game", "pacman", "arcade", "navigation", "standard-mode"] + +[metadata] +task_type = "trajectory" +simulator = "pacman" +robot = "game-agent" +family = "score-600" +dynamics = "static" +protocol = "game-standard/2.2" +oracle = "full" +instance_seed = 42 +expert_time_estimate_hours = 0.5 + +[verifier] +timeout_sec = 120.0 +environment_mode = "separate" +network_mode = "no-network" + +# Resources (PROTOCOL §6): seal the monitor's record first. +[[verifier.collect]] +service = "rcb_monitor" +command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90" +timeout_sec = 120 + +[[verifier.collect]] +service = "main" +command = "kill -9 -1 2>/dev/null; exit 0" +timeout_sec = 30 + +[[verifier.collect]] +service = "sim" +command = "kill -USR1 $(cat /data/server.pid); i=0; while [ ! -f /data/collection.ready ] && [ $i -lt 30 ]; do sleep 1; i=$((i+1)); done; test -f /data/collection.ready && test -f /data/final.json" +timeout_sec = 40 + +[agent] +timeout_sec = 600.0 +network_mode = "public" + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 + +[verifier.env] +RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}" diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/Dockerfile b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/Dockerfile new file mode 100644 index 0000000..51fb620 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/Dockerfile @@ -0,0 +1,11 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +COPY test.sh instance.json /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /grade.py /tests/grade.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /reducers.py /tests/reducers.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /config_schema.py /tests/config_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:pacman-files-0.1.0@sha256:6bec51b36730d5c42218d0cb7eccea95243a642665e780e50f4b33948a2984eb /instance_schema.py /tests/instance_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:pacman-files-0.1.0@sha256:6bec51b36730d5c42218d0cb7eccea95243a642665e780e50f4b33948a2984eb /metric_rules.py /tests/metric_rules.py +RUN chmod +x /tests/test.sh +# resources (PROTOCOL §6) # rcb-monitor +COPY --from=ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a /opt/rcb_monitor/rcb_limits.py /tests/rcb_limits.py +COPY rcb_limits.json /tests/rcb_limits.json diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/instance.json b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/instance.json new file mode 100644 index 0000000..1e7d51a --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/instance.json @@ -0,0 +1,25 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": true, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": false + }, + "benchmark": "pacman", + "env_id": "pacman", + "family": "score-600", + "seed": 42, + "max_steps": 500, + "engine_commit": "e5ddb16df85b91a1d17bb0577621cc7c5e65d738", + "observation_profile": "native-rgb-v1", + "metric_spec": { + "primary": "success", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "act_one_clear" + }, + "initial_state_sha256": "628cb4ead38e34e34a34f78fa4481f2a0ccf8e9139acfae69d79dc997e90e36b" +} diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/rcb_limits.json b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/rcb_limits.json new file mode 100644 index 0000000..ecb96e5 --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/rcb_limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "pacman-600-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/test.sh b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/test.sh new file mode 100755 index 0000000..0cf878a --- /dev/null +++ b/game_first_exam/tasks/pacman/pacman-600-i01-standard/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +rm -rf /logs/verifier/* +trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resources, after the grader (PROTOCOL §6) +p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # untrusted agent files (PROTOCOL H.1) +mkdir -p /logs/verifier +python3 /tests/grade.py 2>/logs/verifier/grade.log diff --git a/game_first_exam/tests/benchmarks/pacman/calibrate.py b/game_first_exam/tests/benchmarks/pacman/calibrate.py new file mode 100644 index 0000000..6763ed7 --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/calibrate.py @@ -0,0 +1,145 @@ +"""Find a native Pac-Man route locally, then replay it on untouched assets. + +The temporary copy only exposes the game's existing state for route search. +The submitted task and the final replay use the original pinned game files. +""" + +import json +import random +import shutil +import sys +from collections import deque +from pathlib import Path +from tempfile import TemporaryDirectory + +ROOT = Path(__file__).resolve().parents[4] +GAME = ROOT.parent / "stack-review" / "benchmark" / "23_pacman" +sys.path[:0] = [str(ROOT / "game_first_exam/runtime"), + str(ROOT / "game_first_exam/benchmarks/pacman")] + +from adapter import Adapter # noqa: E402 + +DIRS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)} +STATE = """() => { + const game = window.__nativePacman; + if (!game || !game.pacman || !game.map) return null; + const tile = game.pacman.getTile(); + return { + player: [tile.col, tile.row], + direction: game.pacman.dir, + ghosts: ['pinky', 'blinky', 'inky', 'sue'].map(name => { + const ghost = game[name]; + if (!ghost) return null; + const at = ghost.getTile(); + return [at.col, at.row, !!ghost._ghostFrightened]; + }).filter(Boolean), + width: game.map.width, + height: game.map.height, + tiles: game.map.tiles.map(tile => [tile.col, tile.row, tile.code, !!tile.item]), + }; +}""" + + +def inspect(game): + return game.page.evaluate(STATE) + + +def choose(state, rng, caution): + x, y = state["player"] + width, height = state["width"], state["height"] + tiles = {(col, row): (code, item) for col, row, code, item in state["tiles"]} + ghosts = [(gx, gy) for gx, gy, afraid in state["ghosts"] if not afraid] + moves = [] + for action, (dx, dy) in DIRS.items(): + nxt = ((x + dx) % width, (y + dy) % height) + if tiles.get(nxt, ("=", False))[0] in ("=", "h"): + continue + route = deque([(nxt, 1)]) + seen = {(x, y), nxt} + distance = 40 + while route: + node, steps = route.popleft() + code, item = tiles.get(node, ("=", False)) + if item and code in (".", "*"): + distance = steps - (2 if code == "*" else 0) + break + for sx, sy in DIRS.values(): + neighbor = ((node[0] + sx) % width, (node[1] + sy) % height) + if neighbor not in seen and tiles.get(neighbor, ("=", False))[0] not in ("=", "h"): + seen.add(neighbor) + route.append((neighbor, steps + 1)) + danger = min((abs(nxt[0] - gx) + abs(nxt[1] - gy) for gx, gy in ghosts), default=99) + score = -distance - caution * max(0, 5 - danger) + rng.uniform(-1.5, 1.5) + if tiles[nxt][1]: + score += 3 + moves.append((score, action)) + return max(moves)[1] if moves else "wait" + + +def episode(assets, index, caution): + rng = random.Random(23 + index * 17) + game = Adapter({}, assets) + route = [] + try: + opening = game.fingerprint() + for step in range(240): + state = inspect(game) + if state is None: + raise RuntimeError("Native game state was not exposed by the temporary probe") + action = choose(state, rng, caution) + route.append(action) + game.step(action) + if game.done(): + break + print("trial", index, "opening", opening, "steps", len(route), "metrics", game.metrics(), flush=True) + return route, game.metrics() + finally: + game.close() + + +def main(): + if not GAME.is_dir(): + raise SystemExit(f"Native game snapshot missing: {GAME}") + with TemporaryDirectory(prefix="pacman-calibrate-") as root: + source = Path(root) / "game" + shutil.copytree(GAME, source) + bundle = source / "bundle.js" + original = bundle.read_text() + marker = ";new(function(t)" + if original.count(marker) != 1: + raise RuntimeError("The pinned game's entry point changed") + bundle.write_text(original.replace(marker, ";window.__nativePacman=new(function(t)", 1)) + best = ([], {"score": 0, "success": 0}) + for trial, caution in enumerate((1, 3, 0, 5, 2, 4, 6, 0)): + route, metrics = episode(root, trial, caution) + if metrics["score"] > best[1]["score"]: + best = route, metrics + if metrics["success"]: + break + print("Best exploratory score:", best[1], flush=True) + if not best[1]["success"]: + return + # Verification uses the original source: only that replay can become a demo. + bundle.write_text(original) + dest = ROOT / "game_first_exam/tasks/pacman/pacman-600-i01-standard/solution/route.json" + dest.unlink(missing_ok=True) + game = Adapter({}, root) + try: + print("Unmodified opening:", game.fingerprint(), flush=True) + for action in best[0]: + if game.done(): + break + game.step(action) + print("Unmodified replay:", game.metrics(), flush=True) + if game.metrics()["success"]: + dest.write_text(json.dumps(best[0], indent=2) + "\n") + print("Route saved:", dest, flush=True) + finally: + game.close() + if dest.is_file(): + from record import main as record_demos + record_demos() + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/tests/benchmarks/pacman/exported.toml b/game_first_exam/tests/benchmarks/pacman/exported.toml new file mode 100644 index 0000000..598486a --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/exported.toml @@ -0,0 +1,7 @@ +[protocols] +standard = ["game-standard/2.2"] + +[[tasks]] +name = "pacman-600-i01-standard" +source_task = "GameWorld-23-Score600" +protocol = "game-standard/2.2" diff --git a/game_first_exam/tests/benchmarks/pacman/ghost_collision/run_harbor.py b/game_first_exam/tests/benchmarks/pacman/ghost_collision/run_harbor.py new file mode 100644 index 0000000..79547d6 --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/ghost_collision/run_harbor.py @@ -0,0 +1,33 @@ +import json +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main(): + root = Path.cwd() + prepare = root / "scripts/prepare_games.py" + if not prepare.is_file(): + raise SystemExit("Run this script from the Game Exam repository root.") + staging = root / "jobs/prepared" + staging.mkdir(parents=True, exist_ok=True) + run = Path(tempfile.mkdtemp(prefix="pacman-ghost-collision-", dir=staging)) + config = run / "control.json" + subprocess.run([sys.executable, str(prepare), "--suite", "pacman", "--output", str(config)], + check=True) + rows = json.loads(config.read_text())["tasks"] + if len(rows) != 1: + raise RuntimeError("Expected one Pac-Man task.") + task = Path(rows[0]["path"]).resolve() + if not task.is_relative_to(run) or task.name != "pacman-600-i01-standard": + raise RuntimeError("Expected a staged copy of Pac-Man 600 points.") + shutil.copyfile(Path(__file__).with_name("solve.py"), task / "solution/solve.py") + subprocess.run([sys.executable, str(root / "scripts/stamp_mtimes.py"), "--full", str(task)], check=True) + subprocess.run(["harbor", "run", "-c", str(config), "-a", "oracle", + "--jobs-dir", str(root / "jobs"), "--job-name", "pacman-failure-control", "-y"], check=True) + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/tests/benchmarks/pacman/ghost_collision/solve.py b/game_first_exam/tests/benchmarks/pacman/ghost_collision/solve.py new file mode 100644 index 0000000..4488e35 --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/ghost_collision/solve.py @@ -0,0 +1,7 @@ +from game_client import GameClient + + +game = GameClient() +state = game.observe() +while not state["done"]: + state = game.step("right", expected_step=state["step"]) diff --git a/game_first_exam/tests/benchmarks/pacman/native_probe.py b/game_first_exam/tests/benchmarks/pacman/native_probe.py new file mode 100644 index 0000000..f8eae88 --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/native_probe.py @@ -0,0 +1,35 @@ +"""Check that the native Pac-Man opening and score advance in Chromium.""" + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[4] +GAME = ROOT.parent / "stack-review" / "benchmark" / "23_pacman" +sys.path[:0] = [str(ROOT / "game_first_exam/runtime"), + str(ROOT / "game_first_exam/benchmarks/pacman")] + +from adapter import Adapter # noqa: E402 + + +def main(): + if not GAME.is_dir(): + raise SystemExit(f"Native GameWorld source missing: {GAME}") + # Adapter accepts a directory with a `game` child. Keep the source out of + # the Game Exam repository so that the upstream rights notice stays intact. + from tempfile import TemporaryDirectory + with TemporaryDirectory() as temporary: + (Path(temporary) / "game").symlink_to(GAME, target_is_directory=True) + game = Adapter({}, temporary) + try: + print("Opening:", game.fingerprint(), game.state["status"], game.metrics()) + for action in ["left", "up", "right", "down"]: + if game.done(): + break + game.step(action) + print(action, game.state["status"], game.metrics()) + finally: + game.close() + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/tests/benchmarks/pacman/record.py b/game_first_exam/tests/benchmarks/pacman/record.py new file mode 100644 index 0000000..53106fa --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/record.py @@ -0,0 +1,53 @@ +"""Record success and game-over examples from the unmodified game snapshot.""" + +import json +import sys +from pathlib import Path +from tempfile import TemporaryDirectory + +import imageio + +ROOT = Path(__file__).resolve().parents[4] +GAME = ROOT.parent / "stack-review" / "benchmark" / "23_pacman" +TASK = ROOT / "game_first_exam/tasks/pacman/pacman-600-i01-standard" +sys.path[:0] = [str(ROOT / "game_first_exam/runtime"), + str(ROOT / "game_first_exam/benchmarks/pacman")] + +from adapter import Adapter # noqa: E402 + + +def record(assets, actions, filename): + game = Adapter({}, assets) + filename.parent.mkdir(parents=True, exist_ok=True) + try: + with imageio.get_writer(filename, fps=2, codec="libx264", quality=7) as video: + video.append_data(game.frame()) + for action in actions: + if game.done(): + break + game.step(action) + video.append_data(game.frame()) + print(filename.name, game.fingerprint(), game.metrics(), flush=True) + return game.metrics() + finally: + game.close() + + +def main(): + route = json.loads((TASK / "solution/route.json").read_text()) + with TemporaryDirectory(prefix="pacman-record-") as temporary: + (Path(temporary) / "game").symlink_to(GAME, target_is_directory=True) + dest = ROOT / "docs/demos/pacman" + success = dest / "600-point-clear.mp4" + if not record(temporary, route, success)["success"]: + success.unlink(missing_ok=True) + raise RuntimeError("Recorded route did not reach 600 points") + failure = dest / "ghost-collision.mp4" + metrics = record(temporary, ["right"] * 500, failure) + if not metrics["deaths"]: + failure.unlink(missing_ok=True) + print("The failure example needs a different route", flush=True) + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/tests/benchmarks/pacman/run.command b/game_first_exam/tests/benchmarks/pacman/run.command new file mode 100644 index 0000000..82e6e6d --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/run.command @@ -0,0 +1,11 @@ +#!/bin/bash +set -euo pipefail +repo="$(cd "$(dirname "$0")/../../../.." && pwd)" +if [ ! -x "$repo/.venv/bin/python" ]; then + python3 -m venv "$repo/.venv" +fi +python="$repo/.venv/bin/python" +"$python" -m pip install -q -r "$repo/game_first_exam/benchmarks/pacman/requirements.txt" +"$python" -m playwright install chromium --only-shell +"$python" "$repo/game_first_exam/tests/benchmarks/pacman/native_probe.py" +"$python" "$repo/game_first_exam/tests/benchmarks/pacman/calibrate.py" diff --git a/game_first_exam/tests/benchmarks/pacman/verify_harbor.command b/game_first_exam/tests/benchmarks/pacman/verify_harbor.command new file mode 100644 index 0000000..a89c514 --- /dev/null +++ b/game_first_exam/tests/benchmarks/pacman/verify_harbor.command @@ -0,0 +1,36 @@ +#!/bin/bash +set -euo pipefail + +repo="$(cd "$(dirname "$0")/../../../.." && pwd)" +base="$(cd "$repo/../Game_exam-main" && pwd)" +export PATH="$base/.venv/bin:/Applications/Docker.app/Contents/Resources/bin:$PATH" +export DOCKER_HOST="unix://$HOME/.docker/run/docker.sock" +export EFE_ROOT="$repo" +cd "$repo" + +docker info --format 'Docker server: {{.ServerVersion}}' +python scripts/files_image.py build pacman-files +harbor run --game-suite pacman --standard -a oracle -y +python game_first_exam/tests/benchmarks/pacman/ghost_collision/run_harbor.py + +python - <<'PY' +import json +from pathlib import Path + +jobs = sorted(Path('jobs').glob('20*/result.json'), key=lambda p: p.stat().st_mtime) +if len(jobs) < 2: + raise SystemExit('Both Harbor jobs must write a result.json') +scores = [] +for path in jobs[-2:]: + stats = json.loads(path.read_text())['stats'] + print(path, 'completed', stats['n_completed_trials'], 'errors', stats['n_errored_trials']) + if stats['n_completed_trials'] != 1 or stats['n_errored_trials']: + raise SystemExit('Harbor failed before grading; inspect the trial result.json') + for name, report in stats.get('evals', {}).items(): + for metric in report.get('metrics', []): + print(name, {key: metric.get(key) for key in ('environment_error', 'primary_score')}) + scores.append(metric.get('primary_score')) +if scores != [1.0, 0.0]: + raise SystemExit(f'Expected success and failure scores [1.0, 0.0], got {scores}') +print('PASS: Oracle clear and failure control were graded separately') +PY diff --git a/game_first_exam/tests/test_game_harbor.py b/game_first_exam/tests/test_game_harbor.py index e6e71f6..5f4d51a 100644 --- a/game_first_exam/tests/test_game_harbor.py +++ b/game_first_exam/tests/test_game_harbor.py @@ -32,13 +32,13 @@ class GameSelection(unittest.TestCase): def test_game_only_default_and_all_selection_never_launches(self): for flags, expected in ((["--list", "--standard"], 30), - (["--all", "--standard", "--list"], 42)): + (["--all", "--standard", "--list"], 43)): with self.subTest(flags=flags), contextlib.redirect_stdout(io.StringIO()) as output, \ patch("efe.harbor") as launch, patch("efe.prepull") as pull: self.assertEqual(efe.run(flags), 0) names = output.getvalue().splitlines() self.assertEqual(len(names), expected) - self.assertTrue(all(name.startswith(("minigrid-", "crafter-", "textworld-", "babaisai-", "minihack-")) + self.assertTrue(all(name.startswith(("minigrid-", "crafter-", "textworld-", "babaisai-", "minihack-", "pacman-")) for name in names)) launch.assert_not_called() pull.assert_not_called() diff --git a/scripts/task_conventions.py b/scripts/task_conventions.py index 36b7e5c..f91b7fd 100644 --- a/scripts/task_conventions.py +++ b/scripts/task_conventions.py @@ -72,6 +72,7 @@ # benchmark's game_first_exam/benchmarks//; BENCHMARKS and BENCHMARK_DIRS below are views of this table, and # ci_checks/ci_scope.py --check holds its UNITS / FILES_IMAGE to it. A new benchmark adds one row here. BENCHMARK_TABLE = [ + ("pacman-", "Pac-Man", "pacman"), ("minihack-", "MiniHack", "minihack"), ("babaisai-", "Baba Is AI", "babaisai"), ("crafter-", "Crafter", "crafter"), diff --git a/scripts/task_resources.toml b/scripts/task_resources.toml index f5e2106..d5e7f9b 100644 --- a/scripts/task_resources.toml +++ b/scripts/task_resources.toml @@ -9,7 +9,7 @@ measured = "CPU-only initial integration; caps chosen conservatively, to be meas # Initial CPU-only game integration caps; measure before increasing concurrency. [[cap]] -match = "^(crafter|textworld|babaisai)-.*-standard$" +match = "^(crafter|textworld|babaisai|pacman)-.*-standard$" main = { cpus = 1, memory_gb = 1, pids = 256, disk_gb = 2 } sim = { cpus = 1, memory_gb = 1, pids = 128 } measured = "Initial integration caps; CPU only, fixed-model evaluation"