Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 46 additions & 2 deletions .github/workflows/games.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 vex3 --standard --list
- run: python game_first_exam/tests/test_game_harbor.py
fresh-clone-smoke:
runs-on: ubuntu-latest
Expand Down Expand Up @@ -77,8 +78,50 @@ jobs:
name: fresh-clone-room-evidence
path: jobs/
retention-days: 7
browser-game-smoke:
runs-on: ubuntu-latest
timeout-minutes: 35
strategy:
fail-fast: false
matrix:
include:
- {suite: vex3, control: vex3/missed_jump}
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: Run the reference solution
env:
SUITE: ${{ matrix.suite }}
run: |
harbor run --game-suite "$SUITE" --standard -c configs/harbor/oracle.json \
--jobs-dir "$PWD/jobs" --job-name browser-reference -y
python ci_checks/check-browser-game-result.py jobs/browser-reference 1
- name: Run the failure control
env:
CONTROL: ${{ matrix.control }}
run: |
python "game_first_exam/tests/benchmarks/$CONTROL/run_harbor.py"
python ci_checks/check-browser-game-result.py jobs 0
- uses: actions/upload-artifact@v4
if: always()
with:
name: ${{ matrix.suite }}-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, browser-game-smoke]
if: ${{ always() }}
runs-on: ubuntu-latest
steps:
Expand All @@ -87,4 +130,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
BROWSER_SMOKE: ${{ needs.browser-game-smoke.result }}
run: test "$BROWSER_SMOKE" = success && test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success
25 changes: 25 additions & 0 deletions ci_checks/check-browser-game-result.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""Verify the Harbor verdict from a browser game's reference or control run."""
import json
import sys
from pathlib import Path


def check(trial_dir, expected):
paths = (
trial_dir.glob("*/verifier/reward.json") if expected == 1 else
(path for path in trial_dir.glob("*/*/verifier/reward.json")
if path.parents[2].name != "browser-reference")
)
rewards = list(paths)
if len(rewards) != 1:
raise ValueError(f"Expected one verifier result under {trial_dir}, found {len(rewards)}")
reward = json.loads(rewards[0].read_text())
errors = ("infra_error", "sim_error", "environment_error")
if (not reward.get("result_valid") or any(reward.get(key) != 0 for key in errors)
or reward.get("steps", 0) <= 0 or reward.get("success") != expected):
raise ValueError(f"Expected a valid result with success={expected}: {reward}")
print(f"{rewards[0]}: success={expected}, steps={reward['steps']}")


if __name__ == "__main__":
check(Path(sys.argv[1]), int(sys.argv[2]))
3 changes: 3 additions & 0 deletions configs/game_benchmarks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.vex3]
schema = "game_first_exam/benchmarks/vex3/instance_schema.py"
10 changes: 10 additions & 0 deletions configs/game_suites/vex3.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
schema_version = "game-suite/2.1"
version = "1.0.0"
tier = "smoke"
name = "games-vex3-minimal-v1.0.0"
files_images = ["connection-files", "game-files", "vex3-files"]

[[tasks]]
name = "vex3-act-one-i01-standard"
benchmark = "vex3"
family = "act-one"
Binary file added docs/demos/vex3/act-one-clear.mp4
Binary file not shown.
Binary file added docs/demos/vex3/missed-jump.mp4
Binary file not shown.
144 changes: 144 additions & 0 deletions game_first_exam/benchmarks/vex3/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""Play the first numbered Vex 3 act using keyboard input and native outcomes."""
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": (),
"right": ("ArrowRight",),
"left": ("ArrowLeft",),
"jump": ("ArrowUp",),
"jump_right": ("ArrowRight", "ArrowUp"),
"jump_left": ("ArrowLeft", "ArrowUp"),
"slide": ("ArrowRight", "ArrowDown"),
}
ORIGIN = "http://vex.test"


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": 800, "height": 600})

def serve(route):
url = urlsplit(route.request.url)
path = (root / unquote(url.path).lstrip("/")).resolve()
if url.netloc == "vex.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)
start = datetime(2025, 1, 1, tzinfo=timezone.utc)
self.page.clock.install(time=start)
self.page.clock.pause_at(start + timedelta(seconds=1))
self.page.goto(ORIGIN + "/index.html?level=1", wait_until="domcontentloaded")
for _ in range(1000):
self.page.clock.run_for(64)
self.state = self.page.evaluate("() => window.gameAPI?.getState()")
if self.state and self.state["is_actionable"] and str(self.state["game_state"]["level"]) == "1":
break
else:
raise RuntimeError(f"Act 1 did not open: {self.state}")
if self.state["metrics"]["deaths"] != 0:
raise RuntimeError("Act 1 opened after a death")
# The player spawns above the floor. Anchor the opening to first contact.
for _ in range(120):
player = self.state["game_state"]["player"]
if player and player["state"] == "0" and player["vx"] == player["vy"] == 0:
break
self.page.clock.run_for(16)
self.state = self.page.evaluate("gameAPI.getState()")
if self.done():
raise RuntimeError("Act ended before the player reached the floor")
else:
raise RuntimeError(f"Act 1 did not settle at spawn: {player}")
# The same grounded player can leave the 30 Hz Phaser accumulator
# at different offsets after loading. Start each episode at one
# fixed offset so a 64 ms action produces the same native ticks.
self.page.evaluate("() => { window.__vex3Game._deltaTime = 44 / 3; }")
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": "Finish Act 1 without dying.",
}

def success(self):
return (str(self.state["game_state"]["level"]) == "1" and
self.state["metrics"]["deaths"] == 0 and self.state["terminal"]["outcome"] == "success")

def done(self):
return self.state["terminal"]["isTerminal"] or self.state["metrics"]["deaths"] > 0

def step(self, action):
if self.done() or action not in KEYS:
raise ValueError("Expected a legal action in a live act")
for key in KEYS[action]:
self.page.keyboard.down(key)
try:
for _ in range(4):
self.page.clock.run_for(16)
self.state = self.page.evaluate("gameAPI.getState()")
if self.done():
break
finally:
for key in KEYS[action]:
self.page.keyboard.up(key)
self.capture()
return Transition(float(self.success()), self.done())

def metrics(self):
metrics = self.state["metrics"]
return {
"deaths": metrics["deaths"],
"checkpoints_passed": metrics["checkpoints_passed"],
"success": int(self.success()),
}

def fingerprint(self):
board = self.state["game_state"]
return state_hash({
"level": board["level"],
"player": board["player"],
"deaths": self.state["metrics"]["deaths"],
"success": int(self.success()),
})

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()
13 changes: 13 additions & 0 deletions game_first_exam/benchmarks/vex3/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
SCHEMA_VERSION = "1.0.0"
BENCHMARK = "vex3"
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"]) != ("vex-3", "act-one", 1500):
raise ValueError("unknown GameWorld task configuration")
18 changes: 18 additions & 0 deletions game_first_exam/benchmarks/vex3/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
def validate_metrics(final, instance):
metrics = final["metrics"]
deaths = metrics["deaths"]
if type(deaths) is not int or deaths < 0:
raise ValueError("Invalid native death count")
checkpoints = metrics["checkpoints_passed"]
if type(checkpoints) is not int or not 0 <= checkpoints <= 4:
raise ValueError("Invalid native checkpoint count")
success = metrics["success"]
if type(success) is not int or success not in (0, 1):
raise ValueError("Invalid native success flag")
won = success == 1
if won and deaths:
raise ValueError("Act 1 requires a deathless finish")
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")
5 changes: 5 additions & 0 deletions game_first_exam/benchmarks/vex3/requirements.txt
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions game_first_exam/images/vex3-files/FILES.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"source": "game_first_exam/benchmarks/vex3",
"files": {
"adapter.py": "b9bc530426cf8f8712786a3bb4c55545a32980e71ec301d0d9448c81a10fc2b2",
"instance_schema.py": "a999b2c2d4e27914f92d8db1d9eb67949c6c73bc71bb8575957e246b6e412fa0",
"metric_rules.py": "9765b7395cbc73570c99b18a738864fbda3439fc5ea1eb96396cb1aa1f52f2c1",
"requirements.txt": "f7b63cd5e9d2d806613a620bb7340f27ce6735ba76c9d5a08f77d48e527d4733"
},
"image": "ghcr.io/mll-lab-nu/efe:vex3-files-0.1.0@sha256:e1eb278ee4601219ca01e409b7b3759ffed8771c65a7300422bac5e192eb2ae6"
}
1 change: 1 addition & 0 deletions game_first_exam/images/vex3-files/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0
19 changes: 19 additions & 0 deletions game_first_exam/tasks/vex3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Vex 3 Act 1

The standard task loads the first numbered act from the pinned GameWorld browser game. The agent sees RGB screenshots and uses movement, jumps, and slides. A deathless finish scores one, and the first death ends the attempt with a score of zero. Checkpoints are recorded as a secondary metric.

The adapter pauses between actions. Once the player lands at spawn, it fixes the 30 Hz Phaser clock phase so the same 64 ms input interval advances the same native updates across runs.

Run the reference and failure control from the repository root.

```sh
harbor run --game-suite vex3 --standard -a oracle -y
python game_first_exam/tests/benchmarks/vex3/missed_jump/run_harbor.py
```

| Replay | Native result |
| --- | --- |
| [Act 1 clear](../../../docs/demos/vex3/act-one-clear.mp4) | Four checkpoints and zero deaths |
| [Missed opening jump](../../../docs/demos/vex3/missed-jump.mp4) | One death |

[Vex 3 source and rights notice](https://github.com/gameworld-project/GameWorld-Games/tree/e5ddb16df85b91a1d17bb0577621cc7c5e65d738/benchmark/30_vex-3)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sha256:5bed0e3c1f1a7dc29d54ffb1a3fecb3944a9921eafa73a6b5f65d82bfc3aae3a
35 changes: 35 additions & 0 deletions game_first_exam/tasks/vex3/vex3-act-one-i01-standard/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# vex3-act-one-i01-standard

| | |
|---|---|
| Benchmark | GameWorld Vex 3 |
| Mode | standard (`game-standard/2.2`) |
| Twin | — (none: GameWorld Vex 3 has no privileged mode, PROTOCOL §2) |
| Simulator / robot | `vex3` / `game-agent` |
| Family / instance | `act-one` / 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
Clear the first numbered act in one life using keyboard input.

## Difficulty
Time jumps over rotating saws, slide underneath a spiked overhang, and climb to the exit using the level's walls and ziplines. The first death ends the attempt.

## Reference solution
See `solution/`.

## Verification
The simulator reads GameWorld's native completion event and death count. The isolated verifier validates the terminal state and awards one point for a deathless clear of Act 1.

## 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.
Original file line number Diff line number Diff line change
@@ -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
Loading