Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

feat(unity,tools): golden check in players; web_check.py reads a WebGL build's console in headless Chrome

eyalgolane1015d8f544f
diff --git a/docs/determinism.md b/docs/determinism.md
index 6856773bc..e6835af4b 100644
--- a/docs/determinism.md
+++ b/docs/determinism.md
@@ -33,7 +33,15 @@ Each constant is written in three places that must agree:
`unity/Assets/Tests/EditMode/SimSmokeTests.cs` runs the same playthroughs inside Unity against `GoldenRun`'s constants
(run `tools/build_sim_for_unity.sh` first so Unity has the current DLLs).
-Verified on .NET and Unity editor Mono. IL2CPP and WebGL: pending (M3 Task 22 checks both players).
+Verified on .NET, Unity editor Mono, a macOS IL2CPP player (Apple clang, no `-ffp-contract=off` needed) and a WebGL
+IL2CPP player in Chrome (M3 Task 22). Re-check with:
+
+```
+"$UNITY" -batchmode -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression disabled -logFile unity-build-web.log
+uv run tools/web_check.py unity/Builds/Web-disabled --query golden --expect "GOLDEN OK 1950" --expect "GOLDEN OK 1952"
+"$UNITY" -batchmode -quit -projectPath unity -buildTarget OSXUniversal -executeMethod Statecraft.Game.EditorTools.Build.Mac -logFile unity-build-mac.log
+"unity/Builds/Mac/Statecraft.app/Contents/MacOS/Statecraft Israel" -batchmode -nographics -golden -logFile unity-golden-mac.log; echo exit=$?
+```
**Any change to a golden hash is a deliberate rules or content change.** Such a change could be to a rule, a system,
content in `content/`, or the hash format. When it happens, update every place above in the same commit, add a row to
diff --git a/tools/README.md b/tools/README.md
index f808f7788..d526d5593 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -11,6 +11,8 @@ Offline data tools (uv inline-script Python). Run from the repo root.
- `hexgrid.py` writes `content/map/hexes.json` from the heightmap and those committed precipitation inputs (no network).
- `settlement_hexes.py` writes `content/map/settlement_hexes.yaml` (committed): the hex that owns each settlement, by the
`hexgrid.settlement_hex` rule. The sim reads it, so it needs no projection maths.
+- `web_check.py` serves a WebGL build on http://localhost and opens it in headless Chrome for Testing (Playwright's
+ cache); it passes when the console shows the expected lines (`GOLDEN OK ...`, `SMOKE OK ...`).
- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.
## Running the tests
@@ -21,7 +23,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q
```
-Expected: `96 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `99 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.py
new file mode 100644
index 000000000..00a58d3d9
--- /dev/null
+++ b/tools/tests/test_web_check.py
@@ -0,0 +1,30 @@
+"""tools/web_check.py: the console-line parser and the static server's headers (no browser needed)."""
+import gzip
+import urllib.request
+
+import web_check as wc
+
+
+def test_console_lines_are_read_from_their_first_line():
+ one = '[1010/025003.375619:INFO:CONSOLE:2] "GOLDEN OK 1950 abc", source: http://localhost:1/index.html (2)'
+ assert wc.CONSOLE.search(one).group(1) == "GOLDEN OK 1950 abc"
+ # Unity's Debug.Log adds a stack trace, so the message continues on the next stderr lines.
+ first = '[1010/030000.1:INFO:CONSOLE:9] "SMOKE OK 5 turns 1949-01-01'
+ assert wc.CONSOLE.search(first).group(1) == "SMOKE OK 5 turns 1949-01-01"
+
+
+def test_precompressed_files_get_content_encoding_and_wasm_its_type(tmp_path):
+ (tmp_path / "Build").mkdir()
+ (tmp_path / "Build" / "game.wasm.br").write_bytes(b"\x00")
+ (tmp_path / "Build" / "game.data.gz").write_bytes(gzip.compress(b"x"))
+ (tmp_path / "index.html").write_text("<html></html>")
+ server = wc.serve(tmp_path)
+ try:
+ base = f"http://localhost:{server.server_address[1]}"
+ r = urllib.request.urlopen(base + "/Build/game.wasm.br")
+ assert (r.headers["Content-Encoding"], r.headers["Content-Type"]) == ("br", "application/wasm")
+ r = urllib.request.Request(base + "/Build/game.data.gz", headers={"Accept-Encoding": "identity"})
+ assert urllib.request.urlopen(r).headers["Content-Encoding"] == "gzip"
+ assert urllib.request.urlopen(base + "/index.html").headers["Content-Encoding"] is None
+ finally:
+ server.shutdown()
diff --git a/tools/web_check.py b/tools/web_check.py
new file mode 100644
index 000000000..a1163ec9f
--- /dev/null
+++ b/tools/web_check.py
@@ -0,0 +1,119 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""Serve a Unity WebGL build on http://localhost and open it in headless Chrome; pass when the console shows every
+expected line, fail on a failure line or a timeout. Uses the Playwright-cached chrome-headless-shell (no npm needed):
+console messages reach stderr with --enable-logging=stderr --v=1 as INFO:CONSOLE... "text", source: ...
+
+Usage (from the repo root):
+ uv run tools/web_check.py unity/Builds/Web-disabled --query "golden" --expect "GOLDEN OK 1950" --expect "GOLDEN OK 1952"
+Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --fail REGEX (default: GOLDEN FAIL|SMOKE FAIL|BOOT FAIL),
+--timeout SECONDS (default 300), --swiftshader (software WebGL when there is no GPU).
+Pre-compressed builds: *.br and *.gz files are served with Content-Encoding, *.wasm(.br/.gz) as application/wasm.
+Brotli needs a secure context; http://localhost is one."""
+import argparse
+import functools
+import http.server
+import os
+import re
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+# A console message's first line; Unity's Debug.Log adds a stack trace on later lines, so the closing quote and
+# ", source:" may be far below. Only the first line is matched.
+CONSOLE = re.compile(r'INFO:CONSOLE[^\]]*\] "(.*?)(?:", source: .*)?$')
+CHROME_GLOB = "ms-playwright/chromium-*/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
+
+
+class Handler(http.server.SimpleHTTPRequestHandler):
+ def end_headers(self):
+ path = self.path.split("?")[0]
+ if path.endswith(".br"):
+ self.send_header("Content-Encoding", "br")
+ elif path.endswith(".gz"):
+ self.send_header("Content-Encoding", "gzip")
+ self.send_header("Cache-Control", "no-store")
+ super().end_headers()
+
+ def guess_type(self, path):
+ base = re.sub(r"\.(br|gz)$", "", str(path))
+ if base.endswith(".wasm"):
+ return "application/wasm"
+ if base.endswith(".js"):
+ return "application/javascript"
+ if base.endswith((".data", ".r16")):
+ return "application/octet-stream"
+ return super().guess_type(base)
+
+ def log_message(self, fmt, *args):
+ if os.environ.get("WEB_CHECK_VERBOSE"):
+ print("http:", fmt % args)
+
+
+def find_chrome() -> Path:
+ found = sorted(Path.home().joinpath("Library", "Caches").glob(CHROME_GLOB))
+ if not found:
+ sys.exit("Chrome for Testing not found under ~/Library/Caches/ms-playwright (npx playwright install chromium)")
+ return found[-1]
+
+
+def serve(root: Path) -> http.server.ThreadingHTTPServer:
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), functools.partial(Handler, directory=str(root)))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("build", type=Path)
+ ap.add_argument("--query", default="")
+ ap.add_argument("--expect", action="append", default=[])
+ ap.add_argument("--fail", default=r"GOLDEN FAIL|SMOKE FAIL|BOOT FAIL")
+ ap.add_argument("--timeout", type=float, default=300)
+ ap.add_argument("--swiftshader", action="store_true")
+ a = ap.parse_args()
+ if not (a.build / "index.html").exists():
+ sys.exit(f"{a.build}/index.html not found")
+ server = serve(a.build)
+ url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{a.query}" if a.query else "")
+ flags = ["--headless=new", "--enable-logging=stderr", "--v=1", "--no-first-run", "--no-default-browser-check",
+ "--autoplay-policy=no-user-gesture-required", "--window-size=1920,1080",
+ "--disable-frame-rate-limit", "--disable-gpu-vsync",
+ f"--user-data-dir={a.build.resolve()}/../.web-check-profile"]
+ if a.swiftshader:
+ flags += ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"]
+ proc = subprocess.Popen([str(find_chrome()), *flags, url], stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")
+ pending, fail, deadline = list(a.expect), re.compile(a.fail), time.time() + a.timeout
+ lines: list[str] = []
+ reader = threading.Thread(target=lambda: lines.extend(iter(proc.stderr.readline, "")), daemon=True)
+ reader.start()
+ seen = 0
+ try:
+ while time.time() < deadline:
+ while seen < len(lines):
+ m = CONSOLE.search(lines[seen]); seen += 1
+ if not m:
+ continue
+ text = m.group(1)
+ print("console:", text)
+ if fail.search(text):
+ print(f"FAIL: {text}")
+ return 1
+ pending = [p for p in pending if p not in text]
+ if not pending:
+ print("PASS: saw " + ", ".join(a.expect))
+ return 0
+ time.sleep(0.2)
+ print("TIMEOUT: never saw " + ", ".join(pending))
+ return 1
+ finally:
+ proc.terminate()
+ server.shutdown()
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.cs
index e5979f143..d9f62ea0b 100644
--- a/unity/Assets/Scripts/Boot/GameBoot.cs
+++ b/unity/Assets/Scripts/Boot/GameBoot.cs
@@ -5,8 +5,9 @@ using UnityEngine;
namespace Statecraft.Game.Boot
{
- /// <summary>The first thing Map.unity runs: loads the game inputs (fetched on WebGL, read from disk elsewhere), builds
- /// the map, then raises Ready for the game (GameRoot) to start. A failure is logged ("BOOT FAIL ...") and kept in Error.</summary>
+ /// <summary>The first thing Map.unity runs: loads the game inputs (fetched on WebGL, read from disk elsewhere), runs
+ /// the golden check when asked (GoldenCheck), builds the map, then raises Ready for the game (GameRoot) to start.
+ /// A failure is logged ("BOOT FAIL ...") and kept in Error.</summary>
public sealed class GameBoot : MonoBehaviour
{
[SerializeField] MapScene map = null!;
@@ -24,8 +25,15 @@ namespace Statecraft.Game.Boot
Inputs = Application.platform == RuntimePlatform.WebGLPlayer
? await GameInputs.FetchAsync(GameInputs.StreamingUrl())
: GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
+ if (GoldenCheck.Requested())
+ {
+ var (ok, lines) = GoldenCheck.Run(Inputs.Content);
+ foreach (var line in lines) Debug.Log(line);
+ // Desktop players run the check headless (-batchmode -nographics) and report through the exit code.
+ if (Application.platform != RuntimePlatform.WebGLPlayer) { Application.Quit(ok ? 0 : 1); return; }
+ }
map.Build(Inputs.Map);
- Debug.Log($"BOOT OK {Inputs.Content.Events.Count} events");
+ Debug.Log($"BOOT OK content {Inputs.Content.Hash}");
Ready?.Invoke(Inputs);
}
catch (Exception e)
diff --git a/unity/Assets/Scripts/Boot/GoldenCheck.cs b/unity/Assets/Scripts/Boot/GoldenCheck.cs
new file mode 100644
index 000000000..9a71bce6b
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/GoldenCheck.cs
@@ -0,0 +1,33 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Statecraft.Sim;
+using UnityEngine;
+
+namespace Statecraft.Game.Boot
+{
+ /// <summary>Runs both golden playthroughs in whatever runtime this is (IL2CPP in players) and reports
+ /// "GOLDEN OK &lt;year&gt; &lt;hash&gt;" or "GOLDEN FAIL &lt;year&gt; &lt;hash&gt; expected &lt;hash&gt;" (docs/determinism.md).
+ /// Asked for by the URL query "golden" on WebGL, or the command-line flag -golden on desktop.</summary>
+ public static class GoldenCheck
+ {
+ public static bool Requested() => Application.platform == RuntimePlatform.WebGLPlayer
+ ? UrlFlags.Has(Application.absoluteURL, "golden")
+ : Environment.GetCommandLineArgs().Contains("-golden");
+
+ public static (bool ok, List<string> lines) Run(Content c)
+ {
+ var lines = new List<string>();
+ bool ok = true;
+ foreach (var (until, expected) in new[] { (GoldenRun.Until1950, GoldenRun.Hash1950), (GoldenRun.Until1952, GoldenRun.Hash1952) })
+ {
+ var hash = GoldenRun.Play(c, until).Hash();
+ var year = until.Year.ToString(System.Globalization.CultureInfo.InvariantCulture);
+ if (hash == expected) lines.Add($"GOLDEN OK {year} {hash}");
+ else { ok = false; lines.Add($"GOLDEN FAIL {year} {hash} expected {expected}"); }
+ }
+ return (ok, lines);
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Boot/GoldenCheck.cs.meta b/unity/Assets/Scripts/Boot/GoldenCheck.cs.meta
new file mode 100644
index 000000000..f835c580f
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/GoldenCheck.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 69e287944b9064c6fba8d6c50e5b6895
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Boot/UrlFlags.cs b/unity/Assets/Scripts/Boot/UrlFlags.cs
new file mode 100644
index 000000000..59bf1fa29
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/UrlFlags.cs
@@ -0,0 +1,20 @@
+#nullable enable
+using System.Globalization;
+using System.Text.RegularExpressions;
+
+namespace Statecraft.Game.Boot
+{
+ /// <summary>Flags in the WebGL page URL's query: "?golden", "&amp;smoke=5", "?profile". A flag must start a query
+ /// parameter and end at a word boundary, so a path such as ".../golden-project/..." never turns one on.</summary>
+ public static class UrlFlags
+ {
+ public static bool Has(string? url, string name) => Regex.IsMatch(url ?? "", @"[?&]" + Regex.Escape(name) + @"\b");
+
+ /// <summary>The flag's integer value ("smoke=5" -> 5), or 0 when absent.</summary>
+ public static int Int(string? url, string name)
+ {
+ var m = Regex.Match(url ?? "", @"[?&]" + Regex.Escape(name) + @"=(\d+)");
+ return m.Success ? int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) : 0;
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Boot/UrlFlags.cs.meta b/unity/Assets/Scripts/Boot/UrlFlags.cs.meta
new file mode 100644
index 000000000..f6bd74694
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/UrlFlags.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: ca5f353f41d4148b38d2db2fb147231d
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/GoldenCheckTests.cs b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs
new file mode 100644
index 000000000..b914fdbbd
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs
@@ -0,0 +1,30 @@
+using NUnit.Framework;
+using Statecraft.Game;
+using Statecraft.Game.Boot;
+using Statecraft.Sim;
+
+public class GoldenCheckTests
+{
+ [Test]
+ public void TheCheckReportsBothGoldenRunsAsOkInTheEditor()
+ {
+ var (ok, lines) = GoldenCheck.Run(ContentLoader.Load(Paths.Content));
+ Assert.IsTrue(ok, string.Join("\n", lines));
+ Assert.AreEqual(new[] { "GOLDEN OK 1950 " + GoldenRun.Hash1950, "GOLDEN OK 1952 " + GoldenRun.Hash1952 }, lines);
+ }
+
+ [TestCase("http://localhost:8000/index.html?golden", true)]
+ [TestCase("http://localhost:8000/index.html?smoke=5&golden", true)]
+ [TestCase("https://html.itch.zone/html/123/golden-project/index.html", false)]
+ [TestCase("http://localhost:8000/index.html?goldenrod=1", false)]
+ [TestCase("http://localhost:8000/index.html", false)]
+ public void TheGoldenFlagIsAQueryParameterNotAPathWord(string url, bool expected) =>
+ Assert.AreEqual(expected, UrlFlags.Has(url, "golden"));
+
+ [Test]
+ public void IntegerFlagsReadTheirValue()
+ {
+ Assert.AreEqual(5, UrlFlags.Int("http://x/index.html?golden&smoke=5", "smoke"));
+ Assert.AreEqual(0, UrlFlags.Int("http://x/smoke=5/index.html", "smoke"));
+ }
+}
diff --git a/unity/Assets/Tests/EditMode/GoldenCheckTests.cs.meta b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs.meta
new file mode 100644
index 000000000..b01dd8482
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: a621a2195cb934edeb6e6d85789fccf5
\ No newline at end of file
diff --git a/unity/Assets/link.xml b/unity/Assets/link.xml
index 009177074..01da2ca19 100644
--- a/unity/Assets/link.xml
+++ b/unity/Assets/link.xml
@@ -1,5 +1,5 @@
<linker>
<assembly fullname="YamlDotNet" preserve="all" />
<assembly fullname="Statecraft.Sim" preserve="all" />
- <assembly fullname="Statecraft.Game"><type fullname="Statecraft.Game.Map.*" preserve="all"/><type fullname="Statecraft.Game.UI.*" preserve="all"/></assembly>
+ <assembly fullname="Statecraft.Game"><type fullname="Statecraft.Game.Map.*" preserve="all"/><type fullname="Statecraft.Game.UI.*" preserve="all"/><type fullname="Statecraft.Game.Boot.*" preserve="all"/></assembly>
</linker>