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 firewater --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: firewater, control: firewater/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.firewater]
schema = "game_first_exam/benchmarks/firewater/instance_schema.py"
10 changes: 10 additions & 0 deletions configs/game_suites/firewater.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-firewater-minimal-v1.0.0"
files_images = ["connection-files", "game-files", "firewater-files"]

[[tasks]]
name = "firewater-forest-exit-i01-standard"
benchmark = "firewater"
family = "forest-exit"
Binary file added docs/demos/firewater/level-1-clear.mp4
Binary file not shown.
Binary file added docs/demos/firewater/level-1-missed-jump.mp4
Binary file not shown.
156 changes: 156 additions & 0 deletions game_first_exam/benchmarks/firewater/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
"""Forest Temple level one, scored by its native terminal outcome."""
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

MOVES = {
"wait": (), "left": ("left",), "right": ("right",),
"jump_left": ("jump", "left"), "jump_right": ("jump", "right"),
}
KEYS = {
"fireboy": {"left": "ArrowLeft", "right": "ArrowRight", "jump": "ArrowUp"},
"watergirl": {"left": "a", "right": "d", "jump": "w"},
}
ORIGIN = "http://forest.test"


class Adapter:
def __init__(self, instance, assets=None):
self.stack = ExitStack()
try:
self.load(Path(assets) / "game")
except BaseException:
self.close()
raise

def load(self, root):
root = root.resolve(strict=True)
driver = self.stack.enter_context(sync_playwright())
browser = driver.chromium.launch(args=["--mute-audio"])
self.stack.callback(browser.close)
self.page = browser.new_page(viewport={"width": 800, "height": 600})

self.cdp = self.page.context.new_cdp_session(self.page)

def serve(route):
url = urlsplit(route.request.url)
path = (root / unquote(url.path).lstrip("/")).resolve()
if url.netloc == "forest.test" and path.is_relative_to(root) and path.is_file():
route.fulfill(path=path)
else:
route.abort()

self.page.route("**/*", serve)
start = datetime(2026, 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(160):
self.page.clock.run_for(250)
state = self.page.evaluate("() => window.gameAPI?.getState()")
if state and state["is_actionable"]:
board = state["game_state"]
if all(board["diamonds"][r]["total"] for r in KEYS) and board["level"] == 1:
self.state = state
break
else:
raise RuntimeError("GameWorld did not initialize forest level 1")
# Let the native opening animation settle before accepting the first action.
self.page.clock.run_for(4000)
self.state = self.page.evaluate("gameAPI.getState()")
# Count native updates. Phaser can render a frame without advancing the physics.
self.page.evaluate("""() => {
const game = window.__fbwg_game || window.Phaser.GAMES[0];
window.forestTicks = 0;
game.plugins.add({postUpdate() { window.forestTicks++; }});
}""")
self.steps = 0
self.capture()

def spec(self):
return {"adapter_version": "1.0.0", "capabilities": Capabilities(True, "enum").to_dict(),
"action_schema": {"type": "string", "enum": [f"{a}/{b}" for a in MOVES for b in MOVES]},
"actions": "fireboy/watergirl, six native updates per paired move",
"goal": "Guide both characters into their matching exits on forest level one."}

def capture(self):
# DevTools captures the composited frame without advancing the paused game clock.
shot = self.cdp.send("Page.captureScreenshot", {"format": "png", "fromSurface": True})
data = b64decode(shot["data"])
with Image.open(BytesIO(data)) as image:
self.rgb = np.array(image.convert("RGB"))

def frame(self):
return self.rgb

def observe(self):
return {"image_png_base64": png(self.rgb)}

def step(self, action):
moves = action.split("/")
if len(moves) != 2 or any(move not in MOVES for move in moves):
raise ValueError("expected two role moves")
if self.state["terminal"]["isTerminal"]:
raise ValueError("episode already ended")
keys = [KEYS[role][direction] for role, move in zip(KEYS, moves) for direction in MOVES[move]]
for key in keys:
self.page.keyboard.down(key)
try:
target = self.page.evaluate("window.forestTicks") + 6
self.page.clock.run_for(96)
for _ in range(16):
ticks = self.page.evaluate("window.forestTicks")
if ticks == target:
break
if ticks > target:
raise RuntimeError("native updates exceeded action interval")
if self.page.evaluate("gameAPI.getState().terminal.isTerminal"):
break
self.page.clock.run_for(16)
else:
raise RuntimeError("native game stopped advancing")
finally:
for key in reversed(keys):
self.page.keyboard.up(key)
self.steps += 1
self.state = self.page.evaluate("gameAPI.getState()")
self.capture()
won = self.success()
return Transition(float(won), self.state["terminal"]["isTerminal"])

def counts(self):
gems = self.state["game_state"]["diamonds"]
return {role: gems[role]["collected"] for role in KEYS}

def success(self):
terminal = self.state["terminal"]
return (self.state["game_state"]["level"] == 1 and terminal["isTerminal"]
and terminal["outcome"] == "success" and terminal["reason"] == "level_completed")

def metrics(self):
return {**self.counts(), "success": int(self.success()), "level": self.state["game_state"]["level"],
"terminal_outcome": self.state["terminal"]["outcome"],
"terminal_reason": self.state["terminal"]["reason"]}

def fingerprint(self):
board = self.state["game_state"]
positions = []
for role in ("player", "watergirl"):
body = board.get(role) or {}
positions.append([round(body[axis] / 8) if body.get(axis) is not None else None
for axis in ("x", "y")])
return state_hash({"level": board["level"], "positions": positions, "gems": self.counts(),
"steps": self.steps, "game_over": self.state["terminal"]["isTerminal"]})

def close(self):
self.stack.close()
13 changes: 13 additions & 0 deletions game_first_exam/benchmarks/firewater/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
SCHEMA_VERSION = "1.0.0"
BENCHMARK = "firewater"
FIELDS = {"engine_commit"}
METRICS = {"success"}
PROFILES = {"native-rgb-v1"}
REDUCERS = {("family_macro", "1.0.0")}


def validate(value):
if value["engine_commit"] != "e5ddb16df85b91a1d17bb0577621cc7c5e65d738":
raise ValueError("unknown GameWorld-Games version")
if (value["env_id"], value["family"], value["max_steps"]) != ("forest-temple-level-1", "forest-exit", 800):
raise ValueError("unknown GameWorld task configuration")
19 changes: 19 additions & 0 deletions game_first_exam/benchmarks/firewater/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""Consistency checks for the terminal result reported by the native forest level."""


def validate_metrics(final, instance):
metrics = final["metrics"]
if metrics["level"] != 1:
raise ValueError("unexpected forest level")
for role in ("fireboy", "watergirl"):
if type(metrics[role]) is not int or metrics[role] < 0:
raise ValueError(f"invalid diamond count for {role}")

terminal = (metrics["terminal_outcome"], metrics["terminal_reason"])
valid_events = {(None, None), ("success", "level_completed"),
("fail", "level_failed"), ("fail", "level_ended")}
if terminal not in valid_events or final["terminated"] != (terminal != (None, None)):
raise ValueError("inconsistent native terminal event")
won = terminal == ("success", "level_completed")
if final["success"] != won or final["return"] != float(won) or metrics["success"] != int(won):
raise ValueError("reward disagrees with native level completion")
5 changes: 5 additions & 0 deletions game_first_exam/benchmarks/firewater/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/firewater-files/FILES.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"image": "ghcr.io/mll-lab-nu/efe:firewater-files-0.1.0@sha256:ab62600ad87d0847d601c5bce3be99243b6cd1d659234af944efded40395fa7a",
"source": "game_first_exam/benchmarks/firewater",
"files": {
"instance_schema.py": "0432b1c48b4f9ecd9839cfa85aa231e70c294b92ac2660ebf088fb11af5c7579",
"requirements.txt": "f7b63cd5e9d2d806613a620bb7340f27ce6735ba76c9d5a08f77d48e527d4733",
"adapter.py": "2834b4346b8c958ea21fb8e8768c9c9e1a9f7a20dbc6a13cfc06c0051d5aa0c5",
"metric_rules.py": "358a3350d3fc17a980f8d136789477ffbd01a0eab566188d19afd691d407fbd7"
}
}
3 changes: 3 additions & 0 deletions game_first_exam/images/firewater-files/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Firewater adapter

Pinned evaluator and simulator adapter for the native Forest Temple level-one exit. Game assets are fetched separately during the simulator build.
1 change: 1 addition & 0 deletions game_first_exam/images/firewater-files/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.1.0
33 changes: 33 additions & 0 deletions game_first_exam/tasks/firewater/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Fireboy and Watergirl in the Forest Temple

This Game Exam task uses GameWorld's original Forest Temple level one. GameWorld 12_01 and 12_02 specify diamond targets. This variant runs all the way to the native successful exit event. Both characters must reach their matching doors. The game reports the diamonds collected as secondary metrics.

Run from the repository root with Docker Desktop running and the project Harbor installation on PATH.

```sh
harbor run --game-suite firewater --standard -a oracle
```

An action advances both roles by six native game updates with the browser clock paused between decisions. The reference solution sends paired actions through GameClient. The verifier checks the native terminal event. A completed episode produces the standard Game Exam replay and final verdict.

- [Pinned upstream task](https://github.com/gameworld-project/GameWorld/blob/84f624bd1e120d30aeebf2eb42a39410e24d3bd4/catalog/tasks/12_fireboy-and-watergirl/12_01.yaml)
- [Pinned game and rights notice](https://github.com/gameworld-project/GameWorld-Games/blob/e5ddb16df85b91a1d17bb0577621cc7c5e65d738/benchmark/12_fireboy-and-watergirl/RIGHTS.md)

The simulator build retrieves the pinned game from upstream. The game assets are downloaded during the simulator build. Oslo Albet retains the game's rights.

## Level one demos and results

| Browser gameplay | Native outcome | Paired moves | Harbor score |
| --- | --- | ---: | ---: |
| [Both characters reach their exits](../../../docs/demos/firewater/level-1-clear.mp4) | `level_completed` | 474 | 1 |
| [Watergirl misses the first lava jump](../../../docs/demos/firewater/level-1-missed-jump.mp4) | `level_failed` | 38 | 0 |

Both Harbor runs returned valid results and zero environment errors. The success run collected all three red and four blue diamonds. The negative control delays Watergirl's first jump while Fireboy follows the reference opening. The clips were recorded separately in the browser. The Harbor recorder stopped before writing a playable MP4.

To reproduce the negative control from the repository root:

```sh
python game_first_exam/tests/benchmarks/firewater/missed_jump/run_harbor.py
```

The control uses a staged task copy with the offline rewarded-ad prompt disabled so the native Game Over menu opens. The agent submits paired moves through the same public client, and the verifier grades the native terminal event.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sha256:0593140315afc1ec721b17277cace5a38d03f96b7089de05d6e90c9456b148d7
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# firewater-forest-exit-i01-standard

| | |
|---|---|
| Benchmark | GameWorld Forest Temple |
| Mode | standard (`game-standard/2.2`) |
| Twin | — (none: GameWorld Forest Temple has no privileged mode, PROTOCOL §2) |
| Simulator / robot | `firewater` / `game-agent` |
| Family / instance | `forest-exit` / seed 0 |
| 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
Bring Fireboy and Watergirl to their matching doors in the original Forest Temple level one.

## Difficulty
Cross three pools and climb the temple. The two players take turns standing on pressure plates to move the purple lift. Push the crate to reach the final ledge.

## Reference solution
The oracle plays a recorded sequence of paired keyboard movements through the public game client. Actions are grouped by room feature in solution/route.json.

## Verification
The isolated verifier checks the native terminal event and level number. Death and an unfinished episode earn zero even if every diamond was collected.

## 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.
Loading