A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Unity: the golden checks play every golden in the manifest, not only 1950 and 1952 (fixes #394) (#984)
Eyal Golan1037fa78c879
diff --git a/.gitignore b/.gitignoreindex f3ecdbd9f..4238aefaf 100644--- a/.gitignore+++ b/.gitignore@@ -59,6 +59,8 @@ unity-*.logcaptures/unity/Assets/StreamingAssets/content/unity/Assets/StreamingAssets/content.meta+unity/Assets/StreamingAssets/golden/+unity/Assets/StreamingAssets/golden.metaunity/Assets/StreamingAssets/collection/unity/Assets/StreamingAssets/collection.metaunity/Builds/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5af009def..b36cd586c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB## [Unreleased]+### Fixed+- The Unity golden checks play every golden in `sim/Statecraft.Sim.Tests/golden/manifest.txt` (`hash1950`, `hash1952`,+ `smoke5`, `mvp-end` and each scenario), not only the 1950 and 1952 runs: one EditMode test and `GoldenCheck` (`-golden`,+ `?golden`) read the manifest, the players ship it and the scenario files, and an unknown or failing golden is a+ `GOLDEN FAIL` line. The lines now name the golden (`GOLDEN OK hash1950 <hash>`, was `GOLDEN OK 1950 <hash>`), and the+ smoke and era-golden play code moved into `GoldenRun` so Unity plays the .NET runs (#394).+## [0.1.0] - 2026-10-18### Addeddiff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 2435fcd9a..844a67fbb 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -18,9 +18,10 @@ GitHub Releases page (and, from M4, on itch.io). Steps 1–3 are a normal pull r```bash"$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression gzip -shareable -logFile "$PWD/unity-build-web-gz.log"git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset- uv run tools/web_check.py unity/Builds/Web-gzip --query "golden&smoke=5" \- --expect "GOLDEN OK 1950 7cf678b6b2b3d55dc0fee7b2efdee9ec7688cdf18964dcaa6e5a7c0018e34a51" \- --expect "GOLDEN OK 1952 9496947232f0c97ed21c0a0b98e6727e7d59c892f9aff12049b5d7e5ee2230e8" \+ golden_expect=(); while read -r name hash; do [[ -z "$name" || "$name" == \#* ]] || golden_expect+=(--expect "GOLDEN OK $name $hash"); done < sim/Statecraft.Sim.Tests/golden/manifest.txt+ # one GOLDEN OK line per manifest golden (#394), e.g. "GOLDEN OK hash1950 7cf678b6b2b3d55dc0fee7b2efdee9ec7688cdf18964dcaa6e5a7c0018e34a51"+ # and "GOLDEN OK hash1952 9496947232f0c97ed21c0a0b98e6727e7d59c892f9aff12049b5d7e5ee2230e8"+ uv run tools/web_check.py unity/Builds/Web-gzip --query "golden&smoke=5" "${golden_expect[@]}" \--expect "SMOKE OK 5 turns 1948-10-15 3005405d64abc6e7418fa1f0d35c36ce5f64ed3af7c5a4c24a73d5dfdb16121f"uv run tools/web_check.py unity/Builds/Web-gzip --startscreen new --timeout 300 --stall 90uv run tools/web_check.py unity/Builds/Web-gzip --startscreen recording --timeout 300 --stall 90diff --git a/docs/determinism.md b/docs/determinism.mdindex b9cb04ee3..ff27d4375 100644--- a/docs/determinism.md+++ b/docs/determinism.md@@ -34,19 +34,22 @@ final `GameState.Hash()` is pinned:`hash1952` stops at the first turn on or after 1 January 1952, which is the game's last turn, so it is the same run as`mvp-end` (`DeterminismTests.TheWholeGameToItsEndIsFixed`). Both names are kept (spec 2026-10-12 section 3 step 6): a-later end date moves only `mvp-end`. `mvp-end` is pinned in the manifest and its snapshot; the players and `web_check`-check `hash1950` and `hash1952`.+later end date moves only `mvp-end`. `mvp-end` is pinned in the manifest and its snapshot; Unity EditMode and every+player check enumerate the manifest, so it and every scenario are checked without another hand-written list.A further value is pinned for the browser smoke run (`?smoke=5`: the golden seed, five turns played through the UI's ownbuttons, answering each event with its first option while the turn's Attention pays for it, the rest left to theirministers): `SMOKE OK 5 turns 1948-10-15 3005405d64abc6e7418fa1f0d35c36ce5f64ed3af7c5a4c24a73d5dfdb16121f`.It depends on the UI path as well as the sim (which option is first, the turn grid), so re-record it when either changes.-Check every build with:+Check every WebGL build with every manifest entry (plus the UI-path smoke line) with:```-uv run tools/web_check.py unity/Builds/Web-<compression> --query "golden&smoke=5" \- --expect "GOLDEN OK 1950 7cf678b6b2b3d55dc0fee7b2efdee9ec7688cdf18964dcaa6e5a7c0018e34a51" \- --expect "GOLDEN OK 1952 9496947232f0c97ed21c0a0b98e6727e7d59c892f9aff12049b5d7e5ee2230e8" \+golden_expect=()+while read -r name hash; do+ [[ -z "$name" || "$name" == \#* ]] && continue+ golden_expect+=(--expect "GOLDEN OK $name $hash")+done < sim/Statecraft.Sim.Tests/golden/manifest.txt+uv run tools/web_check.py unity/Builds/Web-<compression> --query "golden&smoke=5" "${golden_expect[@]}" \--expect "SMOKE OK 5 turns 1948-10-15 3005405d64abc6e7418fa1f0d35c36ce5f64ed3af7c5a4c24a73d5dfdb16121f"```@@ -131,8 +134,10 @@ compare against it. These places must agree with it, and `GoldenManifestTests` f`tools/art_checkpoint.sh` reads its expected hashes from the manifest, so it needs no edit.-`unity/Assets/Tests/EditMode/SimSmokeTests.cs` runs the same playthroughs inside Unity against `GoldenRun`'s constants-(run `uv run tools/build_sim_for_unity.py` first so Unity has the current DLLs).+`unity/Assets/Tests/EditMode/GoldenCheckTests.cs` reads the manifest and runs every entry inside Unity Mono. `GoldenCheck`+does the same in macOS and WebGL IL2CPP; `ContentSync` ships the manifest and scenario YAML, and the WebGL loader fetches+them before the check. `tools/player_golden_check.py` and `tools/release_build.py` also derive their required OK lines+from the complete manifest. Run `uv run tools/build_sim_for_unity.py` first so Unity has the current DLLs.Verified on .NET, Unity editor Mono, a macOS IL2CPP player (Apple clang, no `-ffp-contract=off` needed) and a WebGLIL2CPP player in Chrome (M3 Task 22). The platform checks below used the prior `73590e32` 1952 baseline. The issue #2@@ -155,12 +160,20 @@ Re-checked on macOS after the issue #2 correction (2026-10-14, commit `bd683ee0`Re-check with:```-"$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -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 -CI false -GITHUB_ACTIONS false -TF_BUILD false -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 "$PWD/unity-golden-mac.log"; echo exit=$?+uv run tools/machine_lock.py --shared --wait-unity -- "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unity -runTests -testPlatform EditMode -testFilter GoldenCheckTests -testResults "$PWD/unity-editmode.xml" -logFile "$PWD/unity-editmode.log"+uv run tools/machine_lock.py --shared --wait-unity -- "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression disabled -logFile unity-build-web.log+golden_expect=(); while read -r name hash; do [[ -z "$name" || "$name" == \#* ]] || golden_expect+=(--expect "GOLDEN OK $name $hash"); done < sim/Statecraft.Sim.Tests/golden/manifest.txt+uv run tools/web_check.py unity/Builds/Web-disabled --query golden "${golden_expect[@]}"+uv run tools/machine_lock.py --shared --wait-unity -- "$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget OSXUniversal -executeMethod Statecraft.Game.EditorTools.Build.Mac -logFile unity-build-mac.log+uv run tools/machine_lock.py --shared -- "unity/Builds/Mac/Statecraft.app/Contents/MacOS/Statecraft Israel" -batchmode -nographics -golden -logFile "$PWD/unity-golden-mac.log"; echo exit=$?```+Last full-set run (all seven manifest goldens, one `GOLDEN OK <name> <hash>` line each, every hash equal to the+manifest), 18 October 2026, commit `6d29976b` (#394) on `30fbe580`: Unity editor Mono EditMode (`GoldenCheckTests`,+in a full run of 1,321 tests, 0 failed); WebGL IL2CPP in Chrome (`Web-disabled`, `?golden&smoke=5`, `PASS` with the+`SMOKE OK` line too); and a macOS IL2CPP Universal player on Apple silicon (arm64 slice, `-golden`, exit 0). The x86_64+slice, Windows and Linux players were not run then (the `Player golden` workflow checks them on a release).+The player needs an absolute `-logFile` path: with a relative one it wrote no log file in the check run. The editorcommands are fine with relative paths.diff --git a/sim/Statecraft.Sim.Tests/EraGolden.cs b/sim/Statecraft.Sim.Tests/EraGolden.csindex 7bc374065..078baec49 100644--- a/sim/Statecraft.Sim.Tests/EraGolden.cs+++ b/sim/Statecraft.Sim.Tests/EraGolden.cs@@ -1,5 +1,4 @@using System;-using System.Linq;using Statecraft.Sim;/// <summary>Adds a golden for one era in a few lines (#292): <c>EraGolden.Check("hash_founding_1950", c, "founding", new DateTime(1950, 1, 1))</c>@@ -14,21 +13,7 @@ using Statecraft.Sim;public static class EraGolden{public static GameState Play(Content c, string eraId, DateTime until, ulong seed = GoldenRun.Seed)- {- var era = c.Eras.FirstOrDefault(e => e.Id == eraId) ?? throw new ArgumentException($"no era '{eraId}' (known: {string.Join(", ", c.Eras.Select(e => e.Id))})");- if (era.From != c.Rules.Start)- throw new NotSupportedException($"era '{eraId}' starts {era.From:yyyy-MM-dd}, but a new game starts {c.Rules.Start:yyyy-MM-dd}: a fresh start of a later era needs that era's start values, which are not read yet (chapters design section 6).");- if (until <= era.From || until > era.To) throw new ArgumentException($"until {until:yyyy-MM-dd} is outside era '{eraId}' ({era.From:yyyy-MM-dd} to {era.To:yyyy-MM-dd})");- // GoldenRun.Play's loop, except that a turn ending on or after the era's end is not taken.- var s = Simulation.NewGame(c, seed, Mode.Historical);- for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++)- {- var next = Simulation.Step(c, s, GoldenRun.Orders(c, s)).State;- if (next.Date >= era.To) break;- s = next;- }- return s;- }+ => GoldenRun.PlayEra(c, eraId, until, seed);public static void Check(string name, Content c, string eraId, DateTime until, ulong seed = GoldenRun.Seed){diff --git a/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs b/sim/Statecraft.Sim.Tests/SliceSmokeTests.csindex e4f47a52a..fe76abfdf 100644--- a/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs+++ b/sim/Statecraft.Sim.Tests/SliceSmokeTests.cs@@ -30,22 +30,8 @@ public class SliceSmokeTestsdelegate List<Command> Policy(Content c, GameState s, int turn);- /// <summary>What GameRoot.Smoke does: answer each open event, in the card's order, with its first option button, while- /// the turn's Attention pays for an answer; the rest go to their ministers at the turn's end.</summary>- static List<Command> FirstOption(Content c, GameState s, int turn)- {- var answers = new List<Command>();- var left = s.Attention;- foreach (var e in s.PendingEvents.Select(id => c.Events.First(x => x.Id == id)))- {- var cmd = new ChooseEventOption(e.Id, e.Options[0].Id);- var price = AttentionSystem.Cost(c, s, cmd.Kind);- if (price > left + 1e-9) break;- left -= price;- answers.Add(cmd);- }- return answers;- }+ /// <summary>What GameRoot.Smoke does (GoldenRun.SmokeOrders, shared with Unity's golden check).</summary>+ static List<Command> FirstOption(Content c, GameState s, int turn) => GoldenRun.SmokeOrders(c, s);/// <summary>The golden runs' player (GoldenRun.Orders): HistoricalAI's orders, then the reference player's GDD orders.</summary>static List<Command> Historical(Content c, GameState s, int turn) => GoldenRun.Orders(c, s).ToList();@@ -246,6 +232,8 @@ public class SliceSmokeTestsvar expected = WebSmoke5; // read before an update rewrites the manifest, so a moved value still fails this runif (GoldenManifest.UpdateRequested) GoldenManifest.Update("smoke5", five.Hash());Assert.Equal(expected, FormattableString.Invariant($"SMOKE OK 5 turns {five.Date:yyyy-MM-dd} {five.Hash()}"));+ // The library's run (Unity's golden check, #394) ends on the same state as the session run above.+ Assert.Equal(five.Hash(), GoldenRun.PlaySmoke(Real, 5).Hash());Assert.True(clock.Elapsed < TimeSpan.FromMinutes(1), $"took {clock.Elapsed}");}diff --git a/sim/Statecraft.Sim/GoldenRun.cs b/sim/Statecraft.Sim/GoldenRun.csindex b8c679a1a..b1e3ad50a 100644--- a/sim/Statecraft.Sim/GoldenRun.cs+++ b/sim/Statecraft.Sim/GoldenRun.cs@@ -1,5 +1,6 @@using System;using System.Collections.Generic;+using System.Linq;using Statecraft.Sim.Reference;namespace Statecraft.Sim@@ -41,5 +42,56 @@ namespace Statecraft.Sim/// <summary>The mvp-end golden: the whole game, to its end (Content.End, R-LOOP-004).</summary>public static GameState PlayToEnd(Content c) => Play(c ?? throw new ArgumentNullException(nameof(c)), c.End);++ /// <summary>A fresh start of one era (#292), the run the era goldens pin (EraGolden; golden manifest names+ /// hash_<era>_<year>): the golden seed, Historical mode and <see cref="Orders"/>, as <see cref="Play"/>,+ /// except that the turn that would reach the era's <c>to</c> is not taken (that turn's state already holds the next+ /// era's rules). An era later than the first fails here with a message saying so: NewGame reads only the base+ /// rules' start values. Here, not in the test project, so Unity's golden check plays the same run.</summary>+ public static GameState PlayEra(Content c, string eraId, DateTime until, ulong seed = Seed)+ {+ if (c == null) throw new ArgumentNullException(nameof(c));+ var era = c.Eras.FirstOrDefault(e => e.Id == eraId) ?? throw new ArgumentException($"no era '{eraId}' (known: {string.Join(", ", c.Eras.Select(e => e.Id))})");+ if (era.From != c.Rules.Start)+ throw new NotSupportedException($"era '{eraId}' starts {era.From:yyyy-MM-dd}, but a new game starts {c.Rules.Start:yyyy-MM-dd}: a fresh start of a later era needs that era's start values, which are not read yet (chapters design section 6).");+ if (until <= era.From || until > era.To) throw new ArgumentException($"until {until:yyyy-MM-dd} is outside era '{eraId}' ({era.From:yyyy-MM-dd} to {era.To:yyyy-MM-dd})");+ var s = Simulation.NewGame(c, seed, Mode.Historical);+ for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++)+ {+ var next = Simulation.Step(c, s, Orders(c, s)).State;+ if (next.Date >= era.To) break;+ s = next;+ }+ return s;+ }++ /// <summary>The smoke5 golden's orders for one turn, what the WebGL ?smoke run's GameRoot.Smoke does: each open event,+ /// in the card's order, answered with its first option while the turn's Attention pays for an answer; the rest go+ /// to their ministers at the turn's end (docs/determinism.md). SliceSmokeTests plays the same policy.</summary>+ public static List<Command> SmokeOrders(Content c, GameState s)+ {+ if (c == null) throw new ArgumentNullException(nameof(c));+ var answers = new List<Command>();+ var left = s.Attention;+ foreach (var e in s.PendingEvents.Select(id => c.Events.First(x => x.Id == id)))+ {+ var cmd = new ChooseEventOption(e.Id, e.Options[0].Id);+ var price = AttentionSystem.Cost(c, s, cmd.Kind);+ if (price > left + 1e-9) break;+ left -= price;+ answers.Add(cmd);+ }+ return answers;+ }++ /// <summary>The smoke5 golden: the golden seed, Historical mode, <paramref name="turns"/> turns of <see cref="SmokeOrders"/>.</summary>+ public static GameState PlaySmoke(Content c, int turns)+ {+ if (c == null) throw new ArgumentNullException(nameof(c));+ var s = Simulation.NewGame(c, Seed, Mode.Historical);+ for (int turn = 0; turn < turns && s.Date < Until1952 && s.GameOver == null; turn++)+ s = Simulation.Step(c, s, SmokeOrders(c, s)).State;+ return s;+ }}}diff --git a/tools/README.md b/tools/README.mdindex 804995c10..3f211ba24 100644--- a/tools/README.md+++ b/tools/README.md@@ -43,7 +43,7 @@ Offline data tools (uv inline-script Python). Run from the repo root.- `player_golden_check.py` is the logic of `.github/workflows/player-golden.yml`: `plan` lists the desktop players aGitHub Release carries (their asset names are the contract with the release script) and refuses a partial set, and`run` checks one against GitHub's SHA-256 digest for the asset, unpacks it, checks the notices sit beside the player, runs it- with `-batchmode -nographics -golden` and passes only on exit 0 with both `GOLDEN OK` lines from the golden manifest,+ with `-batchmode -nographics -golden` and passes only on exit 0 with every `GOLDEN OK` line from the golden manifest,printing the player log otherwise. Stdlib only; no Unity and no licence needed.- `package_release.py` zips a WebGL release build (gzip, `unity/Builds/Web-gzip`; #879) for sharing (`unity/Builds/statecraft-m3-web.zip`) and refuses(exit 1) until every sensitive event is `sensitivity-reviewed` (docs/m3-release.md). The files under `Build/` arediff --git a/tools/art_checkpoint.sh b/tools/art_checkpoint.shindex 992380683..4955b5385 100755--- a/tools/art_checkpoint.sh+++ b/tools/art_checkpoint.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# Owner art checkpoint (exits 3 when diorama02's material guards fail, after finishing): a WebGL build (skipped with --no-build when the task has just built), screenshots at# the promo poses from the player itself (?shot: the web tier with its UI and labels), editor renders of both quality-# tiers, and side-by-side images against the promo with colour-blind simulations. Re-checks both golden hashes in the same+# tiers, and side-by-side images against the promo with colour-blind simulations. Re-checks every manifest golden in the same# player run and fails if a screenshot is missing or blank. The art log lives in the main checkout's captures/ so every# worktree appends to one history. --units adds the unit art slice (docs/units.md) to both the WebGL shots (&units) and the# editor renders (-units), and its art-log rows are named <checkpoint-name>-units, so they cannot be mistaken for plain@@ -45,10 +45,14 @@ fiout="captures/visual/$name"rm -rf "$out"; mkdir -p "$out"# The expected hashes come from the golden manifest (docs/determinism.md), so a re-pin needs no edit here.-golden() { awk -v k="$1" '$1 == k { print $2 }' sim/Statecraft.Sim.Tests/golden/manifest.txt; }-hash1950=$(golden hash1950); hash1952=$(golden hash1952)-[[ -n "$hash1950" && -n "$hash1952" ]] || { echo "art_checkpoint: no hash1950/hash1952 in sim/Statecraft.Sim.Tests/golden/manifest.txt" >&2; exit 2; }-uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot${units_query}${proof_query}" --expect "GOLDEN OK 1950 $hash1950" --expect "GOLDEN OK 1952 $hash1952" --expect "SHOT done" --shots "$out" --stall 180 \+golden_expect=()+# (golden_name, not name: $name is the checkpoint's name, used below)+while read -r golden_name golden_hash; do+ [[ -z "$golden_name" || "$golden_name" == \#* ]] && continue+ golden_expect+=(--expect "GOLDEN OK $golden_name $golden_hash")+done < sim/Statecraft.Sim.Tests/golden/manifest.txt+[[ ${#golden_expect[@]} -gt 0 ]] || { echo "art_checkpoint: empty golden manifest" >&2; exit 2; }+uv run tools/web_check.py unity/Builds/Web-disabled --query "golden&shot${units_query}${proof_query}" "${golden_expect[@]}" --expect "SHOT done" --shots "$out" --stall 180 \--fail 'GOLDEN FAIL|SMOKE FAIL|BOOT FAIL|Statecraft/.*(not supported|Unsupported)|(not supported|Unsupported).*Statecraft/'# The poses come from PromoPose.All's source, so a new pose is checked without editing this script (review M3).poses=$(grep -o 'new PromoPose("[A-Za-z0-9_]*"' unity/Assets/Scripts/Map/PromoPose.cs | cut -d'"' -f2)diff --git a/tools/player_golden_check.py b/tools/player_golden_check.pyindex d877b359a..810ef89be 100644--- a/tools/player_golden_check.py+++ b/tools/player_golden_check.py@@ -20,7 +20,7 @@ into an empty folder, finds the player, checks the layout (the notices of REQUIRplayer or the .app), runs it with`-batchmode -nographics -golden -logFile <absolute path>` (docs/determinism.md), the Linux player under `xvfb-run -a`(DISPLAY_WRAPPER: it crashes with no display at all), and passes only when it exits 0 and its log-holds `GOLDEN OK 1950 <hash1950>` and `GOLDEN OK 1952 <hash1952>` from the golden manifest, and no FAIL line. On failure+holds one `GOLDEN OK <name> <hash>` line for every entry in the golden manifest, and no FAIL line. On failureit prints the whole player log. With --arch (the Mac app, run once per slice) the runner's `uname -m` must be thatarchitecture and `lipo -archs` must list it. Exit 0 when the check passes, 1 when it fails, 2 on bad input.@@ -82,7 +82,6 @@ DISPLAY_WRAPPER = {"linux": ["xvfb-run", "-a"]}# Seconds a timed-out run gets between SIGTERM and SIGKILL (stop_group).TERM_GRACE = 5-GOLDENS = (("1950", "hash1950"), ("1952", "hash1952"))FAIL = re.compile(r"\b(GOLDEN FAIL|BOOT FAIL)\b")@@ -140,10 +139,12 @@ def read_manifest(text: str) -> dict[str, str]:def expected_lines(manifest: dict[str, str]) -> list[str]:- missing = [key for _, key in GOLDENS if not re.fullmatch(r"[0-9a-f]{64}", manifest.get(key, ""))]- if missing:- raise ValueError(f"the golden manifest has no SHA-256 for {', '.join(missing)}")- return [f"GOLDEN OK {year} {manifest[key]}" for year, key in GOLDENS]+ if not manifest:+ raise ValueError("the golden manifest has no entries")+ bad = [name for name, value in manifest.items() if not re.fullmatch(r"[0-9a-f]{64}", value)]+ if bad:+ raise ValueError(f"the golden manifest has no SHA-256 for {', '.join(bad)}")+ return [f"GOLDEN OK {name} {value}" for name, value in manifest.items()]def check_log(log: str, expected: list[str], exit_code: int | None) -> list[str]:diff --git a/tools/release_build.py b/tools/release_build.pyindex b09613576..b9d02ada1 100644--- a/tools/release_build.py+++ b/tools/release_build.py@@ -163,8 +163,8 @@ def expected_goldens() -> dict[str, str]:pins = {}for line in (REPO / "sim/Statecraft.Sim.Tests/golden/manifest.txt").read_text().splitlines():name, _, value = line.partition(" ")- if name in ("hash1950", "hash1952"):- pins[name[4:]] = value.strip()+ if name and not name.startswith("#"):+ pins[name] = value.strip()return pins@@ -264,11 +264,10 @@ def golden_lines(log_text: str) -> list[str]:def golden_status(log_text: str, exit_code: int, expected: dict[str, str]) -> str:- """pass only on exit 0, both `GOLDEN OK <year> <pinned hash>` lines exactly as the player prints them (bare, one per+ """pass only on exit 0, every manifest `GOLDEN OK <name> <pinned hash>` line exactly as the player prints it (bare, one perline), and no GOLDEN FAIL or BOOT FAIL line: player_golden_check.check_log, the rule CI applies (issue #546)."""- if sorted(expected) != [year for year, _ in pgc.GOLDENS]:- return "fail"- wanted = [f"GOLDEN OK {year} {expected[year]}" for year, _ in pgc.GOLDENS]+ if not expected or any(not re.fullmatch(r"[0-9a-f]{64}", value) for value in expected.values()): return "fail"+ wanted = [f"GOLDEN OK {name} {value}" for name, value in expected.items()]return "pass" if not pgc.check_log(log_text, wanted, exit_code) else "fail"diff --git a/tools/tests/test_player_golden_check.py b/tools/tests/test_player_golden_check.pyindex 99de4e696..84ff74107 100644--- a/tools/tests/test_player_golden_check.py+++ b/tools/tests/test_player_golden_check.py@@ -19,7 +19,7 @@ import player_golden_check as pgREPO = Path(__file__).resolve().parents[2]H50, H52 = "a" * 64, "b" * 64MANIFEST = f"# comment\nhash1950 {H50}\nhash1952 {H52}\nsmoke5 {'c' * 64}\n"-EXPECTED = [f"GOLDEN OK 1950 {H50}", f"GOLDEN OK 1952 {H52}"]+EXPECTED = [f"GOLDEN OK hash1950 {H50}", f"GOLDEN OK hash1952 {H52}", f"GOLDEN OK smoke5 {'c' * 64}"]def digest(name):@@ -223,10 +223,10 @@ def test_plan_command_writes_the_matrix_to_the_github_output(tmp_path, monkeypatdef test_expected_lines_come_from_the_manifest_and_the_real_manifest_has_them():assert pg.expected_lines(pg.read_manifest(MANIFEST)) == EXPECTED- with pytest.raises(ValueError, match="hash1952"):- pg.expected_lines(pg.read_manifest(f"hash1950 {H50}\n"))+ with pytest.raises(ValueError, match="bad"):+ pg.expected_lines(pg.read_manifest("bad nope\n"))real = pg.read_manifest((REPO / "sim/Statecraft.Sim.Tests/golden/manifest.txt").read_text(encoding="utf-8"))- assert [l.split()[2] for l in pg.expected_lines(real)] == ["1950", "1952"]+ assert [l.split()[2] for l in pg.expected_lines(real)] == list(real)def test_a_passing_log_needs_both_lines_and_exit_zero():@@ -234,17 +234,17 @@ def test_a_passing_log_needs_both_lines_and_exit_zero():assert pg.check_log(log, EXPECTED, 0) == []assert pg.check_log(log, EXPECTED, 1) == ["the player exited 1"]assert pg.check_log(log, EXPECTED, None) == ["the player did not exit before the timeout"]- assert pg.check_log(EXPECTED[0], EXPECTED, 0) == [f"missing line: {EXPECTED[1]}"]+ assert pg.check_log(EXPECTED[0], EXPECTED, 0) == [f"missing line: {line}" for line in EXPECTED[1:]]def test_a_wrong_hash_or_a_fail_line_fails():- wrong = f"GOLDEN OK 1950 {H50}\nGOLDEN FAIL 1952 {'d' * 64} expected {H52}\n"+ wrong = f"GOLDEN OK hash1950 {H50}\nGOLDEN FAIL hash1952 {'d' * 64} expected {H52}\n"assert pg.check_log(wrong, EXPECTED, 1) == ["the player exited 1", f"missing line: {EXPECTED[1]}",- f"failure line: GOLDEN FAIL 1952 {'d' * 64} expected {H52}"]+ f"missing line: {EXPECTED[2]}", f"failure line: GOLDEN FAIL hash1952 {'d' * 64} expected {H52}"]assert pg.check_log("\n".join(EXPECTED) + "\nBOOT FAIL content missing", EXPECTED, 0) == ["failure line: BOOT FAIL content missing"]# A hash prefix or a line with more after it is not the line.- assert pg.check_log(f"GOLDEN OK 1950 {H50[:8]}\nGOLDEN OK 1952 {H52}x", EXPECTED, 0) == [+ assert pg.check_log(f"GOLDEN OK hash1950 {H50[:8]}\nGOLDEN OK hash1952 {H52}x\n{EXPECTED[2]}", EXPECTED, 0) == [f"missing line: {EXPECTED[0]}", f"missing line: {EXPECTED[1]}"]@@ -447,7 +447,7 @@ def test_the_pass_rule_matches_the_real_player_log_format():# more hex digit, is not the expected line.assert pg.check_log("Loading content\n" + "\n".join(EXPECTED) + "\n", EXPECTED, 0) == []assert pg.check_log("\n".join("12:00:01 " + l for l in EXPECTED), EXPECTED, 0) == [f"missing line: {l}" for l in EXPECTED]- assert pg.check_log(EXPECTED[0] + "a\n" + EXPECTED[1], EXPECTED, 0) == [f"missing line: {EXPECTED[0]}"]+ assert pg.check_log(EXPECTED[0] + "a\n" + "\n".join(EXPECTED[1:]), EXPECTED, 0) == [f"missing line: {EXPECTED[0]}"]def test_the_release_script_shares_the_asset_names_the_tag_rule_and_the_pass_rule():@@ -455,7 +455,7 @@ def test_the_release_script_shares_the_asset_names_the_tag_rule_and_the_pass_rulimport release_build as rbassert rb.ARCHIVES == {"mac": pg.ASSETS["macos"], "linux": pg.ASSETS["linux"], "windows": pg.ASSETS["windows"]}assert rb.TAG is pg.TAG- expected = {"1950": H50, "1952": H52}+ expected = {"hash1950": H50, "hash1952": H52, "smoke5": "c" * 64}logs = ["\n".join(EXPECTED), "\n".join("12:00:01 " + l for l in EXPECTED), EXPECTED[0] + "a\n" + EXPECTED[1],"\n".join(EXPECTED) + "\nBOOT FAIL x", EXPECTED[0], ""]for log in logs:diff --git a/tools/tests/test_release_build.py b/tools/tests/test_release_build.pyindex d97377188..64ec6de24 100644--- a/tools/tests/test_release_build.py+++ b/tools/tests/test_release_build.py@@ -29,7 +29,7 @@ def repo(tmp_path):(root / "sim/Statecraft.Sim").mkdir(parents=True)(root / "sim/Statecraft.Sim/SimInfo.cs").write_text(' public const string Version = "0.1.0";\n')(root / "sim/Statecraft.Sim.Tests/golden").mkdir(parents=True)- (root / "sim/Statecraft.Sim.Tests/golden/manifest.txt").write_text(f"# pinned\nhash1950 {H1950}\nhash1952 {H1952}\nsmoke5 abc\n")+ (root / "sim/Statecraft.Sim.Tests/golden/manifest.txt").write_text(f"# pinned\nhash1950 {H1950}\nhash1952 {H1952}\nsmoke5 {'c' * 64}\n")for name in ("LICENSE", "NOTICE", "THIRD-PARTY-NOTICES.md"):(root / name).write_text(f"{name} text\n")(root / "LICENSES").mkdir()@@ -111,8 +111,8 @@ class Fake:code = 1elif "-golden" in cmd:log = Path(cmd[cmd.index("-logFile") + 1])- second = f"GOLDEN OK 1952 {H1952}" if self.golden_ok else f"GOLDEN FAIL 1952 {'f' * 64} expected {H1952}"- log.write_text(f"boot\nGOLDEN OK 1950 {H1950}\n{second}\n")+ second = f"GOLDEN OK hash1952 {H1952}" if self.golden_ok else f"GOLDEN FAIL hash1952 {'f' * 64} expected {H1952}"+ log.write_text(f"boot\nGOLDEN OK hash1950 {H1950}\n{second}\nGOLDEN OK smoke5 {'c' * 64}\n")code = 0 if self.golden_ok else 1elif cmd[0] == "ditto":# Plays `ditto -c -k --norsrc --keepParent SRC ZIP`: a real zip, SRC's name as the top folder.@@ -302,9 +302,8 @@ def test_a_failed_unity_exit_fails_even_when_a_player_is_left_behind(repo, editoassert not [c for c in fake.calls if "-golden" in c]-def test_a_manifest_missing_one_golden_never_passes():- """Mutation M6: both pinned hashes are required, even if the manifest lost one."""- assert rb.golden_status(f"GOLDEN OK 1950 {H1950}\n", 0, {"1950": H1950}) == "fail"+def test_an_empty_or_malformed_manifest_never_passes():+ assert rb.golden_status("GOLDEN OK one nope\n", 0, {"one": "nope"}) == "fail"assert rb.golden_status("", 0, {}) == "fail"@@ -327,7 +326,7 @@ def test_the_record_says_whether_the_tree_stayed_clean(repo, editor, monkeypatchdef test_unity_version_and_goldens_come_from_the_repository(repo, monkeypatch):monkeypatch.setattr(rb, "REPO", repo)assert rb.unity_version() == ("6000.3.25f1", "e1dba0a9aba4")- assert rb.expected_goldens() == {"1950": H1950, "1952": H1952}+ assert rb.expected_goldens() == {"hash1950": H1950, "hash1952": H1952, "smoke5": "c" * 64}assert rb.versions() == {"bundle_version": "0.1.0", "sim_version": "0.1.0"}@@ -508,7 +507,7 @@ def test_the_record_holds_commit_unity_date_hashes_sizes_and_goldens(repo, editoassert exe.is_file()assert mac["golden"]["status"] == "pass"- assert mac["golden"]["lines"] == [f"GOLDEN OK 1950 {H1950}", f"GOLDEN OK 1952 {H1952}"]+ assert mac["golden"]["lines"] == [f"GOLDEN OK hash1950 {H1950}", f"GOLDEN OK hash1952 {H1952}", f"GOLDEN OK smoke5 {'c' * 64}"]assert mac["golden"]["exit_code"] == 0for name in ("linux", "windows"):assert arts[name]["golden"]["status"] == "unchecked"@@ -540,7 +539,7 @@ def test_a_failed_golden_is_recorded_and_fails_the_run(repo, editor, monkeypatchassert run_main(["--platform", "mac", "--out", str(out)], repo, editor, fake, monkeypatch) == 1mac = json.loads((out / "build-record.json").read_text())["artifacts"][0]assert mac["golden"]["status"] == "fail" and mac["golden"]["exit_code"] == 1- assert any(line.startswith("GOLDEN FAIL 1952") for line in mac["golden"]["lines"])+ assert any(line.startswith("GOLDEN FAIL hash1952") for line in mac["golden"]["lines"])def test_golden_lines_must_match_the_pinned_hashes_not_just_say_ok():diff --git a/tools/web_check.py b/tools/web_check.pyindex d5336870c..e7904a7a3 100644--- a/tools/web_check.py+++ b/tools/web_check.py@@ -8,7 +8,7 @@ fail on a failure line or a timeout. Uses Chrome for Testing from the Playwright--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 7cf678b6b2b3d55dc0fee7b2efdee9ec7688cdf18964dcaa6e5a7c0018e34a51" --expect "GOLDEN OK 1952 9496947232f0c97ed21c0a0b98e6727e7d59c892f9aff12049b5d7e5ee2230e8"+ uv run tools/web_check.py unity/Builds/Web-disabled --query "golden" --expect "GOLDEN OK hash1950 7cf678b6b2b3d55dc0fee7b2efdee9ec7688cdf18964dcaa6e5a7c0018e34a51" --expect "GOLDEN OK hash1952 9496947232f0c97ed21c0a0b98e6727e7d59c892f9aff12049b5d7e5ee2230e8"Options: --query Q (page URL query, without '?'), --expect TEXT (repeatable), --fail REGEX (default: GOLDEN FAIL|SMOKE FAIL|BOOT FAIL),--timeout SECONDS (default 300), --stall SECONDS (fail when no console message arrives for that long; 0 = off),--swiftshader (software WebGL when there is no GPU), --dpr N (default 1), --shots DIR (reassemble the player'sdiff --git a/unity/Assets/Editor/ContentSync.cs b/unity/Assets/Editor/ContentSync.csindex 361979a8e..84f21f9be 100644--- a/unity/Assets/Editor/ContentSync.cs+++ b/unity/Assets/Editor/ContentSync.cs@@ -12,6 +12,7 @@ namespace Statecraft.Game.EditorToolspublic sealed class ContentSync : IPreprocessBuildWithReport{public static string Target => Path.Combine(UnityEngine.Application.dataPath, "StreamingAssets", "content");+ public static string GoldenTarget => Path.Combine(UnityEngine.Application.dataPath, "StreamingAssets", "golden");public int callbackOrder => 0;@@ -23,6 +24,12 @@ namespace Statecraft.Game.EditorToolstry { ContentManifest.Verify(Paths.Content, Target); }catch (InvalidDataException e) { throw new BuildFailedException("ContentSync: " + e.Message); }UnityEngine.Debug.Log($"ContentSync: {files.Count} files to {Target}");+ var source = Path.Combine(Paths.RepoRoot, "sim", "Statecraft.Sim.Tests");+ if (Directory.Exists(GoldenTarget)) Directory.Delete(GoldenTarget, true);+ Directory.CreateDirectory(Path.Combine(GoldenTarget, "scenarios"));+ File.Copy(Path.Combine(source, "golden", "manifest.txt"), Path.Combine(GoldenTarget, "manifest.txt"));+ foreach (var scenario in Directory.GetFiles(Path.Combine(source, "scenarios"), "*.yaml"))+ File.Copy(scenario, Path.Combine(GoldenTarget, "scenarios", Path.GetFileName(scenario)));}}}diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.csindex a31182db6..5c6dda67e 100644--- a/unity/Assets/Scripts/Boot/GameBoot.cs+++ b/unity/Assets/Scripts/Boot/GameBoot.cs@@ -48,7 +48,7 @@ namespace Statecraft.Game.BootInputs = await load();if (GoldenCheck.Requested()){- var (ok, lines) = GoldenCheck.Run(Inputs.Content);+ var (ok, lines) = GoldenCheck.Run(Inputs.Content, Inputs.Goldens);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; }diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.csindex 4d240de0c..de41cb963 100644--- a/unity/Assets/Scripts/Boot/GameInputs.cs+++ b/unity/Assets/Scripts/Boot/GameInputs.cs@@ -50,6 +50,7 @@ namespace Statecraft.Game.Boot{public Content Content = null!;public MapInputs Map = null!;+ public GoldenData Goldens = null!;public static MapInputs MapFromDisk(string contentDir, string mapDir) => new MapInputs{@@ -74,8 +75,17 @@ namespace Statecraft.Game.Boot/// <summary>A map-only, cosmetic input: "" when the file is missing (the map then skips that layer with a warning).</summary>static string ReadIfExists(string path) => File.Exists(path) ? File.ReadAllText(path) : "";- public static GameInputs FromDisk(string contentDir, string mapDir) =>- new GameInputs { Content = ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir) };+ /// <summary>The inputs from disk. The golden data (#394) is read in the editor (the repository's manifest and+ /// scenarios) and, in a player, only for a -golden run (the copies ContentSync ships), so a normal boot never+ /// depends on it.</summary>+ public static GameInputs FromDisk(string contentDir, string mapDir)+ {+ var root = Application.isEditor+ ? Path.Combine(Paths.RepoRoot, "sim", "Statecraft.Sim.Tests", "golden")+ : Path.Combine(Application.streamingAssetsPath, "golden");+ var goldens = Application.isEditor || GoldenCheck.Requested() ? GoldenData.FromDisk(root) : new GoldenData();+ return new GameInputs { Content = ContentLoader.Load(contentDir), Map = MapFromDisk(contentDir, mapDir), Goldens = goldens };+ }/// <summary>Builds the inputs from fetched texts (keys are manifest paths) and the packed heightmap's bytes.</summary>public static GameInputs FromTexts(IReadOnlyDictionary<string, string> texts, IEnumerable<string> manifest, string heightmapJson, byte[] r16z)@@ -212,7 +222,11 @@ namespace Statecraft.Game.Bootinternal static async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId, float stallSeconds){var manifest = ContentManifest.Parse(await Text(Start(WithBuildId(baseUrl + "/content/" + ContentManifest.FileName, buildId)), ContentManifest.FileName, stallSeconds));+ var goldenText = GoldenCheck.Requested()+ ? await Text(Start(WithBuildId(baseUrl + "/golden/manifest.txt", buildId)), "golden/manifest.txt", stallSeconds) : "";+ var scenarioNames = goldenText.Length == 0 ? new List<string>() : GoldenData.Parse(goldenText).Select(x => x.name).Where(n => n.StartsWith("scenario-", StringComparison.Ordinal)).Select(n => n.Substring("scenario-".Length)).ToList();var requests = manifest.Select(f => (file: f, request: Start(WithBuildId(baseUrl + "/content/" + f, buildId)))).ToList();+ var scenarioRequests = scenarioNames.Select(n => (name: n, request: Start(WithBuildId(baseUrl + "/golden/scenarios/" + n + ".yaml", buildId)))).ToList();var meta = Start(WithBuildId(baseUrl + "/map/heightmap.json", buildId));var r16z = Start(WithBuildId(baseUrl + "/map/" + HeightmapCodec.FileName, buildId));try@@ -223,12 +237,15 @@ namespace Statecraft.Game.Bootvar r16zBytes = await Bytes(r16z, HeightmapCodec.FileName, stallSeconds);DiagLog.BootPhase($"downloaded {texts.Count + 3} files");var inputs = FromTexts(texts, manifest, metaText, r16zBytes);+ inputs.Goldens = new GoldenData { Manifest = goldenText };+ foreach (var (name, request) in scenarioRequests) inputs.Goldens.Scenarios[name] = await Text(request, "golden/scenarios/" + name + ".yaml", stallSeconds);DiagLog.BootPhase("content parsed and validated");return inputs;}finally{foreach (var (_, request) in requests) Release(request);+ foreach (var (_, request) in scenarioRequests) Release(request);Release(meta); Release(r16z);}}diff --git a/unity/Assets/Scripts/Boot/GoldenCheck.cs b/unity/Assets/Scripts/Boot/GoldenCheck.csindex 84f21e9a9..eba4dbb3f 100644--- a/unity/Assets/Scripts/Boot/GoldenCheck.cs+++ b/unity/Assets/Scripts/Boot/GoldenCheck.cs@@ -2,13 +2,14 @@using System;using System.Collections.Generic;using System.Linq;+using System.Globalization;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 <year> <hash>" or "GOLDEN FAIL <year> <hash> expected <hash>" (docs/determinism.md).+ /// <summary>Runs every manifest golden in whatever runtime this is (IL2CPP in players) and reports+ /// "GOLDEN OK <name> <hash>" or "GOLDEN FAIL <name> <hash> expected <hash>" (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{@@ -19,18 +20,55 @@ namespace Statecraft.Game.Boot/// <summary>The exit code a boot error must quit with: 1 for a desktop -golden run (so it never hangs), else null.</summary>public static int? QuitCodeOnError(bool requested, bool webgl) => requested && !webgl ? 1 : (int?)null;- public static (bool ok, List<string> lines) Run(Content c)+ /// <summary>Plays every golden the manifest lists, in its order, one OK or FAIL line each. A golden this code cannot+ /// play (an unknown name, a missing scenario file) or a run that throws is a FAIL line, never a skipped one, and an+ /// empty manifest fails: a full-set pass needs every line.</summary>+ public static (bool ok, List<string> lines) Run(Content c, GoldenData data){var lines = new List<string>();bool ok = true;- foreach (var (until, expected) in new[] { (GoldenRun.Until1950, GoldenRun.Hash1950), (GoldenRun.Until1952, GoldenRun.Hash1952) })+ IReadOnlyList<(string name, string hash)> goldens;+ try { goldens = GoldenData.Parse(data.Manifest); }+ catch (Exception e) { return (false, new List<string> { $"GOLDEN FAIL manifest {e.Message}" }); }+ if (goldens.Count == 0) return (false, new List<string> { "GOLDEN FAIL manifest has no goldens" });+ foreach (var (name, expected) in goldens){- 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}"); }+ string hash;+ try { hash = Play(name, c, data).Hash(); }+ catch (Exception e) { ok = false; lines.Add($"GOLDEN FAIL {name} {e.GetType().Name}: {e.Message}"); continue; }+ if (hash == expected) lines.Add($"GOLDEN OK {name} {hash}");+ else { ok = false; lines.Add($"GOLDEN FAIL {name} {hash} expected {expected}"); }}return (ok, lines);}++ /// <summary>The run a manifest name pins (docs/determinism.md): hash1950 and hash1952 (GoldenRun.Play), mvp-end+ /// (GoldenRun.PlayToEnd), smoke<N> (GoldenRun.PlaySmoke), scenario-<name> (that scenario file) and the+ /// era goldens hash_<era>_<year> (GoldenRun.PlayEra to 1 January of that year, as EraGolden names them).</summary>+ internal static GameState Play(string name, Content c, GoldenData data)+ {+ if (name == "hash1950") return GoldenRun.Play(c, GoldenRun.Until1950);+ if (name == "hash1952") return GoldenRun.Play(c, GoldenRun.Until1952);+ if (name == "mvp-end") return GoldenRun.PlayToEnd(c);+ if (name.StartsWith("smoke", StringComparison.Ordinal)+ && int.TryParse(name.Substring("smoke".Length), NumberStyles.None, CultureInfo.InvariantCulture, out var turns) && turns > 0)+ return GoldenRun.PlaySmoke(c, turns);+ if (name.StartsWith("scenario-", StringComparison.Ordinal))+ {+ var scenarioName = name.Substring("scenario-".Length);+ if (!data.Scenarios.TryGetValue(scenarioName, out var yaml)) throw new InvalidOperationException($"golden scenario '{scenarioName}' is missing");+ var scenario = Scenario.Parse(yaml);+ if (scenario.Name != scenarioName) throw new InvalidOperationException($"golden scenario file '{scenarioName}' names '{scenario.Name}'");+ return scenario.Play(c);+ }+ if (name.StartsWith("hash_", StringComparison.Ordinal))+ {+ var split = name.LastIndexOf('_');+ if (split <= 5 || !int.TryParse(name.Substring(split + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var year))+ throw new InvalidOperationException($"unknown golden '{name}'");+ return GoldenRun.PlayEra(c, name.Substring(5, split - 5), new DateTime(year, 1, 1));+ }+ throw new InvalidOperationException($"unknown golden '{name}'");+ }}}diff --git a/unity/Assets/Scripts/Boot/GoldenData.cs b/unity/Assets/Scripts/Boot/GoldenData.csnew file mode 100644index 000000000..dd13c46d2--- /dev/null+++ b/unity/Assets/Scripts/Boot/GoldenData.cs@@ -0,0 +1,29 @@+#nullable enable+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;++namespace Statecraft.Game.Boot+{+ /// <summary>The golden manifest and scripted scenarios, shipped beside content so IL2CPP and WebGL run the same set.</summary>+ public sealed class GoldenData+ {+ public string Manifest = "";+ public Dictionary<string, string> Scenarios = new Dictionary<string, string>(StringComparer.Ordinal);++ public static GoldenData FromDisk(string root)+ {+ var manifest = File.ReadAllText(Path.Combine(root, "manifest.txt"));+ var scenarioDir = Directory.Exists(Path.Combine(root, "scenarios")) ? Path.Combine(root, "scenarios") : Path.Combine(Directory.GetParent(root)!.FullName, "scenarios");+ var scenarios = Directory.Exists(scenarioDir)+ ? Directory.GetFiles(scenarioDir, "*.yaml").ToDictionary(Path.GetFileNameWithoutExtension, File.ReadAllText, StringComparer.Ordinal)+ : new Dictionary<string, string>(StringComparer.Ordinal);+ return new GoldenData { Manifest = manifest, Scenarios = scenarios };+ }++ public static IReadOnlyList<(string name, string hash)> Parse(string text) => text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)+ .Where(line => !line.StartsWith("#", StringComparison.Ordinal)).Select(line => line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))+ .Select(parts => parts.Length == 2 ? (parts[0], parts[1]) : throw new InvalidDataException("golden manifest line must be: name hash")).ToList();+ }+}diff --git a/unity/Assets/Scripts/Boot/GoldenData.cs.meta b/unity/Assets/Scripts/Boot/GoldenData.cs.metanew file mode 100644index 000000000..41e333565--- /dev/null+++ b/unity/Assets/Scripts/Boot/GoldenData.cs.meta@@ -0,0 +1,2 @@+fileFormatVersion: 2+guid: 19f8754db22e4be7b1765126ea6e3940diff --git a/unity/Assets/Tests/EditMode/GoldenCheckTests.cs b/unity/Assets/Tests/EditMode/GoldenCheckTests.csindex 37088b875..a37146393 100644--- a/unity/Assets/Tests/EditMode/GoldenCheckTests.cs+++ b/unity/Assets/Tests/EditMode/GoldenCheckTests.cs@@ -2,15 +2,54 @@ using NUnit.Framework;using Statecraft.Game;using Statecraft.Game.Boot;using Statecraft.Sim;+using System.Linq;public class GoldenCheckTests{[Test]- public void TheCheckReportsBothGoldenRunsAsOkInTheEditor()+ public void TheCheckReportsEveryManifestGoldenAsOkInTheEditor(){- var (ok, lines) = GoldenCheck.Run(ContentLoader.Load(Paths.Content));+ var inputs = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);+ var (ok, lines) = GoldenCheck.Run(inputs.Content, inputs.Goldens);+ foreach (var line in lines) TestContext.WriteLine(line); // the full-set evidence in the results XMLAssert.IsTrue(ok, string.Join("\n", lines));- Assert.AreEqual(new[] { "GOLDEN OK 1950 " + GoldenRun.Hash1950, "GOLDEN OK 1952 " + GoldenRun.Hash1952 }, lines);+ var expected = GoldenData.Parse(inputs.Goldens.Manifest).Select(x => "GOLDEN OK " + x.name + " " + x.hash).ToArray();+ CollectionAssert.AreEqual(expected, lines);+ Assert.AreEqual(inputs.Goldens.Scenarios.Count, expected.Count(x => x.StartsWith("GOLDEN OK scenario-")));+ }++ /// <summary>The check plays what the manifest lists, not a list of its own (#394): a golden it cannot play, a missing+ /// scenario file, a wrong hash or an empty manifest each give a FAIL line and fail the run; none is skipped.</summary>+ [Test]+ public void TheCheckFailsLoudlyOnAnUnknownGoldenAWrongHashOrAnEmptyManifest()+ {+ var c = ContentLoader.Load(Paths.Content);+ var h1950 = GoldenRun.Hash1950;+ var manifest = "# c\nhash1950 " + h1950 + "\nmade-up-golden " + h1950 + "\nscenario-nope " + h1950 + "\nhash1952 " + new string('0', 64) + "\n";+ var (ok, lines) = GoldenCheck.Run(c, new GoldenData { Manifest = manifest });+ Assert.IsFalse(ok);+ Assert.AreEqual(4, lines.Count, string.Join("\n", lines));+ Assert.AreEqual("GOLDEN OK hash1950 " + h1950, lines[0]);+ StringAssert.StartsWith("GOLDEN FAIL made-up-golden ", lines[1]);+ StringAssert.StartsWith("GOLDEN FAIL scenario-nope ", lines[2]);+ StringAssert.StartsWith("GOLDEN FAIL hash1952 ", lines[3]);+ var (emptyOk, emptyLines) = GoldenCheck.Run(c, new GoldenData { Manifest = "# nothing pinned\n" });+ Assert.IsFalse(emptyOk);+ StringAssert.StartsWith("GOLDEN FAIL", emptyLines.Single());+ }++ /// <summary>The editor reads the repository's manifest and every scenario file it names (the players read the copies+ /// ContentSync ships), so the set the test plays is the .NET set.</summary>+ [Test]+ public void TheEditorReadsTheWholeManifestAndEveryScenarioFile()+ {+ var g = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap).Goldens;+ var parsed = GoldenData.Parse(g.Manifest);+ var names = parsed.Select(x => x.name).ToList();+ CollectionAssert.IsSubsetOf(new[] { "hash1950", "hash1952", "smoke5", "mvp-end" }, names);+ CollectionAssert.AreEquivalent(names.Where(n => n.StartsWith("scenario-")).Select(n => n.Substring("scenario-".Length)).ToList(), g.Scenarios.Keys.ToList());+ Assert.AreEqual(GoldenRun.Hash1950, parsed.Single(x => x.name == "hash1950").hash);+ Assert.AreEqual(GoldenRun.Hash1952, parsed.Single(x => x.name == "hash1952").hash);}[TestCase("http://localhost:8000/index.html?golden", true)]diff --git a/unity/Assets/Tests/EditMode/SimSmokeTests.cs b/unity/Assets/Tests/EditMode/SimSmokeTests.csindex f0a436c13..db917f13f 100644--- a/unity/Assets/Tests/EditMode/SimSmokeTests.cs+++ b/unity/Assets/Tests/EditMode/SimSmokeTests.cs@@ -17,25 +17,6 @@ public class SimSmokeTestsAssert.IsNotEmpty(ra.State.Hash());}- /// <summary>The golden playthroughs of docs/determinism.md, run on the Unity editor's Mono runtime. The constants are- /// GoldenRun's, which sim/Statecraft.Sim.Tests/DeterminismTests.cs pins on .NET; rebuild the DLLs- /// (uv run tools/build_sim_for_unity.py) after changing them.</summary>- [Test]- public void GoldenPlaythroughTo1950MatchesDotNet()- {- var s = GoldenRun.Play(ContentLoader.Load(Paths.Content), GoldenRun.Until1950);- Assert.IsNull(s.GameOver);- Assert.AreEqual(GoldenRun.Hash1950, s.Hash());- }-- [Test]- public void GoldenPlaythroughTo1952MatchesDotNet()- {- var s = GoldenRun.Play(ContentLoader.Load(Paths.Content), GoldenRun.Until1952);- Assert.AreEqual(GameOverCodes.MvpEnded, s.GameOver); // the game's last turn ends on 15 January 1952 (R-LOOP-004)- Assert.AreEqual(GoldenRun.Hash1952, s.Hash());- }-/// <summary>The save format's strict UTF-8 decoding, on the Unity editor's Mono runtime (it must not depend on the/// BCL's Uri class): an overlong escape is refused, a surrogate pair round-trips.</summary>[Test]