Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
9a8ebc0
Add TowerMind benchmark adapter and isolation tests
maomao868 Nov 20, 2026
25ba584
Read the TowerMind initial observation after the upstream reset
maomao868 Nov 20, 2026
148c230
Handle blank TowerMind startup observations and pin the intended level
maomao868 Nov 20, 2026
2a55b9a
Handle nonempty TowerMind startup frames and log both decode stages
maomao868 Nov 20, 2026
4661c0a
Use TowerMind pixel-only observations in the simulator
maomao868 Nov 20, 2026
da66d63
Preserve upstream TowerMind observations and metrics
maomao868 Nov 20, 2026
b701d0b
Diagnose TowerMind texture readback in Linux CI
maomao868 Nov 20, 2026
21f0136
Compare the Unity text sensor with native diagnostic recording
maomao868 Nov 20, 2026
fddae68
Check text pixel alignment and improve simulator test startup
maomao868 Nov 20, 2026
e87b95c
Test official TowerMind Direct3D player in Linux isolation
maomao868 Nov 20, 2026
11adefd
Match the official TowerMind seed sequence and test Mesa sampling
maomao868 Nov 21, 2026
1abedd4
Preserve TowerMind JSON texture bytes in the isolated Linux player
maomao868 Nov 21, 2026
dad7a73
Register the TowerMind benchmark using a development-only validation …
maomao868 Nov 21, 2026
c714e4d
Verify TowerMind isolation with a disposable Harbor trial
maomao868 Nov 22, 2026
0c3db16
Check Harbor network policy and clear shared verifier logs before gra…
maomao868 Nov 22, 2026
c8b8de6
Wait for the Harbor TowerMind sidecar to serve its public interface
maomao868 Nov 22, 2026
35bb40a
Disable Docker networking for the TowerMind verification container
maomao868 Nov 22, 2026
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
20 changes: 18 additions & 2 deletions .github/workflows/games.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,28 @@ jobs:
strategy:
fail-fast: false
matrix:
benchmark: [common, minigrid, crafter, textworld, babaisai, minihack]
benchmark: [common, minigrid, crafter, textworld, babaisai, minihack, towermind]
steps:
- uses: actions/checkout@v4
with: {persist-credentials: false}
- run: docker build -f game_first_exam/tests/envs/${{ matrix.benchmark }}.Dockerfile -t game-tests:${{ matrix.benchmark }} .
- run: docker run --rm -v "$PWD:/repo:ro" game-tests:${{ matrix.benchmark }} bash game_first_exam/tests/run.sh ${{ matrix.benchmark }}
- if: matrix.benchmark != 'towermind'
run: docker run --rm -v "$PWD:/repo:ro" game-tests:${{ matrix.benchmark }} bash game_first_exam/tests/run.sh ${{ matrix.benchmark }}
- if: matrix.benchmark == 'towermind'
run: docker run --rm --network none -v "$PWD:/repo:ro" game-tests:towermind bash game_first_exam/tests/run.sh towermind
- if: matrix.benchmark == 'towermind'
name: Check TowerMind sandbox boundary from a separate container
run: |
docker build --target client -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind-client .
bash game_first_exam/tests/check-towermind-network.sh
- if: matrix.benchmark == 'towermind'
uses: actions/setup-python@v5
with: {python-version: '3.12'}
- if: matrix.benchmark == 'towermind'
name: Check TowerMind through Harbor's isolated agent and verifier
run: |
python -m pip install -e .
python game_first_exam/tests/check_towermind_harbor.py "$RUNNER_TEMP/towermind-harbor"
harbor:
runs-on: ubuntu-latest
timeout-minutes: 15
Expand Down
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.towermind]
schema = "game_first_exam/benchmarks/towermind/instance_schema.py"
24 changes: 24 additions & 0 deletions game_first_exam/benchmarks/towermind/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# TowerMind adapter

This development integration uses the upstream Unity Linux x86-64 player and both official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts a private copy and applies the level and seed selected for the run, following the upstream LLM example. The level seed is passed through the game configuration. The separate ML-Agents initialization seed uses the official Python example's default. All other game settings come from the pinned archive.

Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The bridge uses the reported sensor names to route the player camera and JSON texture to the official observation wrapper. The first reset observation starts the public episode. The adapter records the first native terminal or interrupted transition and closes the episode.

The public `player-rgb-v1` profile exposes one cached 512脳512 RGB player frame as PNG. Actions carry two coordinates in `[-3, 3]` and a native integer action type from 0 through 11 as a string, for example `"-1.5 1.2 2"`. The official wrapper handles native action mapping. The JSON state, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached RGB pixels, JSON observation, instance identity and step outcomes.

The development instance reports cumulative native reward as its primary metric. It stores the native-invalid and total action counts from the JSON feedback, using the upstream example's criteria and excluding no-ops. The shared runtime's Boolean outcome records native termination with the base alive, using health directly from the native observation.

The CI Harbor 0.23.0 integration check creates a disposable development task in the runner's temporary directory and runs it with the native oracle. It checks the client and sim evidence collection. In the Linux CI trial, Harbor's verifier policy alone allowed a connection to the Docker host bridge. The development task also sets Docker Compose `network_mode: none` for the separate verifier in `tests/docker-compose.yaml`. The check requires only the loopback interface and confirms that the verifier cannot reach the same runner listener the agent reached. Harbor mounts `/logs/verifier` into the agent, so the verifier clears that directory before generating the grade. Simulator evidence comes exclusively from the `sim` artifact declaration.

The Python ML-Agents gRPC listener binds to the simulator's own IPv4 loopback. The network test uses independent sim and client images, an internal Docker network and no shared mounts. Its client only carries the shared HTTP client, the connection helper and the probe. Keep those boundaries when packaging a Harbor task. Upstream static assets are public independently of access to the live simulator.

The files-only image carries implementation and dependency inputs. The test image downloads and verifies the original assets at build time. It uses the upstream Colab example's Xvfb screen settings and lets Unity select its graphics backend. The image includes Mesa's software OpenGL and Vulkan drivers. When starting the official Linux player, the adapter disables the two Mesa anisotropic texture-filter extensions for that process. In the tested llvmpipe environment, the default filtering corrupts the byte values in the JSON sensor at reset. This renderer setting also applies to the player camera. The sensor and its stock decoder are used directly. The simulator loads the Gym bridge from the installed ML-Agents distribution directly because the package's Gym registry initializer attempts a remote manifest fetch. The Linux regression runs the stock wrappers with the upstream LLM launch sequence first, then compares adapter rewards and termination on the same action sequence. The host registers the native schema in `configs/game_benchmarks.toml`. The development instance in `game_first_exam/tests/fixtures/towermind-instance.json` exercises the integration before any exam is frozen.

Run from the repository root on a Linux Docker host.

```bash
docker build -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind .
docker run --rm --network none -v "$PWD:/repo:ro" game-tests:towermind bash game_first_exam/tests/run.sh towermind
docker build --target client -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind-client .
bash game_first_exam/tests/check-towermind-network.sh
```
14 changes: 14 additions & 0 deletions game_first_exam/benchmarks/towermind/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"repository": "https://github.com/tb6147877/TowerMind",
"commit": "7ac5d5cb815ce022cdf6f6d40fa0a9fcc9be3e71",
"files": {
"linux.zip": {
"path": "compressed_env/linux.zip",
"sha256": "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19"
},
"wrappers.py": {
"path": "common/wrappers.py",
"sha256": "440eb20ac34f6fc80dcffca1938c95f49ea178b48a241c03771aae646617a15c"
}
}
}
141 changes: 141 additions & 0 deletions game_first_exam/benchmarks/towermind/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""Expose one cached player RGB frame and one native decision per accepted action."""
from hashlib import sha256
from importlib.metadata import version
import math
from pathlib import Path
import re
from tempfile import TemporaryDirectory

import numpy as np

from config_schema import validate_instance
from contracts import Transition
from encoding import png, state_hash
from instance_schema import CAPABILITIES
from native_assets import prepare_game


NATIVE_ASSETS = Path("/opt/towermind")
COORDINATE = r"-?(?:[0-2](?:\.[0-9]{1,9})?|3(?:\.0{1,9})?)"
ACTION_PATTERN = rf"{COORDINATE} {COORDINATE} (?:[0-9]|1[01])"
ACTION_LENGTH = 28


def parse_action(action):
if not isinstance(action, str) or not re.fullmatch(ACTION_PATTERN, action):
raise ValueError("expected 'x y action_type' within the declared bounds")
x, y, action_type = action.split(" ")
return float(x), float(y), int(action_type)


def open_native(player, wrappers_path):
from native import open_native as launch

return launch(player, wrappers_path)


class Adapter:
def __init__(self, instance, assets=None):
validate_instance(instance)
for package, expected in instance["engine_versions"].items():
if version(package) != expected:
raise ValueError(f"TowerMind dependency version mismatch: {package}")
self.instance = dict(instance)
self._workspace = TemporaryDirectory(prefix="towermind-")
self._env = None
self._decisions = 0
self._return = 0.0
self._counted_actions = self._invalid_actions = 0
self._terminated = self._truncated = False
source = NATIVE_ASSETS if assets is None or not (assets / "linux.zip").is_file() else assets
try:
player = prepare_game(source, Path(self._workspace.name), instance)
self._env, observation = open_native(player, source / "wrappers.py")
self._cache(observation)
except Exception:
self.close()
raise

def _cache(self, observation):
health = observation["text"]["Level_Current_Health"]
if type(health) is not int or health < 0:
raise ValueError("invalid native TowerMind base health")
image = observation["image"]
if image.shape == (3, 512, 512):
image = np.moveaxis(image, 0, -1)
if image.shape != (512, 512, 3) or image.dtype != np.uint8:
raise ValueError("expected native 512x512 RGB uint8 frame")
self._image = np.array(image, copy=True, order="C")
self._image.flags.writeable = False
self._frame_sha256 = sha256(self._image).hexdigest()
self._public_png = png(self._image)
self._native_text = observation["text"]

def spec(self):
return {
"adapter_version": "1.0.0",
"capabilities": dict(CAPABILITIES),
"action_schema": {"type": "string", "pattern": ACTION_PATTERN, "max_length": ACTION_LENGTH},
"observation": "Cached native 512x512 RGB player frame encoded as PNG.",
"actions": "Submit x y action_type. Coordinates are in [-3, 3], and action_type is 0–11.",
}

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

def step(self, action):
if self._terminated or self._truncated:
raise ValueError("episode closed")
observation, reward, done, info = self._env.step(parse_action(action))
reward = float(reward)
if not math.isfinite(reward):
raise ValueError("invalid native TowerMind reward")
outcome = observation["text"]["Agent_Last_Action_Info"]
action_type, error_code = outcome["Action_Index"], outcome["Error_Code"]
if type(action_type) is not int or not 0 <= action_type <= 11 or type(error_code) is not int:
raise ValueError("invalid native TowerMind action feedback")
self._cache(observation)
# Match the upstream LLM example's counters for reported actions.
if action_type != 6:
self._counted_actions += 1
self._invalid_actions += int(error_code > 0)
interrupted = bool(info["step"].interrupted[0]) if done else False
self._terminated = bool(done and not interrupted)
self._truncated = interrupted
self._decisions += 1
self._return += reward
return Transition(reward, self._terminated, self._truncated)

def success(self):
# Compatibility flag for the shared service's native outcome record.
return self._terminated and self._native_text["Level_Current_Health"] > 0

def metrics(self):
return {
"native_return": self._return,
"base_health": self._native_text["Level_Current_Health"],
"native_decisions": self._decisions,
"native_counted_actions": self._counted_actions,
"native_invalid_actions": self._invalid_actions,
}

def fingerprint(self):
# Unity does not export a complete engine checkpoint or the internal RNG state.
return state_hash({
"archive": self.instance["engine_archive_sha256"],
"level": self.instance["level_id"], "seed": self.instance["seed"],
"frame_sha256": self._frame_sha256, "decisions": self._decisions, "return": self._return,
"text": self._native_text,
"terminated": self._terminated, "truncated": self._truncated,
})

def frame(self):
return self._image

def close(self):
try:
if self._env is not None:
env, self._env = self._env, None
env.close()
finally:
self._workspace.cleanup()
37 changes: 37 additions & 0 deletions game_first_exam/benchmarks/towermind/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""Trusted adapter profile. Importable without simulator dependencies."""
from config_schema import validate_engine_versions


SCHEMA_VERSION = "1.0.0"
BENCHMARK = "towermind"
FIELDS = {"level_id", "engine_versions", "engine_archive_sha256"}
METRICS = {"native_return"}
PROFILES = {"player-rgb-v1"}
REDUCERS = {("family_macro", "1.0.0")}
CAPABILITIES = {
"images": True, "action_mode": "text", "timing": "action-stepped", "native_truncation": True,
}
ARCHIVE_SHA256 = "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19"
ENGINE_VERSIONS = {
"mlagents-envs": "1.1.0",
"gym": "0.26.2",
"numpy": "1.23.5",
"grpcio": "1.48.2",
"protobuf": "3.20.3",
"opencv-python-headless": "4.10.0.84",
}


def validate(value):
validate_engine_versions(value["engine_versions"], ENGINE_VERSIONS)
level = value["level_id"]
if type(level) is not int or not 0 <= level <= 8 or value["env_id"] != f"TowerMind-Level-{level}":
raise ValueError("unsupported native TowerMind level")
if value["seed"] == 0:
raise ValueError("TowerMind profile requires a positive seed")
if value["engine_archive_sha256"] != ARCHIVE_SHA256:
raise ValueError("unsupported native TowerMind archive")
if value["capabilities"] != CAPABILITIES:
raise ValueError("TowerMind requires the RGB action-stepped profile")
if value["metric_spec"]["success_label"] != "native_level_completed":
raise ValueError("unsupported TowerMind success label")
17 changes: 17 additions & 0 deletions game_first_exam/benchmarks/towermind/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
"""Validate native outcome evidence without loading Unity."""
def validate_metrics(final, instance):
metrics = final["metrics"]
health = metrics["base_health"]
if type(health) is not int or health < 0:
raise ValueError("invalid TowerMind base health")
if type(metrics["native_decisions"]) is not int or metrics["native_decisions"] != final["steps"]:
raise ValueError("TowerMind decision count disagrees with the service")
reward = metrics["native_return"]
if type(reward) not in (int, float) or reward != final["return"]:
raise ValueError("TowerMind cumulative return disagrees with the service")
counted, invalid = metrics["native_counted_actions"], metrics["native_invalid_actions"]
if type(counted) is not int or type(invalid) is not int or not 0 <= invalid <= counted <= final["steps"]:
raise ValueError("invalid TowerMind action counts")
won = final["reason"] == "native_terminated" and health > 0
if final["success"] != won:
raise ValueError("TowerMind success requires a completed native level with the base alive")
Loading